BaseLine.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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. synchronized (net.getLockObject()) {
  267. float production = net.getSupplierList().stream().map(supplier -> supplier.getEnergyToSupplyNetwork()).reduce(0.0f, (a, b) -> a + b);
  268. float consumption = net.getConsumerList().stream().map(con -> con.getEnergyNeededFromNetwork()).reduce(0.0f, (a, b) -> a + b);
  269. float difference = Math.abs(production - consumption);
  270. println("production:" + production + " consumption:" + consumption);
  271. if (!(production < consumption)) continue;
  272. if (net.getConsumerList().isEmpty() && net.getConsumerSelfSuppliedList().isEmpty()) continue;
  273. //Stream.concat(net.getConsumerList().stream(), net.getConsumerSelfSuppliedList().stream());
  274. int consumerWihtMaxNumberElements = Stream.concat(net.getConsumerList().stream(), net.getConsumerSelfSuppliedList().stream()).map(con -> con.getModel().getNumberOfElements()).max((lhs, rhs) -> Integer.compare(lhs, rhs)).orElse(0);
  275. println("consumerWihtMaxNumberElements:" + consumerWihtMaxNumberElements);
  276. for (int inAktiveCount = 0; inAktiveCount <= consumerWihtMaxNumberElements; inAktiveCount++) {
  277. println("inAktiveCount:" + inAktiveCount);
  278. final int inAktiveCountFinal = inAktiveCount;
  279. 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());
  280. conList.sort((a, b) -> Float.compare(a.getMaximumConsumingElementEnergy(actualIteration), b.getMaximumConsumingElementEnergy(actualIteration)));
  281. consumer:
  282. for (HolonObject con : conList) {
  283. //println("Consumer" + con);
  284. 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());
  285. for (HolonElement element : sortedElementList) {
  286. float elementConsumption = -element.getEnergyAtTimeStep(actualIteration);
  287. if (elementConsumption <= difference) {
  288. println("elementConsumption:" + elementConsumption);
  289. difference -= elementConsumption;
  290. element.setActive(false);
  291. continue consumer;
  292. }
  293. }
  294. }
  295. }
  296. }
  297. }
  298. updateVisual();
  299. }
  300. private void setHolonElemntsAktiv() {
  301. for(int i = 0;i<access.size();i++) {
  302. AccessWrapper aw = access.get(i);
  303. if(aw.getType() == AccessWrapper.HOLONELEMENT) aw.setState(true);
  304. }
  305. }
  306. private void setAllSwitchesClosed() {
  307. for(HolonSwitch hSwitch : switchList) {
  308. hSwitch.setManualMode(true);
  309. hSwitch.setManualState(true);
  310. }
  311. }
  312. /**
  313. * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
  314. * Also initialize the Access Hashmap to swap faster positions.
  315. * @param model
  316. * @return
  317. */
  318. private List<Boolean> extractPositionAndAccess() {
  319. Model model = control.getModel();
  320. switchList = new ArrayList<HolonSwitch>();
  321. objectList = new ArrayList<HolonObject>();
  322. initialState = new ArrayList<Boolean>();
  323. access= new HashMap<Integer, AccessWrapper>();
  324. rollOutNodes((useGroupNode && (dGroupNode != null))? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurIteration());
  325. return initialState;
  326. }
  327. /**
  328. * Method to extract the Informations recursively out of the Model.
  329. * @param nodes
  330. * @param positionToInit
  331. * @param timeStep
  332. */
  333. private void rollOutNodes(List<AbstractCanvasObject> nodes, List<Boolean> positionToInit, int timeStep) {
  334. for(AbstractCanvasObject aCps : nodes) {
  335. if (aCps instanceof HolonObject) {
  336. for (HolonElement hE : ((HolonObject) aCps).getElements()) {
  337. positionToInit.add(hE.isActive());
  338. access.put(positionToInit.size() - 1 , new AccessWrapper(hE));
  339. }
  340. objectList.add((HolonObject) aCps);
  341. }
  342. else if (aCps instanceof HolonSwitch) {
  343. HolonSwitch sw = (HolonSwitch) aCps;
  344. positionToInit.add(sw.getState(timeStep));
  345. switchList.add(sw);
  346. access.put(positionToInit.size() - 1 , new AccessWrapper(sw));
  347. }
  348. else if(aCps instanceof GroupNode) {
  349. rollOutNodes(((GroupNode)aCps).getNodes(), positionToInit ,timeStep );
  350. }
  351. }
  352. }
  353. /**
  354. * To let the User See the current state without touching the Canvas.
  355. */
  356. private void updateVisual() {
  357. control.calculateStateAndVisualForCurrentTimeStep();
  358. control.updateCanvas();
  359. }
  360. /**
  361. * Sets the Model back to its original State before the LAST run.
  362. */
  363. private void resetState() {
  364. setState(initialState);
  365. }
  366. /**
  367. * Sets the State out of the given position for calculation or to show the user.
  368. * @param position
  369. */
  370. private void setState(List<Boolean> position) {
  371. for(int i = 0;i<position.size();i++) {
  372. access.get(i).setState(position.get(i));
  373. }
  374. }
  375. /**
  376. * A Wrapper Class for Access HolonElement and HolonSwitch in one Element and not have to split the List.
  377. */
  378. private class AccessWrapper {
  379. public static final int HOLONELEMENT = 0;
  380. public static final int SWITCH = 1;
  381. private int type;
  382. private HolonSwitch hSwitch;
  383. private HolonElement hElement;
  384. public AccessWrapper(HolonSwitch hSwitch){
  385. type = SWITCH;
  386. this.hSwitch = hSwitch;
  387. }
  388. public AccessWrapper(HolonElement hElement){
  389. type = HOLONELEMENT;
  390. this.hElement = hElement;
  391. }
  392. public void setState(boolean state) {
  393. if(type == HOLONELEMENT) {
  394. hElement.setActive(state);
  395. }else{//is switch
  396. hSwitch.setManualMode(true);
  397. hSwitch.setManualState(state);
  398. }
  399. }
  400. public boolean getState(int timeStep) {
  401. return (type == HOLONELEMENT)?hElement.isActive():hSwitch.getState(timeStep);
  402. }
  403. public int getType() {
  404. return type;
  405. }
  406. }
  407. private class Handle<T>{
  408. public T object;
  409. Handle(T object){
  410. this.object = object;
  411. }
  412. public String toString() {
  413. return object.toString();
  414. }
  415. }
  416. }