AlgorithmFrameworkFlex.java 39 KB

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