AlgorithmFrameworkFlex.java 31 KB

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