FlexExample.java 23 KB

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