AlgorithmFrameworkFlex.java 48 KB

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