AlgorithmFrameworkFlex.java 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099
  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.AbstractCpsObject;
  39. import classes.CpsUpperNode;
  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. private Printer logPrinter = new Printer("logFile.txt");
  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, String logString) {
  357. double objectiveFunction = evaluatePosition(positionToEvaluate);
  358. String toPrint = "oF: " + objectiveFunction + " " + logString;
  359. logPrinter.openStream();
  360. logPrinter.println(toPrint);
  361. logPrinter.closeStream();
  362. return objectiveFunction;
  363. }
  364. protected double evaluatePosition(List<Boolean> positionToEvaluate) {
  365. runProgressbar.step();
  366. // long startTime = System.currentTimeMillis(), endTime;
  367. control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration()); // execution time critical
  368. // endTime = System.currentTimeMillis();
  369. // console.print(" a:" + (endTime - startTime));
  370. // startTime = endTime;
  371. setState(positionToEvaluate); // execution time critical
  372. control.calculateStateOnlyForCurrentTimeStep();
  373. DecoratedState actualstate = control.getSimManager().getActualDecorState();
  374. double result = evaluateState(actualstate);
  375. return result;
  376. }
  377. protected abstract double evaluateState(DecoratedState actualstate);
  378. private void run() {
  379. cancel = false;
  380. control.guiDisable(true);
  381. runPrinter.openStream();
  382. runPrinter.println("");
  383. runPrinter.println("Start:" + stringStatFromActualState());
  384. runPrinter.closeStream();
  385. if(this.useStepping) {
  386. initParameterStepping();
  387. do {
  388. executeAlgoWithParameter();
  389. if(cancel) break;
  390. resetState();
  391. }while(updateOneParameter());
  392. resetParameterStepping();
  393. }else {
  394. executeAlgoWithParameter();
  395. }
  396. updateVisual();
  397. runProgressbar.finishedCancel();
  398. control.guiDisable(false);
  399. }
  400. @SuppressWarnings("rawtypes")
  401. private void initParameterStepping() {
  402. for(ParameterStepping param :this.parameterSteppingList) {
  403. param.init();
  404. }
  405. }
  406. @SuppressWarnings("rawtypes")
  407. private void resetParameterStepping() {
  408. for(ParameterStepping param :this.parameterSteppingList) {
  409. param.reset();
  410. }
  411. }
  412. @SuppressWarnings("rawtypes")
  413. private boolean updateOneParameter() {
  414. List<ParameterStepping> parameterInUseList = this.parameterSteppingList.stream().filter(param -> param.useThisParameter).collect(Collectors.toList());
  415. Collections.reverse(parameterInUseList);
  416. int lastParameter = parameterInUseList.size() - 1 ;
  417. int actualParameter = 0;
  418. for(ParameterStepping param : parameterInUseList) {
  419. if(param.canUpdate()) {
  420. param.update();
  421. return true;
  422. }else {
  423. if(actualParameter == lastParameter) break;
  424. param.reset();
  425. }
  426. actualParameter++;
  427. }
  428. //No Param can be updated
  429. return false;
  430. }
  431. private void executeAlgoWithParameter(){
  432. double startFitness = evaluatePosition(extractPositionAndAccess());
  433. console.println("BitLength: " + access.size());
  434. resetChain.removeLast();
  435. runPrinter.openStream();
  436. runPrinter.println("");
  437. runPrinter.println(algoInformationToPrint());
  438. console.println(algoInformationToPrint());
  439. runPrinter.closeStream();
  440. runProgressbar.start();
  441. Individual runBest = new Individual();
  442. runBest.fitness = Double.MAX_VALUE;
  443. for(int r = 0; r < rounds; r++)
  444. {
  445. startTimer();
  446. Individual roundBest = executeAlgo();
  447. if(cancel)return;
  448. long executionTime = printElapsedTime();
  449. runPrinter.openStream();
  450. runPrinter.println(runList.stream().map(Object::toString).collect(Collectors.joining(", ")));
  451. runPrinter.println(stringStatFromActualState());
  452. runPrinter.println("Result: " + roundBest.fitness + " ExecutionTime:" + executionTime);
  453. runPrinter.closeStream();
  454. resetState();
  455. if(roundBest.fitness < runBest.fitness) runBest = roundBest;
  456. }
  457. control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
  458. this.extractPositionAndAccess();
  459. setState(runBest.position);
  460. updateVisual();
  461. console.println("Start: " + startFitness);
  462. console.println("AlgoResult: " + runBest.fitness);
  463. if(this.algoUseFlexes)calculateAndPrintFlexInfos(control.getSimManager().getActualDecorState());
  464. }
  465. private void calculateAndPrintFlexInfos(DecoratedState state) {
  466. int amountOfUsedFlex = 0;
  467. int amountOfFlex = state.getFlexManager().getAllFlexWrapper().size();
  468. float cost = 0;
  469. int consumingFlex = 0;
  470. float consumingFlexEnergy = 0.0f;
  471. int producingFlex = 0;
  472. float producingFlexEnergy = 0.0f;
  473. int maxCooldown = 0;
  474. int amountEssential = 0;
  475. int amountHigh = 0;
  476. int amountMedium = 0;
  477. int amountLow = 0;
  478. for(FlexWrapper flexWrapper :state.getFlexManager().getAllFlexWrapperWithState(FlexState.IN_USE)) {
  479. amountOfUsedFlex++;
  480. cost += flexWrapper.getFlex().cost;
  481. float energy = flexWrapper.getFlex().bringtmir();
  482. if(energy < 0) {
  483. consumingFlex++;
  484. consumingFlexEnergy += -energy;
  485. }else {
  486. producingFlex++;
  487. producingFlexEnergy += energy;
  488. }
  489. if(flexWrapper.getFlex().getCooldown() > maxCooldown) maxCooldown = flexWrapper.getFlex().getCooldown();
  490. switch(flexWrapper.getFlex().getElement().getPriority()) {
  491. case Essential:
  492. amountEssential++;
  493. break;
  494. case High:
  495. amountHigh++;
  496. break;
  497. case Low:
  498. amountLow++;
  499. break;
  500. case Medium:
  501. amountMedium++;
  502. break;
  503. default:
  504. break;
  505. }
  506. }
  507. //Total Flexibilities:
  508. //Used Flexibilities:
  509. console.println("Used Flex [" + amountOfUsedFlex + "/" + amountOfFlex + "]");
  510. //Consuming Flexibilities:
  511. console.println(consumingFlex + " consuimg flexibilities that consumed " + consumingFlexEnergy + "Energy.");
  512. //Producing Flexibilities
  513. console.println(producingFlex + " producing flexibilities that produce " + producingFlexEnergy + "Energy.");
  514. console.println("Flex in use:\t" + "Low= " + amountLow + "\tMedium= " + amountMedium + "\tHigh= " + amountHigh + "\tEssential= " + amountEssential);
  515. //Total cost:
  516. console.println("Total Cost: "+ cost);
  517. //Longest Cooldown
  518. console.println("Max Cooldown: "+ maxCooldown);
  519. //
  520. }
  521. protected abstract Individual executeAlgo();
  522. private void reset() {
  523. if(runThread.isAlive()) {
  524. console.println("Run have to be cancelled First.");
  525. return;
  526. }
  527. if(!resetChain.isEmpty()) {
  528. console.println("Resetting..");
  529. setState(resetChain.getFirst());
  530. control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
  531. resetChain.clear();
  532. control.resetSimulation();
  533. control.setCurIteration(0);
  534. updateVisual();
  535. }else {
  536. console.println("No run inistialized.");
  537. }
  538. }
  539. /**
  540. * To let the User See the current state without touching the Canvas.
  541. */
  542. private void updateVisual() {
  543. control.calculateStateAndVisualForCurrentTimeStep();
  544. }
  545. /**
  546. * Sets the Model back to its original State before the LAST run.
  547. */
  548. private void resetState() {
  549. control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
  550. setState(resetChain.getLast());
  551. }
  552. /**
  553. * Sets the State out of the given position for calculation or to show the user.
  554. * @param position
  555. */
  556. private void setState(List<Boolean> position) {
  557. int i = 0;
  558. for(Boolean bool: position) {
  559. access.get(i++).setState(bool);
  560. }
  561. }
  562. /**
  563. * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
  564. * Also initialize the Access Hashmap to swap faster positions.
  565. * @param model
  566. * @return
  567. */
  568. protected List<Boolean> extractPositionAndAccess() {
  569. Model model = control.getModel();
  570. access= new ArrayList<AccessWrapper>();
  571. List<Boolean> initialState = new ArrayList<Boolean>();
  572. rollOutNodes((dGroupNode != null)? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurIteration());
  573. resetChain.add(initialState);
  574. if(algoUseFlexes) {
  575. for(FlexWrapper flex :control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.OFFERED)){
  576. access.add(new AccessWrapper(flex.getFlex()));
  577. initialState.add(false);
  578. }
  579. for(FlexWrapper flex :control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.IN_USE)){
  580. access.add(new AccessWrapper(flex.getFlex()));
  581. initialState.add(true);
  582. }
  583. }
  584. //console.println(access.stream().map(Object::toString).collect(Collectors.joining(", ")));
  585. return initialState;
  586. }
  587. /**
  588. * Method to extract the Informations recursively out of the Model.
  589. * @param nodes
  590. * @param positionToInit
  591. * @param timeStep
  592. */
  593. private void rollOutNodes(List<AbstractCpsObject> nodes, List<Boolean> positionToInit, int timeStep) {
  594. for(AbstractCpsObject aCps : nodes) {
  595. if (aCps instanceof HolonObject && algoUseElements) {
  596. for (HolonElement hE : ((HolonObject) aCps).getElements()) {
  597. positionToInit.add(hE.isActive());
  598. access.add(new AccessWrapper(hE));
  599. }
  600. }
  601. else if (aCps instanceof HolonSwitch&& algoUseSwitches) {
  602. HolonSwitch sw = (HolonSwitch) aCps;
  603. positionToInit.add(sw.getState(timeStep));
  604. access.add(new AccessWrapper(sw));
  605. }
  606. else if(aCps instanceof CpsUpperNode) {
  607. rollOutNodes(((CpsUpperNode)aCps).getNodes(), positionToInit ,timeStep );
  608. }
  609. }
  610. }
  611. private String stringStatFromActualState() {
  612. if(dGroupNode != null)
  613. {
  614. //GetActualDecoratedGroupNode
  615. dGroupNode = control.getSimManager().getActualVisualRepresentationalState().getCreatedGroupNodes().get(dGroupNode.getModel());
  616. int amountOfSupplier = dGroupNode.getAmountOfSupplier();
  617. int amountOfConsumer = dGroupNode.getAmountOfConsumer();
  618. int amountOfPassiv = dGroupNode.getAmountOfPassiv();
  619. int amountOfObjects = amountOfSupplier + amountOfConsumer + amountOfPassiv;
  620. int unSuppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
  621. int partiallySuppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
  622. int suppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
  623. int overSuppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
  624. int activeElements = dGroupNode.getAmountOfAktiveElemntsFromHolonObjects();
  625. int elements = dGroupNode.getAmountOfElemntsFromHolonObjects();
  626. return "HolonObjects["
  627. + " Producer: " + amountOfSupplier + "/" + amountOfObjects + "("+ (float)amountOfSupplier/(float)amountOfObjects * 100 + "%)"
  628. + " Unsupplied: " + unSuppliedConsumer + "/" + amountOfObjects + "("+ (float)unSuppliedConsumer/(float)amountOfObjects * 100 + "%)"
  629. + " PartiallySupplied: " + partiallySuppliedConsumer + "/" + amountOfObjects + "("+ (float)partiallySuppliedConsumer/(float)amountOfObjects * 100 + "%)"
  630. + " Supplied: " + suppliedConsumer + "/" + amountOfObjects + "("+ (float)suppliedConsumer/(float)amountOfObjects * 100 + "%)"
  631. + " Passiv: " + overSuppliedConsumer + "/" + amountOfObjects + "("+ (float)overSuppliedConsumer/(float)amountOfObjects * 100 + "%)"
  632. + "]" + " HolonElemnts["
  633. + " Active: " + activeElements + "/" + elements + "("+ (float)activeElements/(float)elements * 100 + "%)"
  634. + "]";
  635. }
  636. DecoratedState state = control.getSimManager().getActualDecorState();
  637. int amountOfSupplier = 0, amountOfConsumer = 0, amountOfPassiv = 0, unSuppliedConsumer = 0, partiallySuppliedConsumer = 0, suppliedConsumer = 0, overSuppliedConsumer = 0;
  638. int activeElements = 0, amountOfelements = 0;
  639. int totalConsumption = 0, totalProduction = 0;
  640. for(DecoratedNetwork net : state.getNetworkList()) {
  641. amountOfConsumer += net.getAmountOfConsumer();
  642. amountOfSupplier += net.getAmountOfSupplier();
  643. amountOfPassiv += net.getAmountOfPassiv();
  644. unSuppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
  645. partiallySuppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
  646. suppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
  647. overSuppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
  648. amountOfelements += net.getAmountOfElements();
  649. activeElements += net.getAmountOfActiveElements();
  650. totalConsumption += net.getTotalConsumption();
  651. totalProduction += net.getTotalProduction();
  652. }
  653. int amountOfObjects = amountOfSupplier + amountOfConsumer + amountOfPassiv;
  654. int difference = Math.abs(totalProduction - totalConsumption);
  655. List<Flexibility> flexActiveList = control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.IN_USE).stream().map(flex -> flex.getFlex()).collect(Collectors.toList());
  656. int amountActiveEssential = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Essential).count();
  657. int amountActiveHigh = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.High).count();
  658. int amountActiveMedium = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Medium).count();
  659. int amountActiveLow = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Low).count();
  660. int amountActiveFlexibilities = amountActiveEssential + amountActiveHigh + amountActiveMedium + amountActiveLow;
  661. int amountHolons = state.getNetworkList().size();
  662. int amountSwitch = state.getDecoratedSwitches().size();
  663. int amountActiveSwitch = (int)state.getDecoratedSwitches().stream().filter(dswitch -> (dswitch.getState() == SwitchState.Closed)).count();
  664. return "HolonObjects["
  665. + " Passiv: " + percentage(amountOfPassiv, amountOfObjects)
  666. + " Producer: " + percentage(amountOfSupplier, amountOfObjects)
  667. + " Consumer: " + percentage(amountOfConsumer, amountOfObjects)
  668. + " Unsupplied: " + percentage(unSuppliedConsumer, amountOfConsumer)
  669. + " PartiallySupplied: " + percentage(partiallySuppliedConsumer, amountOfObjects)
  670. + " Supplied: " + percentage(suppliedConsumer, amountOfConsumer)
  671. + " Over: " + percentage(overSuppliedConsumer, amountOfConsumer)
  672. + "]" + " HolonElemnts["
  673. + " Active: " + percentage(activeElements, amountOfelements)
  674. + "]" + "Flexibilities_active["
  675. + " Essential: " + percentage(amountActiveEssential, amountActiveFlexibilities)
  676. + " High: " + percentage(amountActiveHigh, amountActiveFlexibilities)
  677. + " Medium: " + percentage(amountActiveMedium, amountActiveFlexibilities)
  678. + " Low: " + percentage(amountActiveLow, amountActiveFlexibilities)
  679. + "]" + " activeSwitches:" + percentage(amountActiveSwitch,amountSwitch)
  680. + " Holons: " + amountHolons
  681. + " totalConsumption: " + totalConsumption
  682. + " totalProduction: " + totalProduction
  683. + " difference: " + difference;
  684. }
  685. private String percentage(int actual, int max) {
  686. return actual + "/" + max + "("+ (float)actual/(float)max * 100 + "%)";
  687. }
  688. @Override
  689. public JPanel getPanel() {
  690. return content;
  691. }
  692. @Override
  693. public void setController(Control control) {
  694. this.control = control;
  695. }
  696. private class RunProgressBar{
  697. //progressbar
  698. private JProgressBar progressBar = new JProgressBar();
  699. private int count = 0;
  700. private boolean isActive = false;
  701. public void step() {
  702. if(isActive) progressBar.setValue(count++);
  703. }
  704. public void start() {
  705. progressBar.setIndeterminate(false);
  706. count = 0;
  707. isActive = true;
  708. progressBar.setValue(0);
  709. progressBar.setMaximum(getProgressBarMaxCount());
  710. }
  711. public void cancel() {
  712. isActive = false;
  713. progressBar.setIndeterminate(true);
  714. }
  715. public void finishedCancel() {
  716. progressBar.setIndeterminate(false);
  717. progressBar.setValue(0);
  718. }
  719. public JProgressBar getJProgressBar(){
  720. return progressBar;
  721. }
  722. }
  723. protected abstract int getProgressBarMaxCount();
  724. protected abstract String algoInformationToPrint();
  725. protected abstract String plottFileName();
  726. public class Printer{
  727. private JFileChooser fileChooser = new JFileChooser();
  728. private BufferedWriter out;
  729. public Printer(String filename){
  730. fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
  731. fileChooser.setSelectedFile(new File(filename));
  732. }
  733. public void openStream() {
  734. File file = fileChooser.getSelectedFile();
  735. try {
  736. file.createNewFile();
  737. out = new BufferedWriter(new OutputStreamWriter(
  738. new FileOutputStream(file, true), "UTF-8"));
  739. } catch (IOException e) {
  740. System.out.println(e.getMessage());
  741. }
  742. }
  743. public void println(String stringToPrint) {
  744. try {
  745. out.write(stringToPrint);
  746. out.newLine();
  747. } catch (IOException e) {
  748. System.out.println(e.getMessage());
  749. }
  750. }
  751. public void closeStream() {
  752. try {
  753. out.close();
  754. } catch (IOException e) {
  755. System.out.println(e.getMessage());
  756. }
  757. }
  758. }
  759. /**
  760. * A Wrapper Class for Access HolonElement and HolonSwitch in one Element and not have to split the List.
  761. */
  762. private class AccessWrapper {
  763. public static final int HOLONELEMENT = 0;
  764. public static final int SWITCH = 1;
  765. public static final int FLEXIBILITY = 2;
  766. private int type;
  767. private HolonSwitch hSwitch;
  768. private HolonElement hElement;
  769. private Flexibility flex;
  770. public AccessWrapper(HolonSwitch hSwitch){
  771. type = SWITCH;
  772. this.hSwitch = hSwitch;
  773. }
  774. public AccessWrapper(HolonElement hElement){
  775. type = HOLONELEMENT;
  776. this.hElement = hElement;
  777. }
  778. public AccessWrapper(Flexibility flex){
  779. type = FLEXIBILITY;
  780. this.flex = flex;
  781. }
  782. public void setState(boolean state) {
  783. switch(type) {
  784. case HOLONELEMENT:
  785. hElement.setActive(state);
  786. break;
  787. case SWITCH:
  788. hSwitch.setManualMode(true);
  789. hSwitch.setManualState(state);
  790. break;
  791. case FLEXIBILITY:
  792. if(state) {
  793. control.getSimManager().getActualFlexManager().orderFlex(flex);
  794. }
  795. break;
  796. default:
  797. }
  798. }
  799. public String typeString() {
  800. switch(type) {
  801. case HOLONELEMENT:
  802. return "HOLONELEMENT";
  803. case SWITCH:
  804. return "SWITCH";
  805. case FLEXIBILITY:
  806. return "FLEXIBILITY";
  807. default:
  808. return "unknown";
  809. }
  810. }
  811. public String toString() {
  812. return "[" + typeString() + "]";
  813. }
  814. }
  815. /**
  816. * To create Random and maybe switch the random generation in the future.
  817. */
  818. protected static class Random{
  819. private static java.util.Random random = new java.util.Random();
  820. /**
  821. * True or false
  822. * @return the random boolean.
  823. */
  824. public static boolean nextBoolean(){
  825. return random.nextBoolean();
  826. }
  827. /**
  828. * Between 0.0(inclusive) and 1.0 (exclusive)
  829. * @return the random double.
  830. */
  831. public static double nextDouble() {
  832. return random.nextDouble();
  833. }
  834. /**
  835. * Random Int in Range [min;max[ with UniformDistirbution
  836. * @param min
  837. * @param max
  838. * @return
  839. */
  840. public static int nextIntegerInRange(int min, int max) {
  841. int result = min;
  842. try {
  843. result = min + random.nextInt(max - min);
  844. }catch(java.lang.IllegalArgumentException e){
  845. System.err.println("min : " + min + " max : " + max);
  846. System.err.println("max should be more then min");
  847. }
  848. return result;
  849. }
  850. }
  851. private class Handle<T>{
  852. public T object;
  853. Handle(T object){
  854. this.object = object;
  855. }
  856. public String toString() {
  857. return object.toString();
  858. }
  859. }
  860. public class Individual {
  861. public double fitness;
  862. public List<Boolean> position;
  863. public Individual(){};
  864. /**
  865. * Copy Constructor
  866. */
  867. public Individual(Individual c){
  868. position = c.position.stream().collect(Collectors.toList());
  869. fitness = c.fitness;
  870. }
  871. }
  872. protected class ParameterStepping<T>{
  873. boolean useThisParameter = false;
  874. String paramaterName;
  875. private int count = 0;
  876. int stepps;
  877. T stepSize;
  878. T startValue;
  879. Consumer<T> setter;
  880. Supplier<T> getter;
  881. BiFunction<Integer,T,T> multyply;
  882. BiFunction<T,T,T> add;
  883. ParameterStepping(Consumer<T> setter, Supplier<T> getter, BiFunction<T,T,T> add, BiFunction<Integer,T,T> multyply, T stepSize, int stepps){
  884. this.setter = setter;
  885. this.getter = getter;
  886. this.multyply = multyply;
  887. this.add = add;
  888. this.stepSize = stepSize;
  889. this.stepps = stepps;
  890. }
  891. void init() {
  892. startValue = getter.get();
  893. }
  894. boolean canUpdate() {
  895. return count < stepps;
  896. }
  897. void update(){
  898. if(canUpdate()) {
  899. setter.accept(add.apply(startValue, multyply.apply(count + 1, stepSize)));
  900. count ++;
  901. }
  902. }
  903. void reset() {
  904. setter.accept(startValue);
  905. count = 0;
  906. }
  907. }
  908. }