BaseLine.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. package exampleAlgorithms;
  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.Algorithm;
  40. import classes.AbstractCpsObject;
  41. import classes.CpsUpperNode;
  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 Algorithm {
  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. //Gui Part:
  63. private Control control;
  64. private JTextArea textArea;
  65. private JPanel content = new JPanel();
  66. //ProgressBar
  67. private JProgressBar progressBar = new JProgressBar();
  68. private int progressBarCount = 0;
  69. private long startTime;
  70. private Thread runThread;
  71. public static void main(String[] args)
  72. {
  73. JFrame newFrame = new JFrame("exampleWindow");
  74. BaseLine instance = new BaseLine();
  75. newFrame.setContentPane(instance.getAlgorithmPanel());
  76. newFrame.pack();
  77. newFrame.setVisible(true);
  78. newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  79. }
  80. public BaseLine() {
  81. content.setLayout(new BorderLayout());
  82. textArea = new JTextArea();
  83. textArea.setEditable(false);
  84. JScrollPane scrollPane = new JScrollPane(textArea);
  85. JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
  86. createOptionPanel() , scrollPane);
  87. splitPane.setResizeWeight(0.0);
  88. content.add(splitPane, BorderLayout.CENTER);
  89. content.setPreferredSize(new Dimension(800,800));
  90. }
  91. public JPanel createOptionPanel() {
  92. JPanel optionPanel = new JPanel(new BorderLayout());
  93. JScrollPane scrollPane = new JScrollPane(createParameterPanel());
  94. scrollPane.setBorder(BorderFactory.createTitledBorder("Parameter"));
  95. optionPanel.add(scrollPane, BorderLayout.CENTER);
  96. optionPanel.add(createButtonPanel(), BorderLayout.PAGE_END);
  97. return optionPanel;
  98. }
  99. private Component createParameterPanel() {
  100. JPanel parameterPanel = new JPanel(null);
  101. parameterPanel.setPreferredSize(new Dimension(510,300));
  102. JLabel showDiagnosticsLabel = new JLabel("Set all switches closed:");
  103. showDiagnosticsLabel.setBounds(200, 60, 170, 20);
  104. parameterPanel.add(showDiagnosticsLabel);
  105. JCheckBox switchesCheckBox = new JCheckBox();
  106. switchesCheckBox.setSelected(closeSwitches);
  107. switchesCheckBox.setBounds(370, 60, 25, 20);
  108. switchesCheckBox.addActionListener(actionEvent -> closeSwitches = switchesCheckBox.isSelected());
  109. parameterPanel.add(switchesCheckBox);
  110. return parameterPanel;
  111. }
  112. public JPanel createButtonPanel() {
  113. JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
  114. JButton cancelButton = new JButton("Cancel Run");
  115. cancelButton.addActionListener(actionEvent -> cancel());
  116. buttonPanel.add(cancelButton);
  117. JButton clearButton = new JButton("Clear Console");
  118. clearButton.addActionListener(actionEvent -> clear());
  119. buttonPanel.add(clearButton);
  120. JButton resetButton = new JButton("Reset");
  121. resetButton.setToolTipText("Resets the State to before the Algorithm has runed.");
  122. resetButton.addActionListener(actionEvent -> reset());
  123. buttonPanel.add(resetButton);
  124. JButton runButton = new JButton("Run");
  125. runButton.addActionListener(actionEvent -> {
  126. Runnable task = () -> run();
  127. runThread = new Thread(task);
  128. runThread.start();
  129. });
  130. buttonPanel.add(runButton);
  131. return buttonPanel;
  132. }
  133. private void cancel() {
  134. if(runThread.isAlive()) {
  135. println("");
  136. println("Cancel run.");
  137. cancel = true;
  138. progressBar.setValue(0);
  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.guiDiable(bool);
  167. }
  168. @Override
  169. public JPanel getAlgorithmPanel() {
  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 print(String message) {
  180. textArea.append(message);
  181. }
  182. private void println(String message) {
  183. textArea.append(message + "\n");
  184. }
  185. private void selectGroupNode() {
  186. Object[] possibilities = control.getSimManager().getActualVisualRepresentationalState().getCreatedGroupNodes().values().stream().map(aCps -> new Handle<DecoratedGroupNode>(aCps)).toArray();
  187. @SuppressWarnings("unchecked")
  188. 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, "");
  189. if(selected != null) {
  190. println("Selected: " + selected);
  191. dGroupNode = selected.object;
  192. }
  193. }
  194. private void progressBarStep(){
  195. progressBar.setValue(++progressBarCount);
  196. }
  197. private void calculateProgressBarParameter() {
  198. int max = 100;
  199. progressBarCount = 0;
  200. progressBar.setValue(0);
  201. progressBar.setMaximum(max);
  202. }
  203. private void startTimer(){
  204. startTime = System.currentTimeMillis();
  205. }
  206. private void printElapsedTime(){
  207. long elapsedMilliSeconds = System.currentTimeMillis() - startTime;
  208. println("Execution Time of Algo in Milliseconds:" + elapsedMilliSeconds);
  209. }
  210. //Algo Part:
  211. /**
  212. * The Execution of the BaseLine Algo.
  213. *
  214. *
  215. * Begin
  216. * set HolonElements aktiv;
  217. * for(All Networks) do
  218. * if(not (production < consumption)) continue;
  219. * inAktiveCount = 0;
  220. * while(inAktiveCount <= consumerWihtMaxNumberElements) do
  221. * conList = createListWithConsumerThatHaveInActiveElementsAmountOf(inAktiveCount);
  222. * sortByBiggestElement(conList);
  223. * for(con : conList) do
  224. * for(element : con.getAllActiveElementsSortByConsumption) do
  225. * if(element <= production) do
  226. * set element inAktiv;
  227. * continue;
  228. * end do
  229. * end do
  230. * end do
  231. * inAktiveCount += 1;
  232. * end while
  233. * end for
  234. * End
  235. *
  236. */
  237. private void executeBaseLine() {
  238. extractPositionAndAccess();
  239. int actualIteration = control.getModel().getCurIteration();
  240. if(closeSwitches)setAllSwitchesClosed();
  241. setHolonElemntsAktiv();
  242. control.calculateStateAndVisualForCurrentTimeStep();
  243. DecoratedState actualstate = control.getSimManager().getActualDecorState();
  244. for(DecoratedNetwork net : actualstate.getNetworkList()) {
  245. float production = net.getSupplierList().stream().map(supplier -> supplier.getEnergyToSupplyNetwork()).reduce(0.0f, (a, b) -> a + b);
  246. float consumption = net.getConsumerList().stream().map(con -> con.getEnergyNeededFromNetwork()).reduce(0.0f, (a, b) -> a + b);
  247. float difference = Math.abs(production - consumption);
  248. println("production:" + production + " consumption:" + consumption);
  249. if(!(production < consumption))continue;
  250. if(net.getConsumerList().isEmpty() && net.getConsumerSelfSuppliedList().isEmpty())continue;
  251. //Stream.concat(net.getConsumerList().stream(), net.getConsumerSelfSuppliedList().stream());
  252. int consumerWihtMaxNumberElements = Stream.concat(net.getConsumerList().stream(), net.getConsumerSelfSuppliedList().stream()).map(con -> con.getModel().getNumberOfElements()).max((lhs,rhs) ->Integer.compare(lhs, rhs)).orElse(0);
  253. println("consumerWihtMaxNumberElements:" + consumerWihtMaxNumberElements);
  254. for(int inAktiveCount = 0;inAktiveCount <= consumerWihtMaxNumberElements; inAktiveCount++) {
  255. println("inAktiveCount:" + inAktiveCount);
  256. final int inAktiveCountFinal = inAktiveCount;
  257. List<HolonObject> conList = Stream.concat(net.getConsumerList().stream(), net.getConsumerSelfSuppliedList().stream()).map(con -> con.getModel()).filter(object -> (object.getNumberOfInActiveElements() == inAktiveCountFinal)).collect(Collectors.toList());
  258. conList.sort((a,b) -> Float.compare(a.getMaximumConsumingElementEnergy(actualIteration), b.getMaximumConsumingElementEnergy(actualIteration)));
  259. consumer:
  260. for(HolonObject con: conList) {
  261. println("Consumer" + con);
  262. 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());
  263. for(HolonElement element: sortedElementList) {
  264. float elementConsumption = -element.getEnergyAtTimeStep(actualIteration);
  265. if(elementConsumption <= difference) {
  266. println("elementConsumption:" + elementConsumption);
  267. difference -= elementConsumption;
  268. element.setActive(false);
  269. continue consumer;
  270. }
  271. }
  272. }
  273. }
  274. }
  275. updateVisual();
  276. }
  277. private void setHolonElemntsAktiv() {
  278. for(int i = 0;i<access.size();i++) {
  279. AccessWrapper aw = access.get(i);
  280. if(aw.getType() == AccessWrapper.HOLONELEMENT) aw.setState(true);
  281. }
  282. }
  283. private void setAllSwitchesClosed() {
  284. for(HolonSwitch hSwitch : switchList) {
  285. hSwitch.setManualMode(true);
  286. hSwitch.setManualState(true);
  287. }
  288. }
  289. /**
  290. * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
  291. * Also initialize the Access Hashmap to swap faster positions.
  292. * @param model
  293. * @return
  294. */
  295. private List<Boolean> extractPositionAndAccess() {
  296. Model model = control.getModel();
  297. switchList = new ArrayList<HolonSwitch>();
  298. initialState = new ArrayList<Boolean>();
  299. access= new HashMap<Integer, AccessWrapper>();
  300. rollOutNodes((useGroupNode && (dGroupNode != null))? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurIteration());
  301. return initialState;
  302. }
  303. /**
  304. * Method to extract the Informations recursively out of the Model.
  305. * @param nodes
  306. * @param positionToInit
  307. * @param timeStep
  308. */
  309. private void rollOutNodes(List<AbstractCpsObject> nodes, List<Boolean> positionToInit, int timeStep) {
  310. for(AbstractCpsObject aCps : nodes) {
  311. if (aCps instanceof HolonObject) {
  312. for (HolonElement hE : ((HolonObject) aCps).getElements()) {
  313. positionToInit.add(hE.isActive());
  314. access.put(positionToInit.size() - 1 , new AccessWrapper(hE));
  315. }
  316. }
  317. else if (aCps instanceof HolonSwitch) {
  318. HolonSwitch sw = (HolonSwitch) aCps;
  319. positionToInit.add(sw.getState(timeStep));
  320. switchList.add(sw);
  321. access.put(positionToInit.size() - 1 , new AccessWrapper(sw));
  322. }
  323. else if(aCps instanceof CpsUpperNode) {
  324. rollOutNodes(((CpsUpperNode)aCps).getNodes(), positionToInit ,timeStep );
  325. }
  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. control.updateCanvas();
  334. }
  335. /**
  336. * Sets the Model back to its original State before the LAST run.
  337. */
  338. private void resetState() {
  339. setState(initialState);
  340. }
  341. /**
  342. * Sets the State out of the given position for calculation or to show the user.
  343. * @param position
  344. */
  345. private void setState(List<Boolean> position) {
  346. for(int i = 0;i<position.size();i++) {
  347. access.get(i).setState(position.get(i));
  348. }
  349. }
  350. /**
  351. * A Wrapper Class for Access HolonElement and HolonSwitch in one Element and not have to split the List.
  352. */
  353. private class AccessWrapper {
  354. public static final int HOLONELEMENT = 0;
  355. public static final int SWITCH = 1;
  356. private int type;
  357. private HolonSwitch hSwitch;
  358. private HolonElement hElement;
  359. public AccessWrapper(HolonSwitch hSwitch){
  360. type = SWITCH;
  361. this.hSwitch = hSwitch;
  362. }
  363. public AccessWrapper(HolonElement hElement){
  364. type = HOLONELEMENT;
  365. this.hElement = hElement;
  366. }
  367. public void setState(boolean state) {
  368. if(type == HOLONELEMENT) {
  369. hElement.setActive(state);
  370. }else{//is switch
  371. hSwitch.setManualMode(true);
  372. hSwitch.setManualState(state);
  373. }
  374. }
  375. public boolean getState(int timeStep) {
  376. return (type == HOLONELEMENT)?hElement.isActive():hSwitch.getState(timeStep);
  377. }
  378. public int getType() {
  379. return type;
  380. }
  381. }
  382. private class Handle<T>{
  383. public T object;
  384. Handle(T object){
  385. this.object = object;
  386. }
  387. public String toString() {
  388. return object.toString();
  389. }
  390. }
  391. }