DemoAlgo.java 15 KB

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