AlgorithmFramework.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. package api;
  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.io.BufferedWriter;
  8. import java.io.File;
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11. import java.io.OutputStreamWriter;
  12. import java.util.ArrayList;
  13. import java.util.LinkedList;
  14. import java.util.List;
  15. import java.util.stream.Collectors;
  16. import javax.swing.BorderFactory;
  17. import javax.swing.ImageIcon;
  18. import javax.swing.JButton;
  19. import javax.swing.JFileChooser;
  20. import javax.swing.JOptionPane;
  21. import javax.swing.JPanel;
  22. import javax.swing.JProgressBar;
  23. import javax.swing.JScrollPane;
  24. import javax.swing.JSplitPane;
  25. import classes.AbstractCpsObject;
  26. import classes.CpsUpperNode;
  27. import classes.HolonElement;
  28. import classes.HolonObject;
  29. import classes.HolonSwitch;
  30. import ui.controller.Control;
  31. import ui.model.DecoratedGroupNode;
  32. import ui.model.DecoratedState;
  33. import ui.model.Model;
  34. import ui.view.Console;
  35. public abstract class AlgorithmFramework implements AddOn{
  36. //Algo
  37. protected int rounds = 3;
  38. //Panel
  39. private JPanel content = new JPanel();
  40. protected Console console = new Console();
  41. //Settings groupNode
  42. private boolean useGroupNode = false;
  43. private DecoratedGroupNode dGroupNode = null;
  44. //access
  45. private ArrayList<AccessWrapper> access;
  46. LinkedList<List<Boolean>> resetChain = new LinkedList<List<Boolean>>();
  47. //time
  48. private long startTime;
  49. private RunProgressBar runProgressbar = new RunProgressBar();
  50. //concurrency
  51. private Thread runThread = new Thread();
  52. protected boolean cancel = false;
  53. //holeg interaction
  54. private Control control;
  55. //printing
  56. protected RunDataBase db;
  57. public AlgorithmFramework(){
  58. content.setLayout(new BorderLayout());
  59. JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
  60. createOptionPanel() , console);
  61. splitPane.setResizeWeight(0.0);
  62. content.add(splitPane, BorderLayout.CENTER);
  63. content.setPreferredSize(new Dimension(800,800));
  64. }
  65. public JPanel createOptionPanel() {
  66. JPanel optionPanel = new JPanel(new BorderLayout());
  67. JScrollPane scrollPane = new JScrollPane(createParameterPanel());
  68. scrollPane.setBorder(BorderFactory.createTitledBorder("Parameter"));
  69. optionPanel.add(scrollPane, BorderLayout.CENTER);
  70. optionPanel.add(createButtonPanel(), BorderLayout.PAGE_END);
  71. return optionPanel;
  72. }
  73. private Component createParameterPanel() {
  74. JPanel parameterPanel = new JPanel(null);
  75. parameterPanel.setPreferredSize(new Dimension(510,300));
  76. JProgressBar progressBar = runProgressbar.getJProgressBar();
  77. progressBar.setBounds(350, 155, 185, 20);
  78. progressBar.setStringPainted(true);
  79. parameterPanel.add(progressBar);
  80. JButton selectGroupNodeButton = new JButton("Select GroupNode");
  81. selectGroupNodeButton.setBounds(350, 120, 185, 30);
  82. selectGroupNodeButton.addActionListener(actionEvent -> selectGroupNode());
  83. parameterPanel.add(selectGroupNodeButton);
  84. return parameterPanel;
  85. }
  86. public JPanel createButtonPanel() {
  87. JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
  88. JButton resetButton = new JButton("Reset");
  89. resetButton.setToolTipText("Resets the State to before the Algorithm has runed.");
  90. resetButton.addActionListener(actionEvent -> reset());
  91. buttonPanel.add(resetButton);
  92. JButton cancelButton = new JButton("Cancel Run");
  93. cancelButton.addActionListener(actionEvent -> cancel());
  94. buttonPanel.add(cancelButton);
  95. JButton fitnessButton = new JButton("Fitness");
  96. fitnessButton.setToolTipText("Fitness for the current state.");
  97. fitnessButton.addActionListener(actionEvent -> fitness());
  98. buttonPanel.add(fitnessButton);
  99. JButton runButton = new JButton("Run");
  100. runButton.addActionListener(actionEvent -> {
  101. Runnable task = () -> run();
  102. runThread = new Thread(task);
  103. runThread.start();
  104. });
  105. buttonPanel.add(runButton);
  106. return buttonPanel;
  107. }
  108. private void startTimer(){
  109. startTime = System.currentTimeMillis();
  110. }
  111. private void printElapsedTime(){
  112. long elapsedMilliSeconds = System.currentTimeMillis() - startTime;
  113. console.println("Execution Time of Algo in Milliseconds:" + elapsedMilliSeconds);
  114. }
  115. private void cancel() {
  116. if(runThread.isAlive()) {
  117. console.println("Cancel run.");
  118. cancel = true;
  119. runProgressbar.stop();
  120. } else {
  121. console.println("Nothing to cancel.");
  122. }
  123. }
  124. private void fitness() {
  125. if(runThread.isAlive()) {
  126. console.println("Run have to be cancelled First.");
  127. return;
  128. }
  129. double currentFitness = evaluatePosition(extractPositionAndAccess());
  130. resetChain.removeLast();
  131. console.println("Actual Fitnessvalue: " + currentFitness);
  132. }
  133. private void selectGroupNode() {
  134. Object[] possibilities = control.getSimManager().getActualVisualRepresentationalState().getCreatedGroupNodes().values().stream().map(aCps -> new Handle<DecoratedGroupNode>(aCps)).toArray();
  135. @SuppressWarnings("unchecked")
  136. 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, "");
  137. if(selected != null) {
  138. console.println("Selected: " + selected);
  139. dGroupNode = selected.object;
  140. }
  141. }
  142. protected double evaluatePosition(List<Boolean> positionToEvaluate) {
  143. runProgressbar.step();
  144. setState(positionToEvaluate);
  145. control.calculateStateOnlyForCurrentTimeStep();
  146. DecoratedState actualstate = control.getSimManager().getActualDecorState();
  147. return evaluateState(actualstate);
  148. }
  149. protected abstract double evaluateState(DecoratedState actualstate);
  150. private void run() {
  151. cancel = false;
  152. control.guiDisable(true);
  153. executeAlgoWithParameter();
  154. updateVisual();
  155. control.guiDisable(false);
  156. }
  157. private void executeAlgoWithParameter(){
  158. runProgressbar.start();
  159. int actualIteration = control.getModel().getCurIteration();
  160. console.println("TimeStep:" + actualIteration);
  161. startTimer();
  162. Individual runBest = new Individual();
  163. runBest.fitness = Double.MAX_VALUE;
  164. db = new RunDataBase();
  165. for(int r = 0; r < rounds; r++)
  166. {
  167. Individual roundBest = executeAlgo();
  168. if(cancel)return;
  169. resetState();
  170. if(roundBest.fitness < runBest.fitness) runBest = roundBest;
  171. }
  172. printElapsedTime();
  173. setState(runBest.position);
  174. updateVisual();
  175. console.println("AlgoResult:" + runBest.fitness);
  176. runProgressbar.stop();
  177. }
  178. protected abstract Individual executeAlgo();
  179. private void reset() {
  180. if(runThread.isAlive()) {
  181. console.println("Run have to be cancelled First.");
  182. return;
  183. }
  184. if(!resetChain.isEmpty()) {
  185. console.println("Resetting..");
  186. setState(resetChain.getFirst());
  187. resetChain.clear();
  188. control.resetSimulation();
  189. control.setCurIteration(0);
  190. updateVisual();
  191. }else {
  192. console.println("No run inistialized.");
  193. }
  194. }
  195. /**
  196. * To let the User See the current state without touching the Canvas.
  197. */
  198. private void updateVisual() {
  199. control.calculateStateAndVisualForCurrentTimeStep();
  200. }
  201. /**
  202. * Sets the Model back to its original State before the LAST run.
  203. */
  204. private void resetState() {
  205. setState(resetChain.getLast());
  206. }
  207. /**
  208. * Sets the State out of the given position for calculation or to show the user.
  209. * @param position
  210. */
  211. private void setState(List<Boolean> position) {
  212. int i = 0;
  213. for(Boolean bool: position) {
  214. access.get(i++).setState(bool);
  215. }
  216. }
  217. /**
  218. * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
  219. * Also initialize the Access Hashmap to swap faster positions.
  220. * @param model
  221. * @return
  222. */
  223. protected List<Boolean> extractPositionAndAccess() {
  224. Model model = control.getModel();
  225. access= new ArrayList<AccessWrapper>();
  226. List<Boolean> initialState = new ArrayList<Boolean>();
  227. rollOutNodes((useGroupNode && (dGroupNode != null))? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurIteration());
  228. resetChain.add(initialState);
  229. return initialState;
  230. }
  231. /**
  232. * Method to extract the Informations recursively out of the Model.
  233. * @param nodes
  234. * @param positionToInit
  235. * @param timeStep
  236. */
  237. private void rollOutNodes(List<AbstractCpsObject> nodes, List<Boolean> positionToInit, int timeStep) {
  238. for(AbstractCpsObject aCps : nodes) {
  239. if (aCps instanceof HolonObject) {
  240. for (HolonElement hE : ((HolonObject) aCps).getElements()) {
  241. positionToInit.add(hE.isActive());
  242. access.add(new AccessWrapper(hE));
  243. }
  244. }
  245. else if (aCps instanceof HolonSwitch) {
  246. HolonSwitch sw = (HolonSwitch) aCps;
  247. positionToInit.add(sw.getState(timeStep));
  248. access.add(new AccessWrapper(sw));
  249. }
  250. else if(aCps instanceof CpsUpperNode) {
  251. rollOutNodes(((CpsUpperNode)aCps).getNodes(), positionToInit ,timeStep );
  252. }
  253. }
  254. }
  255. @Override
  256. public JPanel getPanel() {
  257. return content;
  258. }
  259. @Override
  260. public void setController(Control control) {
  261. this.control = control;
  262. }
  263. private class RunProgressBar{
  264. //progressbar
  265. private JProgressBar progressBar = new JProgressBar();
  266. private int count = 0;
  267. private boolean isActive = false;
  268. public void step() {
  269. if(isActive) progressBar.setValue(count++);
  270. progressBar.setMaximum(getProgressBarMaxCount());
  271. }
  272. public void start() {
  273. isActive = true;
  274. progressBar.setValue(0);
  275. }
  276. public void stop() {
  277. isActive = false;
  278. }
  279. public JProgressBar getJProgressBar(){
  280. return progressBar;
  281. }
  282. }
  283. protected abstract int getProgressBarMaxCount();
  284. public class RunDataBase{
  285. List<List<Double>> allRuns = new ArrayList<List<Double>>();
  286. public void insertNewRun(List<Double> newRun){
  287. allRuns.add(newRun);
  288. }
  289. }
  290. public class RunPrinter{
  291. //Fields
  292. private JFileChooser fileChooser = new JFileChooser();
  293. private boolean append = false;
  294. //Constructor
  295. public RunPrinter(String filename) {
  296. this(filename, false);
  297. }
  298. public RunPrinter(String filename, boolean append){
  299. this.append = append;
  300. fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
  301. fileChooser.setSelectedFile(new File(filename));
  302. }
  303. //public methods
  304. public void enableAppend(boolean enable) {
  305. append = enable;
  306. }
  307. public void setFilename(String filename) {
  308. fileChooser.setSelectedFile(new File(filename));
  309. }
  310. public void print(String info) {
  311. File file = fileChooser.getSelectedFile();
  312. try {
  313. file.createNewFile();
  314. BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
  315. new FileOutputStream(file, append), "UTF-8"));
  316. printToStream(out, info);
  317. out.close();
  318. } catch (IOException e) {
  319. System.out.println(e.getMessage());
  320. }
  321. }
  322. //private methods
  323. private void printToStream(BufferedWriter out, String info) throws IOException {
  324. out.write(info);
  325. out.newLine();
  326. if(db != null)
  327. out.write(db.allRuns.stream().map(list -> list.stream().map(Object::toString).collect(Collectors.joining(","))).collect(Collectors.joining(System.lineSeparator())));
  328. }
  329. }
  330. /**
  331. * A Wrapper Class for Access HolonElement and HolonSwitch in one Element and not have to split the List.
  332. */
  333. private class AccessWrapper {
  334. public static final int HOLONELEMENT = 0;
  335. public static final int SWITCH = 1;
  336. private int type;
  337. private HolonSwitch hSwitch;
  338. private HolonElement hElement;
  339. public AccessWrapper(HolonSwitch hSwitch){
  340. type = SWITCH;
  341. this.hSwitch = hSwitch;
  342. }
  343. public AccessWrapper(HolonElement hElement){
  344. type = HOLONELEMENT;
  345. this.hElement = hElement;
  346. }
  347. public void setState(boolean state) {
  348. if(type == HOLONELEMENT) {
  349. hElement.setActive(state);
  350. }else{//is switch
  351. hSwitch.setManualMode(true);
  352. hSwitch.setManualState(state);
  353. }
  354. }
  355. public boolean getState(int timeStep) {
  356. return (type == HOLONELEMENT)?hElement.isActive():hSwitch.getState(timeStep);
  357. }
  358. public int getType() {
  359. return type;
  360. }
  361. }
  362. /**
  363. * To create Random and maybe switch the random generation in the future.
  364. */
  365. protected static class Random{
  366. private static java.util.Random random = new java.util.Random();
  367. /**
  368. * True or false
  369. * @return the random boolean.
  370. */
  371. public static boolean nextBoolean(){
  372. return random.nextBoolean();
  373. }
  374. /**
  375. * Between 0.0(inclusive) and 1.0 (exclusive)
  376. * @return the random double.
  377. */
  378. public static double nextDouble() {
  379. return random.nextDouble();
  380. }
  381. /**
  382. * Random Int in Range [min;max[ with UniformDistirbution
  383. * @param min
  384. * @param max
  385. * @return
  386. */
  387. public static int nextIntegerInRange(int min, int max) {
  388. return min + random.nextInt(max - min);
  389. }
  390. }
  391. private class Handle<T>{
  392. public T object;
  393. Handle(T object){
  394. this.object = object;
  395. }
  396. public String toString() {
  397. return object.toString();
  398. }
  399. }
  400. public class Individual {
  401. public double fitness;
  402. public List<Boolean> position;
  403. public Individual(){};
  404. /**
  405. * Copy Constructor
  406. */
  407. public Individual(Individual c){
  408. position = c.position.stream().collect(Collectors.toList());
  409. fitness = c.fitness;
  410. }
  411. }
  412. }