FlexExample.java 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  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.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 holeg.api.AddOn;
  28. import holeg.model.AbstractCanvasObject;
  29. import holeg.model.Flexibility;
  30. import holeg.model.GroupNode;
  31. import holeg.model.HolonElement;
  32. import holeg.model.HolonObject;
  33. import holeg.model.HolonSwitch;
  34. import holeg.model.Flexibility.FlexState;
  35. import holeg.model.HolonElement.Priority;
  36. import holeg.ui.controller.Control;
  37. import holeg.ui.model.DecoratedGroupNode;
  38. import holeg.ui.model.DecoratedNetwork;
  39. import holeg.ui.model.DecoratedState;
  40. import holeg.ui.model.Model;
  41. import holeg.ui.model.DecoratedHolonObject.HolonObjectState;
  42. public class FlexExample implements AddOn {
  43. //Settings For GroupNode using and cancel
  44. private boolean useGroupNode = false;
  45. private DecoratedGroupNode dGroupNode = null;
  46. private boolean cancel = false;
  47. private boolean overAllTimeSteps = false;
  48. //Parameter defined by Algo
  49. private HashMap<Integer, AccessWrapper> access;
  50. LinkedList<List<Boolean>> resetChain = new LinkedList<List<Boolean>>();
  51. private List<Boolean> initialState;
  52. private List<HolonSwitch> switchList;
  53. private List<HolonObject> objectList;
  54. //Gui Part:
  55. private Control control;
  56. private JTextArea textArea;
  57. private JPanel content = new JPanel();
  58. //ProgressBar
  59. private long startTime;
  60. private Thread runThread;
  61. public static void main(String[] args)
  62. {
  63. JFrame newFrame = new JFrame("exampleWindow");
  64. DemoAlgo instance = new DemoAlgo();
  65. newFrame.setContentPane(instance.getPanel());
  66. newFrame.pack();
  67. newFrame.setVisible(true);
  68. newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  69. }
  70. public FlexExample() {
  71. content.setLayout(new BorderLayout());
  72. textArea = new JTextArea();
  73. textArea.setEditable(false);
  74. JScrollPane scrollPane = new JScrollPane(textArea);
  75. JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
  76. createOptionPanel() , scrollPane);
  77. splitPane.setResizeWeight(0.0);
  78. content.add(splitPane, BorderLayout.CENTER);
  79. content.setPreferredSize(new Dimension(800,800));
  80. }
  81. public JPanel createOptionPanel() {
  82. JPanel optionPanel = new JPanel(new BorderLayout());
  83. JScrollPane scrollPane = new JScrollPane(createParameterPanel());
  84. scrollPane.setBorder(BorderFactory.createTitledBorder("Parameter"));
  85. optionPanel.add(scrollPane, BorderLayout.CENTER);
  86. optionPanel.add(createButtonPanel(), BorderLayout.PAGE_END);
  87. return optionPanel;
  88. }
  89. private Component createParameterPanel() {
  90. JPanel parameterPanel = new JPanel(null);
  91. parameterPanel.setPreferredSize(new Dimension(510,300));
  92. // JLabel showDiagnosticsLabel = new JLabel("Set all switches closed:");
  93. // showDiagnosticsLabel.setBounds(200, 60, 170, 20);
  94. // parameterPanel.add(showDiagnosticsLabel);
  95. JPanel borderPanel = new JPanel(null);
  96. borderPanel.setBounds(200, 85, 185, 50);
  97. borderPanel.setBorder(BorderFactory.createTitledBorder(""));
  98. parameterPanel.add(borderPanel);
  99. JLabel showGroupNodeLabel = new JLabel("Use Group Node:");
  100. showGroupNodeLabel.setBounds(10, 1, 170, 20);
  101. borderPanel.add(showGroupNodeLabel);
  102. JButton selectGroupNodeButton = new JButton("Select GroupNode");
  103. selectGroupNodeButton.setEnabled(false);
  104. selectGroupNodeButton.setBounds(10, 25, 165, 20);
  105. selectGroupNodeButton.addActionListener(actionEvent -> selectGroupNode());
  106. borderPanel.add(selectGroupNodeButton);
  107. JCheckBox useGroupNodeCheckBox = new JCheckBox();
  108. useGroupNodeCheckBox.setSelected(false);
  109. useGroupNodeCheckBox.setBounds(155, 1, 25, 20);
  110. useGroupNodeCheckBox.addActionListener(actionEvent -> {
  111. useGroupNode = useGroupNodeCheckBox.isSelected();
  112. selectGroupNodeButton.setEnabled(useGroupNode);
  113. });
  114. borderPanel.add(useGroupNodeCheckBox);
  115. JCheckBox overAllTimeStepsCheckbox = new JCheckBox("overAllTimeSteps");
  116. overAllTimeStepsCheckbox.setSelected(false);
  117. overAllTimeStepsCheckbox.setBounds(20, 30, 250, 30);
  118. overAllTimeStepsCheckbox.addActionListener(actionEvent -> {
  119. overAllTimeSteps = overAllTimeStepsCheckbox.isSelected();
  120. });
  121. parameterPanel.add(overAllTimeStepsCheckbox);
  122. NumberFormat format = NumberFormat.getIntegerInstance();
  123. format.setGroupingUsed(false);
  124. format.setParseIntegerOnly(true);
  125. NumberFormatter integerFormatter = new NumberFormatter(format);
  126. integerFormatter.setMinimum(0);
  127. integerFormatter.setCommitsOnValidEdit(true);
  128. JLabel portLabel = new JLabel("between:");
  129. portLabel.setBounds(10, 330, 70, 30);
  130. parameterPanel.add(portLabel);
  131. JLabel afterLabel = new JLabel("after:");
  132. afterLabel.setBounds(10, 360, 70, 30);
  133. parameterPanel.add(afterLabel);
  134. return parameterPanel;
  135. }
  136. public JPanel createButtonPanel() {
  137. JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
  138. JButton resetButton = new JButton("ResetAll");
  139. resetButton.setToolTipText("Resets the State to before the Algorithm has runed.");
  140. resetButton.addActionListener(actionEvent -> resetAll());
  141. buttonPanel.add(resetButton);
  142. JButton cancelButton = new JButton("Cancel Run");
  143. cancelButton.addActionListener(actionEvent -> cancel());
  144. buttonPanel.add(cancelButton);
  145. JButton clearButton = new JButton("Clear Console");
  146. clearButton.addActionListener(actionEvent -> clear());
  147. buttonPanel.add(clearButton);
  148. JButton undoButton = new JButton("Undo");
  149. undoButton.setToolTipText("One Algo Step Back.");
  150. undoButton.addActionListener(actionEvent -> resetLast());
  151. buttonPanel.add(undoButton);
  152. JButton runButton = new JButton("Run");
  153. runButton.addActionListener(actionEvent -> {
  154. Runnable task = () -> {
  155. if(this.overAllTimeSteps)runAll();
  156. else run();
  157. };
  158. runThread = new Thread(task);
  159. runThread.start();
  160. });
  161. buttonPanel.add(runButton);
  162. return buttonPanel;
  163. }
  164. private void cancel() {
  165. if(runThread.isAlive()) {
  166. println("");
  167. println("Cancel run.");
  168. cancel = true;
  169. } else {
  170. println("Nothing to cancel.");
  171. }
  172. }
  173. private void runAll() {
  174. cancel = false;
  175. disableGuiInput(true);
  176. startTimer();
  177. control.resetSimulation();
  178. RunResult result= new RunResult();
  179. for(int i = 0; i < 100; i++) {
  180. control.setCurIteration(i);
  181. executeDemoAlgo(result);
  182. if(cancel) {
  183. resetLast();
  184. disableGuiInput(false);
  185. return;
  186. }
  187. }
  188. updateVisual();
  189. calculateAllResults(result);
  190. println("Amount of activatedFlex:" + result.activatedFlex + " Amount of deactivatedElements:"+ result.deactivatedElements + " TotalCost:"+result.totalCost);
  191. printElapsedTime();
  192. disableGuiInput(false);
  193. }
  194. private void run() {
  195. disableGuiInput(true);
  196. startTimer();
  197. executeDemoAlgo(new RunResult());
  198. updateVisual();
  199. printElapsedTime();
  200. disableGuiInput(false);
  201. }
  202. private void resetLast() {
  203. if(!resetChain.isEmpty()) {
  204. println("Resetting..");
  205. resetState();
  206. resetChain.removeLast();
  207. control.resetSimulation();
  208. updateVisual();
  209. }else {
  210. println("No run inistialized.");
  211. }
  212. }
  213. private void resetAll() {
  214. if(!resetChain.isEmpty()) {
  215. println("Resetting..");
  216. setState(resetChain.getFirst());
  217. resetChain.clear();
  218. control.resetSimulation();
  219. control.setCurIteration(0);
  220. updateVisual();
  221. }else {
  222. println("No run inistialized.");
  223. }
  224. }
  225. private void disableGuiInput(boolean bool) {
  226. control.guiDisable(bool);
  227. }
  228. @Override
  229. public JPanel getPanel() {
  230. return content;
  231. }
  232. @Override
  233. public void setController(Control control) {
  234. this.control = control;
  235. }
  236. private void clear() {
  237. textArea.setText("");
  238. }
  239. private void println(String message) {
  240. textArea.append(message + "\n");
  241. }
  242. private void selectGroupNode() {
  243. control.getSimManager().getActualVisualRepresentationalState().ifPresent(state -> {
  244. Object[] possibilities = state.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. }
  253. private void startTimer(){
  254. startTime = System.currentTimeMillis();
  255. }
  256. private void printElapsedTime(){
  257. long elapsedMilliSeconds = System.currentTimeMillis() - startTime;
  258. println("Execution Time of Algo in Milliseconds:" + elapsedMilliSeconds);
  259. }
  260. //Algo Part:
  261. /**
  262. * The Execution of the FlexAlgo.
  263. *
  264. *
  265. * Begin
  266. * for(All Networks) do
  267. *
  268. * if(not (production < consumption)) continue;
  269. *
  270. *
  271. * for(Priority emergencyShutDownPriority: priorityListASC) do
  272. * difference = Math.abs(production - consumption);
  273. * amountOfAllEnergyOffered = sumEnergyAvailable(flexList);
  274. * if(amountOfAllEnergyOffered > difference) break;
  275. * shutDownAllConsumerWithPriority(emergencyShutDownPriority)
  276. * end for
  277. *
  278. * takeAKombinationOfOffers(); (nach welchem Kriterium)
  279. *
  280. *
  281. * end for
  282. * End
  283. *
  284. */
  285. private void executeDemoAlgo(RunResult result) {
  286. extractPositionAndAccess();
  287. int actualIteration = control.getModel().getActualTimeStep();
  288. println("TimeStep:" + actualIteration);
  289. control.calculateStateOnlyForCurrentTimeStep();
  290. List<Priority> priorityListASC = createPriorityListASC();
  291. DecoratedState actualstate = control.getSimManager().getActualDecorState().get();
  292. for(DecoratedNetwork net : actualstate.getNetworkList()) {
  293. float production = net.getSupplierList().stream().map(supplier -> supplier.getEnergyToSupplyNetwork()).reduce(0.0f, (a, b) -> a + b);
  294. float consumption = net.getConsumerList().stream().map(con -> con.getEnergyNeededFromNetwork()).reduce(0.0f, (a, b) -> a + b);
  295. float difference = Math.abs(production - consumption);
  296. println("production: " + production);
  297. println("consumption: " + consumption);
  298. println("difference: " + difference);
  299. if(production > consumption) continue;
  300. if(difference == 0)continue;
  301. Set<HolonElement> allHolonElemntsInThisNetwork = createListOfAllHolonElemnts(net);
  302. List<Flexibility> flexList = control.getModel().getAllFlexibilities();
  303. List<Flexibility> allOfferedFlex = flexList.stream().filter(flex -> flex.getState().equals(FlexState.OFFERED)).toList();
  304. List<Flexibility> allFlexThatGetMeEnergy = allOfferedFlex.stream().filter(flexWrapper -> (flexWrapper.energyReleased() > 0)).collect(Collectors.toList());
  305. float amountOfAllEnergyOffered = sumEnergyAvailable(allFlexThatGetMeEnergy);
  306. println("amountOfAllFlexEnergyOffered:" + amountOfAllEnergyOffered);
  307. //ShuddownPriorities
  308. for(Priority emergencyShutDownPriority: priorityListASC) {
  309. if(amountOfAllEnergyOffered >= difference) break;
  310. println("ShutDown: " + emergencyShutDownPriority);
  311. difference -= shutDownAllConsumerElementsWithPriority(allHolonElemntsInThisNetwork, emergencyShutDownPriority, result);
  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. println("Activated FlexThisTimeStep: "+ amountflexActivated+" CostForThisTimeStep:" + costForThisTimeStep);
  332. result.totalCost += costForThisTimeStep;
  333. }
  334. calculateStateResult(result);
  335. }
  336. private void calculateStateResult(RunResult result) {
  337. control.calculateStateOnlyForCurrentTimeStep();
  338. RunResult.TimeStepStateResult timeStepState = result.addTimeStepStateResult();
  339. for(DecoratedNetwork network: control.getSimManager().getActualDecorState().get().getNetworkList()) {
  340. timeStepState.amountOfConsumer += network.getAmountOfConsumer();
  341. timeStepState.amountOfConsumerOverSupplied += network.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
  342. timeStepState.amountOfConsumerPartiallySupplied += network.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
  343. timeStepState.amountOfConsumerSupplied += network.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
  344. timeStepState.amountOfConsumerUnSupplied += network.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
  345. timeStepState.amountOfPassiv += network.getAmountOfPassiv();
  346. timeStepState.amountOfProducer += network.getAmountOfSupplier();
  347. }
  348. println("Producer: " + timeStepState.amountOfProducer);
  349. println("Consumer: " + timeStepState.amountOfConsumer);
  350. println("ConsumerOverSupplied: " + timeStepState.amountOfConsumerOverSupplied);
  351. println("ConsumerSupplied: " + timeStepState.amountOfConsumerSupplied);
  352. println("ConsumerPartiallySupplied: " + timeStepState.amountOfConsumerPartiallySupplied);
  353. println("ConsumerUnSupplied: " + timeStepState.amountOfConsumerUnSupplied);
  354. println("ConsumerUnSupplied: " + timeStepState.amountOfPassiv);
  355. }
  356. private void calculateAllResults(RunResult result) {
  357. println("----------");
  358. println("Average producer proportion: " + result.getAvergaeProportionWithState(HolonObjectState.PRODUCER));
  359. println("Average producer OverSupplied: " + result.getAvergaeProportionWithState(HolonObjectState.OVER_SUPPLIED));
  360. println("Average producer Supplied: " + result.getAvergaeProportionWithState(HolonObjectState.SUPPLIED));
  361. println("Average producer PartiallySupplied: " + result.getAvergaeProportionWithState(HolonObjectState.PARTIALLY_SUPPLIED));
  362. println("Average producer NotSupplied: " + result.getAvergaeProportionWithState(HolonObjectState.NOT_SUPPLIED));
  363. println("Average producer NoEnergy: " + result.getAvergaeProportionWithState(HolonObjectState.NO_ENERGY));
  364. }
  365. private float shutDownAllConsumerElementsWithPriority(Set<HolonElement> allHolonElemntsInThisNetwork,
  366. Priority emergencyShutDownPriority, RunResult result) {
  367. List<HolonElement> elementsOfPriorityToShutdown = allHolonElemntsInThisNetwork.stream().filter(hElement -> hElement.isConsumer() && hElement.getPriority() == emergencyShutDownPriority && !hElement.isFlexActive() && hElement.active).collect(Collectors.toList());
  368. //.forEach(hElement -> hElement.setActive(false));
  369. float energyGained = elementsOfPriorityToShutdown.stream().map(hElement -> -hElement.getEnergy()).reduce(0.0f, (a, b) -> a + b);
  370. elementsOfPriorityToShutdown.forEach(hElement -> hElement.active = false);
  371. int shutdownCount = elementsOfPriorityToShutdown.size();
  372. result.deactivatedElements += shutdownCount;
  373. println("Gained " + energyGained + "Energy from Shutdown with Priority:" + emergencyShutDownPriority + " AmountOfShutDowned HolonElements: " + shutdownCount);
  374. return energyGained;
  375. }
  376. private Set<HolonElement> createListOfAllHolonElemnts(DecoratedNetwork net) {
  377. Set<HolonElement> allHolonElemntsInThisNetwork = new HashSet<HolonElement>();
  378. allHolonElemntsInThisNetwork.addAll(net.getConsumerList().stream().flatMap(con -> con.getModel().getElements().stream()).collect(Collectors.toList()));
  379. allHolonElemntsInThisNetwork.addAll(net.getConsumerSelfSuppliedList().stream().flatMap(con -> con.getModel().getElements().stream()).collect(Collectors.toList()));
  380. allHolonElemntsInThisNetwork.addAll(net.getSupplierList().stream().flatMap(con -> con.getModel().getElements().stream()).collect(Collectors.toList()));
  381. return allHolonElemntsInThisNetwork;
  382. }
  383. private float sumEnergyAvailable(List<Flexibility> flexList) {
  384. HashMap<HolonElement, Flexibility> dublicateFilter = new HashMap<HolonElement, Flexibility>();
  385. flexList.stream().forEach(flex -> dublicateFilter.put(flex.getElement(), flex));
  386. return dublicateFilter.values().stream().map(flex -> flex.energyReleased()).reduce(0.0f,Float::sum);
  387. }
  388. private List<Priority> createPriorityListASC() {
  389. List<Priority> priorityASC = new ArrayList<Priority>();
  390. priorityASC.add(Priority.Low);
  391. priorityASC.add(Priority.Medium);
  392. priorityASC.add(Priority.High);
  393. priorityASC.add(Priority.Essential);
  394. return priorityASC;
  395. }
  396. /**
  397. * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
  398. * Also initialize the Access Hashmap to swap faster positions.
  399. * @param ModelTest
  400. * @return
  401. */
  402. private List<Boolean> extractPositionAndAccess() {
  403. Model model = control.getModel();
  404. switchList = new ArrayList<HolonSwitch>();
  405. objectList = new ArrayList<HolonObject>();
  406. initialState = new ArrayList<Boolean>();
  407. access= new HashMap<Integer, AccessWrapper>();
  408. rollOutNodes((useGroupNode && (dGroupNode != null))? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getActualTimeStep());
  409. resetChain.add(initialState);
  410. return initialState;
  411. }
  412. /**
  413. * Method to extract the Informations recursively out of the Model.
  414. * @param nodes
  415. * @param positionToInit
  416. * @param timeStep
  417. */
  418. private void rollOutNodes(List<AbstractCanvasObject> nodes, List<Boolean> positionToInit, int timeStep) {
  419. for(AbstractCanvasObject aCps : nodes) {
  420. if (aCps instanceof HolonObject hO) {
  421. for (HolonElement hE : hO.getElements()) {
  422. positionToInit.add(hE.active);
  423. access.put(positionToInit.size() - 1 , new AccessWrapper(hE));
  424. }
  425. objectList.add(hO);
  426. }
  427. else if (aCps instanceof HolonSwitch sw) {
  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 groupnode) {
  433. rollOutNodes(groupnode.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.active = 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. }