FlexExample.java 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. package holeg.algorithm.example;
  2. import java.awt.BorderLayout;
  3. import java.awt.Component;
  4. import java.awt.Dimension;
  5. import java.awt.FlowLayout;
  6. import java.awt.image.BufferedImage;
  7. import java.text.NumberFormat;
  8. import java.util.ArrayList;
  9. import java.util.HashMap;
  10. import java.util.HashSet;
  11. import java.util.LinkedList;
  12. import java.util.List;
  13. import java.util.Set;
  14. import java.util.stream.Collectors;
  15. import java.util.stream.Stream;
  16. import javax.swing.BorderFactory;
  17. import javax.swing.ImageIcon;
  18. import javax.swing.JButton;
  19. import javax.swing.JCheckBox;
  20. import javax.swing.JFrame;
  21. import javax.swing.JLabel;
  22. import javax.swing.JOptionPane;
  23. import javax.swing.JPanel;
  24. import javax.swing.JScrollPane;
  25. import javax.swing.JSplitPane;
  26. import javax.swing.JTextArea;
  27. import javax.swing.text.NumberFormatter;
  28. import holeg.api.AddOn;
  29. import holeg.model.AbstractCanvasObject;
  30. import holeg.model.Flexibility;
  31. import holeg.model.GroupNode;
  32. import holeg.model.HolonElement;
  33. import holeg.model.HolonObject;
  34. import holeg.model.HolonSwitch;
  35. import holeg.model.Flexibility.FlexState;
  36. import holeg.model.HolonElement.Priority;
  37. import holeg.ui.controller.Control;
  38. import holeg.ui.model.DecoratedGroupNode;
  39. import holeg.ui.model.DecoratedNetwork;
  40. import holeg.ui.model.DecoratedState;
  41. import holeg.ui.model.Model;
  42. import holeg.ui.model.DecoratedHolonObject.HolonObjectState;
  43. public class FlexExample implements AddOn {
  44. //Settings For GroupNode using and cancel
  45. private boolean useGroupNode = false;
  46. private DecoratedGroupNode dGroupNode = null;
  47. private boolean cancel = false;
  48. private boolean overAllTimeSteps = false;
  49. //Parameter defined by Algo
  50. private HashMap<Integer, AccessWrapper> access;
  51. LinkedList<List<Boolean>> resetChain = new LinkedList<List<Boolean>>();
  52. private List<Boolean> initialState;
  53. private List<HolonSwitch> switchList;
  54. private List<HolonObject> objectList;
  55. //Gui Part:
  56. private Control control;
  57. private JTextArea textArea;
  58. private JPanel content = new JPanel();
  59. //ProgressBar
  60. private long startTime;
  61. private Thread runThread;
  62. public static void main(String[] args)
  63. {
  64. JFrame newFrame = new JFrame("exampleWindow");
  65. DemoAlgo instance = new DemoAlgo();
  66. newFrame.setContentPane(instance.getPanel());
  67. newFrame.pack();
  68. newFrame.setVisible(true);
  69. newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  70. }
  71. public FlexExample() {
  72. content.setLayout(new BorderLayout());
  73. textArea = new JTextArea();
  74. textArea.setEditable(false);
  75. JScrollPane scrollPane = new JScrollPane(textArea);
  76. JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
  77. createOptionPanel() , scrollPane);
  78. splitPane.setResizeWeight(0.0);
  79. content.add(splitPane, BorderLayout.CENTER);
  80. content.setPreferredSize(new Dimension(800,800));
  81. }
  82. public JPanel createOptionPanel() {
  83. JPanel optionPanel = new JPanel(new BorderLayout());
  84. JScrollPane scrollPane = new JScrollPane(createParameterPanel());
  85. scrollPane.setBorder(BorderFactory.createTitledBorder("Parameter"));
  86. optionPanel.add(scrollPane, BorderLayout.CENTER);
  87. optionPanel.add(createButtonPanel(), BorderLayout.PAGE_END);
  88. return optionPanel;
  89. }
  90. private Component createParameterPanel() {
  91. JPanel parameterPanel = new JPanel(null);
  92. parameterPanel.setPreferredSize(new Dimension(510,300));
  93. // JLabel showDiagnosticsLabel = new JLabel("Set all switches closed:");
  94. // showDiagnosticsLabel.setBounds(200, 60, 170, 20);
  95. // parameterPanel.add(showDiagnosticsLabel);
  96. JPanel borderPanel = new JPanel(null);
  97. borderPanel.setBounds(200, 85, 185, 50);
  98. borderPanel.setBorder(BorderFactory.createTitledBorder(""));
  99. parameterPanel.add(borderPanel);
  100. JLabel showGroupNodeLabel = new JLabel("Use Group Node:");
  101. showGroupNodeLabel.setBounds(10, 1, 170, 20);
  102. borderPanel.add(showGroupNodeLabel);
  103. JButton selectGroupNodeButton = new JButton("Select GroupNode");
  104. selectGroupNodeButton.setEnabled(false);
  105. selectGroupNodeButton.setBounds(10, 25, 165, 20);
  106. selectGroupNodeButton.addActionListener(actionEvent -> selectGroupNode());
  107. borderPanel.add(selectGroupNodeButton);
  108. JCheckBox useGroupNodeCheckBox = new JCheckBox();
  109. useGroupNodeCheckBox.setSelected(false);
  110. useGroupNodeCheckBox.setBounds(155, 1, 25, 20);
  111. useGroupNodeCheckBox.addActionListener(actionEvent -> {
  112. useGroupNode = useGroupNodeCheckBox.isSelected();
  113. selectGroupNodeButton.setEnabled(useGroupNode);
  114. });
  115. borderPanel.add(useGroupNodeCheckBox);
  116. JCheckBox overAllTimeStepsCheckbox = new JCheckBox("overAllTimeSteps");
  117. overAllTimeStepsCheckbox.setSelected(false);
  118. overAllTimeStepsCheckbox.setBounds(20, 30, 250, 30);
  119. overAllTimeStepsCheckbox.addActionListener(actionEvent -> {
  120. overAllTimeSteps = overAllTimeStepsCheckbox.isSelected();
  121. });
  122. parameterPanel.add(overAllTimeStepsCheckbox);
  123. NumberFormat format = NumberFormat.getIntegerInstance();
  124. format.setGroupingUsed(false);
  125. format.setParseIntegerOnly(true);
  126. NumberFormatter integerFormatter = new NumberFormatter(format);
  127. integerFormatter.setMinimum(0);
  128. integerFormatter.setCommitsOnValidEdit(true);
  129. JLabel portLabel = new JLabel("between:");
  130. portLabel.setBounds(10, 330, 70, 30);
  131. parameterPanel.add(portLabel);
  132. JLabel afterLabel = new JLabel("after:");
  133. afterLabel.setBounds(10, 360, 70, 30);
  134. parameterPanel.add(afterLabel);
  135. return parameterPanel;
  136. }
  137. public JPanel createButtonPanel() {
  138. JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
  139. JButton resetButton = new JButton("ResetAll");
  140. resetButton.setToolTipText("Resets the State to before the Algorithm has runed.");
  141. resetButton.addActionListener(actionEvent -> resetAll());
  142. buttonPanel.add(resetButton);
  143. JButton cancelButton = new JButton("Cancel Run");
  144. cancelButton.addActionListener(actionEvent -> cancel());
  145. buttonPanel.add(cancelButton);
  146. JButton clearButton = new JButton("Clear Console");
  147. clearButton.addActionListener(actionEvent -> clear());
  148. buttonPanel.add(clearButton);
  149. JButton undoButton = new JButton("Undo");
  150. undoButton.setToolTipText("One Algo Step Back.");
  151. undoButton.addActionListener(actionEvent -> resetLast());
  152. buttonPanel.add(undoButton);
  153. JButton runButton = new JButton("Run");
  154. runButton.addActionListener(actionEvent -> {
  155. Runnable task = () -> {
  156. if(this.overAllTimeSteps)runAll();
  157. else run();
  158. };
  159. runThread = new Thread(task);
  160. runThread.start();
  161. });
  162. buttonPanel.add(runButton);
  163. return buttonPanel;
  164. }
  165. private void cancel() {
  166. if(runThread.isAlive()) {
  167. println("");
  168. println("Cancel run.");
  169. cancel = true;
  170. } else {
  171. println("Nothing to cancel.");
  172. }
  173. }
  174. private void runAll() {
  175. cancel = false;
  176. disableGuiInput(true);
  177. startTimer();
  178. control.resetSimulation();
  179. RunResult result= new RunResult();
  180. for(int i = 0; i < 100; i++) {
  181. control.getModel().setCurrentIteration(i);
  182. executeDemoAlgo(result);
  183. if(cancel) {
  184. resetLast();
  185. disableGuiInput(false);
  186. return;
  187. }
  188. }
  189. updateVisual();
  190. calculateAllResults(result);
  191. println("Amount of activatedFlex:" + result.activatedFlex + " Amount of deactivatedElements:"+ result.deactivatedElements + " TotalCost:"+result.totalCost);
  192. printElapsedTime();
  193. disableGuiInput(false);
  194. }
  195. private void run() {
  196. disableGuiInput(true);
  197. startTimer();
  198. executeDemoAlgo(new RunResult());
  199. updateVisual();
  200. printElapsedTime();
  201. disableGuiInput(false);
  202. }
  203. private void resetLast() {
  204. if(!resetChain.isEmpty()) {
  205. println("Resetting..");
  206. resetState();
  207. resetChain.removeLast();
  208. control.resetSimulation();
  209. updateVisual();
  210. }else {
  211. println("No run inistialized.");
  212. }
  213. }
  214. private void resetAll() {
  215. if(!resetChain.isEmpty()) {
  216. println("Resetting..");
  217. setState(resetChain.getFirst());
  218. resetChain.clear();
  219. control.resetSimulation();
  220. control.getModel().setCurrentIteration(0);
  221. updateVisual();
  222. }else {
  223. println("No run inistialized.");
  224. }
  225. }
  226. private void disableGuiInput(boolean bool) {
  227. control.guiDisable(bool);
  228. }
  229. @Override
  230. public JPanel getPanel() {
  231. return content;
  232. }
  233. @Override
  234. public void setController(Control control) {
  235. this.control = control;
  236. }
  237. private void clear() {
  238. textArea.setText("");
  239. }
  240. private void println(String message) {
  241. textArea.append(message + "\n");
  242. }
  243. private void selectGroupNode() {
  244. control.getSimManager().getActualVisualRepresentationalState().ifPresent(state -> {
  245. Object[] possibilities = state.getCreatedGroupNodes().values().stream().map(aCps -> new Handle<DecoratedGroupNode>(aCps)).toArray();
  246. @SuppressWarnings("unchecked")
  247. Handle<DecoratedGroupNode> selected = (Handle<DecoratedGroupNode>) JOptionPane.showInputDialog(content, "Select GroupNode:", "GroupNode?", JOptionPane.OK_OPTION,new ImageIcon(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)) , possibilities, "");
  248. if(selected != null) {
  249. println("Selected: " + selected);
  250. dGroupNode = selected.object;
  251. }
  252. });
  253. }
  254. private void startTimer(){
  255. startTime = System.currentTimeMillis();
  256. }
  257. private void printElapsedTime(){
  258. long elapsedMilliSeconds = System.currentTimeMillis() - startTime;
  259. println("Execution Time of Algo in Milliseconds:" + elapsedMilliSeconds);
  260. }
  261. //Algo Part:
  262. /**
  263. * The Execution of the FlexAlgo.
  264. *
  265. *
  266. * Begin
  267. * for(All Networks) do
  268. *
  269. * if(not (production < consumption)) continue;
  270. *
  271. *
  272. * for(Priority emergencyShutDownPriority: priorityListASC) do
  273. * difference = Math.abs(production - consumption);
  274. * amountOfAllEnergyOffered = sumEnergyAvailable(flexList);
  275. * if(amountOfAllEnergyOffered > difference) break;
  276. * shutDownAllConsumerWithPriority(emergencyShutDownPriority)
  277. * end for
  278. *
  279. * takeAKombinationOfOffers(); (nach welchem Kriterium)
  280. *
  281. *
  282. * end for
  283. * End
  284. *
  285. */
  286. private void executeDemoAlgo(RunResult result) {
  287. extractPositionAndAccess();
  288. int actualIteration = control.getModel().getCurrentIteration();
  289. println("TimeStep:" + actualIteration);
  290. control.calculateStateOnlyForCurrentTimeStep();
  291. List<Priority> priorityListASC = createPriorityListASC();
  292. DecoratedState actualstate = control.getSimManager().getActualDecorState().get();
  293. for(DecoratedNetwork net : actualstate.getNetworkList()) {
  294. float production = net.getSupplierList().stream().map(supplier -> supplier.getEnergyToSupplyNetwork()).reduce(0.0f, (a, b) -> a + b);
  295. float consumption = net.getConsumerList().stream().map(con -> con.getEnergyNeededFromNetwork()).reduce(0.0f, (a, b) -> a + b);
  296. float difference = Math.abs(production - consumption);
  297. println("production: " + production);
  298. println("consumption: " + consumption);
  299. println("difference: " + difference);
  300. if(production > consumption) continue;
  301. if(difference == 0)continue;
  302. Set<HolonElement> allHolonElemntsInThisNetwork = createListOfAllHolonElemnts(net);
  303. List<Flexibility> flexList = control.getModel().getAllFlexibilities();
  304. List<Flexibility> allOfferedFlex = flexList.stream().filter(flex -> flex.getState().equals(FlexState.OFFERED)).toList();
  305. List<Flexibility> allFlexThatGetMeEnergy = allOfferedFlex.stream().filter(flexWrapper -> (flexWrapper.energyReleased() > 0)).collect(Collectors.toList());
  306. float amountOfAllEnergyOffered = sumEnergyAvailable(allFlexThatGetMeEnergy);
  307. println("amountOfAllFlexEnergyOffered:" + amountOfAllEnergyOffered);
  308. //ShuddownPriorities
  309. for(Priority emergencyShutDownPriority: priorityListASC) {
  310. if(amountOfAllEnergyOffered >= difference) break;
  311. println("ShutDown: " + emergencyShutDownPriority);
  312. difference -= shutDownAllConsumerElementsWithPriority(allHolonElemntsInThisNetwork, emergencyShutDownPriority, result);
  313. }
  314. //SortFlexes
  315. allFlexThatGetMeEnergy.sort((flex1, flex2) -> Float.compare(flex1.cost / flex1.energyReleased(), flex2.cost / flex2.energyReleased()));
  316. //OrderFlexes
  317. float costForThisTimeStep = 0f;
  318. int amountflexActivated = 0;
  319. for(Flexibility flex : allFlexThatGetMeEnergy) {
  320. if(!flex.canOrder()) continue;
  321. float energy = flex.energyReleased();
  322. if(energy <= difference) {
  323. println("energyGained:" + energy);
  324. difference -= energy;
  325. costForThisTimeStep += flex.cost;
  326. flex.order();
  327. amountflexActivated++;
  328. continue;
  329. }
  330. }
  331. result.activatedFlex += amountflexActivated;
  332. println("Activated FlexThisTimeStep: "+ amountflexActivated+" CostForThisTimeStep:" + costForThisTimeStep);
  333. result.totalCost += costForThisTimeStep;
  334. }
  335. calculateStateResult(result);
  336. }
  337. private void calculateStateResult(RunResult result) {
  338. control.calculateStateOnlyForCurrentTimeStep();
  339. RunResult.TimeStepStateResult timeStepState = result.addTimeStepStateResult();
  340. for(DecoratedNetwork network: control.getSimManager().getActualDecorState().get().getNetworkList()) {
  341. timeStepState.amountOfConsumer += network.getAmountOfConsumer();
  342. timeStepState.amountOfConsumerOverSupplied += network.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
  343. timeStepState.amountOfConsumerPartiallySupplied += network.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
  344. timeStepState.amountOfConsumerSupplied += network.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
  345. timeStepState.amountOfConsumerUnSupplied += network.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
  346. timeStepState.amountOfPassiv += network.getAmountOfPassiv();
  347. timeStepState.amountOfProducer += network.getAmountOfSupplier();
  348. }
  349. println("Producer: " + timeStepState.amountOfProducer);
  350. println("Consumer: " + timeStepState.amountOfConsumer);
  351. println("ConsumerOverSupplied: " + timeStepState.amountOfConsumerOverSupplied);
  352. println("ConsumerSupplied: " + timeStepState.amountOfConsumerSupplied);
  353. println("ConsumerPartiallySupplied: " + timeStepState.amountOfConsumerPartiallySupplied);
  354. println("ConsumerUnSupplied: " + timeStepState.amountOfConsumerUnSupplied);
  355. println("ConsumerUnSupplied: " + timeStepState.amountOfPassiv);
  356. }
  357. private void calculateAllResults(RunResult result) {
  358. println("----------");
  359. println("Average producer proportion: " + result.getAvergaeProportionWithState(HolonObjectState.PRODUCER));
  360. println("Average producer OverSupplied: " + result.getAvergaeProportionWithState(HolonObjectState.OVER_SUPPLIED));
  361. println("Average producer Supplied: " + result.getAvergaeProportionWithState(HolonObjectState.SUPPLIED));
  362. println("Average producer PartiallySupplied: " + result.getAvergaeProportionWithState(HolonObjectState.PARTIALLY_SUPPLIED));
  363. println("Average producer NotSupplied: " + result.getAvergaeProportionWithState(HolonObjectState.NOT_SUPPLIED));
  364. println("Average producer NoEnergy: " + result.getAvergaeProportionWithState(HolonObjectState.NO_ENERGY));
  365. }
  366. private float shutDownAllConsumerElementsWithPriority(Set<HolonElement> allHolonElemntsInThisNetwork,
  367. Priority emergencyShutDownPriority, RunResult result) {
  368. List<HolonElement> elementsOfPriorityToShutdown = allHolonElemntsInThisNetwork.stream().filter(hElement -> hElement.isConsumer() && hElement.getPriority() == emergencyShutDownPriority && !hElement.isFlexActive() && hElement.active).collect(Collectors.toList());
  369. //.forEach(hElement -> hElement.setActive(false));
  370. float energyGained = elementsOfPriorityToShutdown.stream().map(hElement -> -hElement.getEnergy()).reduce(0.0f, (a, b) -> a + b);
  371. elementsOfPriorityToShutdown.forEach(hElement -> hElement.active = false);
  372. int shutdownCount = elementsOfPriorityToShutdown.size();
  373. result.deactivatedElements += shutdownCount;
  374. println("Gained " + energyGained + "Energy from Shutdown with Priority:" + emergencyShutDownPriority + " AmountOfShutDowned HolonElements: " + shutdownCount);
  375. return energyGained;
  376. }
  377. private Set<HolonElement> createListOfAllHolonElemnts(DecoratedNetwork net) {
  378. Set<HolonElement> allHolonElemntsInThisNetwork = new HashSet<HolonElement>();
  379. allHolonElemntsInThisNetwork.addAll(net.getConsumerList().stream().flatMap(con -> con.getModel().getElements()).collect(Collectors.toList()));
  380. allHolonElemntsInThisNetwork.addAll(net.getConsumerSelfSuppliedList().stream().flatMap(con -> con.getModel().getElements()).collect(Collectors.toList()));
  381. allHolonElemntsInThisNetwork.addAll(net.getSupplierList().stream().flatMap(con -> con.getModel().getElements()).collect(Collectors.toList()));
  382. return allHolonElemntsInThisNetwork;
  383. }
  384. private float sumEnergyAvailable(List<Flexibility> flexList) {
  385. HashMap<HolonElement, Flexibility> dublicateFilter = new HashMap<HolonElement, Flexibility>();
  386. flexList.stream().forEach(flex -> dublicateFilter.put(flex.getElement(), flex));
  387. return dublicateFilter.values().stream().map(flex -> flex.energyReleased()).reduce(0.0f,Float::sum);
  388. }
  389. private List<Priority> createPriorityListASC() {
  390. List<Priority> priorityASC = new ArrayList<Priority>();
  391. priorityASC.add(Priority.Low);
  392. priorityASC.add(Priority.Medium);
  393. priorityASC.add(Priority.High);
  394. priorityASC.add(Priority.Essential);
  395. return priorityASC;
  396. }
  397. /**
  398. * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
  399. * Also initialize the Access Hashmap to swap faster positions.
  400. * @param ModelTest
  401. * @return
  402. */
  403. private List<Boolean> extractPositionAndAccess() {
  404. Model model = control.getModel();
  405. switchList = new ArrayList<HolonSwitch>();
  406. objectList = new ArrayList<HolonObject>();
  407. initialState = new ArrayList<Boolean>();
  408. access= new HashMap<Integer, AccessWrapper>();
  409. rollOutNodes((useGroupNode && (dGroupNode != null))? dGroupNode.getModel().getObjectsInThisLayer() :model.getCanvas().getObjectsInThisLayer(), initialState, model.getCurrentIteration());
  410. resetChain.add(initialState);
  411. return initialState;
  412. }
  413. /**
  414. * Method to extract the Informations recursively out of the Model.
  415. * @param nodes
  416. * @param positionToInit
  417. * @param timeStep
  418. */
  419. private void rollOutNodes(Stream<AbstractCanvasObject> nodes, List<Boolean> positionToInit, int timeStep) {
  420. nodes.forEach(aCps -> {
  421. if (aCps instanceof HolonObject hO) {
  422. hO.getElements().forEach(hE -> {
  423. positionToInit.add(hE.active);
  424. access.put(positionToInit.size() - 1 , new AccessWrapper(hE));
  425. });
  426. objectList.add(hO);
  427. }
  428. else if (aCps instanceof HolonSwitch sw) {
  429. positionToInit.add(sw.getState(timeStep));
  430. switchList.add(sw);
  431. access.put(positionToInit.size() - 1 , new AccessWrapper(sw));
  432. }
  433. else if(aCps instanceof GroupNode groupnode) {
  434. rollOutGroupNode(groupnode, positionToInit ,timeStep);
  435. }
  436. });
  437. }
  438. private void rollOutGroupNode (GroupNode groupNode, List<Boolean> positionToInit, int timeStep) {
  439. groupNode.getAllHolonObjectsRecursive().forEach(hObject -> {
  440. hObject.getElements().forEach(hE -> {
  441. positionToInit.add(hE.active);
  442. access.put(positionToInit.size() - 1 , new AccessWrapper(hE));
  443. });
  444. objectList.add(hObject);
  445. });
  446. groupNode.getAllSwitchObjectsRecursive().forEach(sw -> {
  447. positionToInit.add(sw.getState(timeStep));
  448. switchList.add(sw);
  449. access.put(positionToInit.size() - 1 , new AccessWrapper(sw));
  450. });
  451. }
  452. /**
  453. * To let the User See the current state without touching the Canvas.
  454. */
  455. private void updateVisual() {
  456. control.calculateStateAndVisualForCurrentTimeStep();
  457. //control.updateCanvas();
  458. //control.getGui().triggerUpdateController(null);
  459. }
  460. /**
  461. * Sets the Model back to its original State before the LAST run.
  462. */
  463. private void resetState() {
  464. setState(resetChain.getLast());
  465. }
  466. /**
  467. * Sets the State out of the given position for calculation or to show the user.
  468. * @param position
  469. */
  470. private void setState(List<Boolean> position) {
  471. for(int i = 0;i<position.size();i++) {
  472. access.get(i).setState(position.get(i));
  473. }
  474. }
  475. /**
  476. * A Wrapper Class for Access HolonElement and HolonSwitch in one Element and not have to split the List.
  477. */
  478. private class AccessWrapper {
  479. public static final int HOLONELEMENT = 0;
  480. public static final int SWITCH = 1;
  481. private int type;
  482. private HolonSwitch hSwitch;
  483. private HolonElement hElement;
  484. public AccessWrapper(HolonSwitch hSwitch){
  485. type = SWITCH;
  486. this.hSwitch = hSwitch;
  487. }
  488. public AccessWrapper(HolonElement hElement){
  489. type = HOLONELEMENT;
  490. this.hElement = hElement;
  491. }
  492. public void setState(boolean state) {
  493. if(type == HOLONELEMENT) {
  494. hElement.active = state;
  495. }else{//is switch
  496. hSwitch.setManualMode(true);
  497. hSwitch.setManualState(state);
  498. }
  499. }
  500. }
  501. private class RunResult {
  502. public int activatedFlex = 0;
  503. public int deactivatedElements = 0;
  504. public float totalCost = 0;
  505. public LinkedList<TimeStepStateResult> timeStepList = new LinkedList<TimeStepStateResult>();
  506. public TimeStepStateResult addTimeStepStateResult(){
  507. TimeStepStateResult aResult = new TimeStepStateResult();
  508. timeStepList.add(aResult);
  509. return aResult;
  510. }
  511. public class TimeStepStateResult{
  512. public int amountOfProducer = 0;
  513. public int amountOfConsumer = 0;
  514. public int amountOfPassiv = 0;
  515. public int amountOfConsumerOverSupplied = 0;
  516. public int amountOfConsumerSupplied = 0;
  517. public int amountOfConsumerPartiallySupplied = 0;
  518. public int amountOfConsumerUnSupplied= 0;
  519. public float getProportionWithState(HolonObjectState state) {
  520. float amountOfObjects = amountOfProducer + amountOfConsumer + amountOfPassiv;
  521. switch(state) {
  522. case NOT_SUPPLIED:
  523. return (float) amountOfConsumerUnSupplied / amountOfObjects;
  524. case NO_ENERGY:
  525. return (float) amountOfPassiv / amountOfObjects;
  526. case OVER_SUPPLIED:
  527. return (float) amountOfConsumerOverSupplied / amountOfObjects;
  528. case PARTIALLY_SUPPLIED:
  529. return (float) amountOfConsumerPartiallySupplied / amountOfObjects;
  530. case PRODUCER:
  531. return (float) amountOfProducer / amountOfObjects;
  532. case SUPPLIED:
  533. return (float) amountOfConsumerSupplied / amountOfObjects;
  534. default:
  535. return 0.f;
  536. }
  537. }
  538. }
  539. public float getAvergaeProportionWithState(HolonObjectState state) {
  540. return timeStepList.stream().map(step -> step.getProportionWithState(state)).reduce((a,b) -> (a + b)).orElse(0.f) / (float) 100;
  541. }
  542. }
  543. private class Handle<T>{
  544. public T object;
  545. Handle(T object){
  546. this.object = object;
  547. }
  548. public String toString() {
  549. return object.toString();
  550. }
  551. }
  552. }