AlgorithmFrameworkFlex.java 48 KB

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