AlgorithmFrameworkFlex.java 33 KB

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