BaseLine.java 14 KB

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