AlgorithmFrameworkFlex.java 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  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. resetChain.removeLast();
  432. runPrinter.println(algoInformationToPrint());
  433. runProgressbar.start();
  434. Individual runBest = new Individual();
  435. runBest.fitness = Double.MAX_VALUE;
  436. for(int r = 0; r < rounds; r++)
  437. {
  438. startTimer();
  439. Individual roundBest = executeAlgo();
  440. long executionTime = printElapsedTime();
  441. runPrinter.println(runList.stream().map(Object::toString).collect(Collectors.joining(", ")));
  442. runPrinter.println(stringStatFromActualState());
  443. runPrinter.println("ExecutionTime:" + executionTime);
  444. if(cancel)return;
  445. resetState();
  446. if(roundBest.fitness < runBest.fitness) runBest = roundBest;
  447. }
  448. control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
  449. this.extractPositionAndAccess();
  450. setState(runBest.position);
  451. updateVisual();
  452. console.println("Start: " + startFitness);
  453. console.println("AlgoResult: " + runBest.fitness);
  454. if(this.algoUseFlexes)calculateAndPrintFlexInfos(control.getSimManager().getActualDecorState());
  455. }
  456. private void calculateAndPrintFlexInfos(DecoratedState state) {
  457. int amountOfUsedFlex = 0;
  458. int amountOfFlex = state.getFlexManager().getAllFlexWrapper().size();
  459. float cost = 0;
  460. int consumingFlex = 0;
  461. float consumingFlexEnergy = 0.0f;
  462. int producingFlex = 0;
  463. float producingFlexEnergy = 0.0f;
  464. int maxCooldown = 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. }
  478. //Total Flexibilities:
  479. //Used Flexibilities:
  480. console.println("Used Flex [" + amountOfUsedFlex + "/" + amountOfFlex + "]");
  481. //Consuming Flexibilities:
  482. console.println(consumingFlex + " consuimg flexibilities that consumed " + consumingFlexEnergy + "Energy.");
  483. //Producing Flexibilities
  484. console.println(producingFlex + " producing flexibilities that produce " + producingFlexEnergy + "Energy.");
  485. //Total cost:
  486. console.println("Total Cost: "+ cost);
  487. //Longest Cooldown
  488. console.println("Max Cooldown: "+ maxCooldown);
  489. //
  490. }
  491. protected abstract Individual executeAlgo();
  492. private void reset() {
  493. if(runThread.isAlive()) {
  494. console.println("Run have to be cancelled First.");
  495. return;
  496. }
  497. if(!resetChain.isEmpty()) {
  498. console.println("Resetting..");
  499. setState(resetChain.getFirst());
  500. control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
  501. resetChain.clear();
  502. control.resetSimulation();
  503. control.setCurIteration(0);
  504. updateVisual();
  505. }else {
  506. console.println("No run inistialized.");
  507. }
  508. }
  509. /**
  510. * To let the User See the current state without touching the Canvas.
  511. */
  512. private void updateVisual() {
  513. control.calculateStateAndVisualForCurrentTimeStep();
  514. }
  515. /**
  516. * Sets the Model back to its original State before the LAST run.
  517. */
  518. private void resetState() {
  519. control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
  520. setState(resetChain.getLast());
  521. }
  522. /**
  523. * Sets the State out of the given position for calculation or to show the user.
  524. * @param position
  525. */
  526. private void setState(List<Boolean> position) {
  527. int i = 0;
  528. for(Boolean bool: position) {
  529. access.get(i++).setState(bool);
  530. }
  531. }
  532. /**
  533. * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
  534. * Also initialize the Access Hashmap to swap faster positions.
  535. * @param model
  536. * @return
  537. */
  538. protected List<Boolean> extractPositionAndAccess() {
  539. Model model = control.getModel();
  540. access= new ArrayList<AccessWrapper>();
  541. List<Boolean> initialState = new ArrayList<Boolean>();
  542. rollOutNodes((dGroupNode != null)? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurIteration());
  543. resetChain.add(initialState);
  544. if(algoUseFlexes) {
  545. for(FlexWrapper flex :control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.OFFERED)){
  546. access.add(new AccessWrapper(flex.getFlex()));
  547. initialState.add(false);
  548. }
  549. for(FlexWrapper flex :control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.IN_USE)){
  550. access.add(new AccessWrapper(flex.getFlex()));
  551. initialState.add(true);
  552. }
  553. }
  554. //console.println(access.stream().map(Object::toString).collect(Collectors.joining(", ")));
  555. return initialState;
  556. }
  557. /**
  558. * Method to extract the Informations recursively out of the Model.
  559. * @param nodes
  560. * @param positionToInit
  561. * @param timeStep
  562. */
  563. private void rollOutNodes(List<AbstractCpsObject> nodes, List<Boolean> positionToInit, int timeStep) {
  564. for(AbstractCpsObject aCps : nodes) {
  565. if (aCps instanceof HolonObject && algoUseElements) {
  566. for (HolonElement hE : ((HolonObject) aCps).getElements()) {
  567. positionToInit.add(hE.isActive());
  568. access.add(new AccessWrapper(hE));
  569. }
  570. }
  571. else if (aCps instanceof HolonSwitch&& algoUseSwitches) {
  572. HolonSwitch sw = (HolonSwitch) aCps;
  573. positionToInit.add(sw.getState(timeStep));
  574. access.add(new AccessWrapper(sw));
  575. }
  576. else if(aCps instanceof CpsUpperNode) {
  577. rollOutNodes(((CpsUpperNode)aCps).getNodes(), positionToInit ,timeStep );
  578. }
  579. }
  580. }
  581. private String stringStatFromActualState() {
  582. if(dGroupNode != null)
  583. {
  584. //GetActualDecoratedGroupNode
  585. dGroupNode = control.getSimManager().getActualVisualRepresentationalState().getCreatedGroupNodes().get(dGroupNode.getModel());
  586. int amountOfSupplier = dGroupNode.getAmountOfSupplier();
  587. int amountOfConsumer = dGroupNode.getAmountOfConsumer();
  588. int amountOfPassiv = dGroupNode.getAmountOfPassiv();
  589. int amountOfObjects = amountOfSupplier + amountOfConsumer + amountOfPassiv;
  590. int unSuppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
  591. int partiallySuppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
  592. int suppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
  593. int overSuppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
  594. int activeElements = dGroupNode.getAmountOfAktiveElemntsFromHolonObjects();
  595. int elements = dGroupNode.getAmountOfElemntsFromHolonObjects();
  596. return "HolonObjects["
  597. + " Producer: " + amountOfSupplier + "/" + amountOfObjects + "("+ (float)amountOfSupplier/(float)amountOfObjects * 100 + "%)"
  598. + " Unsupplied: " + unSuppliedConsumer + "/" + amountOfObjects + "("+ (float)unSuppliedConsumer/(float)amountOfObjects * 100 + "%)"
  599. + " PartiallySupplied: " + partiallySuppliedConsumer + "/" + amountOfObjects + "("+ (float)partiallySuppliedConsumer/(float)amountOfObjects * 100 + "%)"
  600. + " Supplied: " + suppliedConsumer + "/" + amountOfObjects + "("+ (float)suppliedConsumer/(float)amountOfObjects * 100 + "%)"
  601. + " Passiv: " + overSuppliedConsumer + "/" + amountOfObjects + "("+ (float)overSuppliedConsumer/(float)amountOfObjects * 100 + "%)"
  602. + "]" + " HolonElemnts["
  603. + " Active: " + activeElements + "/" + elements + "("+ (float)activeElements/(float)elements * 100 + "%)"
  604. + "]";
  605. }
  606. return "[No GroupNode Use == No detailed Info]";
  607. }
  608. @Override
  609. public JPanel getPanel() {
  610. return content;
  611. }
  612. @Override
  613. public void setController(Control control) {
  614. this.control = control;
  615. }
  616. private class RunProgressBar{
  617. //progressbar
  618. private JProgressBar progressBar = new JProgressBar();
  619. private int count = 0;
  620. private boolean isActive = false;
  621. public void step() {
  622. if(isActive) progressBar.setValue(count++);
  623. }
  624. public void start() {
  625. progressBar.setIndeterminate(false);
  626. count = 0;
  627. isActive = true;
  628. progressBar.setValue(0);
  629. progressBar.setMaximum(getProgressBarMaxCount());
  630. }
  631. public void cancel() {
  632. isActive = false;
  633. progressBar.setIndeterminate(true);
  634. }
  635. public void finishedCancel() {
  636. progressBar.setIndeterminate(false);
  637. progressBar.setValue(0);
  638. }
  639. public JProgressBar getJProgressBar(){
  640. return progressBar;
  641. }
  642. }
  643. protected abstract int getProgressBarMaxCount();
  644. protected abstract String algoInformationToPrint();
  645. protected abstract String plottFileName();
  646. public class Printer{
  647. private JFileChooser fileChooser = new JFileChooser();
  648. private BufferedWriter out;
  649. public Printer(String filename){
  650. fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
  651. fileChooser.setSelectedFile(new File(filename));
  652. }
  653. public void openStream() {
  654. File file = fileChooser.getSelectedFile();
  655. try {
  656. file.createNewFile();
  657. out = new BufferedWriter(new OutputStreamWriter(
  658. new FileOutputStream(file, true), "UTF-8"));
  659. } catch (IOException e) {
  660. System.out.println(e.getMessage());
  661. }
  662. }
  663. public void println(String stringToPrint) {
  664. try {
  665. out.write(stringToPrint);
  666. out.newLine();
  667. } catch (IOException e) {
  668. System.out.println(e.getMessage());
  669. }
  670. }
  671. public void closeStream() {
  672. try {
  673. out.close();
  674. } catch (IOException e) {
  675. System.out.println(e.getMessage());
  676. }
  677. }
  678. }
  679. /**
  680. * A Wrapper Class for Access HolonElement and HolonSwitch in one Element and not have to split the List.
  681. */
  682. private class AccessWrapper {
  683. public static final int HOLONELEMENT = 0;
  684. public static final int SWITCH = 1;
  685. public static final int FLEXIBILITY = 2;
  686. private int type;
  687. private HolonSwitch hSwitch;
  688. private HolonElement hElement;
  689. private Flexibility flex;
  690. public AccessWrapper(HolonSwitch hSwitch){
  691. type = SWITCH;
  692. this.hSwitch = hSwitch;
  693. }
  694. public AccessWrapper(HolonElement hElement){
  695. type = HOLONELEMENT;
  696. this.hElement = hElement;
  697. }
  698. public AccessWrapper(Flexibility flex){
  699. type = FLEXIBILITY;
  700. this.flex = flex;
  701. }
  702. public void setState(boolean state) {
  703. switch(type) {
  704. case HOLONELEMENT:
  705. hElement.setActive(state);
  706. break;
  707. case SWITCH:
  708. hSwitch.setManualMode(true);
  709. hSwitch.setManualState(state);
  710. break;
  711. case FLEXIBILITY:
  712. if(state) {
  713. control.getSimManager().getActualFlexManager().orderFlex(flex);
  714. }
  715. break;
  716. default:
  717. }
  718. }
  719. public String typeString() {
  720. switch(type) {
  721. case HOLONELEMENT:
  722. return "HOLONELEMENT";
  723. case SWITCH:
  724. return "SWITCH";
  725. case FLEXIBILITY:
  726. return "FLEXIBILITY";
  727. default:
  728. return "unknown";
  729. }
  730. }
  731. public String toString() {
  732. return "[" + typeString() + "]";
  733. }
  734. }
  735. /**
  736. * To create Random and maybe switch the random generation in the future.
  737. */
  738. protected static class Random{
  739. private static java.util.Random random = new java.util.Random();
  740. /**
  741. * True or false
  742. * @return the random boolean.
  743. */
  744. public static boolean nextBoolean(){
  745. return random.nextBoolean();
  746. }
  747. /**
  748. * Between 0.0(inclusive) and 1.0 (exclusive)
  749. * @return the random double.
  750. */
  751. public static double nextDouble() {
  752. return random.nextDouble();
  753. }
  754. /**
  755. * Random Int in Range [min;max[ with UniformDistirbution
  756. * @param min
  757. * @param max
  758. * @return
  759. */
  760. public static int nextIntegerInRange(int min, int max) {
  761. return min + random.nextInt(max - min);
  762. }
  763. }
  764. private class Handle<T>{
  765. public T object;
  766. Handle(T object){
  767. this.object = object;
  768. }
  769. public String toString() {
  770. return object.toString();
  771. }
  772. }
  773. public class Individual {
  774. public double fitness;
  775. public List<Boolean> position;
  776. public Individual(){};
  777. /**
  778. * Copy Constructor
  779. */
  780. public Individual(Individual c){
  781. position = c.position.stream().collect(Collectors.toList());
  782. fitness = c.fitness;
  783. }
  784. }
  785. protected class ParameterStepping<T>{
  786. boolean useThisParameter = false;
  787. String paramaterName;
  788. private int count = 0;
  789. int stepps;
  790. T stepSize;
  791. T startValue;
  792. Consumer<T> setter;
  793. Supplier<T> getter;
  794. BiFunction<Integer,T,T> multyply;
  795. BiFunction<T,T,T> add;
  796. ParameterStepping(Consumer<T> setter, Supplier<T> getter, BiFunction<T,T,T> add, BiFunction<Integer,T,T> multyply, T stepSize, int stepps){
  797. this.setter = setter;
  798. this.getter = getter;
  799. this.multyply = multyply;
  800. this.add = add;
  801. this.stepSize = stepSize;
  802. this.stepps = stepps;
  803. }
  804. void init() {
  805. startValue = getter.get();
  806. }
  807. boolean canUpdate() {
  808. return count < stepps;
  809. }
  810. void update(){
  811. if(canUpdate()) {
  812. setter.accept(add.apply(startValue, multyply.apply(count + 1, stepSize)));
  813. count ++;
  814. }
  815. }
  816. void reset() {
  817. setter.accept(startValue);
  818. count = 0;
  819. }
  820. }
  821. }