FlexExample.java 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  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.Optional;
  14. import java.util.Set;
  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.JFrame;
  22. import javax.swing.JLabel;
  23. import javax.swing.JOptionPane;
  24. import javax.swing.JPanel;
  25. import javax.swing.JScrollPane;
  26. import javax.swing.JSplitPane;
  27. import javax.swing.JTextArea;
  28. import javax.swing.text.NumberFormatter;
  29. import holeg.api.AddOn;
  30. import holeg.model.AbstractCanvasObject;
  31. import holeg.model.Flexibility;
  32. import holeg.model.GroupNode;
  33. import holeg.model.HolonElement;
  34. import holeg.model.HolonObject;
  35. import holeg.model.HolonObject.HolonObjectState;
  36. import holeg.model.HolonSwitch.SwitchMode;
  37. import holeg.model.HolonSwitch.SwitchState;
  38. import holeg.model.HolonSwitch;
  39. import holeg.model.Flexibility.FlexState;
  40. import holeg.model.HolonElement.Priority;
  41. import holeg.ui.controller.Control;
  42. import holeg.ui.model.Model;
  43. public class FlexExample implements AddOn {
  44. //Settings For GroupNode using and cancel
  45. private boolean useGroupNode = false;
  46. private Optional<GroupNode> groupnode = Optional.empty();
  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.guiSetEnabled(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. Object[] possibilities = control.getModel().getCanvas().getAllGroupNodeObjectsRecursive().toArray();
  245. @SuppressWarnings("unchecked")
  246. GroupNode selected = (GroupNode) JOptionPane.showInputDialog(content, "Select GroupNode:", "GroupNode?", JOptionPane.OK_OPTION,new ImageIcon(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)) , possibilities, "");
  247. if(selected != null) {
  248. println("Selected: " + selected);
  249. groupnode = Optional.of(selected);
  250. }
  251. }
  252. private void startTimer(){
  253. startTime = System.currentTimeMillis();
  254. }
  255. private void printElapsedTime(){
  256. long elapsedMilliSeconds = System.currentTimeMillis() - startTime;
  257. println("Execution Time of Algo in Milliseconds:" + elapsedMilliSeconds);
  258. }
  259. //Algo Part:
  260. /**
  261. * The Execution of the FlexAlgo.
  262. *
  263. *
  264. * Begin
  265. * for(All Networks) do
  266. *
  267. * if(not (production < consumption)) continue;
  268. *
  269. *
  270. * for(Priority emergencyShutDownPriority: priorityListASC) do
  271. * difference = Math.abs(production - consumption);
  272. * amountOfAllEnergyOffered = sumEnergyAvailable(flexList);
  273. * if(amountOfAllEnergyOffered > difference) break;
  274. * shutDownAllConsumerWithPriority(emergencyShutDownPriority)
  275. * end for
  276. *
  277. * takeAKombinationOfOffers(); (nach welchem Kriterium)
  278. *
  279. *
  280. * end for
  281. * End
  282. *
  283. */
  284. private void executeDemoAlgo(RunResult result) {
  285. extractPositionAndAccess();
  286. int actualIteration = control.getModel().getCurrentIteration();
  287. println("TimeStep:" + actualIteration);
  288. control.calculateStateOnlyForCurrentTimeStep();
  289. List<Priority> priorityListASC = createPriorityListASC();
  290. // DecoratedState actualstate = control.getSimManager().getActualDecorState().get();
  291. // for(DecoratedNetwork net : actualstate.getNetworkList()) {
  292. // float production = net.getSupplierList().stream().map(supplier -> supplier.getEnergyToSupplyNetwork()).reduce(0.0f, (a, b) -> a + b);
  293. // float consumption = net.getConsumerList().stream().map(con -> con.getEnergyNeededFromNetwork()).reduce(0.0f, (a, b) -> a + b);
  294. // float difference = Math.abs(production - consumption);
  295. // println("production: " + production);
  296. // println("consumption: " + consumption);
  297. // println("difference: " + difference);
  298. // if(production > consumption) continue;
  299. // if(difference == 0)continue;
  300. // Set<HolonElement> allHolonElemntsInThisNetwork = createListOfAllHolonElemnts(net);
  301. // List<Flexibility> flexList = control.getModel().getAllFlexibilities();
  302. // List<Flexibility> allOfferedFlex = flexList.stream().filter(flex -> flex.getState().equals(FlexState.OFFERED)).toList();
  303. // List<Flexibility> allFlexThatGetMeEnergy = allOfferedFlex.stream().filter(flexWrapper -> (flexWrapper.energyReleased() > 0)).collect(Collectors.toList());
  304. // float amountOfAllEnergyOffered = sumEnergyAvailable(allFlexThatGetMeEnergy);
  305. // println("amountOfAllFlexEnergyOffered:" + amountOfAllEnergyOffered);
  306. // //ShuddownPriorities
  307. // for(Priority emergencyShutDownPriority: priorityListASC) {
  308. // if(amountOfAllEnergyOffered >= difference) break;
  309. // println("ShutDown: " + emergencyShutDownPriority);
  310. // difference -= shutDownAllConsumerElementsWithPriority(allHolonElemntsInThisNetwork, emergencyShutDownPriority, result);
  311. // }
  312. //
  313. // //SortFlexes
  314. // allFlexThatGetMeEnergy.sort((flex1, flex2) -> Float.compare(flex1.cost / flex1.energyReleased(), flex2.cost / flex2.energyReleased()));
  315. // //OrderFlexes
  316. // float costForThisTimeStep = 0f;
  317. // int amountflexActivated = 0;
  318. // for(Flexibility flex : allFlexThatGetMeEnergy) {
  319. // if(!flex.canOrder()) continue;
  320. // float energy = flex.energyReleased();
  321. // if(energy <= difference) {
  322. // println("energyGained:" + energy);
  323. // difference -= energy;
  324. // costForThisTimeStep += flex.cost;
  325. // flex.order();
  326. // amountflexActivated++;
  327. // continue;
  328. // }
  329. // }
  330. // result.activatedFlex += amountflexActivated;
  331. //
  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. //
  341. // for(DecoratedNetwork network: control.getSimManager().getActualDecorState().get().getNetworkList()) {
  342. // timeStepState.amountOfConsumer += network.getAmountOfConsumer();
  343. // timeStepState.amountOfConsumerOverSupplied += network.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
  344. // timeStepState.amountOfConsumerPartiallySupplied += network.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
  345. // timeStepState.amountOfConsumerSupplied += network.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
  346. // timeStepState.amountOfConsumerUnSupplied += network.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
  347. // timeStepState.amountOfPassiv += network.getAmountOfPassiv();
  348. // timeStepState.amountOfProducer += network.getAmountOfSupplier();
  349. // }
  350. // println("Producer: " + timeStepState.amountOfProducer);
  351. // println("Consumer: " + timeStepState.amountOfConsumer);
  352. // println("ConsumerOverSupplied: " + timeStepState.amountOfConsumerOverSupplied);
  353. // println("ConsumerSupplied: " + timeStepState.amountOfConsumerSupplied);
  354. // println("ConsumerPartiallySupplied: " + timeStepState.amountOfConsumerPartiallySupplied);
  355. // println("ConsumerUnSupplied: " + timeStepState.amountOfConsumerUnSupplied);
  356. // println("ConsumerUnSupplied: " + timeStepState.amountOfPassiv);
  357. }
  358. private void calculateAllResults(RunResult result) {
  359. println("----------");
  360. println("Average producer proportion: " + result.getAvergaeProportionWithState(HolonObjectState.PRODUCER));
  361. println("Average producer OverSupplied: " + result.getAvergaeProportionWithState(HolonObjectState.OVER_SUPPLIED));
  362. println("Average producer Supplied: " + result.getAvergaeProportionWithState(HolonObjectState.SUPPLIED));
  363. println("Average producer PartiallySupplied: " + result.getAvergaeProportionWithState(HolonObjectState.PARTIALLY_SUPPLIED));
  364. println("Average producer NotSupplied: " + result.getAvergaeProportionWithState(HolonObjectState.NOT_SUPPLIED));
  365. println("Average producer NoEnergy: " + result.getAvergaeProportionWithState(HolonObjectState.NO_ENERGY));
  366. }
  367. private float shutDownAllConsumerElementsWithPriority(Set<HolonElement> allHolonElemntsInThisNetwork,
  368. Priority emergencyShutDownPriority, RunResult result) {
  369. List<HolonElement> elementsOfPriorityToShutdown = allHolonElemntsInThisNetwork.stream().filter(hElement -> hElement.isConsumer() && hElement.getPriority() == emergencyShutDownPriority && !hElement.isFlexActive() && hElement.active).collect(Collectors.toList());
  370. //.forEach(hElement -> hElement.setActive(false));
  371. float energyGained = elementsOfPriorityToShutdown.stream().map(hElement -> -hElement.getEnergy()).reduce(0.0f, (a, b) -> a + b);
  372. elementsOfPriorityToShutdown.forEach(hElement -> hElement.active = false);
  373. int shutdownCount = elementsOfPriorityToShutdown.size();
  374. result.deactivatedElements += shutdownCount;
  375. println("Gained " + energyGained + "Energy from Shutdown with Priority:" + emergencyShutDownPriority + " AmountOfShutDowned HolonElements: " + shutdownCount);
  376. return energyGained;
  377. }
  378. private float sumEnergyAvailable(List<Flexibility> flexList) {
  379. HashMap<HolonElement, Flexibility> dublicateFilter = new HashMap<HolonElement, Flexibility>();
  380. flexList.stream().forEach(flex -> dublicateFilter.put(flex.getElement(), flex));
  381. return dublicateFilter.values().stream().map(flex -> flex.energyReleased()).reduce(0.0f,Float::sum);
  382. }
  383. private List<Priority> createPriorityListASC() {
  384. List<Priority> priorityASC = new ArrayList<Priority>();
  385. priorityASC.add(Priority.Low);
  386. priorityASC.add(Priority.Medium);
  387. priorityASC.add(Priority.High);
  388. priorityASC.add(Priority.Essential);
  389. return priorityASC;
  390. }
  391. /**
  392. * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
  393. * Also initialize the Access Hashmap to swap faster positions.
  394. * @param ModelTest
  395. * @return
  396. */
  397. private List<Boolean> extractPositionAndAccess() {
  398. Model model = control.getModel();
  399. switchList = new ArrayList<HolonSwitch>();
  400. objectList = new ArrayList<HolonObject>();
  401. initialState = new ArrayList<Boolean>();
  402. access= new HashMap<Integer, AccessWrapper>();
  403. rollOutNodes((useGroupNode && (groupnode.isPresent()))? groupnode.get().getObjectsInThisLayer() :model.getCanvas().getObjectsInThisLayer(), initialState, model.getCurrentIteration());
  404. resetChain.add(initialState);
  405. return initialState;
  406. }
  407. /**
  408. * Method to extract the Informations recursively out of the Model.
  409. * @param nodes
  410. * @param positionToInit
  411. * @param timeStep
  412. */
  413. private void rollOutNodes(Stream<AbstractCanvasObject> nodes, List<Boolean> positionToInit, int timeStep) {
  414. nodes.forEach(aCps -> {
  415. if (aCps instanceof HolonObject hO) {
  416. hO.getElements().forEach(hE -> {
  417. positionToInit.add(hE.active);
  418. access.put(positionToInit.size() - 1 , new AccessWrapper(hE));
  419. });
  420. objectList.add(hO);
  421. }
  422. else if (aCps instanceof HolonSwitch sw) {
  423. positionToInit.add(sw.getState().isClosed());
  424. switchList.add(sw);
  425. access.put(positionToInit.size() - 1 , new AccessWrapper(sw));
  426. }
  427. else if(aCps instanceof GroupNode groupnode) {
  428. rollOutGroupNode(groupnode, positionToInit ,timeStep);
  429. }
  430. });
  431. }
  432. private void rollOutGroupNode (GroupNode groupNode, List<Boolean> positionToInit, int timeStep) {
  433. groupNode.getAllHolonObjectsRecursive().forEach(hObject -> {
  434. hObject.getElements().forEach(hE -> {
  435. positionToInit.add(hE.active);
  436. access.put(positionToInit.size() - 1 , new AccessWrapper(hE));
  437. });
  438. objectList.add(hObject);
  439. });
  440. groupNode.getAllSwitchObjectsRecursive().forEach(sw -> {
  441. positionToInit.add(sw.getState().isClosed());
  442. switchList.add(sw);
  443. access.put(positionToInit.size() - 1 , new AccessWrapper(sw));
  444. });
  445. }
  446. /**
  447. * To let the User See the current state without touching the Canvas.
  448. */
  449. private void updateVisual() {
  450. control.calculateStateAndVisualForCurrentTimeStep();
  451. //control.updateCanvas();
  452. //control.getGui().triggerUpdateController(null);
  453. }
  454. /**
  455. * Sets the Model back to its original State before the LAST run.
  456. */
  457. private void resetState() {
  458. setState(resetChain.getLast());
  459. }
  460. /**
  461. * Sets the State out of the given position for calculation or to show the user.
  462. * @param position
  463. */
  464. private void setState(List<Boolean> position) {
  465. for(int i = 0;i<position.size();i++) {
  466. access.get(i).setState(position.get(i));
  467. }
  468. }
  469. /**
  470. * A Wrapper Class for Access HolonElement and HolonSwitch in one Element and not have to split the List.
  471. */
  472. private class AccessWrapper {
  473. public static final int HOLONELEMENT = 0;
  474. public static final int SWITCH = 1;
  475. private int type;
  476. private HolonSwitch hSwitch;
  477. private HolonElement hElement;
  478. public AccessWrapper(HolonSwitch hSwitch){
  479. type = SWITCH;
  480. this.hSwitch = hSwitch;
  481. }
  482. public AccessWrapper(HolonElement hElement){
  483. type = HOLONELEMENT;
  484. this.hElement = hElement;
  485. }
  486. public void setState(boolean state) {
  487. if(type == HOLONELEMENT) {
  488. hElement.active = state;
  489. }else{//is switch
  490. hSwitch.setMode(SwitchMode.Manual);
  491. hSwitch.setManualState(state ? SwitchState.Closed : SwitchState.Open);
  492. }
  493. }
  494. }
  495. private class RunResult {
  496. public int activatedFlex = 0;
  497. public int deactivatedElements = 0;
  498. public float totalCost = 0;
  499. public LinkedList<TimeStepStateResult> timeStepList = new LinkedList<TimeStepStateResult>();
  500. public TimeStepStateResult addTimeStepStateResult(){
  501. TimeStepStateResult aResult = new TimeStepStateResult();
  502. timeStepList.add(aResult);
  503. return aResult;
  504. }
  505. public class TimeStepStateResult{
  506. public int amountOfProducer = 0;
  507. public int amountOfConsumer = 0;
  508. public int amountOfPassiv = 0;
  509. public int amountOfConsumerOverSupplied = 0;
  510. public int amountOfConsumerSupplied = 0;
  511. public int amountOfConsumerPartiallySupplied = 0;
  512. public int amountOfConsumerUnSupplied= 0;
  513. public float getProportionWithState(HolonObjectState state) {
  514. float amountOfObjects = amountOfProducer + amountOfConsumer + amountOfPassiv;
  515. switch(state) {
  516. case NOT_SUPPLIED:
  517. return (float) amountOfConsumerUnSupplied / amountOfObjects;
  518. case NO_ENERGY:
  519. return (float) amountOfPassiv / amountOfObjects;
  520. case OVER_SUPPLIED:
  521. return (float) amountOfConsumerOverSupplied / amountOfObjects;
  522. case PARTIALLY_SUPPLIED:
  523. return (float) amountOfConsumerPartiallySupplied / amountOfObjects;
  524. case PRODUCER:
  525. return (float) amountOfProducer / amountOfObjects;
  526. case SUPPLIED:
  527. return (float) amountOfConsumerSupplied / amountOfObjects;
  528. default:
  529. return 0.f;
  530. }
  531. }
  532. }
  533. public float getAvergaeProportionWithState(HolonObjectState state) {
  534. return timeStepList.stream().map(step -> step.getProportionWithState(state)).reduce((a,b) -> (a + b)).orElse(0.f) / (float) 100;
  535. }
  536. }
  537. private class Handle<T>{
  538. public T object;
  539. Handle(T object){
  540. this.object = object;
  541. }
  542. public String toString() {
  543. return object.toString();
  544. }
  545. }
  546. }