AlgorithmFrameworkFlex.java 42 KB

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