FlexExample.java 23 KB

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