AlgorithmFrameworkFlex.java 33 KB

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