FlexExample.java 23 KB

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