AlgorithmFrameworkFlex.java 37 KB

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