AlgorithmFrameworkFlex.java 38 KB

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