AlgorithmFramework.java 19 KB

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