AlgorithmFrameworkFlex.java 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  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. amountOfConsumer += net.getAmountOfConsumer();
  646. amountOfSupplier += net.getAmountOfSupplier();
  647. amountOfPassiv += net.getAmountOfPassiv();
  648. unSuppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
  649. partiallySuppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
  650. suppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
  651. overSuppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
  652. amountOfelements += net.getAmountOfElements();
  653. activeElements += net.getAmountOfActiveElements();
  654. totalConsumption += net.getTotalConsumption();
  655. totalProduction += net.getTotalProduction();
  656. }
  657. int amountOfObjects = amountOfSupplier + amountOfConsumer + amountOfPassiv;
  658. int difference = Math.abs(totalProduction - totalConsumption);
  659. List<Flexibility> flexActiveList = control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.IN_USE).stream().map(flex -> flex.getFlex()).collect(Collectors.toList());
  660. int amountActiveEssential = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Essential).count();
  661. int amountActiveHigh = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.High).count();
  662. int amountActiveMedium = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Medium).count();
  663. int amountActiveLow = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Low).count();
  664. int amountActiveFlexibilities = amountActiveEssential + amountActiveHigh + amountActiveMedium + amountActiveLow;
  665. int amountHolons = state.getNetworkList().size();
  666. int amountSwitch = state.getDecoratedSwitches().size();
  667. int amountActiveSwitch = (int)state.getDecoratedSwitches().stream().filter(dswitch -> (dswitch.getState() == SwitchState.Closed)).count();
  668. DoubleSummaryStatistics overStat = state.getNetworkList().stream().flatMap(net -> {
  669. return net.getConsumerList().stream().filter(con -> con.getState() == HolonObjectState.OVER_SUPPLIED);
  670. }).mapToDouble(con -> con.getSupplyBarPercentage()).summaryStatistics();
  671. DoubleSummaryStatistics partiallyStat = state.getNetworkList().stream().flatMap(net -> {
  672. return net.getConsumerList().stream().filter(con -> con.getState() == HolonObjectState.PARTIALLY_SUPPLIED);
  673. }).mapToDouble(con -> con.getSupplyBarPercentage()).summaryStatistics();
  674. return "HolonObjects["
  675. + " Passiv: " + percentage(amountOfPassiv, amountOfObjects)
  676. + " Producer: " + percentage(amountOfSupplier, amountOfObjects)
  677. + " Consumer: " + percentage(amountOfConsumer, amountOfObjects)
  678. + " Unsupplied: " + percentage(unSuppliedConsumer, amountOfConsumer)
  679. + " PartiallySupplied: " + percentage(partiallySuppliedConsumer, amountOfConsumer)
  680. + " with SupplyPercentage(Min: " + partiallyStat.getMin()
  681. + " Max: "+ partiallyStat.getMax()
  682. + " Average: " +partiallyStat.getAverage() + ")"
  683. + " Supplied: " + percentage(suppliedConsumer, amountOfConsumer)
  684. + " Over: " + percentage(overSuppliedConsumer, amountOfConsumer)
  685. + " with SupplyPercentage(Min: " + overStat.getMin()
  686. + " Max: "+ overStat.getMax()
  687. + " Average: " + overStat.getAverage() + ")"
  688. + "]" + " HolonElemnts["
  689. + " Active: " + percentage(activeElements, amountOfelements)
  690. + "]" + "Flexibilities_active["
  691. + " Essential: " + percentage(amountActiveEssential, amountActiveFlexibilities)
  692. + " High: " + percentage(amountActiveHigh, amountActiveFlexibilities)
  693. + " Medium: " + percentage(amountActiveMedium, amountActiveFlexibilities)
  694. + " Low: " + percentage(amountActiveLow, amountActiveFlexibilities)
  695. + "]" + " activeSwitches:" + percentage(amountActiveSwitch,amountSwitch)
  696. + " Holons: " + amountHolons
  697. + " totalConsumption: " + totalConsumption
  698. + " totalProduction: " + totalProduction
  699. + " difference: " + difference;
  700. }
  701. private String percentage(int actual, int max) {
  702. return actual + "/" + max + "("+ (float)actual/(float)max * 100 + "%)";
  703. }
  704. @Override
  705. public JPanel getPanel() {
  706. return content;
  707. }
  708. @Override
  709. public void setController(Control control) {
  710. this.control = control;
  711. }
  712. private class RunProgressBar{
  713. //progressbar
  714. private JProgressBar progressBar = new JProgressBar();
  715. private int count = 0;
  716. private boolean isActive = false;
  717. public void step() {
  718. if(isActive) progressBar.setValue(count++);
  719. }
  720. public void start() {
  721. progressBar.setIndeterminate(false);
  722. count = 0;
  723. isActive = true;
  724. progressBar.setValue(0);
  725. progressBar.setMaximum(getProgressBarMaxCount());
  726. }
  727. public void cancel() {
  728. isActive = false;
  729. progressBar.setIndeterminate(true);
  730. }
  731. public void finishedCancel() {
  732. progressBar.setIndeterminate(false);
  733. progressBar.setValue(0);
  734. }
  735. public JProgressBar getJProgressBar(){
  736. return progressBar;
  737. }
  738. }
  739. protected abstract int getProgressBarMaxCount();
  740. protected abstract String algoInformationToPrint();
  741. protected abstract String plottFileName();
  742. public class Printer{
  743. private JFileChooser fileChooser = new JFileChooser();
  744. private BufferedWriter out;
  745. public Printer(String filename){
  746. fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
  747. fileChooser.setSelectedFile(new File(filename));
  748. }
  749. public void openStream() {
  750. File file = fileChooser.getSelectedFile();
  751. try {
  752. file.createNewFile();
  753. out = new BufferedWriter(new OutputStreamWriter(
  754. new FileOutputStream(file, true), "UTF-8"));
  755. } catch (IOException e) {
  756. System.out.println(e.getMessage());
  757. }
  758. }
  759. public void println(String stringToPrint) {
  760. try {
  761. out.write(stringToPrint);
  762. out.newLine();
  763. } catch (IOException e) {
  764. System.out.println(e.getMessage());
  765. }
  766. }
  767. public void closeStream() {
  768. try {
  769. out.close();
  770. } catch (IOException e) {
  771. System.out.println(e.getMessage());
  772. }
  773. }
  774. }
  775. /**
  776. * A Wrapper Class for Access HolonElement and HolonSwitch in one Element and not have to split the List.
  777. */
  778. private class AccessWrapper {
  779. public static final int HOLONELEMENT = 0;
  780. public static final int SWITCH = 1;
  781. public static final int FLEXIBILITY = 2;
  782. private int type;
  783. private HolonSwitch hSwitch;
  784. private HolonElement hElement;
  785. private Flexibility flex;
  786. public AccessWrapper(HolonSwitch hSwitch){
  787. type = SWITCH;
  788. this.hSwitch = hSwitch;
  789. }
  790. public AccessWrapper(HolonElement hElement){
  791. type = HOLONELEMENT;
  792. this.hElement = hElement;
  793. }
  794. public AccessWrapper(Flexibility flex){
  795. type = FLEXIBILITY;
  796. this.flex = flex;
  797. }
  798. public void setState(boolean state) {
  799. switch(type) {
  800. case HOLONELEMENT:
  801. hElement.setActive(state);
  802. break;
  803. case SWITCH:
  804. hSwitch.setManualMode(true);
  805. hSwitch.setManualState(state);
  806. break;
  807. case FLEXIBILITY:
  808. if(state) {
  809. control.getSimManager().getActualFlexManager().orderFlex(flex);
  810. }
  811. break;
  812. default:
  813. }
  814. }
  815. public String typeString() {
  816. switch(type) {
  817. case HOLONELEMENT:
  818. return "HOLONELEMENT";
  819. case SWITCH:
  820. return "SWITCH";
  821. case FLEXIBILITY:
  822. return "FLEXIBILITY";
  823. default:
  824. return "unknown";
  825. }
  826. }
  827. public String toString() {
  828. return "[" + typeString() + "]";
  829. }
  830. }
  831. /**
  832. * To create Random and maybe switch the random generation in the future.
  833. */
  834. protected static class Random{
  835. private static java.util.Random random = new java.util.Random();
  836. /**
  837. * True or false
  838. * @return the random boolean.
  839. */
  840. public static boolean nextBoolean(){
  841. return random.nextBoolean();
  842. }
  843. /**
  844. * Between 0.0(inclusive) and 1.0 (exclusive)
  845. * @return the random double.
  846. */
  847. public static double nextDouble() {
  848. return random.nextDouble();
  849. }
  850. /**
  851. * Random Int in Range [min;max[ with UniformDistirbution
  852. * @param min
  853. * @param max
  854. * @return
  855. */
  856. public static int nextIntegerInRange(int min, int max) {
  857. int result = min;
  858. try {
  859. result = min + random.nextInt(max - min);
  860. }catch(java.lang.IllegalArgumentException e){
  861. System.err.println("min : " + min + " max : " + max);
  862. System.err.println("max should be more then min");
  863. }
  864. return result;
  865. }
  866. }
  867. private class Handle<T>{
  868. public T object;
  869. Handle(T object){
  870. this.object = object;
  871. }
  872. public String toString() {
  873. return object.toString();
  874. }
  875. }
  876. public class Individual {
  877. public double fitness;
  878. public List<Boolean> position;
  879. public Individual(){};
  880. /**
  881. * Copy Constructor
  882. */
  883. public Individual(Individual c){
  884. position = c.position.stream().collect(Collectors.toList());
  885. fitness = c.fitness;
  886. }
  887. String positionToString() {
  888. return position.stream().map(bool -> (bool?"1":"0")).collect(Collectors.joining());
  889. }
  890. }
  891. protected class ParameterStepping<T>{
  892. boolean useThisParameter = false;
  893. String paramaterName;
  894. private int count = 0;
  895. int stepps;
  896. T stepSize;
  897. T startValue;
  898. Consumer<T> setter;
  899. Supplier<T> getter;
  900. BiFunction<Integer,T,T> multyply;
  901. BiFunction<T,T,T> add;
  902. ParameterStepping(Consumer<T> setter, Supplier<T> getter, BiFunction<T,T,T> add, BiFunction<Integer,T,T> multyply, T stepSize, int stepps){
  903. this.setter = setter;
  904. this.getter = getter;
  905. this.multyply = multyply;
  906. this.add = add;
  907. this.stepSize = stepSize;
  908. this.stepps = stepps;
  909. }
  910. void init() {
  911. startValue = getter.get();
  912. }
  913. boolean canUpdate() {
  914. return count < stepps;
  915. }
  916. void update(){
  917. if(canUpdate()) {
  918. setter.accept(add.apply(startValue, multyply.apply(count + 1, stepSize)));
  919. count ++;
  920. }
  921. }
  922. void reset() {
  923. setter.accept(startValue);
  924. count = 0;
  925. }
  926. }
  927. }