FlexExample.java 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  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. synchronized (net.getLockObject()) {
  314. float production = net.getSupplierList().stream().map(supplier -> supplier.getEnergyToSupplyNetwork()).reduce(0.0f, (a, b) -> a + b);
  315. float consumption = net.getConsumerList().stream().map(con -> con.getEnergyNeededFromNetwork()).reduce(0.0f, (a, b) -> a + b);
  316. float difference = Math.abs(production - consumption);
  317. println("production: " + production);
  318. println("consumption: " + consumption);
  319. println("difference: " + difference);
  320. if (production > consumption) continue;
  321. if (difference == 0) continue;
  322. Set<HolonElement> allHolonElemntsInThisNetwork = createListOfAllHolonElemnts(net);
  323. FlexManager flexManager = control.getSimManager().getActualFlexManager();
  324. List<FlexWrapper> allOfferedFlex = flexManager.getAllFlexWrapperWithState(FlexState.OFFERED).stream().filter(flexWrapper -> allHolonElemntsInThisNetwork.contains(flexWrapper.getFlex().getElement())).collect(Collectors.toList());
  325. List<FlexWrapper> allFlexThatGetMeEnergy = allOfferedFlex.stream().filter(flexWrapper -> (flexWrapper.getFlex().bringtmir() > 0)).collect(Collectors.toList());
  326. float amountOfAllEnergyOffered = sumEnergyAvailable(allFlexThatGetMeEnergy);
  327. println("amountOfAllFlexEnergyOffered:" + amountOfAllEnergyOffered);
  328. //ShuddownPriorities
  329. for (Priority emergencyShutDownPriority : priorityListASC) {
  330. if (amountOfAllEnergyOffered >= difference) break;
  331. println("ShutDown: " + emergencyShutDownPriority);
  332. difference -= shutDownAllConsumerElementsWithPriority(flexManager, allHolonElemntsInThisNetwork, emergencyShutDownPriority, result);
  333. }
  334. //SortFlexes
  335. allFlexThatGetMeEnergy.sort((flex1, flex2) -> Float.compare(flex1.getFlex().cost / flex1.getFlex().bringtmir(), flex2.getFlex().cost / flex2.getFlex().bringtmir()));
  336. //OrderFlexes
  337. float costForThisTimeStep = 0f;
  338. int amountflexActivated = 0;
  339. for (FlexWrapper flexWrapper : allFlexThatGetMeEnergy) {
  340. if (!flexWrapper.canOrder()) continue;
  341. float energy = flexWrapper.getFlex().bringtmir();
  342. if (energy <= difference) {
  343. println("energyGained:" + energy);
  344. difference -= energy;
  345. costForThisTimeStep += flexWrapper.getFlex().cost;
  346. flexWrapper.order();
  347. amountflexActivated++;
  348. continue;
  349. }
  350. }
  351. result.activatedFlex += amountflexActivated;
  352. println("Activated FlexThisTimeStep: " + amountflexActivated + " CostForThisTimeStep:" + costForThisTimeStep);
  353. result.totalCost += costForThisTimeStep;
  354. }
  355. }
  356. calculateStateResult(result);
  357. }
  358. private void calculateStateResult(RunResult result) {
  359. control.calculateStateOnlyForCurrentTimeStep();
  360. RunResult.TimeStepStateResult timeStepState = result.addTimeStepStateResult();
  361. for(DecoratedNetwork network: control.getSimManager().getActualDecorState().getNetworkList()) {
  362. timeStepState.amountOfConsumer += network.getAmountOfConsumer();
  363. timeStepState.amountOfConsumerOverSupplied += network.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
  364. timeStepState.amountOfConsumerPartiallySupplied += network.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
  365. timeStepState.amountOfConsumerSupplied += network.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
  366. timeStepState.amountOfConsumerUnSupplied += network.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
  367. timeStepState.amountOfPassiv += network.getAmountOfPassiv();
  368. timeStepState.amountOfProducer += network.getAmountOfSupplier();
  369. }
  370. println("Producer: " + timeStepState.amountOfProducer);
  371. println("Consumer: " + timeStepState.amountOfConsumer);
  372. println("ConsumerOverSupplied: " + timeStepState.amountOfConsumerOverSupplied);
  373. println("ConsumerSupplied: " + timeStepState.amountOfConsumerSupplied);
  374. println("ConsumerPartiallySupplied: " + timeStepState.amountOfConsumerPartiallySupplied);
  375. println("ConsumerUnSupplied: " + timeStepState.amountOfConsumerUnSupplied);
  376. println("ConsumerUnSupplied: " + timeStepState.amountOfPassiv);
  377. }
  378. private void calculateAllResults(RunResult result) {
  379. println("----------");
  380. println("Average producer proportion: " + result.getAvergaeProportionWithState(HolonObjectState.PRODUCER));
  381. println("Average producer OverSupplied: " + result.getAvergaeProportionWithState(HolonObjectState.OVER_SUPPLIED));
  382. println("Average producer Supplied: " + result.getAvergaeProportionWithState(HolonObjectState.SUPPLIED));
  383. println("Average producer PartiallySupplied: " + result.getAvergaeProportionWithState(HolonObjectState.PARTIALLY_SUPPLIED));
  384. println("Average producer NotSupplied: " + result.getAvergaeProportionWithState(HolonObjectState.NOT_SUPPLIED));
  385. println("Average producer NoEnergy: " + result.getAvergaeProportionWithState(HolonObjectState.NO_ENERGY));
  386. }
  387. private float shutDownAllConsumerElementsWithPriority(FlexManager flexManager, Set<HolonElement> allHolonElemntsInThisNetwork,
  388. Priority emergencyShutDownPriority, RunResult result) {
  389. List<HolonElement> elementsOfPriorityToShutdown = allHolonElemntsInThisNetwork.stream().filter(hElement -> hElement.isConsumer() && hElement.getPriority() == emergencyShutDownPriority && !hElement.isFlexActive(flexManager) && hElement.isActive()).collect(Collectors.toList());
  390. //.forEach(hElement -> hElement.setActive(false));
  391. float energyGained = elementsOfPriorityToShutdown.stream().map(hElement -> -hElement.getEnergyPerElement() * hElement.getAmount()).reduce(0.0f, (a, b) -> a + b);
  392. elementsOfPriorityToShutdown.forEach(hElement -> hElement.setActive(false));
  393. int shutdownCount = elementsOfPriorityToShutdown.size();
  394. result.deactivatedElements += shutdownCount;
  395. println("Gained " + energyGained + "Energy from Shutdown with Priority:" + emergencyShutDownPriority + " AmountOfShutDowned HolonElements: " + shutdownCount);
  396. return energyGained;
  397. }
  398. private Set<HolonElement> createListOfAllHolonElemnts(DecoratedNetwork net) {
  399. Set<HolonElement> allHolonElemntsInThisNetwork = new HashSet<HolonElement>();
  400. synchronized (net.getLockObject()) {
  401. allHolonElemntsInThisNetwork.addAll(net.getConsumerList().stream().flatMap(con -> con.getModel().getElements().stream()).collect(Collectors.toList()));
  402. allHolonElemntsInThisNetwork.addAll(net.getConsumerSelfSuppliedList().stream().flatMap(con -> con.getModel().getElements().stream()).collect(Collectors.toList()));
  403. allHolonElemntsInThisNetwork.addAll(net.getSupplierList().stream().flatMap(con -> con.getModel().getElements().stream()).collect(Collectors.toList()));
  404. }
  405. return allHolonElemntsInThisNetwork;
  406. }
  407. private float sumEnergyAvailable(List<FlexWrapper> flexList) {
  408. HashMap<HolonElement, FlexWrapper> dublicateFilter = new HashMap<HolonElement, FlexWrapper>();
  409. flexList.stream().forEach(flexWrapper -> dublicateFilter.put(flexWrapper.getFlex().getElement(), flexWrapper));
  410. return dublicateFilter.values().stream().map(flexWrapper -> flexWrapper.getFlex().bringtmir()).reduce(0.0f,(a, b) -> a + b);
  411. }
  412. private List<Priority> createPriorityListASC() {
  413. List<Priority> priorityASC = new ArrayList<Priority>();
  414. priorityASC.add(Priority.Low);
  415. priorityASC.add(Priority.Medium);
  416. priorityASC.add(Priority.High);
  417. priorityASC.add(Priority.Essential);
  418. return priorityASC;
  419. }
  420. /**
  421. * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
  422. * Also initialize the Access Hashmap to swap faster positions.
  423. * @param model
  424. * @return
  425. */
  426. private List<Boolean> extractPositionAndAccess() {
  427. Model model = control.getModel();
  428. switchList = new ArrayList<HolonSwitch>();
  429. objectList = new ArrayList<HolonObject>();
  430. initialState = new ArrayList<Boolean>();
  431. access= new HashMap<Integer, AccessWrapper>();
  432. rollOutNodes((useGroupNode && (dGroupNode != null))? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurIteration());
  433. resetChain.add(initialState);
  434. return initialState;
  435. }
  436. /**
  437. * Method to extract the Informations recursively out of the Model.
  438. * @param nodes
  439. * @param positionToInit
  440. * @param timeStep
  441. */
  442. private void rollOutNodes(List<AbstractCanvasObject> nodes, List<Boolean> positionToInit, int timeStep) {
  443. for(AbstractCanvasObject aCps : nodes) {
  444. if (aCps instanceof HolonObject) {
  445. for (HolonElement hE : ((HolonObject) aCps).getElements()) {
  446. positionToInit.add(hE.isActive());
  447. access.put(positionToInit.size() - 1 , new AccessWrapper(hE));
  448. }
  449. objectList.add((HolonObject) aCps);
  450. }
  451. else if (aCps instanceof HolonSwitch) {
  452. HolonSwitch sw = (HolonSwitch) aCps;
  453. positionToInit.add(sw.getState(timeStep));
  454. switchList.add(sw);
  455. access.put(positionToInit.size() - 1 , new AccessWrapper(sw));
  456. }
  457. else if(aCps instanceof GroupNode) {
  458. rollOutNodes(((GroupNode)aCps).getNodes(), positionToInit ,timeStep );
  459. }
  460. }
  461. }
  462. /**
  463. * To let the User See the current state without touching the Canvas.
  464. */
  465. private void updateVisual() {
  466. control.calculateStateAndVisualForCurrentTimeStep();
  467. //control.updateCanvas();
  468. //control.getGui().triggerUpdateController(null);
  469. }
  470. /**
  471. * Sets the Model back to its original State before the LAST run.
  472. */
  473. private void resetState() {
  474. setState(resetChain.getLast());
  475. }
  476. /**
  477. * Sets the State out of the given position for calculation or to show the user.
  478. * @param position
  479. */
  480. private void setState(List<Boolean> position) {
  481. for(int i = 0;i<position.size();i++) {
  482. access.get(i).setState(position.get(i));
  483. }
  484. }
  485. private void addObjectToList(List<AbstractCanvasObject> listToSearch, List<HolonObject> listToAdd){
  486. for (AbstractCanvasObject aCps : listToSearch) {
  487. if (aCps instanceof HolonObject) listToAdd.add((HolonObject) aCps);
  488. else if(aCps instanceof GroupNode) {
  489. addObjectToList(((GroupNode)aCps).getNodes(),listToAdd);
  490. }
  491. }
  492. }
  493. /**
  494. * A Wrapper Class for Access HolonElement and HolonSwitch in one Element and not have to split the List.
  495. */
  496. private class AccessWrapper {
  497. public static final int HOLONELEMENT = 0;
  498. public static final int SWITCH = 1;
  499. private int type;
  500. private HolonSwitch hSwitch;
  501. private HolonElement hElement;
  502. public AccessWrapper(HolonSwitch hSwitch){
  503. type = SWITCH;
  504. this.hSwitch = hSwitch;
  505. }
  506. public AccessWrapper(HolonElement hElement){
  507. type = HOLONELEMENT;
  508. this.hElement = hElement;
  509. }
  510. public void setState(boolean state) {
  511. if(type == HOLONELEMENT) {
  512. hElement.setActive(state);
  513. }else{//is switch
  514. hSwitch.setManualMode(true);
  515. hSwitch.setManualState(state);
  516. }
  517. }
  518. public boolean getState(int timeStep) {
  519. return (type == HOLONELEMENT)?hElement.isActive():hSwitch.getState(timeStep);
  520. }
  521. public int getType() {
  522. return type;
  523. }
  524. }
  525. private class RunResult {
  526. public int activatedFlex = 0;
  527. public int deactivatedElements = 0;
  528. public float totalCost = 0;
  529. public LinkedList<TimeStepStateResult> timeStepList = new LinkedList<TimeStepStateResult>();
  530. public TimeStepStateResult addTimeStepStateResult(){
  531. TimeStepStateResult aResult = new TimeStepStateResult();
  532. timeStepList.add(aResult);
  533. return aResult;
  534. }
  535. public class TimeStepStateResult{
  536. public int amountOfProducer = 0;
  537. public int amountOfConsumer = 0;
  538. public int amountOfPassiv = 0;
  539. public int amountOfConsumerOverSupplied = 0;
  540. public int amountOfConsumerSupplied = 0;
  541. public int amountOfConsumerPartiallySupplied = 0;
  542. public int amountOfConsumerUnSupplied= 0;
  543. public float getProportionWithState(HolonObjectState state) {
  544. float amountOfObjects = amountOfProducer + amountOfConsumer + amountOfPassiv;
  545. switch(state) {
  546. case NOT_SUPPLIED:
  547. return (float) amountOfConsumerUnSupplied / amountOfObjects;
  548. case NO_ENERGY:
  549. return (float) amountOfPassiv / amountOfObjects;
  550. case OVER_SUPPLIED:
  551. return (float) amountOfConsumerOverSupplied / amountOfObjects;
  552. case PARTIALLY_SUPPLIED:
  553. return (float) amountOfConsumerPartiallySupplied / amountOfObjects;
  554. case PRODUCER:
  555. return (float) amountOfProducer / amountOfObjects;
  556. case SUPPLIED:
  557. return (float) amountOfConsumerSupplied / amountOfObjects;
  558. default:
  559. return 0.f;
  560. }
  561. }
  562. }
  563. public float getAvergaeProportionWithState(HolonObjectState state) {
  564. return timeStepList.stream().map(step -> step.getProportionWithState(state)).reduce((a,b) -> (a + b)).orElse(0.f) / (float) 100;
  565. }
  566. }
  567. private class Handle<T>{
  568. public T object;
  569. Handle(T object){
  570. this.object = object;
  571. }
  572. public String toString() {
  573. return object.toString();
  574. }
  575. }
  576. }