BaseLine.java 15 KB

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