AlgorithmFrameworkFlex.java 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  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.Collections;
  16. import java.util.LinkedList;
  17. import java.util.List;
  18. import java.util.Locale;
  19. import java.util.function.BiFunction;
  20. import java.util.function.Consumer;
  21. import java.util.function.Supplier;
  22. import java.util.stream.Collectors;
  23. import javax.swing.BorderFactory;
  24. import javax.swing.Box;
  25. import javax.swing.BoxLayout;
  26. import javax.swing.ImageIcon;
  27. import javax.swing.JButton;
  28. import javax.swing.JCheckBox;
  29. import javax.swing.JFileChooser;
  30. import javax.swing.JFormattedTextField;
  31. import javax.swing.JLabel;
  32. import javax.swing.JOptionPane;
  33. import javax.swing.JPanel;
  34. import javax.swing.JProgressBar;
  35. import javax.swing.JScrollPane;
  36. import javax.swing.JSplitPane;
  37. import javax.swing.text.NumberFormatter;
  38. import classes.AbstractCanvasObject;
  39. import classes.GroupNode;
  40. import classes.Flexibility;
  41. import classes.HolonElement;
  42. import classes.HolonObject;
  43. import classes.HolonSwitch;
  44. import classes.HolonElement.Priority;
  45. import ui.controller.Control;
  46. import ui.controller.FlexManager.FlexState;
  47. import ui.controller.FlexManager.FlexWrapper;
  48. import ui.model.DecoratedGroupNode;
  49. import ui.model.DecoratedState;
  50. import ui.model.Model;
  51. import ui.model.DecoratedHolonObject.HolonObjectState;
  52. import ui.model.DecoratedSwitch.SwitchState;
  53. import ui.model.DecoratedNetwork;
  54. import ui.view.Console;
  55. public abstract class AlgorithmFrameworkFlex implements AddOn{
  56. //Algo
  57. protected int rounds = 1;
  58. //Panel
  59. private JPanel content = new JPanel();
  60. protected Console console = new Console();
  61. private JPanel borderPanel = new JPanel();
  62. //Settings groupNode
  63. private DecoratedGroupNode dGroupNode = null;
  64. //access
  65. private ArrayList<AccessWrapper> access;
  66. LinkedList<List<Boolean>> resetChain = new LinkedList<List<Boolean>>();
  67. boolean algoUseElements = false, algoUseSwitches = true, algoUseFlexes = true;
  68. //time
  69. private long startTime;
  70. private RunProgressBar runProgressbar = new RunProgressBar();
  71. //concurrency
  72. private Thread runThread = new Thread();
  73. protected boolean cancel = false;
  74. //holeg interaction
  75. protected Control control;
  76. //printing
  77. private Printer runPrinter = new Printer(plottFileName());
  78. protected List<Double> runList = new LinkedList<Double>();
  79. //Parameter
  80. @SuppressWarnings("rawtypes")
  81. LinkedList<ParameterStepping> parameterSteppingList= new LinkedList<ParameterStepping>();
  82. protected boolean useStepping = false;
  83. public AlgorithmFrameworkFlex(){
  84. content.setLayout(new BorderLayout());
  85. JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
  86. createOptionPanel() , console);
  87. splitPane.setResizeWeight(0.0);
  88. content.add(splitPane, BorderLayout.CENTER);
  89. content.setPreferredSize(new Dimension(1200,800));
  90. //Add rounds
  91. }
  92. private JPanel createOptionPanel() {
  93. JPanel optionPanel = new JPanel(new BorderLayout());
  94. JScrollPane scrollPane = new JScrollPane(createParameterPanel());
  95. scrollPane.setBorder(BorderFactory.createTitledBorder("Parameter"));
  96. optionPanel.add(scrollPane, BorderLayout.CENTER);
  97. optionPanel.add(createButtonPanel(), BorderLayout.PAGE_END);
  98. return optionPanel;
  99. }
  100. private Component createParameterPanel() {
  101. JPanel parameterPanel = new JPanel(null);
  102. parameterPanel.setPreferredSize(new Dimension(510,300));
  103. borderPanel.setLayout(new BoxLayout(borderPanel, BoxLayout.PAGE_AXIS));
  104. addIntParameter("Rounds", rounds, intInput -> rounds = intInput, () -> rounds, 1);
  105. JScrollPane scrollPane = new JScrollPane(borderPanel);
  106. scrollPane.setBounds(10, 0, 850, 292);
  107. scrollPane.setBorder(BorderFactory.createEmptyBorder());
  108. parameterPanel.add(scrollPane);
  109. JButton selectGroupNodeButton = new JButton("Select GroupNode");
  110. selectGroupNodeButton.setBounds(900, 0, 185, 30);
  111. selectGroupNodeButton.addActionListener(actionEvent -> selectGroupNode());
  112. parameterPanel.add(selectGroupNodeButton);
  113. JProgressBar progressBar = runProgressbar.getJProgressBar();
  114. progressBar.setBounds(900, 35, 185, 20);
  115. progressBar.setStringPainted(true);
  116. parameterPanel.add(progressBar);
  117. JCheckBox useElements = new JCheckBox("Elements");
  118. useElements.setSelected(algoUseElements);
  119. useElements.setBounds(900, 70, 185, 20);
  120. useElements.addActionListener(actionEvent -> algoUseElements = useElements.isSelected());
  121. parameterPanel.add(useElements);
  122. JCheckBox useSwitches = new JCheckBox("Switches");
  123. useSwitches.setSelected(algoUseSwitches);
  124. useSwitches.setBounds(900, 90, 185, 20);
  125. useSwitches.addActionListener(actionEvent -> algoUseSwitches = useSwitches.isSelected());
  126. parameterPanel.add(useSwitches);
  127. JCheckBox useFlexes = new JCheckBox("Flexibilities");
  128. useFlexes.setSelected(algoUseFlexes);
  129. useFlexes.setBounds(900, 110, 185, 20);
  130. useFlexes.addActionListener(actionEvent -> algoUseFlexes = useFlexes.isSelected());
  131. parameterPanel.add(useFlexes);
  132. return parameterPanel;
  133. }
  134. private JPanel createButtonPanel() {
  135. JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
  136. JButton resetButton = new JButton("Reset");
  137. resetButton.setToolTipText("Resets the State to before the Algorithm has runed.");
  138. resetButton.addActionListener(actionEvent -> reset());
  139. buttonPanel.add(resetButton);
  140. JButton cancelButton = new JButton("Cancel Run");
  141. cancelButton.addActionListener(actionEvent -> cancel());
  142. buttonPanel.add(cancelButton);
  143. JButton fitnessButton = new JButton("Fitness");
  144. fitnessButton.setToolTipText("Fitness for the current state.");
  145. fitnessButton.addActionListener(actionEvent -> fitness());
  146. buttonPanel.add(fitnessButton);
  147. JButton runButton = new JButton("Run");
  148. runButton.addActionListener(actionEvent -> {
  149. Runnable task = () -> run();
  150. runThread = new Thread(task);
  151. runThread.start();
  152. });
  153. buttonPanel.add(runButton);
  154. return buttonPanel;
  155. }
  156. //ParameterImports
  157. //int
  158. protected void addIntParameter(String parameterName, int parameterValue, Consumer<Integer> setter, Supplier<Integer> getter) {
  159. this.addIntParameter(parameterName, parameterValue, setter, getter, Integer.MIN_VALUE, Integer.MAX_VALUE);
  160. }
  161. protected void addIntParameter(String parameterName, int parameterValue, Consumer<Integer> setter, Supplier<Integer> getter, int parameterMinValue) {
  162. this.addIntParameter(parameterName, parameterValue, setter, getter, parameterMinValue, Integer.MAX_VALUE);
  163. }
  164. protected void addIntParameter(String parameterName, int parameterValue, Consumer<Integer> setter, Supplier<Integer> getter, int parameterMinValue, int parameterMaxValue) {
  165. JPanel singleParameterPanel = new JPanel();
  166. singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
  167. singleParameterPanel.setAlignmentX(0.0f);
  168. singleParameterPanel.add(new JLabel(parameterName + ": "));
  169. singleParameterPanel.add(Box.createHorizontalGlue());
  170. NumberFormat format = NumberFormat.getIntegerInstance();
  171. format.setGroupingUsed(false);
  172. format.setParseIntegerOnly(true);
  173. NumberFormatter integerFormatter = new NumberFormatter(format);
  174. integerFormatter.setMinimum(parameterMinValue);
  175. integerFormatter.setMaximum(parameterMaxValue);
  176. integerFormatter.setCommitsOnValidEdit(true);
  177. JFormattedTextField singleParameterTextField = new JFormattedTextField(integerFormatter);
  178. singleParameterTextField.setValue(parameterValue);
  179. String minValue = (parameterMinValue == Integer.MIN_VALUE)?"Integer.MIN_VALUE":String.valueOf(parameterMinValue);
  180. String maxValue = (parameterMaxValue == Integer.MAX_VALUE)?"Integer.MAX_VALUE":String.valueOf(parameterMaxValue);
  181. singleParameterTextField.setToolTipText("Only integer \u2208 [" + minValue + "," + maxValue + "]");
  182. singleParameterTextField.addPropertyChangeListener(actionEvent -> setter.accept(Integer.parseInt(singleParameterTextField.getValue().toString())));
  183. singleParameterTextField.setMaximumSize(new Dimension(200, 30));
  184. singleParameterTextField.setPreferredSize(new Dimension(200, 30));
  185. singleParameterPanel.add(singleParameterTextField);
  186. ParameterStepping<Integer> intParameterStepping = new ParameterStepping<Integer>(setter, getter, Integer::sum , (a,b) -> a * b, 1, 1);
  187. intParameterStepping.useThisParameter = false;
  188. parameterSteppingList.add(intParameterStepping);
  189. JCheckBox useSteppingCheckBox = new JCheckBox();
  190. useSteppingCheckBox.setSelected(false);
  191. singleParameterPanel.add(useSteppingCheckBox);
  192. JLabel stepsLabel = new JLabel("Steps: ");
  193. stepsLabel.setEnabled(false);
  194. singleParameterPanel.add(stepsLabel);
  195. NumberFormatter stepFormatter = new NumberFormatter(format);
  196. stepFormatter.setMinimum(1);
  197. stepFormatter.setMaximum(Integer.MAX_VALUE);
  198. stepFormatter.setCommitsOnValidEdit(true);
  199. JFormattedTextField stepsTextField = new JFormattedTextField(stepFormatter);
  200. stepsTextField.setEnabled(false);
  201. stepsTextField.setValue(1);
  202. stepsTextField.setToolTipText("Only integer \u2208 [" + 1 + "," + Integer.MAX_VALUE + "]");
  203. stepsTextField.addPropertyChangeListener(actionEvent -> intParameterStepping.stepps = Integer.parseInt(stepsTextField.getValue().toString()));
  204. stepsTextField.setMaximumSize(new Dimension(40, 30));
  205. stepsTextField.setPreferredSize(new Dimension(40, 30));
  206. singleParameterPanel.add(stepsTextField);
  207. JLabel stepsSizeLabel = new JLabel("StepsSize: ");
  208. stepsSizeLabel.setEnabled(false);
  209. singleParameterPanel.add(stepsSizeLabel);
  210. JFormattedTextField stepsSizeTextField = new JFormattedTextField(stepFormatter);
  211. stepsSizeTextField.setEnabled(false);
  212. stepsSizeTextField.setValue(1);
  213. stepsSizeTextField.setToolTipText("Only integer \u2208 [" + 1 + "," + Integer.MAX_VALUE + "]");
  214. stepsSizeTextField.addPropertyChangeListener(actionEvent -> intParameterStepping.stepSize = Integer.parseInt(stepsSizeTextField.getValue().toString()));
  215. stepsSizeTextField.setMaximumSize(new Dimension(40, 30));
  216. stepsSizeTextField.setPreferredSize(new Dimension(40, 30));
  217. singleParameterPanel.add(stepsSizeTextField);
  218. useSteppingCheckBox.addActionListener(actionEvent -> {
  219. boolean enabled = useSteppingCheckBox.isSelected();
  220. intParameterStepping.useThisParameter = enabled;
  221. this.useStepping = this.parameterSteppingList.stream().anyMatch(parameter -> parameter.useThisParameter);
  222. stepsLabel.setEnabled(enabled);
  223. stepsTextField.setEnabled(enabled);
  224. stepsSizeLabel.setEnabled(enabled);
  225. stepsSizeTextField.setEnabled(enabled);
  226. });
  227. borderPanel.add(singleParameterPanel);
  228. }
  229. //double
  230. protected void addDoubleParameter(String parameterName, double parameterValue, Consumer<Double> setter, Supplier<Double> getter) {
  231. this.addDoubleParameter(parameterName, parameterValue, setter, getter, Double.MIN_VALUE, Double.MAX_VALUE);
  232. }
  233. protected void addDoubleParameter(String parameterName, double parameterValue, Consumer<Double> setter, Supplier<Double> getter, double parameterMinValue) {
  234. this.addDoubleParameter(parameterName, parameterValue, setter, getter, parameterMinValue, Double.MAX_VALUE);
  235. }
  236. protected void addDoubleParameter(String parameterName, double parameterValue, Consumer<Double> setter, Supplier<Double> getter, double parameterMinValue, double parameterMaxValue) {
  237. JPanel singleParameterPanel = new JPanel();
  238. singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
  239. singleParameterPanel.setAlignmentX(0.0f);
  240. singleParameterPanel.add(new JLabel(parameterName + ": "));
  241. singleParameterPanel.add(Box.createHorizontalGlue());
  242. NumberFormat doubleFormat = NumberFormat.getNumberInstance(Locale.US);
  243. doubleFormat.setMinimumFractionDigits(1);
  244. doubleFormat.setMaximumFractionDigits(10);
  245. doubleFormat.setRoundingMode(RoundingMode.HALF_UP);
  246. NumberFormatter doubleFormatter = new NumberFormatter(doubleFormat);
  247. doubleFormatter.setMinimum(parameterMinValue);
  248. doubleFormatter.setMaximum(parameterMaxValue);
  249. doubleFormatter.setCommitsOnValidEdit(true);
  250. JFormattedTextField singleParameterTextField = new JFormattedTextField(doubleFormatter);
  251. singleParameterTextField.setValue(parameterValue);
  252. String minValue = (parameterMinValue == Double.MIN_VALUE)?"Double.MIN_VALUE":String.valueOf(parameterMinValue);
  253. String maxValue = (parameterMaxValue == Double.MAX_VALUE)?"Double.MAX_VALUE":String.valueOf(parameterMaxValue);
  254. singleParameterTextField.setToolTipText("Only double \u2208 [" + minValue + "," + maxValue + "]");
  255. singleParameterTextField.addPropertyChangeListener(actionEvent -> setter.accept(Double.parseDouble(singleParameterTextField.getValue().toString())));
  256. singleParameterTextField.setMaximumSize(new Dimension(200, 30));
  257. singleParameterTextField.setPreferredSize(new Dimension(200, 30));
  258. singleParameterPanel.add(singleParameterTextField);
  259. ParameterStepping<Double> doubleParameterStepping = new ParameterStepping<Double>(setter, getter, (a,b) -> a+b , (a,b) -> a * b, 1.0, 1);
  260. doubleParameterStepping.useThisParameter = false;
  261. parameterSteppingList.add(doubleParameterStepping);
  262. JCheckBox useSteppingCheckBox = new JCheckBox();
  263. useSteppingCheckBox.setSelected(false);
  264. singleParameterPanel.add(useSteppingCheckBox);
  265. JLabel stepsLabel = new JLabel("Steps: ");
  266. stepsLabel.setEnabled(false);
  267. singleParameterPanel.add(stepsLabel);
  268. NumberFormat format = NumberFormat.getIntegerInstance();
  269. format.setGroupingUsed(false);
  270. format.setParseIntegerOnly(true);
  271. NumberFormatter integerFormatter = new NumberFormatter(format);
  272. integerFormatter.setMinimum(1);
  273. integerFormatter.setMaximum(Integer.MAX_VALUE);
  274. integerFormatter.setCommitsOnValidEdit(true);
  275. JFormattedTextField stepsTextField = new JFormattedTextField(integerFormatter);
  276. stepsTextField.setEnabled(false);
  277. stepsTextField.setValue(1);
  278. stepsTextField.setToolTipText("Only integer \u2208 [" + 1 + "," + Integer.MAX_VALUE + "]");
  279. stepsTextField.addPropertyChangeListener(actionEvent -> doubleParameterStepping.stepps = Integer.parseInt(stepsTextField.getValue().toString()));
  280. stepsTextField.setMaximumSize(new Dimension(40, 30));
  281. stepsTextField.setPreferredSize(new Dimension(40, 30));
  282. singleParameterPanel.add(stepsTextField);
  283. JLabel stepsSizeLabel = new JLabel("StepsSize: ");
  284. stepsSizeLabel.setEnabled(false);
  285. singleParameterPanel.add(stepsSizeLabel);
  286. NumberFormatter doubleFormatterForStepping = new NumberFormatter(doubleFormat);
  287. doubleFormatterForStepping.setCommitsOnValidEdit(true);
  288. JFormattedTextField stepsSizeTextField = new JFormattedTextField(doubleFormatterForStepping);
  289. stepsSizeTextField.setEnabled(false);
  290. stepsSizeTextField.setValue(1.0);
  291. stepsSizeTextField.setToolTipText("Only double");
  292. stepsSizeTextField.addPropertyChangeListener(actionEvent -> doubleParameterStepping.stepSize = Double.parseDouble(stepsSizeTextField.getValue().toString()));
  293. stepsSizeTextField.setMaximumSize(new Dimension(40, 30));
  294. stepsSizeTextField.setPreferredSize(new Dimension(40, 30));
  295. singleParameterPanel.add(stepsSizeTextField);
  296. useSteppingCheckBox.addActionListener(actionEvent -> {
  297. boolean enabled = useSteppingCheckBox.isSelected();
  298. doubleParameterStepping.useThisParameter = enabled;
  299. this.useStepping = this.parameterSteppingList.stream().anyMatch(parameter -> parameter.useThisParameter);
  300. stepsLabel.setEnabled(enabled);
  301. stepsTextField.setEnabled(enabled);
  302. stepsSizeLabel.setEnabled(enabled);
  303. stepsSizeTextField.setEnabled(enabled);
  304. });
  305. borderPanel.add(singleParameterPanel);
  306. }
  307. //boolean
  308. protected void addBooleanParameter(String parameterName, boolean parameterValue, Consumer<Boolean> setter){
  309. JPanel singleParameterPanel = new JPanel();
  310. singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
  311. singleParameterPanel.setAlignmentX(0.0f);
  312. singleParameterPanel.add(new JLabel(parameterName + ": "));
  313. singleParameterPanel.add(Box.createHorizontalGlue());
  314. JCheckBox useGroupNodeCheckBox = new JCheckBox();
  315. useGroupNodeCheckBox.setSelected(parameterValue);
  316. useGroupNodeCheckBox.addActionListener(actionEvent -> setter.accept(useGroupNodeCheckBox.isSelected()));
  317. singleParameterPanel.add(useGroupNodeCheckBox);
  318. borderPanel.add(singleParameterPanel);
  319. }
  320. private void startTimer(){
  321. startTime = System.currentTimeMillis();
  322. }
  323. private long printElapsedTime(){
  324. long elapsedMilliSeconds = System.currentTimeMillis() - startTime;
  325. console.println("Execution Time of Algo in Milliseconds:" + elapsedMilliSeconds);
  326. return elapsedMilliSeconds;
  327. }
  328. private void cancel() {
  329. if(runThread.isAlive()) {
  330. console.println("Cancel run.");
  331. cancel = true;
  332. runProgressbar.cancel();
  333. } else {
  334. console.println("Nothing to cancel.");
  335. }
  336. }
  337. private void fitness() {
  338. if(runThread.isAlive()) {
  339. console.println("Run have to be cancelled First.");
  340. return;
  341. }
  342. double currentFitness = evaluatePosition(extractPositionAndAccess());
  343. resetChain.removeLast();
  344. console.println("Actual Fitnessvalue: " + currentFitness);
  345. }
  346. private void selectGroupNode() {
  347. Object[] possibilities = control.getSimManager().getActualVisualRepresentationalState().getCreatedGroupNodes().values().stream().map(aCps -> new Handle<DecoratedGroupNode>(aCps)).toArray();
  348. @SuppressWarnings("unchecked")
  349. 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, "");
  350. if(selected != null) {
  351. console.println("Selected: " + selected);
  352. dGroupNode = selected.object;
  353. }
  354. }
  355. protected double evaluatePosition(List<Boolean> positionToEvaluate) {
  356. runProgressbar.step();
  357. // long startTime = System.currentTimeMillis(), endTime;
  358. control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration()); // execution time critical
  359. // endTime = System.currentTimeMillis();
  360. // console.print(" a:" + (endTime - startTime));
  361. // startTime = endTime;
  362. setState(positionToEvaluate); // execution time critical
  363. // endTime = System.currentTimeMillis();
  364. // console.print(" b:" + (endTime - startTime));
  365. // startTime = endTime;
  366. control.calculateStateOnlyForCurrentTimeStep();
  367. // endTime = System.currentTimeMillis();
  368. // console.print(" c:" + (endTime - startTime));
  369. // startTime = endTime;
  370. DecoratedState actualstate = control.getSimManager().getActualDecorState();
  371. // endTime = System.currentTimeMillis();
  372. // console.print(" d:" + (endTime - startTime));
  373. // startTime = endTime;
  374. double result = evaluateState(actualstate);
  375. // endTime = System.currentTimeMillis();
  376. // console.print(" e:" + (endTime - startTime));
  377. // startTime = endTime;
  378. // long inUse = actualstate.getFlexManager().getAllFlexWrapperWithState(FlexState.IN_USE).size();
  379. // long all = actualstate.getFlexManager().getAllFlexWrapper().size();
  380. // console.println(" [" + inUse + "/" + all + "]");
  381. return result;
  382. }
  383. protected abstract double evaluateState(DecoratedState actualstate);
  384. private void run() {
  385. cancel = false;
  386. control.guiDisable(true);
  387. runPrinter.openStream();
  388. runPrinter.println("");
  389. runPrinter.println("Start:" + stringStatFromActualState());
  390. runPrinter.closeStream();
  391. if(this.useStepping) {
  392. initParameterStepping();
  393. do {
  394. executeAlgoWithParameter();
  395. if(cancel) break;
  396. resetState();
  397. }while(updateOneParameter());
  398. resetParameterStepping();
  399. }else {
  400. executeAlgoWithParameter();
  401. }
  402. updateVisual();
  403. runProgressbar.finishedCancel();
  404. control.guiDisable(false);
  405. }
  406. @SuppressWarnings("rawtypes")
  407. private void initParameterStepping() {
  408. for(ParameterStepping param :this.parameterSteppingList) {
  409. param.init();
  410. }
  411. }
  412. @SuppressWarnings("rawtypes")
  413. private void resetParameterStepping() {
  414. for(ParameterStepping param :this.parameterSteppingList) {
  415. param.reset();
  416. }
  417. }
  418. @SuppressWarnings("rawtypes")
  419. private boolean updateOneParameter() {
  420. List<ParameterStepping> parameterInUseList = this.parameterSteppingList.stream().filter(param -> param.useThisParameter).collect(Collectors.toList());
  421. Collections.reverse(parameterInUseList);
  422. int lastParameter = parameterInUseList.size() - 1 ;
  423. int actualParameter = 0;
  424. for(ParameterStepping param : parameterInUseList) {
  425. if(param.canUpdate()) {
  426. param.update();
  427. return true;
  428. }else {
  429. if(actualParameter == lastParameter) break;
  430. param.reset();
  431. }
  432. actualParameter++;
  433. }
  434. //No Param can be updated
  435. return false;
  436. }
  437. private void executeAlgoWithParameter(){
  438. double startFitness = evaluatePosition(extractPositionAndAccess());
  439. console.println("BitLength: " + access.size());
  440. resetChain.removeLast();
  441. runPrinter.openStream();
  442. runPrinter.println("");
  443. runPrinter.println(algoInformationToPrint());
  444. console.println(algoInformationToPrint());
  445. runPrinter.closeStream();
  446. runProgressbar.start();
  447. Individual runBest = new Individual();
  448. runBest.fitness = Double.MAX_VALUE;
  449. for(int r = 0; r < rounds; r++)
  450. {
  451. startTimer();
  452. Individual roundBest = executeAlgo();
  453. if(cancel)return;
  454. long executionTime = printElapsedTime();
  455. runPrinter.openStream();
  456. runPrinter.println(runList.stream().map(Object::toString).collect(Collectors.joining(", ")));
  457. runPrinter.println(stringStatFromActualState());
  458. runPrinter.println("Result: " + roundBest.fitness + " ExecutionTime:" + executionTime);
  459. runPrinter.closeStream();
  460. resetState();
  461. if(roundBest.fitness < runBest.fitness) runBest = roundBest;
  462. }
  463. control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
  464. this.extractPositionAndAccess();
  465. setState(runBest.position);
  466. updateVisual();
  467. console.println("Start: " + startFitness);
  468. console.println("AlgoResult: " + runBest.fitness);
  469. if(this.algoUseFlexes)calculateAndPrintFlexInfos(control.getSimManager().getActualDecorState());
  470. }
  471. private void calculateAndPrintFlexInfos(DecoratedState state) {
  472. int amountOfUsedFlex = 0;
  473. int amountOfFlex = state.getFlexManager().getAllFlexWrapper().size();
  474. float cost = 0;
  475. int consumingFlex = 0;
  476. float consumingFlexEnergy = 0.0f;
  477. int producingFlex = 0;
  478. float producingFlexEnergy = 0.0f;
  479. int maxCooldown = 0;
  480. int amountEssential = 0;
  481. int amountHigh = 0;
  482. int amountMedium = 0;
  483. int amountLow = 0;
  484. for(FlexWrapper flexWrapper :state.getFlexManager().getAllFlexWrapperWithState(FlexState.IN_USE)) {
  485. amountOfUsedFlex++;
  486. cost += flexWrapper.getFlex().cost;
  487. float energy = flexWrapper.getFlex().bringtmir();
  488. if(energy < 0) {
  489. consumingFlex++;
  490. consumingFlexEnergy += -energy;
  491. }else {
  492. producingFlex++;
  493. producingFlexEnergy += energy;
  494. }
  495. if(flexWrapper.getFlex().getCooldown() > maxCooldown) maxCooldown = flexWrapper.getFlex().getCooldown();
  496. switch(flexWrapper.getFlex().getElement().getPriority()) {
  497. case Essential:
  498. amountEssential++;
  499. break;
  500. case High:
  501. amountHigh++;
  502. break;
  503. case Low:
  504. amountLow++;
  505. break;
  506. case Medium:
  507. amountMedium++;
  508. break;
  509. default:
  510. break;
  511. }
  512. }
  513. //Total Flexibilities:
  514. //Used Flexibilities:
  515. console.println("Used Flex [" + amountOfUsedFlex + "/" + amountOfFlex + "]");
  516. //Consuming Flexibilities:
  517. console.println(consumingFlex + " consuimg flexibilities that consumed " + consumingFlexEnergy + "Energy.");
  518. //Producing Flexibilities
  519. console.println(producingFlex + " producing flexibilities that produce " + producingFlexEnergy + "Energy.");
  520. console.println("Flex in use:\t" + "Low= " + amountLow + "\tMedium= " + amountMedium + "\tHigh= " + amountHigh + "\tEssential= " + amountEssential);
  521. //Total cost:
  522. console.println("Total Cost: "+ cost);
  523. //Longest Cooldown
  524. console.println("Max Cooldown: "+ maxCooldown);
  525. //
  526. }
  527. protected abstract Individual executeAlgo();
  528. private void reset() {
  529. if(runThread.isAlive()) {
  530. console.println("Run have to be cancelled First.");
  531. return;
  532. }
  533. if(!resetChain.isEmpty()) {
  534. console.println("Resetting..");
  535. setState(resetChain.getFirst());
  536. control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
  537. resetChain.clear();
  538. control.resetSimulation();
  539. control.setCurIteration(0);
  540. updateVisual();
  541. }else {
  542. console.println("No run inistialized.");
  543. }
  544. }
  545. /**
  546. * To let the User See the current state without touching the Canvas.
  547. */
  548. private void updateVisual() {
  549. control.calculateStateAndVisualForCurrentTimeStep();
  550. }
  551. /**
  552. * Sets the Model back to its original State before the LAST run.
  553. */
  554. private void resetState() {
  555. control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
  556. setState(resetChain.getLast());
  557. }
  558. /**
  559. * Sets the State out of the given position for calculation or to show the user.
  560. * @param position
  561. */
  562. private void setState(List<Boolean> position) {
  563. int i = 0;
  564. for(Boolean bool: position) {
  565. access.get(i++).setState(bool);
  566. }
  567. }
  568. /**
  569. * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
  570. * Also initialize the Access Hashmap to swap faster positions.
  571. * @param model
  572. * @return
  573. */
  574. protected List<Boolean> extractPositionAndAccess() {
  575. Model model = control.getModel();
  576. access= new ArrayList<AccessWrapper>();
  577. List<Boolean> initialState = new ArrayList<Boolean>();
  578. rollOutNodes((dGroupNode != null)? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurIteration());
  579. resetChain.add(initialState);
  580. if(algoUseFlexes) {
  581. for(FlexWrapper flex :control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.OFFERED)){
  582. access.add(new AccessWrapper(flex.getFlex()));
  583. initialState.add(false);
  584. }
  585. for(FlexWrapper flex :control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.IN_USE)){
  586. access.add(new AccessWrapper(flex.getFlex()));
  587. initialState.add(true);
  588. }
  589. }
  590. //console.println(access.stream().map(Object::toString).collect(Collectors.joining(", ")));
  591. return initialState;
  592. }
  593. /**
  594. * Method to extract the Informations recursively out of the Model.
  595. * @param nodes
  596. * @param positionToInit
  597. * @param timeStep
  598. */
  599. private void rollOutNodes(List<AbstractCanvasObject> nodes, List<Boolean> positionToInit, int timeStep) {
  600. for(AbstractCanvasObject aCps : nodes) {
  601. if (aCps instanceof HolonObject && algoUseElements) {
  602. for (HolonElement hE : ((HolonObject) aCps).getElements()) {
  603. positionToInit.add(hE.isActive());
  604. access.add(new AccessWrapper(hE));
  605. }
  606. }
  607. else if (aCps instanceof HolonSwitch&& algoUseSwitches) {
  608. HolonSwitch sw = (HolonSwitch) aCps;
  609. positionToInit.add(sw.getState(timeStep));
  610. access.add(new AccessWrapper(sw));
  611. }
  612. else if(aCps instanceof GroupNode) {
  613. rollOutNodes(((GroupNode)aCps).getNodes(), positionToInit ,timeStep );
  614. }
  615. }
  616. }
  617. private String stringStatFromActualState() {
  618. if(dGroupNode != null)
  619. {
  620. //GetActualDecoratedGroupNode
  621. dGroupNode = control.getSimManager().getActualVisualRepresentationalState().getCreatedGroupNodes().get(dGroupNode.getModel());
  622. int amountOfSupplier = dGroupNode.getAmountOfSupplier();
  623. int amountOfConsumer = dGroupNode.getAmountOfConsumer();
  624. int amountOfPassiv = dGroupNode.getAmountOfPassiv();
  625. int amountOfObjects = amountOfSupplier + amountOfConsumer + amountOfPassiv;
  626. int unSuppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
  627. int partiallySuppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
  628. int suppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
  629. int overSuppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
  630. int activeElements = dGroupNode.getAmountOfAktiveElemntsFromHolonObjects();
  631. int elements = dGroupNode.getAmountOfElemntsFromHolonObjects();
  632. return "HolonObjects["
  633. + " Producer: " + amountOfSupplier + "/" + amountOfObjects + "("+ (float)amountOfSupplier/(float)amountOfObjects * 100 + "%)"
  634. + " Unsupplied: " + unSuppliedConsumer + "/" + amountOfObjects + "("+ (float)unSuppliedConsumer/(float)amountOfObjects * 100 + "%)"
  635. + " PartiallySupplied: " + partiallySuppliedConsumer + "/" + amountOfObjects + "("+ (float)partiallySuppliedConsumer/(float)amountOfObjects * 100 + "%)"
  636. + " Supplied: " + suppliedConsumer + "/" + amountOfObjects + "("+ (float)suppliedConsumer/(float)amountOfObjects * 100 + "%)"
  637. + " Passiv: " + overSuppliedConsumer + "/" + amountOfObjects + "("+ (float)overSuppliedConsumer/(float)amountOfObjects * 100 + "%)"
  638. + "]" + " HolonElemnts["
  639. + " Active: " + activeElements + "/" + elements + "("+ (float)activeElements/(float)elements * 100 + "%)"
  640. + "]";
  641. }
  642. DecoratedState state = control.getSimManager().getActualDecorState();
  643. int amountOfSupplier = 0, amountOfConsumer = 0, amountOfPassiv = 0, unSuppliedConsumer = 0, partiallySuppliedConsumer = 0, suppliedConsumer = 0, overSuppliedConsumer = 0;
  644. int activeElements = 0, amountOfelements = 0;
  645. int totalConsumption = 0, totalProduction = 0;
  646. for(DecoratedNetwork net : state.getNetworkList()) {
  647. amountOfConsumer += net.getAmountOfConsumer();
  648. amountOfSupplier += net.getAmountOfSupplier();
  649. amountOfPassiv += net.getAmountOfPassiv();
  650. unSuppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
  651. partiallySuppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
  652. suppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
  653. overSuppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
  654. amountOfelements += net.getAmountOfElements();
  655. activeElements += net.getAmountOfActiveElements();
  656. totalConsumption += net.getTotalConsumption();
  657. totalProduction += net.getTotalProduction();
  658. }
  659. int amountOfObjects = amountOfSupplier + amountOfConsumer + amountOfPassiv;
  660. int difference = Math.abs(totalProduction - totalConsumption);
  661. List<Flexibility> flexActiveList = control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.IN_USE).stream().map(flex -> flex.getFlex()).collect(Collectors.toList());
  662. int amountActiveEssential = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Essential).count();
  663. int amountActiveHigh = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.High).count();
  664. int amountActiveMedium = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Medium).count();
  665. int amountActiveLow = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Low).count();
  666. int amountActiveFlexibilities = amountActiveEssential + amountActiveHigh + amountActiveMedium + amountActiveLow;
  667. int amountHolons = state.getNetworkList().size();
  668. int amountSwitch = state.getDecoratedSwitches().size();
  669. int amountActiveSwitch = (int)state.getDecoratedSwitches().stream().filter(dswitch -> (dswitch.getState() == SwitchState.Closed)).count();
  670. return "HolonObjects["
  671. + " Passiv: " + percentage(amountOfPassiv, amountOfObjects)
  672. + " Producer: " + percentage(amountOfSupplier, amountOfObjects)
  673. + " Consumer: " + percentage(amountOfConsumer, amountOfObjects)
  674. + " Unsupplied: " + percentage(unSuppliedConsumer, amountOfConsumer)
  675. + " PartiallySupplied: " + percentage(partiallySuppliedConsumer, amountOfObjects)
  676. + " Supplied: " + percentage(suppliedConsumer, amountOfConsumer)
  677. + " Over: " + percentage(overSuppliedConsumer, amountOfConsumer)
  678. + "]" + " HolonElemnts["
  679. + " Active: " + percentage(activeElements, amountOfelements)
  680. + "]" + "Flexibilities_active["
  681. + " Essential: " + percentage(amountActiveEssential, amountActiveFlexibilities)
  682. + " High: " + percentage(amountActiveHigh, amountActiveFlexibilities)
  683. + " Medium: " + percentage(amountActiveMedium, amountActiveFlexibilities)
  684. + " Low: " + percentage(amountActiveLow, amountActiveFlexibilities)
  685. + "]" + " activeSwitches:" + percentage(amountActiveSwitch,amountSwitch)
  686. + " Holons: " + amountHolons
  687. + " totalConsumption: " + totalConsumption
  688. + " totalProduction: " + totalProduction
  689. + " difference: " + difference;
  690. }
  691. private String percentage(int actual, int max) {
  692. return actual + "/" + max + "("+ (float)actual/(float)max * 100 + "%)";
  693. }
  694. @Override
  695. public JPanel getPanel() {
  696. return content;
  697. }
  698. @Override
  699. public void setController(Control control) {
  700. this.control = control;
  701. }
  702. private class RunProgressBar{
  703. //progressbar
  704. private JProgressBar progressBar = new JProgressBar();
  705. private int count = 0;
  706. private boolean isActive = false;
  707. public void step() {
  708. if(isActive) progressBar.setValue(count++);
  709. }
  710. public void start() {
  711. progressBar.setIndeterminate(false);
  712. count = 0;
  713. isActive = true;
  714. progressBar.setValue(0);
  715. progressBar.setMaximum(getProgressBarMaxCount());
  716. }
  717. public void cancel() {
  718. isActive = false;
  719. progressBar.setIndeterminate(true);
  720. }
  721. public void finishedCancel() {
  722. progressBar.setIndeterminate(false);
  723. progressBar.setValue(0);
  724. }
  725. public JProgressBar getJProgressBar(){
  726. return progressBar;
  727. }
  728. }
  729. protected abstract int getProgressBarMaxCount();
  730. protected abstract String algoInformationToPrint();
  731. protected abstract String plottFileName();
  732. public class Printer{
  733. private JFileChooser fileChooser = new JFileChooser();
  734. private BufferedWriter out;
  735. public Printer(String filename){
  736. fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
  737. fileChooser.setSelectedFile(new File(filename));
  738. }
  739. public void openStream() {
  740. File file = fileChooser.getSelectedFile();
  741. try {
  742. file.createNewFile();
  743. out = new BufferedWriter(new OutputStreamWriter(
  744. new FileOutputStream(file, true), "UTF-8"));
  745. } catch (IOException e) {
  746. System.out.println(e.getMessage());
  747. }
  748. }
  749. public void println(String stringToPrint) {
  750. try {
  751. out.write(stringToPrint);
  752. out.newLine();
  753. } catch (IOException e) {
  754. System.out.println(e.getMessage());
  755. }
  756. }
  757. public void closeStream() {
  758. try {
  759. out.close();
  760. } catch (IOException e) {
  761. System.out.println(e.getMessage());
  762. }
  763. }
  764. }
  765. /**
  766. * A Wrapper Class for Access HolonElement and HolonSwitch in one Element and not have to split the List.
  767. */
  768. private class AccessWrapper {
  769. public static final int HOLONELEMENT = 0;
  770. public static final int SWITCH = 1;
  771. public static final int FLEXIBILITY = 2;
  772. private int type;
  773. private HolonSwitch hSwitch;
  774. private HolonElement hElement;
  775. private Flexibility flex;
  776. public AccessWrapper(HolonSwitch hSwitch){
  777. type = SWITCH;
  778. this.hSwitch = hSwitch;
  779. }
  780. public AccessWrapper(HolonElement hElement){
  781. type = HOLONELEMENT;
  782. this.hElement = hElement;
  783. }
  784. public AccessWrapper(Flexibility flex){
  785. type = FLEXIBILITY;
  786. this.flex = flex;
  787. }
  788. public void setState(boolean state) {
  789. switch(type) {
  790. case HOLONELEMENT:
  791. hElement.setActive(state);
  792. break;
  793. case SWITCH:
  794. hSwitch.setManualMode(true);
  795. hSwitch.setManualState(state);
  796. break;
  797. case FLEXIBILITY:
  798. if(state) {
  799. control.getSimManager().getActualFlexManager().orderFlex(flex);
  800. }
  801. break;
  802. default:
  803. }
  804. }
  805. public String typeString() {
  806. switch(type) {
  807. case HOLONELEMENT:
  808. return "HOLONELEMENT";
  809. case SWITCH:
  810. return "SWITCH";
  811. case FLEXIBILITY:
  812. return "FLEXIBILITY";
  813. default:
  814. return "unknown";
  815. }
  816. }
  817. public String toString() {
  818. return "[" + typeString() + "]";
  819. }
  820. }
  821. /**
  822. * To create Random and maybe switch the random generation in the future.
  823. */
  824. protected static class Random{
  825. private static java.util.Random random = new java.util.Random();
  826. /**
  827. * True or false
  828. * @return the random boolean.
  829. */
  830. public static boolean nextBoolean(){
  831. return random.nextBoolean();
  832. }
  833. /**
  834. * Between 0.0(inclusive) and 1.0 (exclusive)
  835. * @return the random double.
  836. */
  837. public static double nextDouble() {
  838. return random.nextDouble();
  839. }
  840. /**
  841. * Random Int in Range [min;max[ with UniformDistirbution
  842. * @param min
  843. * @param max
  844. * @return
  845. */
  846. public static int nextIntegerInRange(int min, int max) {
  847. int result = min;
  848. try {
  849. result = min + random.nextInt(max - min);
  850. }catch(java.lang.IllegalArgumentException e){
  851. System.err.println("min : " + min + " max : " + max);
  852. System.err.println("max should be more then min");
  853. }
  854. return result;
  855. }
  856. }
  857. private class Handle<T>{
  858. public T object;
  859. Handle(T object){
  860. this.object = object;
  861. }
  862. public String toString() {
  863. return object.toString();
  864. }
  865. }
  866. public class Individual {
  867. public double fitness;
  868. public List<Boolean> position;
  869. public Individual(){};
  870. /**
  871. * Copy Constructor
  872. */
  873. public Individual(Individual c){
  874. position = c.position.stream().collect(Collectors.toList());
  875. fitness = c.fitness;
  876. }
  877. }
  878. protected class ParameterStepping<T>{
  879. boolean useThisParameter = false;
  880. String paramaterName;
  881. private int count = 0;
  882. int stepps;
  883. T stepSize;
  884. T startValue;
  885. Consumer<T> setter;
  886. Supplier<T> getter;
  887. BiFunction<Integer,T,T> multyply;
  888. BiFunction<T,T,T> add;
  889. ParameterStepping(Consumer<T> setter, Supplier<T> getter, BiFunction<T,T,T> add, BiFunction<Integer,T,T> multyply, T stepSize, int stepps){
  890. this.setter = setter;
  891. this.getter = getter;
  892. this.multyply = multyply;
  893. this.add = add;
  894. this.stepSize = stepSize;
  895. this.stepps = stepps;
  896. }
  897. void init() {
  898. startValue = getter.get();
  899. }
  900. boolean canUpdate() {
  901. return count < stepps;
  902. }
  903. void update(){
  904. if(canUpdate()) {
  905. setter.accept(add.apply(startValue, multyply.apply(count + 1, stepSize)));
  906. count ++;
  907. }
  908. }
  909. void reset() {
  910. setter.accept(startValue);
  911. count = 0;
  912. }
  913. }
  914. }