AlgorithmFrameworkFlex.java 48 KB

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