AlgorithmFrameworkFlex.java 48 KB

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