BaseLine.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. package holeg.algorithm.binary;
  2. import holeg.api.AddOn;
  3. import holeg.model.AbstractCanvasObject;
  4. import holeg.model.GroupNode;
  5. import holeg.model.HolonElement;
  6. import holeg.model.HolonObject;
  7. import holeg.model.HolonSwitch;
  8. import holeg.model.HolonSwitch.SwitchMode;
  9. import holeg.model.HolonSwitch.SwitchState;
  10. import holeg.model.Model;
  11. import holeg.ui.controller.Control;
  12. import java.awt.BorderLayout;
  13. import java.awt.Component;
  14. import java.awt.Dimension;
  15. import java.awt.FlowLayout;
  16. import java.awt.image.BufferedImage;
  17. import java.util.ArrayList;
  18. import java.util.HashMap;
  19. import java.util.List;
  20. import java.util.Optional;
  21. import java.util.stream.Stream;
  22. import javax.swing.BorderFactory;
  23. import javax.swing.ImageIcon;
  24. import javax.swing.JButton;
  25. import javax.swing.JCheckBox;
  26. import javax.swing.JFrame;
  27. import javax.swing.JLabel;
  28. import javax.swing.JOptionPane;
  29. import javax.swing.JPanel;
  30. import javax.swing.JScrollPane;
  31. import javax.swing.JSplitPane;
  32. import javax.swing.JTextArea;
  33. public class BaseLine implements AddOn {
  34. //Parameter for Algo with default Values:
  35. private boolean closeSwitches = true;
  36. //Settings For GroupNode using and cancel
  37. private boolean useGroupNode = false;
  38. private Optional<GroupNode> groupNode = Optional.empty();
  39. private boolean cancel = false;
  40. //Parameter defined by Algo
  41. private HashMap<Integer, AccessWrapper> access;
  42. private List<Boolean> initialState;
  43. private List<HolonSwitch> switchList;
  44. private List<HolonObject> objectList;
  45. //Gui Part:
  46. private Control control;
  47. private JTextArea textArea;
  48. private JPanel content = new JPanel();
  49. //ProgressBar
  50. private long startTime;
  51. private Thread runThread;
  52. public BaseLine() {
  53. content.setLayout(new BorderLayout());
  54. textArea = new JTextArea();
  55. textArea.setEditable(false);
  56. JScrollPane scrollPane = new JScrollPane(textArea);
  57. JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
  58. createOptionPanel(), scrollPane);
  59. splitPane.setResizeWeight(0.0);
  60. content.add(splitPane, BorderLayout.CENTER);
  61. content.setPreferredSize(new Dimension(800, 800));
  62. }
  63. public static void main(String[] args) {
  64. JFrame newFrame = new JFrame("exampleWindow");
  65. BaseLine instance = new BaseLine();
  66. newFrame.setContentPane(instance.getPanel());
  67. newFrame.pack();
  68. newFrame.setVisible(true);
  69. newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  70. }
  71. public JPanel createOptionPanel() {
  72. JPanel optionPanel = new JPanel(new BorderLayout());
  73. JScrollPane scrollPane = new JScrollPane(createParameterPanel());
  74. scrollPane.setBorder(BorderFactory.createTitledBorder("Parameter"));
  75. optionPanel.add(scrollPane, BorderLayout.CENTER);
  76. optionPanel.add(createButtonPanel(), BorderLayout.PAGE_END);
  77. return optionPanel;
  78. }
  79. private Component createParameterPanel() {
  80. JPanel parameterPanel = new JPanel(null);
  81. parameterPanel.setPreferredSize(new Dimension(510, 300));
  82. JLabel showDiagnosticsLabel = new JLabel("Set all switches closed:");
  83. showDiagnosticsLabel.setBounds(200, 60, 170, 20);
  84. parameterPanel.add(showDiagnosticsLabel);
  85. JPanel borderPanel = new JPanel(null);
  86. borderPanel.setBounds(200, 85, 185, 50);
  87. borderPanel.setBorder(BorderFactory.createTitledBorder(""));
  88. parameterPanel.add(borderPanel);
  89. JLabel showGroupNodeLabel = new JLabel("Use Group Node:");
  90. showGroupNodeLabel.setBounds(10, 1, 170, 20);
  91. borderPanel.add(showGroupNodeLabel);
  92. JButton selectGroupNodeButton = new JButton("Select GroupNode");
  93. selectGroupNodeButton.setEnabled(false);
  94. selectGroupNodeButton.setBounds(10, 25, 165, 20);
  95. selectGroupNodeButton.addActionListener(actionEvent -> selectGroupNode());
  96. borderPanel.add(selectGroupNodeButton);
  97. JCheckBox useGroupNodeCheckBox = new JCheckBox();
  98. useGroupNodeCheckBox.setSelected(false);
  99. useGroupNodeCheckBox.setBounds(155, 1, 25, 20);
  100. useGroupNodeCheckBox.addActionListener(actionEvent -> {
  101. useGroupNode = useGroupNodeCheckBox.isSelected();
  102. selectGroupNodeButton.setEnabled(useGroupNode);
  103. });
  104. borderPanel.add(useGroupNodeCheckBox);
  105. JCheckBox switchesCheckBox = new JCheckBox();
  106. switchesCheckBox.setSelected(closeSwitches);
  107. switchesCheckBox.setBounds(370, 60, 25, 20);
  108. switchesCheckBox.addActionListener(
  109. actionEvent -> closeSwitches = switchesCheckBox.isSelected());
  110. parameterPanel.add(switchesCheckBox);
  111. return parameterPanel;
  112. }
  113. public JPanel createButtonPanel() {
  114. JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
  115. JButton cancelButton = new JButton("Cancel Run");
  116. cancelButton.addActionListener(actionEvent -> cancel());
  117. buttonPanel.add(cancelButton);
  118. JButton clearButton = new JButton("Clear Console");
  119. clearButton.addActionListener(actionEvent -> clear());
  120. buttonPanel.add(clearButton);
  121. JButton resetButton = new JButton("Reset");
  122. resetButton.setToolTipText("Resets the State to before the Algorithm has runed.");
  123. resetButton.addActionListener(actionEvent -> reset());
  124. buttonPanel.add(resetButton);
  125. JButton runButton = new JButton("Run");
  126. runButton.addActionListener(actionEvent -> {
  127. Runnable task = () -> run();
  128. runThread = new Thread(task);
  129. runThread.start();
  130. });
  131. buttonPanel.add(runButton);
  132. return buttonPanel;
  133. }
  134. private void cancel() {
  135. if (runThread.isAlive()) {
  136. println("");
  137. println("Cancel run.");
  138. cancel = true;
  139. } else {
  140. println("Nothing to cancel.");
  141. }
  142. }
  143. private void run() {
  144. cancel = false;
  145. disableGuiInput(true);
  146. startTimer();
  147. executeBaseLine();
  148. if (cancel) {
  149. reset();
  150. disableGuiInput(false);
  151. return;
  152. }
  153. printElapsedTime();
  154. disableGuiInput(false);
  155. }
  156. private void reset() {
  157. if (initialState != null) {
  158. println("Resetting..");
  159. resetState();
  160. updateVisual();
  161. } else {
  162. println("No run inistialized.");
  163. }
  164. }
  165. private void disableGuiInput(boolean bool) {
  166. control.guiSetEnabled(bool);
  167. }
  168. @Override
  169. public JPanel getPanel() {
  170. return content;
  171. }
  172. @Override
  173. public void setController(Control control) {
  174. this.control = control;
  175. }
  176. private void clear() {
  177. textArea.setText("");
  178. }
  179. private void println(String message) {
  180. textArea.append(message + "\n");
  181. }
  182. private void selectGroupNode() {
  183. Object[] possibilities = control.getModel().getCanvas().getAllGroupNodeObjectsRecursive()
  184. .toArray();
  185. GroupNode selected = (GroupNode) JOptionPane.showInputDialog(content, "Select GroupNode:",
  186. "GroupNode?", JOptionPane.OK_OPTION,
  187. new ImageIcon(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)), possibilities, "");
  188. if (selected != null) {
  189. println("Selected: " + selected);
  190. groupNode = Optional.of(selected);
  191. }
  192. }
  193. private void startTimer() {
  194. startTime = System.currentTimeMillis();
  195. }
  196. private void printElapsedTime() {
  197. long elapsedMilliSeconds = System.currentTimeMillis() - startTime;
  198. println("Execution Time of Algo in Milliseconds:" + elapsedMilliSeconds);
  199. }
  200. //Algo Part:
  201. /**
  202. * The Execution of the BaseLine Algo.
  203. * <p>
  204. * <p>
  205. * Begin set HolonElements aktiv; for(All Networks) do if(not (production < consumption))
  206. * continue; inAktiveCount = 0; while(inAktiveCount <= consumerWihtMaxNumberElements) do conList =
  207. * createListWithConsumerThatHaveInActiveElementsAmountOf(inAktiveCount);
  208. * sortByBiggestElement(conList); for(con : conList) do for(element :
  209. * con.getAllActiveElementsSortByConsumption) do if(element <= production) do set element inAktiv;
  210. * continue; end do end do end do inAktiveCount += 1; end while end for End
  211. */
  212. private void executeBaseLine() {
  213. extractPositionAndAccess();
  214. if (closeSwitches) {
  215. setAllSwitchesClosed();
  216. }
  217. setHolonElemntsAktiv();
  218. control.calculateStateForCurrentIteration();
  219. // DecoratedState actualstate = control.getSimManager().getActualDecorState().get();
  220. // for(DecoratedNetwork net : actualstate.getNetworkList()) {
  221. // float production = net.getSupplierList().stream().map(supplier -> supplier.getEnergyToSupplyNetwork()).reduce(0.0f, (a, b) -> a + b);
  222. // float consumption = net.getConsumerList().stream().map(con -> con.getEnergyNeededFromNetwork()).reduce(0.0f, (a, b) -> a + b);
  223. // float difference = Math.abs(production - consumption);
  224. // println("production:" + production + " consumption:" + consumption);
  225. // if(!(production < consumption))continue;
  226. // if(net.getConsumerList().isEmpty() && net.getConsumerSelfSuppliedList().isEmpty())continue;
  227. // //Stream.concat(net.getConsumerList().stream(), net.getConsumerSelfSuppliedList().stream());
  228. // int consumerWihtMaxNumberElements = Stream.concat(net.getConsumerList().stream(), net.getConsumerSelfSuppliedList().stream()).map(con -> con.getModel().getNumberOfElements()).max((lhs,rhs) ->Integer.compare(lhs, rhs)).orElse(0);
  229. // println("consumerWihtMaxNumberElements:" + consumerWihtMaxNumberElements);
  230. // for(int inAktiveCount = 0;inAktiveCount <= consumerWihtMaxNumberElements; inAktiveCount++) {
  231. // println("inAktiveCount:" + inAktiveCount);
  232. // final int inAktiveCountFinal = inAktiveCount;
  233. // List<HolonObject> conList = Stream.concat(net.getConsumerList().stream(), net.getConsumerSelfSuppliedList().stream()).map(con -> con.getModel()).filter(object -> objectList.contains(object)).filter(object -> (object.getNumberOfInActiveElements() == inAktiveCountFinal)).collect(Collectors.toList());
  234. // conList.sort((a,b) -> Float.compare(a.getMaximumConsumingElementEnergy(), b.getMaximumConsumingElementEnergy()));
  235. // consumer:
  236. // for(HolonObject con: conList) {
  237. // //println("Consumer" + con);
  238. // List<HolonElement> sortedElementList = con.getElements().filter(ele -> ele.active && ele.isConsumer()).sorted((a,b) -> -Float.compare(-a.getActualEnergy(), -b.getActualEnergy())).collect(Collectors.toList());
  239. // for(HolonElement element: sortedElementList) {
  240. // float elementConsumption = -element.getActualEnergy();
  241. // if(elementConsumption <= difference) {
  242. // println("elementConsumption:" + elementConsumption);
  243. // difference -= elementConsumption;
  244. // element.active = false;
  245. // continue consumer;
  246. // }
  247. // }
  248. // }
  249. // }
  250. // }
  251. updateVisual();
  252. }
  253. private void setHolonElemntsAktiv() {
  254. for (int i = 0; i < access.size(); i++) {
  255. AccessWrapper aw = access.get(i);
  256. if (aw.getType() == AccessWrapper.HOLONELEMENT) {
  257. aw.setState(true);
  258. }
  259. }
  260. }
  261. private void setAllSwitchesClosed() {
  262. for (HolonSwitch hSwitch : switchList) {
  263. hSwitch.setMode(SwitchMode.Manual);
  264. hSwitch.setManualState(SwitchState.Closed);
  265. }
  266. }
  267. /**
  268. * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects
  269. * on the Canvas. Also initialize the Access Hashmap to swap faster positions.
  270. *
  271. * @return
  272. */
  273. private List<Boolean> extractPositionAndAccess() {
  274. Model model = control.getModel();
  275. switchList = new ArrayList<HolonSwitch>();
  276. objectList = new ArrayList<HolonObject>();
  277. initialState = new ArrayList<Boolean>();
  278. access = new HashMap<Integer, AccessWrapper>();
  279. rollOutNodes((useGroupNode && groupNode.isPresent()) ? groupNode.get().getObjectsInThisLayer()
  280. : model.getCanvas().getObjectsInThisLayer(), initialState, model.getCurrentIteration());
  281. return initialState;
  282. }
  283. /**
  284. * Method to extract the Informations recursively out of the Model.
  285. *
  286. * @param nodes
  287. * @param positionToInit
  288. * @param timeStep
  289. */
  290. private void rollOutNodes(Stream<AbstractCanvasObject> nodes, List<Boolean> positionToInit,
  291. int timeStep) {
  292. nodes.forEach(aCps -> {
  293. if (aCps instanceof HolonObject hO) {
  294. hO.elementsStream().forEach(hE -> {
  295. positionToInit.add(hE.active);
  296. access.put(positionToInit.size() - 1, new AccessWrapper(hE));
  297. });
  298. objectList.add(hO);
  299. } else if (aCps instanceof HolonSwitch sw) {
  300. positionToInit.add(sw.getState().isClosed());
  301. switchList.add(sw);
  302. access.put(positionToInit.size() - 1, new AccessWrapper(sw));
  303. } else if (aCps instanceof GroupNode groupnode) {
  304. rollOutGroupNode(groupnode, positionToInit, timeStep);
  305. }
  306. });
  307. }
  308. private void rollOutGroupNode(GroupNode groupNode, List<Boolean> positionToInit, int timeStep) {
  309. groupNode.getAllHolonObjectsRecursive().forEach(hObject -> {
  310. hObject.elementsStream().forEach(hE -> {
  311. positionToInit.add(hE.active);
  312. access.put(positionToInit.size() - 1, new AccessWrapper(hE));
  313. });
  314. objectList.add(hObject);
  315. });
  316. groupNode.getAllSwitchObjectsRecursive().forEach(sw -> {
  317. positionToInit.add(sw.getState().isClosed());
  318. switchList.add(sw);
  319. access.put(positionToInit.size() - 1, new AccessWrapper(sw));
  320. });
  321. }
  322. /**
  323. * To let the User See the current state without touching the Canvas.
  324. */
  325. private void updateVisual() {
  326. control.calculateStateForCurrentIteration();
  327. }
  328. /**
  329. * Sets the Model back to its original State before the LAST run.
  330. */
  331. private void resetState() {
  332. setState(initialState);
  333. }
  334. /**
  335. * Sets the State out of the given position for calculation or to show the user.
  336. *
  337. * @param position
  338. */
  339. private void setState(List<Boolean> position) {
  340. for (int i = 0; i < position.size(); i++) {
  341. access.get(i).setState(position.get(i));
  342. }
  343. }
  344. /**
  345. * A Wrapper Class for Access HolonElement and HolonSwitch in one Element and not have to split
  346. * the List.
  347. */
  348. private class AccessWrapper {
  349. public static final int HOLONELEMENT = 0;
  350. public static final int SWITCH = 1;
  351. private int type;
  352. private HolonSwitch hSwitch;
  353. private HolonElement hElement;
  354. public AccessWrapper(HolonSwitch hSwitch) {
  355. type = SWITCH;
  356. this.hSwitch = hSwitch;
  357. }
  358. public AccessWrapper(HolonElement hElement) {
  359. type = HOLONELEMENT;
  360. this.hElement = hElement;
  361. }
  362. public void setState(boolean state) {
  363. if (type == HOLONELEMENT) {
  364. hElement.active = state;
  365. } else {//is switch
  366. hSwitch.setMode(SwitchMode.Manual);
  367. hSwitch.setManualState(state ? SwitchState.Closed : SwitchState.Open);
  368. }
  369. }
  370. public int getType() {
  371. return type;
  372. }
  373. }
  374. }