BaseLine.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. package 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.stream.Collectors;
  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 api.AddOn;
  24. import classes.AbstractCanvasObject;
  25. import classes.GroupNode;
  26. import classes.HolonElement;
  27. import classes.HolonObject;
  28. import classes.HolonSwitch;
  29. import ui.controller.Control;
  30. import ui.model.Model;
  31. import ui.model.DecoratedGroupNode;
  32. import ui.model.DecoratedNetwork;
  33. import ui.model.DecoratedState;
  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 DecoratedGroupNode dGroupNode = null;
  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.guiDisable(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.getSimManager().getActualVisualRepresentationalState().getCreatedGroupNodes().values().stream().map(aCps -> new Handle<DecoratedGroupNode>(aCps)).toArray();
  185. @SuppressWarnings("unchecked")
  186. 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, "");
  187. if(selected != null) {
  188. println("Selected: " + selected);
  189. dGroupNode = selected.object;
  190. }
  191. }
  192. private void startTimer(){
  193. startTime = System.currentTimeMillis();
  194. }
  195. private void printElapsedTime(){
  196. long elapsedMilliSeconds = System.currentTimeMillis() - startTime;
  197. println("Execution Time of Algo in Milliseconds:" + elapsedMilliSeconds);
  198. }
  199. //Algo Part:
  200. /**
  201. * The Execution of the BaseLine Algo.
  202. *
  203. *
  204. * Begin
  205. * set HolonElements aktiv;
  206. * for(All Networks) do
  207. * if(not (production < consumption)) continue;
  208. * inAktiveCount = 0;
  209. * while(inAktiveCount <= consumerWihtMaxNumberElements) do
  210. * conList = createListWithConsumerThatHaveInActiveElementsAmountOf(inAktiveCount);
  211. * sortByBiggestElement(conList);
  212. * for(con : conList) do
  213. * for(element : con.getAllActiveElementsSortByConsumption) do
  214. * if(element <= production) do
  215. * set element inAktiv;
  216. * continue;
  217. * end do
  218. * end do
  219. * end do
  220. * inAktiveCount += 1;
  221. * end while
  222. * end for
  223. * End
  224. *
  225. */
  226. private void executeBaseLine() {
  227. extractPositionAndAccess();
  228. int actualIteration = control.getModel().getCurIteration();
  229. if(closeSwitches)setAllSwitchesClosed();
  230. setHolonElemntsAktiv();
  231. control.calculateStateAndVisualForCurrentTimeStep();
  232. DecoratedState actualstate = control.getSimManager().getActualDecorState();
  233. for(DecoratedNetwork net : actualstate.getNetworkList()) {
  234. float production = net.getSupplierList().stream().map(supplier -> supplier.getEnergyToSupplyNetwork()).reduce(0.0f, (a, b) -> a + b);
  235. float consumption = net.getConsumerList().stream().map(con -> con.getEnergyNeededFromNetwork()).reduce(0.0f, (a, b) -> a + b);
  236. float difference = Math.abs(production - consumption);
  237. println("production:" + production + " consumption:" + consumption);
  238. if(!(production < consumption))continue;
  239. if(net.getConsumerList().isEmpty() && net.getConsumerSelfSuppliedList().isEmpty())continue;
  240. //Stream.concat(net.getConsumerList().stream(), net.getConsumerSelfSuppliedList().stream());
  241. int consumerWihtMaxNumberElements = Stream.concat(net.getConsumerList().stream(), net.getConsumerSelfSuppliedList().stream()).map(con -> con.getModel().getNumberOfElements()).max((lhs,rhs) ->Integer.compare(lhs, rhs)).orElse(0);
  242. println("consumerWihtMaxNumberElements:" + consumerWihtMaxNumberElements);
  243. for(int inAktiveCount = 0;inAktiveCount <= consumerWihtMaxNumberElements; inAktiveCount++) {
  244. println("inAktiveCount:" + inAktiveCount);
  245. final int inAktiveCountFinal = inAktiveCount;
  246. 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());
  247. conList.sort((a,b) -> Float.compare(a.getMaximumConsumingElementEnergy(actualIteration), b.getMaximumConsumingElementEnergy(actualIteration)));
  248. consumer:
  249. for(HolonObject con: conList) {
  250. //println("Consumer" + con);
  251. List<HolonElement> sortedElementList = con.getElements().stream().filter(ele -> ele.isActive() && ele.isConsumer()).sorted((a,b) -> -Float.compare(-a.getEnergyAtTimeStep(actualIteration), -b.getEnergyAtTimeStep(actualIteration))).collect(Collectors.toList());
  252. for(HolonElement element: sortedElementList) {
  253. float elementConsumption = -element.getEnergyAtTimeStep(actualIteration);
  254. if(elementConsumption <= difference) {
  255. println("elementConsumption:" + elementConsumption);
  256. difference -= elementConsumption;
  257. element.setActive(false);
  258. continue consumer;
  259. }
  260. }
  261. }
  262. }
  263. }
  264. updateVisual();
  265. }
  266. private void setHolonElemntsAktiv() {
  267. for(int i = 0;i<access.size();i++) {
  268. AccessWrapper aw = access.get(i);
  269. if(aw.getType() == AccessWrapper.HOLONELEMENT) aw.setState(true);
  270. }
  271. }
  272. private void setAllSwitchesClosed() {
  273. for(HolonSwitch hSwitch : switchList) {
  274. hSwitch.setManualMode(true);
  275. hSwitch.setManualState(true);
  276. }
  277. }
  278. /**
  279. * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
  280. * Also initialize the Access Hashmap to swap faster positions.
  281. * @param model
  282. * @return
  283. */
  284. private List<Boolean> extractPositionAndAccess() {
  285. Model model = control.getModel();
  286. switchList = new ArrayList<HolonSwitch>();
  287. objectList = new ArrayList<HolonObject>();
  288. initialState = new ArrayList<Boolean>();
  289. access= new HashMap<Integer, AccessWrapper>();
  290. rollOutNodes((useGroupNode && (dGroupNode != null))? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurIteration());
  291. return initialState;
  292. }
  293. /**
  294. * Method to extract the Informations recursively out of the Model.
  295. * @param nodes
  296. * @param positionToInit
  297. * @param timeStep
  298. */
  299. private void rollOutNodes(List<AbstractCanvasObject> nodes, List<Boolean> positionToInit, int timeStep) {
  300. for(AbstractCanvasObject aCps : nodes) {
  301. if (aCps instanceof HolonObject) {
  302. for (HolonElement hE : ((HolonObject) aCps).getElements()) {
  303. positionToInit.add(hE.isActive());
  304. access.put(positionToInit.size() - 1 , new AccessWrapper(hE));
  305. }
  306. objectList.add((HolonObject) aCps);
  307. }
  308. else if (aCps instanceof HolonSwitch) {
  309. HolonSwitch sw = (HolonSwitch) aCps;
  310. positionToInit.add(sw.getState(timeStep));
  311. switchList.add(sw);
  312. access.put(positionToInit.size() - 1 , new AccessWrapper(sw));
  313. }
  314. else if(aCps instanceof GroupNode) {
  315. rollOutNodes(((GroupNode)aCps).getNodes(), positionToInit ,timeStep );
  316. }
  317. }
  318. }
  319. /**
  320. * To let the User See the current state without touching the Canvas.
  321. */
  322. private void updateVisual() {
  323. control.calculateStateAndVisualForCurrentTimeStep();
  324. control.updateCanvas();
  325. }
  326. /**
  327. * Sets the Model back to its original State before the LAST run.
  328. */
  329. private void resetState() {
  330. setState(initialState);
  331. }
  332. /**
  333. * Sets the State out of the given position for calculation or to show the user.
  334. * @param position
  335. */
  336. private void setState(List<Boolean> position) {
  337. for(int i = 0;i<position.size();i++) {
  338. access.get(i).setState(position.get(i));
  339. }
  340. }
  341. /**
  342. * A Wrapper Class for Access HolonElement and HolonSwitch in one Element and not have to split the List.
  343. */
  344. private class AccessWrapper {
  345. public static final int HOLONELEMENT = 0;
  346. public static final int SWITCH = 1;
  347. private int type;
  348. private HolonSwitch hSwitch;
  349. private HolonElement hElement;
  350. public AccessWrapper(HolonSwitch hSwitch){
  351. type = SWITCH;
  352. this.hSwitch = hSwitch;
  353. }
  354. public AccessWrapper(HolonElement hElement){
  355. type = HOLONELEMENT;
  356. this.hElement = hElement;
  357. }
  358. public void setState(boolean state) {
  359. if(type == HOLONELEMENT) {
  360. hElement.setActive(state);
  361. }else{//is switch
  362. hSwitch.setManualMode(true);
  363. hSwitch.setManualState(state);
  364. }
  365. }
  366. public int getType() {
  367. return type;
  368. }
  369. }
  370. private class Handle<T>{
  371. public T object;
  372. Handle(T object){
  373. this.object = object;
  374. }
  375. public String toString() {
  376. return object.toString();
  377. }
  378. }
  379. }