BaseLine.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. package holeg.algorithm.binary;
  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.util.ArrayList;
  8. import java.util.HashMap;
  9. import java.util.List;
  10. import java.util.Optional;
  11. import java.util.stream.Stream;
  12. import javax.swing.BorderFactory;
  13. import javax.swing.ImageIcon;
  14. import javax.swing.JButton;
  15. import javax.swing.JCheckBox;
  16. import javax.swing.JFrame;
  17. import javax.swing.JLabel;
  18. import javax.swing.JOptionPane;
  19. import javax.swing.JPanel;
  20. import javax.swing.JScrollPane;
  21. import javax.swing.JSplitPane;
  22. import javax.swing.JTextArea;
  23. import holeg.api.AddOn;
  24. import holeg.model.AbstractCanvasObject;
  25. import holeg.model.GroupNode;
  26. import holeg.model.HolonElement;
  27. import holeg.model.HolonObject;
  28. import holeg.model.HolonSwitch;
  29. import holeg.model.HolonSwitch.SwitchMode;
  30. import holeg.model.HolonSwitch.SwitchState;
  31. import holeg.ui.controller.Control;
  32. import holeg.model.Model;
  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 static void main(String[] args)
  53. {
  54. JFrame newFrame = new JFrame("exampleWindow");
  55. BaseLine instance = new BaseLine();
  56. newFrame.setContentPane(instance.getPanel());
  57. newFrame.pack();
  58. newFrame.setVisible(true);
  59. newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  60. }
  61. public BaseLine() {
  62. content.setLayout(new BorderLayout());
  63. textArea = new JTextArea();
  64. textArea.setEditable(false);
  65. JScrollPane scrollPane = new JScrollPane(textArea);
  66. JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
  67. createOptionPanel() , scrollPane);
  68. splitPane.setResizeWeight(0.0);
  69. content.add(splitPane, BorderLayout.CENTER);
  70. content.setPreferredSize(new Dimension(800,800));
  71. }
  72. public JPanel createOptionPanel() {
  73. JPanel optionPanel = new JPanel(new BorderLayout());
  74. JScrollPane scrollPane = new JScrollPane(createParameterPanel());
  75. scrollPane.setBorder(BorderFactory.createTitledBorder("Parameter"));
  76. optionPanel.add(scrollPane, BorderLayout.CENTER);
  77. optionPanel.add(createButtonPanel(), BorderLayout.PAGE_END);
  78. return optionPanel;
  79. }
  80. private Component createParameterPanel() {
  81. JPanel parameterPanel = new JPanel(null);
  82. parameterPanel.setPreferredSize(new Dimension(510,300));
  83. JLabel showDiagnosticsLabel = new JLabel("Set all switches closed:");
  84. showDiagnosticsLabel.setBounds(200, 60, 170, 20);
  85. parameterPanel.add(showDiagnosticsLabel);
  86. JPanel borderPanel = new JPanel(null);
  87. borderPanel.setBounds(200, 85, 185, 50);
  88. borderPanel.setBorder(BorderFactory.createTitledBorder(""));
  89. parameterPanel.add(borderPanel);
  90. JLabel showGroupNodeLabel = new JLabel("Use Group Node:");
  91. showGroupNodeLabel.setBounds(10, 1, 170, 20);
  92. borderPanel.add(showGroupNodeLabel);
  93. JButton selectGroupNodeButton = new JButton("Select GroupNode");
  94. selectGroupNodeButton.setEnabled(false);
  95. selectGroupNodeButton.setBounds(10, 25, 165, 20);
  96. selectGroupNodeButton.addActionListener(actionEvent -> selectGroupNode());
  97. borderPanel.add(selectGroupNodeButton);
  98. JCheckBox useGroupNodeCheckBox = new JCheckBox();
  99. useGroupNodeCheckBox.setSelected(false);
  100. useGroupNodeCheckBox.setBounds(155, 1, 25, 20);
  101. useGroupNodeCheckBox.addActionListener(actionEvent -> {
  102. useGroupNode = useGroupNodeCheckBox.isSelected();
  103. selectGroupNodeButton.setEnabled(useGroupNode);
  104. });
  105. borderPanel.add(useGroupNodeCheckBox);
  106. JCheckBox switchesCheckBox = new JCheckBox();
  107. switchesCheckBox.setSelected(closeSwitches);
  108. switchesCheckBox.setBounds(370, 60, 25, 20);
  109. switchesCheckBox.addActionListener(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().toArray();
  184. GroupNode selected = (GroupNode) JOptionPane.showInputDialog(content, "Select GroupNode:", "GroupNode?", JOptionPane.OK_OPTION,new ImageIcon(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)) , possibilities, "");
  185. if(selected != null) {
  186. println("Selected: " + selected);
  187. groupNode = Optional.of(selected);
  188. }
  189. }
  190. private void startTimer(){
  191. startTime = System.currentTimeMillis();
  192. }
  193. private void printElapsedTime(){
  194. long elapsedMilliSeconds = System.currentTimeMillis() - startTime;
  195. println("Execution Time of Algo in Milliseconds:" + elapsedMilliSeconds);
  196. }
  197. //Algo Part:
  198. /**
  199. * The Execution of the BaseLine Algo.
  200. *
  201. *
  202. * Begin
  203. * set HolonElements aktiv;
  204. * for(All Networks) do
  205. * if(not (production < consumption)) continue;
  206. * inAktiveCount = 0;
  207. * while(inAktiveCount <= consumerWihtMaxNumberElements) do
  208. * conList = createListWithConsumerThatHaveInActiveElementsAmountOf(inAktiveCount);
  209. * sortByBiggestElement(conList);
  210. * for(con : conList) do
  211. * for(element : con.getAllActiveElementsSortByConsumption) do
  212. * if(element <= production) do
  213. * set element inAktiv;
  214. * continue;
  215. * end do
  216. * end do
  217. * end do
  218. * inAktiveCount += 1;
  219. * end while
  220. * end for
  221. * End
  222. *
  223. */
  224. private void executeBaseLine() {
  225. extractPositionAndAccess();
  226. if(closeSwitches)setAllSwitchesClosed();
  227. setHolonElemntsAktiv();
  228. control.calculateStateAndVisualForCurrentTimeStep();
  229. // DecoratedState actualstate = control.getSimManager().getActualDecorState().get();
  230. // for(DecoratedNetwork net : actualstate.getNetworkList()) {
  231. // float production = net.getSupplierList().stream().map(supplier -> supplier.getEnergyToSupplyNetwork()).reduce(0.0f, (a, b) -> a + b);
  232. // float consumption = net.getConsumerList().stream().map(con -> con.getEnergyNeededFromNetwork()).reduce(0.0f, (a, b) -> a + b);
  233. // float difference = Math.abs(production - consumption);
  234. // println("production:" + production + " consumption:" + consumption);
  235. // if(!(production < consumption))continue;
  236. // if(net.getConsumerList().isEmpty() && net.getConsumerSelfSuppliedList().isEmpty())continue;
  237. // //Stream.concat(net.getConsumerList().stream(), net.getConsumerSelfSuppliedList().stream());
  238. // int consumerWihtMaxNumberElements = Stream.concat(net.getConsumerList().stream(), net.getConsumerSelfSuppliedList().stream()).map(con -> con.getModel().getNumberOfElements()).max((lhs,rhs) ->Integer.compare(lhs, rhs)).orElse(0);
  239. // println("consumerWihtMaxNumberElements:" + consumerWihtMaxNumberElements);
  240. // for(int inAktiveCount = 0;inAktiveCount <= consumerWihtMaxNumberElements; inAktiveCount++) {
  241. // println("inAktiveCount:" + inAktiveCount);
  242. // final int inAktiveCountFinal = inAktiveCount;
  243. // 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());
  244. // conList.sort((a,b) -> Float.compare(a.getMaximumConsumingElementEnergy(), b.getMaximumConsumingElementEnergy()));
  245. // consumer:
  246. // for(HolonObject con: conList) {
  247. // //println("Consumer" + con);
  248. // List<HolonElement> sortedElementList = con.getElements().filter(ele -> ele.active && ele.isConsumer()).sorted((a,b) -> -Float.compare(-a.getActualEnergy(), -b.getActualEnergy())).collect(Collectors.toList());
  249. // for(HolonElement element: sortedElementList) {
  250. // float elementConsumption = -element.getActualEnergy();
  251. // if(elementConsumption <= difference) {
  252. // println("elementConsumption:" + elementConsumption);
  253. // difference -= elementConsumption;
  254. // element.active = false;
  255. // continue consumer;
  256. // }
  257. // }
  258. // }
  259. // }
  260. // }
  261. updateVisual();
  262. }
  263. private void setHolonElemntsAktiv() {
  264. for(int i = 0;i<access.size();i++) {
  265. AccessWrapper aw = access.get(i);
  266. if(aw.getType() == AccessWrapper.HOLONELEMENT) aw.setState(true);
  267. }
  268. }
  269. private void setAllSwitchesClosed() {
  270. for(HolonSwitch hSwitch : switchList) {
  271. hSwitch.setMode(SwitchMode.Manual);
  272. hSwitch.setManualState(SwitchState.Closed);
  273. }
  274. }
  275. /**
  276. * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
  277. * Also initialize the Access Hashmap to swap faster positions.
  278. * @return
  279. */
  280. private List<Boolean> extractPositionAndAccess() {
  281. Model model = control.getModel();
  282. switchList = new ArrayList<HolonSwitch>();
  283. objectList = new ArrayList<HolonObject>();
  284. initialState = new ArrayList<Boolean>();
  285. access= new HashMap<Integer, AccessWrapper>();
  286. rollOutNodes((useGroupNode && groupNode.isPresent())? groupNode.get().getObjectsInThisLayer() :model.getCanvas().getObjectsInThisLayer(), initialState, model.getCurrentIteration());
  287. return initialState;
  288. }
  289. /**
  290. * Method to extract the Informations recursively out of the Model.
  291. * @param nodes
  292. * @param positionToInit
  293. * @param timeStep
  294. */
  295. private void rollOutNodes(Stream<AbstractCanvasObject> nodes, List<Boolean> positionToInit, int timeStep) {
  296. nodes.forEach(aCps -> {
  297. if (aCps instanceof HolonObject hO) {
  298. hO.elementsStream().forEach(hE -> {
  299. positionToInit.add(hE.active);
  300. access.put(positionToInit.size() - 1 , new AccessWrapper(hE));
  301. });
  302. objectList.add(hO);
  303. }
  304. else if (aCps instanceof HolonSwitch sw) {
  305. positionToInit.add(sw.getState().isClosed());
  306. switchList.add(sw);
  307. access.put(positionToInit.size() - 1 , new AccessWrapper(sw));
  308. }
  309. else if(aCps instanceof GroupNode groupnode) {
  310. rollOutGroupNode(groupnode, positionToInit ,timeStep);
  311. }
  312. });
  313. }
  314. private void rollOutGroupNode (GroupNode groupNode, List<Boolean> positionToInit, int timeStep) {
  315. groupNode.getAllHolonObjectsRecursive().forEach(hObject -> {
  316. hObject.elementsStream().forEach(hE -> {
  317. positionToInit.add(hE.active);
  318. access.put(positionToInit.size() - 1 , new AccessWrapper(hE));
  319. });
  320. objectList.add(hObject);
  321. });
  322. groupNode.getAllSwitchObjectsRecursive().forEach(sw -> {
  323. positionToInit.add(sw.getState().isClosed());
  324. switchList.add(sw);
  325. access.put(positionToInit.size() - 1 , new AccessWrapper(sw));
  326. });
  327. }
  328. /**
  329. * To let the User See the current state without touching the Canvas.
  330. */
  331. private void updateVisual() {
  332. control.calculateStateAndVisualForCurrentTimeStep();
  333. }
  334. /**
  335. * Sets the Model back to its original State before the LAST run.
  336. */
  337. private void resetState() {
  338. setState(initialState);
  339. }
  340. /**
  341. * Sets the State out of the given position for calculation or to show the user.
  342. * @param position
  343. */
  344. private void setState(List<Boolean> position) {
  345. for(int i = 0;i<position.size();i++) {
  346. access.get(i).setState(position.get(i));
  347. }
  348. }
  349. /**
  350. * A Wrapper Class for Access HolonElement and HolonSwitch in one Element and not have to split the List.
  351. */
  352. private class AccessWrapper {
  353. public static final int HOLONELEMENT = 0;
  354. public static final int SWITCH = 1;
  355. private int type;
  356. private HolonSwitch hSwitch;
  357. private HolonElement hElement;
  358. public AccessWrapper(HolonSwitch hSwitch){
  359. type = SWITCH;
  360. this.hSwitch = hSwitch;
  361. }
  362. public AccessWrapper(HolonElement hElement){
  363. type = HOLONELEMENT;
  364. this.hElement = hElement;
  365. }
  366. public void setState(boolean state) {
  367. if(type == HOLONELEMENT) {
  368. hElement.active = state;
  369. }else{//is switch
  370. hSwitch.setMode(SwitchMode.Manual);
  371. hSwitch.setManualState(state ? SwitchState.Closed : SwitchState.Open);
  372. }
  373. }
  374. public int getType() {
  375. return type;
  376. }
  377. }
  378. }