AlgorithmFrameworkFlex.java 48 KB

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