FlexExample.java 22 KB

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