AlgorithmFrameworkFlex.java 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364
  1. package api;
  2. import java.awt.BorderLayout;
  3. import java.awt.Component;
  4. import java.awt.Dimension;
  5. import java.awt.FlowLayout;
  6. import java.awt.image.BufferedImage;
  7. import java.io.BufferedWriter;
  8. import java.io.File;
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11. import java.io.OutputStreamWriter;
  12. import java.math.RoundingMode;
  13. import java.text.NumberFormat;
  14. import java.util.ArrayList;
  15. import java.util.Collections;
  16. import java.util.DoubleSummaryStatistics;
  17. import java.util.HashMap;
  18. import java.util.LinkedList;
  19. import java.util.List;
  20. import java.util.Locale;
  21. import java.util.function.BiFunction;
  22. import java.util.function.Consumer;
  23. import java.util.function.Supplier;
  24. import java.util.stream.Collectors;
  25. import javax.swing.BorderFactory;
  26. import javax.swing.Box;
  27. import javax.swing.BoxLayout;
  28. import javax.swing.ImageIcon;
  29. import javax.swing.JButton;
  30. import javax.swing.JCheckBox;
  31. import javax.swing.JComboBox;
  32. import javax.swing.JFileChooser;
  33. import javax.swing.JFormattedTextField;
  34. import javax.swing.JLabel;
  35. import javax.swing.JOptionPane;
  36. import javax.swing.JPanel;
  37. import javax.swing.JProgressBar;
  38. import javax.swing.JScrollPane;
  39. import javax.swing.JSplitPane;
  40. import javax.swing.text.NumberFormatter;
  41. import algorithm.objectiveFunction.ObjectiveFunctionByCarlos;
  42. import algorithm.objectiveFunction.SwitchObjectiveFunction;
  43. import classes.AbstractCanvasObject;
  44. import classes.GroupNode;
  45. import classes.Flexibility;
  46. import classes.HolonElement;
  47. import classes.HolonObject;
  48. import classes.HolonSwitch;
  49. import classes.HolonElement.Priority;
  50. import ui.controller.Control;
  51. import ui.controller.FlexManager.FlexState;
  52. import ui.controller.FlexManager.FlexWrapper;
  53. import ui.model.DecoratedGroupNode;
  54. import ui.model.DecoratedState;
  55. import ui.model.Model;
  56. import ui.model.DecoratedHolonObject.HolonObjectState;
  57. import ui.model.DecoratedSwitch.SwitchState;
  58. import ui.model.DecoratedNetwork;
  59. import ui.view.Console;
  60. import utility.ImageImport;
  61. import utility.StringFormat;
  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 useKillSwitches = new JCheckBox("KillSwitch");
  146. useKillSwitches.setSelected(algoUseFlexes);
  147. useKillSwitches.setBounds(900, 130, 185, 20);
  148. useKillSwitches.addActionListener(actionEvent ->
  149. {
  150. cancel();
  151. reset();
  152. algoUseKillSwitch = useKillSwitches.isSelected();
  153. });
  154. parameterPanel.add(useKillSwitches);
  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 before the Algorithm has runed.");
  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("Fitness");
  190. fitnessButton.setToolTipText("Fitness for the current state.");
  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("StepsSize: ");
  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("StepsSize: ");
  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 of Algo 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. Object[] possibilities = control.getSimManager().getActualVisualRepresentationalState().getCreatedGroupNodes().values().stream().map(aCps -> new Handle<DecoratedGroupNode>(aCps)).toArray();
  394. @SuppressWarnings("unchecked")
  395. 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, "");
  396. if(selected != null) {
  397. console.println("Selected: " + selected);
  398. dGroupNode = selected.object;
  399. }
  400. }
  401. protected double evaluatePosition(List<Boolean> positionToEvaluate) {
  402. runProgressbar.step();
  403. setState(positionToEvaluate); // execution time critical
  404. DecoratedState actualstate = control.getSimManager().getActualDecorState();
  405. double result = evaluateState(actualstate);
  406. return result;
  407. }
  408. private double evaluateState(DecoratedState actualstate) {
  409. switch(this.evaluationFunction) {
  410. case Switch:
  411. return SwitchObjectiveFunction.getFitnessValueForState(actualstate);
  412. case Normal:
  413. default:
  414. return ObjectiveFunctionByCarlos.getFitnessValueForState(actualstate);
  415. }
  416. }
  417. private void run() {
  418. cancel = false;
  419. control.guiDisable(true);
  420. runPrinter.openStream();
  421. runPrinter.println("");
  422. runPrinter.println("Start:" + stringStatFromRunValues(getRunValuesFromActualState()));
  423. runPrinter.closeStream();
  424. if(this.useStepping) {
  425. initParameterStepping();
  426. do {
  427. executeAlgoWithParameter();
  428. if(cancel) break;
  429. resetState();
  430. }while(updateOneParameter());
  431. resetParameterStepping();
  432. }else {
  433. executeAlgoWithParameter();
  434. }
  435. updateVisual();
  436. runProgressbar.finishedCancel();
  437. control.guiDisable(false);
  438. if(this.useEmailNotification && !cancel) {
  439. EmailNotification.sendEmail(this.getClass().getName() + " finished", "Execution done.");
  440. }
  441. }
  442. @SuppressWarnings("rawtypes")
  443. private void initParameterStepping() {
  444. for(ParameterStepping param :this.parameterSteppingList) {
  445. param.init();
  446. }
  447. }
  448. @SuppressWarnings("rawtypes")
  449. private void resetParameterStepping() {
  450. for(ParameterStepping param :this.parameterSteppingList) {
  451. param.reset();
  452. }
  453. }
  454. @SuppressWarnings("rawtypes")
  455. private boolean updateOneParameter() {
  456. List<ParameterStepping> parameterInUseList = this.parameterSteppingList.stream().filter(param -> param.useThisParameter).collect(Collectors.toList());
  457. Collections.reverse(parameterInUseList);
  458. int lastParameter = parameterInUseList.size() - 1 ;
  459. int actualParameter = 0;
  460. for(ParameterStepping param : parameterInUseList) {
  461. if(param.canUpdate()) {
  462. param.update();
  463. return true;
  464. }else {
  465. if(actualParameter == lastParameter) break;
  466. param.reset();
  467. }
  468. actualParameter++;
  469. }
  470. //No Param can be updated
  471. return false;
  472. }
  473. private void executeAlgoWithParameter(){
  474. double startFitness = evaluatePosition(extractPositionAndAccess());
  475. console.println("BitLength: " + access.size());
  476. resetChain.removeLast();
  477. runPrinter.openStream();
  478. runPrinter.println(algoInformationToPrint());
  479. console.println(algoInformationToPrint());
  480. runPrinter.closeStream();
  481. runProgressbar.start();
  482. Individual runBest = new Individual();
  483. runBest.fitness = Double.MAX_VALUE;
  484. this.avg = new RunAverage();
  485. for(int r = 0; r < rounds; r++)
  486. {
  487. startTimer();
  488. Individual roundBest = executeAlgo();
  489. if(cancel)return;
  490. long executionTime = printElapsedTime();
  491. setState(roundBest.position);
  492. runPrinter.openStream();
  493. runPrinter.println(runList.stream().map(value -> StringFormat.doubleFixedPlaces(2,value)).collect(Collectors.joining(", ")));
  494. RunValues val = getRunValuesFromActualState();
  495. val.result = roundBest.fitness;
  496. val.executionTime = executionTime;
  497. avg.addRun(val);
  498. runPrinter.println("Result: " + StringFormat.doubleFixedPlaces(2,roundBest.fitness) + " ExecutionTime:" + executionTime + " " + stringStatFromRunValues(val));
  499. runPrinter.closeStream();
  500. resetState();
  501. if(roundBest.fitness < runBest.fitness) runBest = roundBest;
  502. }
  503. control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
  504. this.extractPositionAndAccess();
  505. setState(runBest.position);
  506. updateVisual();
  507. console.println("Start: " + StringFormat.doubleFixedPlaces(2,startFitness));
  508. console.println("AlgoResult: " + StringFormat.doubleFixedPlaces(2,runBest.fitness));
  509. if(this.algoUseFlexes)calculateAndPrintFlexInfos(control.getSimManager().getActualDecorState());
  510. runPrinter.openStream();
  511. if(rounds > 1) {
  512. RunValues avgRun = avg.getAverage();
  513. runPrinter.println("Average.Result: " + StringFormat.doubleFixedPlaces(2, avgRun.result) + " Average.ExecutionTime:" + avgRun.executionTime + " " + this.stringStatFromRunValues(avg.getAverage(), "Average."));
  514. }
  515. runPrinter.println("");
  516. runPrinter.closeStream();
  517. }
  518. private void calculateAndPrintFlexInfos(DecoratedState state) {
  519. int amountOfUsedFlex = 0;
  520. int amountOfFlex = state.getFlexManager().getAllFlexWrapper().size();
  521. float cost = 0;
  522. int consumingFlex = 0;
  523. float consumingFlexEnergy = 0.0f;
  524. int producingFlex = 0;
  525. float producingFlexEnergy = 0.0f;
  526. int maxCooldown = 0;
  527. int amountEssential = 0;
  528. int amountHigh = 0;
  529. int amountMedium = 0;
  530. int amountLow = 0;
  531. for(FlexWrapper flexWrapper :state.getFlexManager().getAllFlexWrapperWithState(FlexState.IN_USE)) {
  532. amountOfUsedFlex++;
  533. cost += flexWrapper.getFlex().cost;
  534. float energy = flexWrapper.getFlex().bringtmir();
  535. if(energy < 0) {
  536. consumingFlex++;
  537. consumingFlexEnergy += -energy;
  538. }else {
  539. producingFlex++;
  540. producingFlexEnergy += energy;
  541. }
  542. if(flexWrapper.getFlex().getCooldown() > maxCooldown) maxCooldown = flexWrapper.getFlex().getCooldown();
  543. switch(flexWrapper.getFlex().getElement().getPriority()) {
  544. case Essential:
  545. amountEssential++;
  546. break;
  547. case High:
  548. amountHigh++;
  549. break;
  550. case Low:
  551. amountLow++;
  552. break;
  553. case Medium:
  554. amountMedium++;
  555. break;
  556. default:
  557. break;
  558. }
  559. }
  560. //Total Flexibilities:
  561. //Used Flexibilities:
  562. console.println("Used Flex [" + amountOfUsedFlex + "/" + amountOfFlex + "]");
  563. //Consuming Flexibilities:
  564. console.println(consumingFlex + " consuimg flexibilities that consumed " + consumingFlexEnergy + "Energy.");
  565. //Producing Flexibilities
  566. console.println(producingFlex + " producing flexibilities that produce " + producingFlexEnergy + "Energy.");
  567. console.println("Flex in use:\t" + "Low= " + amountLow + "\tMedium= " + amountMedium + "\tHigh= " + amountHigh + "\tEssential= " + amountEssential);
  568. //Total cost:
  569. console.println("Total Cost: "+ cost);
  570. //Longest Cooldown
  571. console.println("Max Cooldown: "+ maxCooldown);
  572. //
  573. }
  574. protected abstract Individual executeAlgo();
  575. private void reset() {
  576. if(runThread.isAlive()) {
  577. console.println("Run have to be cancelled First.");
  578. return;
  579. }
  580. if(!resetChain.isEmpty()) {
  581. console.println("Resetting..");
  582. setState(resetChain.getFirst());
  583. resetChain.clear();
  584. control.resetSimulation();
  585. control.setCurIteration(0);
  586. updateVisual();
  587. }else {
  588. console.println("No run inistialized.");
  589. }
  590. }
  591. /**
  592. * To let the User See the current state without touching the Canvas.
  593. */
  594. private void updateVisual() {
  595. control.calculateStateAndVisualForCurrentTimeStep();
  596. }
  597. /**
  598. * Sets the Model back to its original State before the LAST run.
  599. */
  600. private void resetState() {
  601. setState(resetChain.getLast());
  602. }
  603. /**
  604. * Sets the State out of the given position for calculation or to show the user.
  605. * @param position
  606. */
  607. private void setState(List<Boolean> position) {
  608. control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
  609. int i = 0;
  610. for(Boolean bool: position) {
  611. access.get(i++).setState(bool);
  612. }
  613. control.calculateStateOnlyForCurrentTimeStep();
  614. }
  615. /**
  616. * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
  617. * Also initialize the Access Hashmap to swap faster positions.
  618. * @param model
  619. * @return
  620. */
  621. protected List<Boolean> extractPositionAndAccess() {
  622. Model model = control.getModel();
  623. this.accessKillSwitch = new HashMap<HolonObject, AccessWrapper>();
  624. access= new ArrayList<AccessWrapper>();
  625. List<Boolean> initialState = new ArrayList<Boolean>();
  626. rollOutNodes((dGroupNode != null)? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurIteration());
  627. resetChain.add(initialState);
  628. if(algoUseFlexes) {
  629. for(FlexWrapper flex :control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.OFFERED)){
  630. //flex.getFlex().getElement().parentObject;
  631. AccessWrapper killSwitchAccess = this.algoUseKillSwitch ? this.accessKillSwitch.get(flex.getFlex().getElement().parentObject): null;;
  632. access.add(new AccessWrapper(flex.getFlex(), killSwitchAccess));
  633. initialState.add(false);
  634. }
  635. for(FlexWrapper flex :control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.IN_USE)){
  636. AccessWrapper killSwitchAccess = this.algoUseKillSwitch ? this.accessKillSwitch.get(flex.getFlex().getElement().parentObject): null;
  637. access.add(new AccessWrapper(flex.getFlex(), killSwitchAccess));
  638. initialState.add(true);
  639. }
  640. }
  641. //console.println(access.stream().map(Object::toString).collect(Collectors.joining(", ")));
  642. return initialState;
  643. }
  644. /**
  645. * Method to extract the Informations recursively out of the Model.
  646. * @param nodes
  647. * @param positionToInit
  648. * @param timeStep
  649. */
  650. private void rollOutNodes(List<AbstractCanvasObject> nodes, List<Boolean> positionToInit, int timeStep) {
  651. for(AbstractCanvasObject aCps : nodes) {
  652. if (aCps instanceof HolonObject) {
  653. HolonObject hObject = (HolonObject) aCps;
  654. AccessWrapper killSwitchAccess = new AccessWrapper(hObject);
  655. if(this.algoUseKillSwitch) {
  656. positionToInit.add(false);
  657. access.add(killSwitchAccess);
  658. accessKillSwitch.put(hObject, killSwitchAccess);
  659. }
  660. if(this.algoUseElements) {
  661. for (HolonElement hE : hObject.getElements()) {
  662. positionToInit.add(hE.isActive());
  663. access.add(new AccessWrapper(hE, killSwitchAccess));
  664. }
  665. }
  666. }
  667. else if (aCps instanceof HolonSwitch&& algoUseSwitches) {
  668. HolonSwitch sw = (HolonSwitch) aCps;
  669. positionToInit.add(sw.getState(timeStep));
  670. access.add(new AccessWrapper(sw));
  671. }
  672. else if(aCps instanceof GroupNode) {
  673. rollOutNodes(((GroupNode)aCps).getNodes(), positionToInit ,timeStep );
  674. }
  675. }
  676. }
  677. private RunValues getRunValuesFromActualState() {
  678. RunValues val = new RunValues();
  679. if(dGroupNode != null)
  680. {
  681. //GetActualDecoratedGroupNode
  682. dGroupNode = control.getSimManager().getActualVisualRepresentationalState().getCreatedGroupNodes().get(dGroupNode.getModel());
  683. val.producer = dGroupNode.getAmountOfSupplier();
  684. val.consumer = dGroupNode.getAmountOfConsumer();
  685. val.passiv = dGroupNode.getAmountOfPassiv();
  686. val.objects = val.producer + val.consumer + val.passiv;
  687. val.unsupplied = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
  688. val.partiallySupplied = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
  689. val.supplied = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
  690. val.overSupplied = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
  691. val.activeElements = dGroupNode.getAmountOfAktiveElemntsFromHolonObjects();
  692. val.elements = dGroupNode.getAmountOfElemntsFromHolonObjects();
  693. //TODO what should be printed happen when only groupNode are selected
  694. }
  695. DecoratedState state = control.getSimManager().getActualDecorState();
  696. for(DecoratedNetwork net : state.getNetworkList()) {
  697. val.consumer += net.getAmountOfConsumer();
  698. val.producer += net.getAmountOfSupplier();
  699. val.passiv += net.getAmountOfPassiv();
  700. val.unsupplied += net.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
  701. val.partiallySupplied += net.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
  702. val.supplied += net.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
  703. val.overSupplied += net.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
  704. val.elements += net.getAmountOfElements();
  705. val.activeElements += net.getAmountOfActiveElements();
  706. val.consumption += net.getTotalConsumption();
  707. val.production += net.getTotalProduction();
  708. }
  709. val.objects = val.consumer + val.producer + val.passiv;
  710. val.difference= Math.abs(val.production - val.consumption);
  711. List<Flexibility> flexActiveList = control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.IN_USE).stream().map(flex -> flex.getFlex()).collect(Collectors.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: " + StringFormat.doubleFixedPlaces(2, val.partiallyMin)
  753. + " " + prefix +"Partially.SupplyPercentage.Max: "+ StringFormat.doubleFixedPlaces(2, val.partiallyMax)
  754. + " " + prefix +"Partially.SupplyPercentage.Average: " + StringFormat.doubleFixedPlaces(2, val.partiallyAverage)
  755. + " " + prefix +"Over.SupplyPercentage.Min: " + StringFormat.doubleFixedPlaces(2, val.overMin)
  756. + " " + prefix +"Over.SupplyPercentage.Max: "+ StringFormat.doubleFixedPlaces(2, val.overMax)
  757. + " " + prefix +"Over.SupplyPercentage.Average: " + StringFormat.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 StringFormat.doubleTwoPlaces(numerator) + "/" + StringFormat.doubleTwoPlaces(denominator) + " "+ StringFormat.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.isActive());
  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.setActive(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. control.getSimManager().getActualFlexManager().orderFlex(flex);
  1001. }
  1002. break;
  1003. case KillSwitch:
  1004. if(state) {
  1005. for (HolonElement hE : hObject.getElements()) {
  1006. hE.setActive(false);
  1007. }
  1008. }else {
  1009. for(int i = 0; i < hObject.getElements().size(); i++) {
  1010. hObject.getElements().get(i).setActive(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. }