DemoAlgo.java 15 KB

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