AlgorithmFrameworkFlex.java 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369
  1. package holeg.api;
  2. import java.awt.BorderLayout;
  3. import java.awt.Component;
  4. import java.awt.Dimension;
  5. import java.awt.FlowLayout;
  6. import java.awt.image.BufferedImage;
  7. import java.io.BufferedWriter;
  8. import java.io.File;
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11. import java.io.OutputStreamWriter;
  12. import java.math.RoundingMode;
  13. import java.text.NumberFormat;
  14. import java.util.ArrayList;
  15. import java.util.Collections;
  16. import java.util.DoubleSummaryStatistics;
  17. import java.util.HashMap;
  18. import java.util.Iterator;
  19. import java.util.LinkedList;
  20. import java.util.List;
  21. import java.util.Locale;
  22. import java.util.function.BiFunction;
  23. import java.util.function.Consumer;
  24. import java.util.function.Supplier;
  25. import java.util.stream.Collectors;
  26. import java.util.stream.Stream;
  27. import javax.swing.BorderFactory;
  28. import javax.swing.Box;
  29. import javax.swing.BoxLayout;
  30. import javax.swing.ImageIcon;
  31. import javax.swing.JButton;
  32. import javax.swing.JCheckBox;
  33. import javax.swing.JComboBox;
  34. import javax.swing.JFileChooser;
  35. import javax.swing.JFormattedTextField;
  36. import javax.swing.JLabel;
  37. import javax.swing.JOptionPane;
  38. import javax.swing.JPanel;
  39. import javax.swing.JProgressBar;
  40. import javax.swing.JScrollPane;
  41. import javax.swing.JSplitPane;
  42. import javax.swing.text.NumberFormatter;
  43. import holeg.addon.helper.EmailNotification;
  44. import holeg.algorithm.objective_function.ObjectiveFunctionByCarlos;
  45. import holeg.algorithm.objective_function.SwitchObjectiveFunction;
  46. import holeg.model.Flexibility;
  47. import holeg.model.HolonElement;
  48. import holeg.model.HolonObject;
  49. import holeg.model.HolonSwitch;
  50. import holeg.preferences.ImagePreference;
  51. import holeg.model.Flexibility.FlexState;
  52. import holeg.model.HolonElement.Priority;
  53. import holeg.ui.controller.Control;
  54. import holeg.ui.model.DecoratedGroupNode;
  55. import holeg.ui.model.DecoratedNetwork;
  56. import holeg.ui.model.DecoratedState;
  57. import holeg.ui.model.Model;
  58. import holeg.ui.model.DecoratedHolonObject.HolonObjectState;
  59. import holeg.ui.model.DecoratedSwitch.SwitchState;
  60. import holeg.ui.view.component.Console;
  61. import holeg.utility.image.Import;
  62. import holeg.utility.math.decimal.Format;
  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(Import.loadImage(ImagePreference.Button.Settings, 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. control.getSimManager().getActualVisualRepresentationalState().ifPresent(state -> {
  395. Object[] possibilities = state.getCreatedGroupNodes().values().stream().map(aCps -> new Handle<DecoratedGroupNode>(aCps)).toArray();
  396. @SuppressWarnings("unchecked")
  397. 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, "");
  398. if(selected != null) {
  399. console.println("Selected: " + selected);
  400. dGroupNode = selected.object;
  401. }
  402. });
  403. }
  404. protected double evaluatePosition(List<Boolean> positionToEvaluate) {
  405. runProgressbar.step();
  406. setState(positionToEvaluate); // execution time critical
  407. DecoratedState actualstate = control.getSimManager().getActualDecorState().get();
  408. double result = evaluateState(actualstate);
  409. return result;
  410. }
  411. private double evaluateState(DecoratedState actualstate) {
  412. switch(this.evaluationFunction) {
  413. case Switch:
  414. return SwitchObjectiveFunction.getFitnessValueForState(actualstate);
  415. case Normal:
  416. default:
  417. return ObjectiveFunctionByCarlos.getFitnessValueForState(actualstate);
  418. }
  419. }
  420. private void run() {
  421. cancel = false;
  422. control.guiDisable(true);
  423. runPrinter.openStream();
  424. runPrinter.println("");
  425. runPrinter.println("Start:" + stringStatFromRunValues(getRunValuesFromActualState()));
  426. runPrinter.closeStream();
  427. if(this.useStepping) {
  428. initParameterStepping();
  429. do {
  430. executeAlgoWithParameter();
  431. if(cancel) break;
  432. resetState();
  433. }while(updateOneParameter());
  434. resetParameterStepping();
  435. }else {
  436. executeAlgoWithParameter();
  437. }
  438. updateVisual();
  439. runProgressbar.finishedCancel();
  440. control.guiDisable(false);
  441. if(this.useEmailNotification && !cancel) {
  442. EmailNotification.sendEmail(this.getClass().getName() + " finished", "Execution done.");
  443. }
  444. }
  445. @SuppressWarnings("rawtypes")
  446. private void initParameterStepping() {
  447. for(ParameterStepping param :this.parameterSteppingList) {
  448. param.init();
  449. }
  450. }
  451. @SuppressWarnings("rawtypes")
  452. private void resetParameterStepping() {
  453. for(ParameterStepping param :this.parameterSteppingList) {
  454. param.reset();
  455. }
  456. }
  457. @SuppressWarnings("rawtypes")
  458. private boolean updateOneParameter() {
  459. List<ParameterStepping> parameterInUseList = this.parameterSteppingList.stream().filter(param -> param.useThisParameter).collect(Collectors.toList());
  460. Collections.reverse(parameterInUseList);
  461. int lastParameter = parameterInUseList.size() - 1 ;
  462. int actualParameter = 0;
  463. for(ParameterStepping param : parameterInUseList) {
  464. if(param.canUpdate()) {
  465. param.update();
  466. return true;
  467. }else {
  468. if(actualParameter == lastParameter) break;
  469. param.reset();
  470. }
  471. actualParameter++;
  472. }
  473. //No Param can be updated
  474. return false;
  475. }
  476. private void executeAlgoWithParameter(){
  477. double startFitness = evaluatePosition(extractPositionAndAccess());
  478. console.println("BitLength: " + access.size());
  479. resetChain.removeLast();
  480. runPrinter.openStream();
  481. runPrinter.println(algoInformationToPrint());
  482. console.println(algoInformationToPrint());
  483. runPrinter.closeStream();
  484. runProgressbar.start();
  485. Individual runBest = new Individual();
  486. runBest.fitness = Double.MAX_VALUE;
  487. this.avg = new RunAverage();
  488. for(int r = 0; r < rounds; r++)
  489. {
  490. startTimer();
  491. Individual roundBest = executeAlgo();
  492. if(cancel)return;
  493. long executionTime = printElapsedTime();
  494. setState(roundBest.position);
  495. runPrinter.openStream();
  496. runPrinter.println(runList.stream().map(value -> Format.doubleFixedPlaces(2,value)).collect(Collectors.joining(", ")));
  497. RunValues val = getRunValuesFromActualState();
  498. val.result = roundBest.fitness;
  499. val.executionTime = executionTime;
  500. avg.addRun(val);
  501. runPrinter.println("Result: " + Format.doubleFixedPlaces(2,roundBest.fitness) + " ExecutionTime:" + executionTime + " " + stringStatFromRunValues(val));
  502. runPrinter.closeStream();
  503. resetState();
  504. if(roundBest.fitness < runBest.fitness) runBest = roundBest;
  505. }
  506. this.extractPositionAndAccess();
  507. setState(runBest.position);
  508. updateVisual();
  509. console.println("Start: " + Format.doubleFixedPlaces(2,startFitness));
  510. console.println("AlgoResult: " + Format.doubleFixedPlaces(2,runBest.fitness));
  511. if(this.algoUseFlexes)calculateAndPrintFlexInfos(control.getSimManager().getActualDecorState().get());
  512. runPrinter.openStream();
  513. if(rounds > 1) {
  514. RunValues avgRun = avg.getAverage();
  515. runPrinter.println("Average.Result: " + Format.doubleFixedPlaces(2, avgRun.result) + " Average.ExecutionTime:" + avgRun.executionTime + " " + this.stringStatFromRunValues(avg.getAverage(), "Average."));
  516. }
  517. runPrinter.println("");
  518. runPrinter.closeStream();
  519. }
  520. private void calculateAndPrintFlexInfos(DecoratedState state) {
  521. int amountOfUsedFlex = 0;
  522. List<Flexibility> allFlex = state.getAllFlex().toList();
  523. int amountOfFlex = allFlex.size();
  524. float cost = 0;
  525. int consumingFlex = 0;
  526. float consumingFlexEnergy = 0.0f;
  527. int producingFlex = 0;
  528. float producingFlexEnergy = 0.0f;
  529. int maxCooldown = 0;
  530. int amountEssential = 0;
  531. int amountHigh = 0;
  532. int amountMedium = 0;
  533. int amountLow = 0;
  534. Stream<Flexibility> allFlexInUse = allFlex.stream().filter(flex -> flex.getState().equals(FlexState.IN_USE));
  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.getModel().setCurrentIteration(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(initialState);
  633. resetChain.add(initialState);
  634. if(algoUseFlexes) {
  635. List<Flexibility> flexList = model.getAllFlexibilities();
  636. List<Flexibility> allOfferedFLex = flexList.stream().filter(flex -> flex.getState() == FlexState.OFFERED).toList();
  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. List<Flexibility> allInUseFLex = flexList.stream().filter(flex -> flex.getState() == FlexState.IN_USE).toList();
  644. for(Flexibility flex : allInUseFLex){
  645. AccessWrapper killSwitchAccess = this.algoUseKillSwitch ? this.accessKillSwitch.get(flex.getElement().parentObject): null;
  646. access.add(new AccessWrapper(flex, killSwitchAccess));
  647. initialState.add(true);
  648. }
  649. }
  650. //console.println(access.stream().map(Object::toString).collect(Collectors.joining(", ")));
  651. return initialState;
  652. }
  653. private void rollOutNodes(List<Boolean> positionToInit) {
  654. boolean groupNodeSelected = dGroupNode != null;
  655. int timeStep = control.getModel().getCurrentIteration();
  656. Stream<HolonObject> holonObjects = groupNodeSelected ? dGroupNode.getModel().getAllHolonObjectsRecursive() : control.getModel().getCanvas().getAllHolonObjectsRecursive();
  657. Stream<HolonSwitch> holonSwitches = groupNodeSelected ? dGroupNode.getModel().getAllSwitchObjectsRecursive(): control.getModel().getCanvas().getAllSwitchObjectsRecursive();
  658. holonObjects.forEach(hObject -> {
  659. AccessWrapper killSwitchAccess = new AccessWrapper(hObject);
  660. if(this.algoUseKillSwitch) {
  661. positionToInit.add(false);
  662. access.add(killSwitchAccess);
  663. accessKillSwitch.put(hObject, killSwitchAccess);
  664. }
  665. if(this.algoUseElements) {
  666. hObject.getElements().forEach(hE -> {
  667. positionToInit.add(hE.active);
  668. access.add(new AccessWrapper(hE, killSwitchAccess));
  669. });
  670. }
  671. });
  672. holonSwitches.forEach(sw -> {
  673. positionToInit.add(sw.getState(timeStep));
  674. access.add(new AccessWrapper(sw));
  675. });
  676. }
  677. private RunValues getRunValuesFromActualState() {
  678. RunValues val = new RunValues();
  679. if(dGroupNode != null)
  680. {
  681. //GetActualDecoratedGroupNode
  682. dGroupNode = control.getSimManager().getActualVisualRepresentationalState().get().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(Tom2021-12-1) what should be printed happen when only groupNode are selected
  694. }
  695. DecoratedState state = control.getSimManager().getActualDecorState().get();
  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> flexList = control.getModel().getAllFlexibilities();
  712. List<Flexibility> flexActiveList = flexList.stream().filter(flex -> flex.getState().equals(FlexState.IN_USE)).toList();
  713. val.essentialFlex = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Essential).count();
  714. val.highFlex = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.High).count();
  715. val.mediumFlex = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Medium).count();
  716. val.lowFlex = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Low).count();
  717. val.flexebilities = val.essentialFlex + val.highFlex + val.mediumFlex + val.lowFlex;
  718. val.holon = state.getNetworkList().size();
  719. val.switches = state.getDecoratedSwitches().size();
  720. val.activeSwitches = (int)state.getDecoratedSwitches().stream().filter(dswitch -> (dswitch.getState() == SwitchState.Closed)).count();
  721. DoubleSummaryStatistics overStat = state.getNetworkList().stream().flatMap(net -> {
  722. return net.getConsumerList().stream().filter(con -> con.getState() == HolonObjectState.OVER_SUPPLIED);
  723. }).mapToDouble(con -> con.getSupplyBarPercentage()).summaryStatistics();
  724. DoubleSummaryStatistics partiallyStat = state.getNetworkList().stream().flatMap(net -> {
  725. return net.getConsumerList().stream().filter(con -> con.getState() == HolonObjectState.PARTIALLY_SUPPLIED);
  726. }).mapToDouble(con -> con.getSupplyBarPercentage()).summaryStatistics();
  727. val.partiallyMin = filterInf(partiallyStat.getMin());
  728. val.partiallyMax = filterInf(partiallyStat.getMax());
  729. val.partiallyAverage = filterInf(partiallyStat.getAverage());
  730. val.overMin = filterInf(overStat.getMin());
  731. val.overMax = filterInf(overStat.getMax());
  732. val.overAverage = filterInf(overStat.getAverage());
  733. return val;
  734. }
  735. private double filterInf(double value) {
  736. if(value == Double.NEGATIVE_INFINITY || value == Double.POSITIVE_INFINITY || value == Double.NaN) {
  737. return 0;
  738. }else {
  739. return value;
  740. }
  741. }
  742. private String stringStatFromRunValues(RunValues val){
  743. return stringStatFromRunValues(val , "");
  744. }
  745. private String stringStatFromRunValues(RunValues val, String prefix) {
  746. return prefix +"Passiv: " + percentage(val.passiv, val.objects)
  747. + " " + prefix +"Producer: " + percentage(val.producer, val.objects)
  748. + " " + prefix +"Consumer: " + percentage(val.consumer, val.objects)
  749. + " " + prefix +"Unsupplied: " + percentage(val.unsupplied, val.objects)
  750. + " " + prefix +"Partially: " + percentage(val.partiallySupplied, val.objects)
  751. + " " + prefix +"Over: " + percentage(val.overSupplied, val.objects)
  752. + " " + prefix +"Supplied: " + percentage(val.supplied, val.objects)
  753. + " " + prefix +"Partially.SupplyPercentage.Min: " + Format.doubleFixedPlaces(2, val.partiallyMin)
  754. + " " + prefix +"Partially.SupplyPercentage.Max: "+ Format.doubleFixedPlaces(2, val.partiallyMax)
  755. + " " + prefix +"Partially.SupplyPercentage.Average: " + Format.doubleFixedPlaces(2, val.partiallyAverage)
  756. + " " + prefix +"Over.SupplyPercentage.Min: " + Format.doubleFixedPlaces(2, val.overMin)
  757. + " " + prefix +"Over.SupplyPercentage.Max: "+ Format.doubleFixedPlaces(2, val.overMax)
  758. + " " + prefix +"Over.SupplyPercentage.Average: " + Format.doubleFixedPlaces(2, val.overAverage)
  759. + " " + prefix +"HolonElemnts.Active:" + percentage(val.activeElements, val.elements)
  760. + " " + prefix +"Flexibilities.Essential: " + percentage(val.essentialFlex, val.flexebilities)
  761. + " " + prefix +"Flexibilities.High: " + percentage(val.highFlex, val.flexebilities)
  762. + " " + prefix +"Flexibilities.Medium: " + percentage(val.mediumFlex, val.flexebilities)
  763. + " " + prefix +"Flexibilities.Low: " + percentage(val.lowFlex, val.flexebilities)
  764. + " " + prefix +"Switches.Active:" + percentage(val.activeSwitches,val.switches)
  765. + " " + prefix +"Holons: " + val.holon
  766. + " " + prefix +"TotalConsumption: " + val.consumption
  767. + " " + prefix +"TotalProduction: " + val.production
  768. + " " + prefix +"Difference: " + val.difference;
  769. }
  770. private String percentage(double numerator , double denominator) {
  771. if((int)denominator == 0) {
  772. return "-%";
  773. }
  774. return Format.doubleTwoPlaces(numerator) + "/" + Format.doubleTwoPlaces(denominator) + " "+ Format.doubleFixedPlaces(2,(float)numerator /(float)denominator * 100) + "%";
  775. }
  776. @Override
  777. public JPanel getPanel() {
  778. return content;
  779. }
  780. @Override
  781. public void setController(Control control) {
  782. this.control = control;
  783. }
  784. private class RunProgressBar{
  785. //progressbar
  786. private JProgressBar progressBar = new JProgressBar();
  787. private int count = 0;
  788. private boolean isActive = false;
  789. public void step() {
  790. if(isActive) progressBar.setValue(count++);
  791. }
  792. public void start() {
  793. progressBar.setIndeterminate(false);
  794. count = 0;
  795. isActive = true;
  796. progressBar.setValue(0);
  797. progressBar.setMaximum(getProgressBarMaxCount());
  798. }
  799. public void cancel() {
  800. isActive = false;
  801. progressBar.setIndeterminate(true);
  802. }
  803. public void finishedCancel() {
  804. progressBar.setIndeterminate(false);
  805. progressBar.setValue(0);
  806. }
  807. public JProgressBar getJProgressBar(){
  808. return progressBar;
  809. }
  810. }
  811. protected abstract int getProgressBarMaxCount();
  812. protected abstract String algoInformationToPrint();
  813. protected abstract String plottFileName();
  814. public class Printer{
  815. private JFileChooser fileChooser = new JFileChooser();
  816. private BufferedWriter out;
  817. public Printer(String filename){
  818. fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
  819. fileChooser.setSelectedFile(new File(filename));
  820. }
  821. public void openStream() {
  822. File file = fileChooser.getSelectedFile();
  823. try {
  824. file.createNewFile();
  825. out = new BufferedWriter(new OutputStreamWriter(
  826. new FileOutputStream(file, true), "UTF-8"));
  827. } catch (IOException e) {
  828. System.out.println(e.getMessage());
  829. }
  830. }
  831. public void println(String stringToPrint) {
  832. try {
  833. out.write(stringToPrint);
  834. out.newLine();
  835. } catch (IOException e) {
  836. System.out.println(e.getMessage());
  837. }
  838. }
  839. public void closeStream() {
  840. try {
  841. out.close();
  842. } catch (IOException e) {
  843. System.out.println(e.getMessage());
  844. }
  845. }
  846. }
  847. private class RunValues{
  848. public double result;
  849. public double executionTime;
  850. public double objects;
  851. public double passiv;
  852. public double consumer;
  853. public double supplied;
  854. public double producer;
  855. public double unsupplied;
  856. public double partiallySupplied;
  857. public double overSupplied;
  858. public double partiallyMin;
  859. public double partiallyMax;
  860. public double partiallyAverage;
  861. public double overMin;
  862. public double overMax;
  863. public double overAverage;
  864. public double activeElements;
  865. public double elements;
  866. public double essentialFlex;
  867. public double highFlex;
  868. public double mediumFlex;
  869. public double lowFlex;
  870. public double flexebilities;
  871. public double switches;
  872. public double activeSwitches;
  873. public double holon;
  874. public double consumption;
  875. public double production;
  876. public double difference;
  877. }
  878. private class RunAverage{
  879. private int runCount = 0;
  880. //Values
  881. private RunValues sum = new RunValues();
  882. public void addRun(RunValues val) {
  883. sum.result += val.result;
  884. sum.executionTime += val.executionTime;
  885. sum.passiv += val.passiv;
  886. sum.consumer += val.consumer;
  887. sum.producer += val.producer;
  888. sum.unsupplied += val.unsupplied;
  889. sum.partiallySupplied += val.partiallySupplied;
  890. sum.overSupplied += val.overSupplied;
  891. sum.activeElements += val.activeElements;
  892. sum.elements += val.elements;
  893. sum.essentialFlex += val.essentialFlex;
  894. sum.highFlex += val.highFlex;
  895. sum.mediumFlex += val.mediumFlex;
  896. sum.lowFlex += val.lowFlex;
  897. sum.flexebilities += val.flexebilities;
  898. sum.holon += val.holon;
  899. sum.switches += val.switches;
  900. sum.activeSwitches += val.activeSwitches;
  901. sum.consumption += val.consumption;
  902. sum.production += val.production;
  903. sum.difference += val.difference;
  904. sum.objects += val.objects;
  905. sum.supplied += val.supplied;
  906. sum.partiallyMin += val.partiallyMin;
  907. sum.partiallyMax += val.partiallyMax;
  908. sum.partiallyAverage += val.partiallyAverage;
  909. sum.overMin += val.overMin;
  910. sum.overMax += val.overMax;
  911. sum.overAverage += val.overAverage;
  912. runCount++;
  913. }
  914. public RunValues getAverage() {
  915. RunValues avg = new RunValues();
  916. if(runCount == 0) {
  917. return avg;
  918. }
  919. avg.result = sum.result / runCount;
  920. avg.executionTime = sum.executionTime / runCount;
  921. avg.passiv = sum.passiv / runCount;
  922. avg.consumer = sum.consumer / runCount;
  923. avg.producer = sum.producer / runCount;
  924. avg.unsupplied = sum.unsupplied / runCount;
  925. avg.partiallySupplied = sum.partiallySupplied / runCount;
  926. avg.overSupplied = sum.overSupplied / runCount;
  927. avg.activeElements = sum.activeElements / runCount;
  928. avg.elements = sum.elements / runCount;
  929. avg.essentialFlex = sum.essentialFlex / runCount;
  930. avg.highFlex = sum.highFlex / runCount;
  931. avg.mediumFlex = sum.mediumFlex / runCount;
  932. avg.lowFlex = sum.lowFlex / runCount;
  933. avg.flexebilities = sum.flexebilities / runCount;
  934. avg.holon = sum.holon / runCount;
  935. avg.switches = sum.switches / runCount;
  936. avg.activeSwitches = sum.activeSwitches / runCount;
  937. avg.consumption = sum.consumption / runCount;
  938. avg.production = sum.production / runCount;
  939. avg.difference = sum.difference / runCount;
  940. avg.objects = sum.objects / runCount;
  941. avg.supplied = sum.supplied / runCount;
  942. avg.supplied = sum.supplied / runCount;
  943. avg.partiallyMin = sum.partiallyMin / runCount;
  944. avg.partiallyMax = sum.partiallyMax / runCount;
  945. avg.partiallyAverage = sum.partiallyAverage / runCount;
  946. avg.overMin = sum.overMin / runCount;
  947. avg.overMax = sum.overMax / runCount;
  948. avg.overAverage = sum.overAverage / runCount;
  949. return avg;
  950. }
  951. }
  952. private enum AccessType {None, HolonElement, Switch, Flexibility, KillSwitch};
  953. /**
  954. * A Wrapper Class for Access HolonElement and HolonSwitch in one Element and not have to split the List.
  955. */
  956. private class AccessWrapper {
  957. private AccessType type;
  958. private List<Boolean> intialStatesOfElementForKilllSwitch;
  959. private HolonObject hObject;
  960. private HolonSwitch hSwitch;
  961. private HolonElement hElement;
  962. private Flexibility flex;
  963. private AccessWrapper correspondingKillSwitch;
  964. private boolean lastState;
  965. public AccessWrapper(HolonObject hObject){
  966. type = AccessType.KillSwitch;
  967. this.hObject = hObject;
  968. intialStatesOfElementForKilllSwitch = new ArrayList<Boolean>();
  969. hObject.getElements().forEach(hE -> {
  970. intialStatesOfElementForKilllSwitch.add(hE.active);
  971. });
  972. }
  973. public AccessWrapper(HolonSwitch hSwitch){
  974. type = AccessType.Switch;
  975. this.hSwitch = hSwitch;
  976. }
  977. public AccessWrapper(HolonElement hElement, AccessWrapper correspondingKillSwitch){
  978. type = AccessType.HolonElement;
  979. this.hElement = hElement;
  980. this.correspondingKillSwitch = correspondingKillSwitch;
  981. }
  982. public AccessWrapper(Flexibility flex, AccessWrapper correspondingKillSwitch){
  983. type = AccessType.Flexibility;
  984. this.flex = flex;
  985. this.correspondingKillSwitch = correspondingKillSwitch;
  986. }
  987. public void setState(boolean state) {
  988. lastState = state;
  989. switch(type) {
  990. case HolonElement:
  991. if(!algoUseKillSwitch || (algoUseKillSwitch && !correspondingKillSwitch.getLastState())) {
  992. hElement.active = state;
  993. }
  994. break;
  995. case Switch:
  996. hSwitch.setManualMode(true);
  997. hSwitch.setManualState(state);
  998. break;
  999. case Flexibility:
  1000. if(state && (!algoUseKillSwitch || (algoUseKillSwitch && !correspondingKillSwitch.getLastState()))) {
  1001. flex.order();
  1002. }
  1003. break;
  1004. case KillSwitch:
  1005. if(state) {
  1006. hObject.getElements().forEach(hE -> {
  1007. hE.active = false;
  1008. });
  1009. }else {
  1010. List<HolonElement> eleList = hObject.getElements().toList();
  1011. for(int i = 0; i < eleList.size(); i++) {
  1012. eleList.get(i).active = intialStatesOfElementForKilllSwitch.get(i);
  1013. }
  1014. }
  1015. break;
  1016. default:
  1017. break;
  1018. }
  1019. }
  1020. public boolean getLastState() {
  1021. return lastState;
  1022. }
  1023. public String typeString() {
  1024. switch(type) {
  1025. case HolonElement:
  1026. return "HolonElement";
  1027. case Switch:
  1028. return "Switch";
  1029. case Flexibility:
  1030. return "Flexibility";
  1031. case KillSwitch:
  1032. return "KillSwitch";
  1033. default:
  1034. return "unknown";
  1035. }
  1036. }
  1037. public String toString() {
  1038. return "[" + typeString() + "]";
  1039. }
  1040. }
  1041. /**
  1042. * To create Random and maybe switch the random generation in the future.
  1043. */
  1044. protected static class Random{
  1045. private static java.util.Random random = new java.util.Random();
  1046. /**
  1047. * True or false
  1048. * @return the random boolean.
  1049. */
  1050. public static boolean nextBoolean(){
  1051. return random.nextBoolean();
  1052. }
  1053. /**
  1054. * Between 0.0(inclusive) and 1.0 (exclusive)
  1055. * @return the random double.
  1056. */
  1057. public static double nextDouble() {
  1058. return random.nextDouble();
  1059. }
  1060. /**
  1061. * Random Int in Range [min;max[ with UniformDistirbution
  1062. * @param min
  1063. * @param max
  1064. * @return
  1065. */
  1066. public static int nextIntegerInRange(int min, int max) {
  1067. int result = min;
  1068. try {
  1069. result = min + random.nextInt(max - min);
  1070. }catch(java.lang.IllegalArgumentException e){
  1071. System.err.println("min : " + min + " max : " + max);
  1072. System.err.println("max should be more then min");
  1073. }
  1074. return result;
  1075. }
  1076. }
  1077. private class Handle<T>{
  1078. public T object;
  1079. Handle(T object){
  1080. this.object = object;
  1081. }
  1082. public String toString() {
  1083. return object.toString();
  1084. }
  1085. }
  1086. public class Individual {
  1087. public double fitness;
  1088. public List<Boolean> position;
  1089. public Individual(){};
  1090. /**
  1091. * Copy Constructor
  1092. */
  1093. public Individual(Individual c){
  1094. position = c.position.stream().collect(Collectors.toList());
  1095. fitness = c.fitness;
  1096. }
  1097. String positionToString() {
  1098. return position.stream().map(bool -> (bool?"1":"0")).collect(Collectors.joining());
  1099. }
  1100. }
  1101. protected class ParameterStepping<T>{
  1102. boolean useThisParameter = false;
  1103. String paramaterName;
  1104. private int count = 0;
  1105. int stepps;
  1106. T stepSize;
  1107. T startValue;
  1108. Consumer<T> setter;
  1109. Supplier<T> getter;
  1110. BiFunction<Integer,T,T> multyply;
  1111. BiFunction<T,T,T> add;
  1112. ParameterStepping(Consumer<T> setter, Supplier<T> getter, BiFunction<T,T,T> add, BiFunction<Integer,T,T> multyply, T stepSize, int stepps){
  1113. this.setter = setter;
  1114. this.getter = getter;
  1115. this.multyply = multyply;
  1116. this.add = add;
  1117. this.stepSize = stepSize;
  1118. this.stepps = stepps;
  1119. }
  1120. void init() {
  1121. startValue = getter.get();
  1122. }
  1123. boolean canUpdate() {
  1124. return count < stepps;
  1125. }
  1126. void update(){
  1127. if(canUpdate()) {
  1128. setter.accept(add.apply(startValue, multyply.apply(count + 1, stepSize)));
  1129. count ++;
  1130. }
  1131. }
  1132. void reset() {
  1133. setter.accept(startValue);
  1134. count = 0;
  1135. }
  1136. }
  1137. }