AlgorithmFrameworkFlex.java 48 KB

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