AlgorithmFrameworkFlex.java 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362
  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.Optional;
  23. import java.util.function.BiFunction;
  24. import java.util.function.Consumer;
  25. import java.util.function.Supplier;
  26. import java.util.stream.Collectors;
  27. import java.util.stream.Stream;
  28. import javax.swing.BorderFactory;
  29. import javax.swing.Box;
  30. import javax.swing.BoxLayout;
  31. import javax.swing.ImageIcon;
  32. import javax.swing.JButton;
  33. import javax.swing.JCheckBox;
  34. import javax.swing.JComboBox;
  35. import javax.swing.JFileChooser;
  36. import javax.swing.JFormattedTextField;
  37. import javax.swing.JLabel;
  38. import javax.swing.JOptionPane;
  39. import javax.swing.JPanel;
  40. import javax.swing.JProgressBar;
  41. import javax.swing.JScrollPane;
  42. import javax.swing.JSplitPane;
  43. import javax.swing.text.NumberFormatter;
  44. import holeg.addon.helper.EmailNotification;
  45. import holeg.algorithm.objective_function.ObjectiveFunctionByCarlos;
  46. import holeg.algorithm.objective_function.SwitchObjectiveFunction;
  47. import holeg.model.Flexibility;
  48. import holeg.model.HolonElement;
  49. import holeg.model.HolonObject;
  50. import holeg.model.HolonSwitch;
  51. import holeg.preferences.ImagePreference;
  52. import holeg.model.Flexibility.FlexState;
  53. import holeg.model.GroupNode;
  54. import holeg.model.HolonElement.Priority;
  55. import holeg.model.HolonSwitch.SwitchMode;
  56. import holeg.model.HolonSwitch.SwitchState;
  57. import holeg.ui.controller.Control;
  58. import holeg.ui.model.Model;
  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 Optional<GroupNode> groupNode = Optional.empty();
  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(ImagePreference.Button.Settings, 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. Object[] possibilities = control.getModel().getCanvas().getAllGroupNodeObjectsRecursive().toArray();
  394. @SuppressWarnings("unchecked")
  395. GroupNode selected = (GroupNode) JOptionPane.showInputDialog(content, "Select GroupNode:", "GroupNode?", JOptionPane.OK_OPTION,new ImageIcon(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)) , possibilities, "");
  396. if(selected != null) {
  397. console.println("Selected: " + selected);
  398. groupNode = Optional.of(selected);
  399. }
  400. }
  401. protected double evaluatePosition(List<Boolean> positionToEvaluate) {
  402. runProgressbar.step();
  403. setState(positionToEvaluate); // execution time critical
  404. double result = evaluateState();
  405. return result;
  406. }
  407. private double evaluateState() {
  408. switch(this.evaluationFunction) {
  409. case Switch:
  410. return SwitchObjectiveFunction.getFitnessValueForState(control.getModel());
  411. case Normal:
  412. default:
  413. return ObjectiveFunctionByCarlos.getFitnessValueForState(control.getModel());
  414. }
  415. }
  416. private void run() {
  417. cancel = false;
  418. control.guiSetEnabled(true);
  419. runPrinter.openStream();
  420. runPrinter.println("");
  421. runPrinter.println("Start:" + stringStatFromRunValues(getRunValuesFromActualState()));
  422. runPrinter.closeStream();
  423. if(this.useStepping) {
  424. initParameterStepping();
  425. do {
  426. executeAlgoWithParameter();
  427. if(cancel) break;
  428. resetState();
  429. }while(updateOneParameter());
  430. resetParameterStepping();
  431. }else {
  432. executeAlgoWithParameter();
  433. }
  434. updateVisual();
  435. runProgressbar.finishedCancel();
  436. control.guiSetEnabled(false);
  437. if(this.useEmailNotification && !cancel) {
  438. EmailNotification.sendEmail(this.getClass().getName() + " finished", "Execution done.");
  439. }
  440. }
  441. @SuppressWarnings("rawtypes")
  442. private void initParameterStepping() {
  443. for(ParameterStepping param :this.parameterSteppingList) {
  444. param.init();
  445. }
  446. }
  447. @SuppressWarnings("rawtypes")
  448. private void resetParameterStepping() {
  449. for(ParameterStepping param :this.parameterSteppingList) {
  450. param.reset();
  451. }
  452. }
  453. @SuppressWarnings("rawtypes")
  454. private boolean updateOneParameter() {
  455. List<ParameterStepping> parameterInUseList = this.parameterSteppingList.stream().filter(param -> param.useThisParameter).collect(Collectors.toList());
  456. Collections.reverse(parameterInUseList);
  457. int lastParameter = parameterInUseList.size() - 1 ;
  458. int actualParameter = 0;
  459. for(ParameterStepping param : parameterInUseList) {
  460. if(param.canUpdate()) {
  461. param.update();
  462. return true;
  463. }else {
  464. if(actualParameter == lastParameter) break;
  465. param.reset();
  466. }
  467. actualParameter++;
  468. }
  469. //No Param can be updated
  470. return false;
  471. }
  472. private void executeAlgoWithParameter(){
  473. double startFitness = evaluatePosition(extractPositionAndAccess());
  474. console.println("BitLength: " + access.size());
  475. resetChain.removeLast();
  476. runPrinter.openStream();
  477. runPrinter.println(algoInformationToPrint());
  478. console.println(algoInformationToPrint());
  479. runPrinter.closeStream();
  480. runProgressbar.start();
  481. Individual runBest = new Individual();
  482. runBest.fitness = Double.MAX_VALUE;
  483. this.avg = new RunAverage();
  484. for(int r = 0; r < rounds; r++)
  485. {
  486. startTimer();
  487. Individual roundBest = executeAlgo();
  488. if(cancel)return;
  489. long executionTime = printElapsedTime();
  490. setState(roundBest.position);
  491. runPrinter.openStream();
  492. runPrinter.println(runList.stream().map(value -> Format.doubleFixedPlaces(2,value)).collect(Collectors.joining(", ")));
  493. RunValues val = getRunValuesFromActualState();
  494. val.result = roundBest.fitness;
  495. val.executionTime = executionTime;
  496. avg.addRun(val);
  497. runPrinter.println("Result: " + Format.doubleFixedPlaces(2,roundBest.fitness) + " ExecutionTime:" + executionTime + " " + stringStatFromRunValues(val));
  498. runPrinter.closeStream();
  499. resetState();
  500. if(roundBest.fitness < runBest.fitness) runBest = roundBest;
  501. }
  502. this.extractPositionAndAccess();
  503. setState(runBest.position);
  504. updateVisual();
  505. console.println("Start: " + Format.doubleFixedPlaces(2,startFitness));
  506. console.println("AlgoResult: " + Format.doubleFixedPlaces(2,runBest.fitness));
  507. if(this.algoUseFlexes)calculateAndPrintFlexInfos();
  508. runPrinter.openStream();
  509. if(rounds > 1) {
  510. RunValues avgRun = avg.getAverage();
  511. runPrinter.println("Average.Result: " + Format.doubleFixedPlaces(2, avgRun.result) + " Average.ExecutionTime:" + avgRun.executionTime + " " + this.stringStatFromRunValues(avg.getAverage(), "Average."));
  512. }
  513. runPrinter.println("");
  514. runPrinter.closeStream();
  515. }
  516. private void calculateAndPrintFlexInfos() {
  517. int amountOfUsedFlex = 0;
  518. List<Flexibility> allFlex = control.getModel().getAllFlexibilities();
  519. int amountOfFlex = allFlex.size();
  520. float cost = 0;
  521. int consumingFlex = 0;
  522. float consumingFlexEnergy = 0.0f;
  523. int producingFlex = 0;
  524. float producingFlexEnergy = 0.0f;
  525. int maxCooldown = 0;
  526. int amountEssential = 0;
  527. int amountHigh = 0;
  528. int amountMedium = 0;
  529. int amountLow = 0;
  530. Stream<Flexibility> allFlexInUse = allFlex.stream().filter(flex -> flex.getState().equals(FlexState.IN_USE));
  531. Iterator<Flexibility> iterInUseFlex = allFlexInUse.iterator();
  532. while(iterInUseFlex.hasNext()) {
  533. Flexibility flex = iterInUseFlex.next();
  534. amountOfUsedFlex++;
  535. cost += flex.cost;
  536. float energy = flex.energyReleased();
  537. if(energy < 0) {
  538. consumingFlex++;
  539. consumingFlexEnergy += -energy;
  540. }else {
  541. producingFlex++;
  542. producingFlexEnergy += energy;
  543. }
  544. if(flex.getCooldown() > maxCooldown) maxCooldown = flex.getCooldown();
  545. switch(flex.getElement().getPriority()) {
  546. case Essential:
  547. amountEssential++;
  548. break;
  549. case High:
  550. amountHigh++;
  551. break;
  552. case Low:
  553. amountLow++;
  554. break;
  555. case Medium:
  556. amountMedium++;
  557. break;
  558. default:
  559. break;
  560. }
  561. }
  562. //Total Flexibilities:
  563. //Used Flexibilities:
  564. console.println("Used Flex [" + amountOfUsedFlex + "/" + amountOfFlex + "]");
  565. //Consuming Flexibilities:
  566. console.println(consumingFlex + " consuimg flexibilities that consumed " + consumingFlexEnergy + "Energy.");
  567. //Producing Flexibilities
  568. console.println(producingFlex + " producing flexibilities that produce " + producingFlexEnergy + "Energy.");
  569. console.println("Flex in use:\t" + "Low= " + amountLow + "\tMedium= " + amountMedium + "\tHigh= " + amountHigh + "\tEssential= " + amountEssential);
  570. //Total cost:
  571. console.println("Total Cost: "+ cost);
  572. //Longest Cooldown
  573. console.println("Max Cooldown: "+ maxCooldown);
  574. //
  575. }
  576. protected abstract Individual executeAlgo();
  577. private void reset() {
  578. if(runThread.isAlive()) {
  579. console.println("Run have to be cancelled First.");
  580. return;
  581. }
  582. if(!resetChain.isEmpty()) {
  583. console.println("Resetting..");
  584. setState(resetChain.getFirst());
  585. resetChain.clear();
  586. control.resetSimulation();
  587. control.getModel().setCurrentIteration(0);
  588. updateVisual();
  589. }else {
  590. console.println("No run inistialized.");
  591. }
  592. }
  593. /**
  594. * To let the User See the current state without touching the Canvas.
  595. */
  596. private void updateVisual() {
  597. control.calculateStateAndVisualForCurrentTimeStep();
  598. }
  599. /**
  600. * Sets the Model back to its original State before the LAST run.
  601. */
  602. private void resetState() {
  603. setState(resetChain.getLast());
  604. }
  605. /**
  606. * Sets the State out of the given position for calculation or to show the user.
  607. * @param position
  608. */
  609. private void setState(List<Boolean> position) {
  610. control.resetSimulation();
  611. int i = 0;
  612. for(Boolean bool: position) {
  613. access.get(i++).setState(bool);
  614. }
  615. control.calculateStateOnlyForCurrentTimeStep();
  616. }
  617. /**
  618. * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
  619. * Also initialize the Access Hashmap to swap faster positions.
  620. * @param ModelTest
  621. * @return
  622. */
  623. protected List<Boolean> extractPositionAndAccess() {
  624. Model model = control.getModel();
  625. this.accessKillSwitch = new HashMap<HolonObject, AccessWrapper>();
  626. access= new ArrayList<AccessWrapper>();
  627. List<Boolean> initialState = new ArrayList<Boolean>();
  628. rollOutNodes(initialState);
  629. resetChain.add(initialState);
  630. if(algoUseFlexes) {
  631. List<Flexibility> flexList = model.getAllFlexibilities();
  632. List<Flexibility> allOfferedFLex = flexList.stream().filter(flex -> flex.getState() == FlexState.OFFERED).toList();
  633. for(Flexibility flex :allOfferedFLex){
  634. //flex.getFlex().getElement().parentObject;
  635. AccessWrapper killSwitchAccess = this.algoUseKillSwitch ? this.accessKillSwitch.get(flex.getElement().parentObject): null;;
  636. access.add(new AccessWrapper(flex, killSwitchAccess));
  637. initialState.add(false);
  638. }
  639. List<Flexibility> allInUseFLex = flexList.stream().filter(flex -> flex.getState() == FlexState.IN_USE).toList();
  640. for(Flexibility flex : allInUseFLex){
  641. AccessWrapper killSwitchAccess = this.algoUseKillSwitch ? this.accessKillSwitch.get(flex.getElement().parentObject): null;
  642. access.add(new AccessWrapper(flex, killSwitchAccess));
  643. initialState.add(true);
  644. }
  645. }
  646. //console.println(access.stream().map(Object::toString).collect(Collectors.joining(", ")));
  647. return initialState;
  648. }
  649. private void rollOutNodes(List<Boolean> positionToInit) {
  650. boolean groupNodeSelected = groupNode.isPresent();
  651. int timeStep = control.getModel().getCurrentIteration();
  652. Stream<HolonObject> holonObjects = groupNodeSelected ? groupNode.get().getAllHolonObjectsRecursive() : control.getModel().getCanvas().getAllHolonObjectsRecursive();
  653. Stream<HolonSwitch> holonSwitches = groupNodeSelected ? groupNode.get().getAllSwitchObjectsRecursive(): control.getModel().getCanvas().getAllSwitchObjectsRecursive();
  654. holonObjects.forEach(hObject -> {
  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. hObject.getElements().forEach(hE -> {
  663. positionToInit.add(hE.active);
  664. access.add(new AccessWrapper(hE, killSwitchAccess));
  665. });
  666. }
  667. });
  668. holonSwitches.forEach(sw -> {
  669. positionToInit.add(sw.getState().isClosed());
  670. access.add(new AccessWrapper(sw));
  671. });
  672. }
  673. //TODO(Tom2022-01-13) fix print
  674. private RunValues getRunValuesFromActualState() {
  675. RunValues val = new RunValues();
  676. //TODO(Tom2021-12-1) what should be printed happen when only groupNode are selected
  677. groupNode.ifPresent(groupnode -> {
  678. // val.producer = dGroupNode.getAmountOfSupplier();
  679. // val.consumer = dGroupNode.getAmountOfConsumer();
  680. // val.passiv = dGroupNode.getAmountOfPassiv();
  681. // val.objects = val.producer + val.consumer + val.passiv;
  682. // val.unsupplied = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
  683. // val.partiallySupplied = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
  684. // val.supplied = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
  685. // val.overSupplied = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
  686. //
  687. //
  688. // val.activeElements = dGroupNode.getAmountOfAktiveElemntsFromHolonObjects();
  689. // val.elements = dGroupNode.getAmountOfElemntsFromHolonObjects();
  690. });
  691. // for(DecoratedNetwork net : state.getNetworkList()) {
  692. // val.consumer += net.getAmountOfConsumer();
  693. // val.producer += net.getAmountOfSupplier();
  694. // val.passiv += net.getAmountOfPassiv();
  695. // val.unsupplied += net.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
  696. // val.partiallySupplied += net.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
  697. // val.supplied += net.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
  698. // val.overSupplied += net.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
  699. // val.elements += net.getAmountOfElements();
  700. // val.activeElements += net.getAmountOfActiveElements();
  701. // val.consumption += net.getTotalConsumption();
  702. // val.production += net.getTotalProduction();
  703. // }
  704. // val.objects = val.consumer + val.producer + val.passiv;
  705. // val.difference= Math.abs(val.production - val.consumption);
  706. //
  707. //
  708. // List<Flexibility> flexList = control.getModel().getAllFlexibilities();
  709. // List<Flexibility> flexActiveList = flexList.stream().filter(flex -> flex.getState().equals(FlexState.IN_USE)).toList();
  710. //
  711. // val.essentialFlex = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Essential).count();
  712. // val.highFlex = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.High).count();
  713. // val.mediumFlex = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Medium).count();
  714. // val.lowFlex = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Low).count();
  715. // val.flexebilities = val.essentialFlex + val.highFlex + val.mediumFlex + val.lowFlex;
  716. // val.holon = state.getNetworkList().size();
  717. // val.switches = state.getDecoratedSwitches().size();
  718. // val.activeSwitches = (int)state.getDecoratedSwitches().stream().filter(dswitch -> (dswitch.getState() == SwitchState.Closed)).count();
  719. //
  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. //
  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. //
  728. // val.partiallyMin = filterInf(partiallyStat.getMin());
  729. // val.partiallyMax = filterInf(partiallyStat.getMax());
  730. // val.partiallyAverage = filterInf(partiallyStat.getAverage());
  731. //
  732. // val.overMin = filterInf(overStat.getMin());
  733. // val.overMax = filterInf(overStat.getMax());
  734. // val.overAverage = filterInf(overStat.getAverage());
  735. return val;
  736. }
  737. private double filterInf(double value) {
  738. if(value == Double.NEGATIVE_INFINITY || value == Double.POSITIVE_INFINITY || value == Double.NaN) {
  739. return 0;
  740. }else {
  741. return value;
  742. }
  743. }
  744. private String stringStatFromRunValues(RunValues val){
  745. return stringStatFromRunValues(val , "");
  746. }
  747. private String stringStatFromRunValues(RunValues val, String prefix) {
  748. return prefix +"Passiv: " + percentage(val.passiv, val.objects)
  749. + " " + prefix +"Producer: " + percentage(val.producer, val.objects)
  750. + " " + prefix +"Consumer: " + percentage(val.consumer, val.objects)
  751. + " " + prefix +"Unsupplied: " + percentage(val.unsupplied, val.objects)
  752. + " " + prefix +"Partially: " + percentage(val.partiallySupplied, val.objects)
  753. + " " + prefix +"Over: " + percentage(val.overSupplied, val.objects)
  754. + " " + prefix +"Supplied: " + percentage(val.supplied, val.objects)
  755. + " " + prefix +"Partially.SupplyPercentage.Min: " + Format.doubleFixedPlaces(2, val.partiallyMin)
  756. + " " + prefix +"Partially.SupplyPercentage.Max: "+ Format.doubleFixedPlaces(2, val.partiallyMax)
  757. + " " + prefix +"Partially.SupplyPercentage.Average: " + Format.doubleFixedPlaces(2, val.partiallyAverage)
  758. + " " + prefix +"Over.SupplyPercentage.Min: " + Format.doubleFixedPlaces(2, val.overMin)
  759. + " " + prefix +"Over.SupplyPercentage.Max: "+ Format.doubleFixedPlaces(2, val.overMax)
  760. + " " + prefix +"Over.SupplyPercentage.Average: " + Format.doubleFixedPlaces(2, val.overAverage)
  761. + " " + prefix +"HolonElemnts.Active:" + percentage(val.activeElements, val.elements)
  762. + " " + prefix +"Flexibilities.Essential: " + percentage(val.essentialFlex, val.flexebilities)
  763. + " " + prefix +"Flexibilities.High: " + percentage(val.highFlex, val.flexebilities)
  764. + " " + prefix +"Flexibilities.Medium: " + percentage(val.mediumFlex, val.flexebilities)
  765. + " " + prefix +"Flexibilities.Low: " + percentage(val.lowFlex, val.flexebilities)
  766. + " " + prefix +"Switches.Active:" + percentage(val.activeSwitches,val.switches)
  767. + " " + prefix +"Holons: " + val.holon
  768. + " " + prefix +"TotalConsumption: " + val.consumption
  769. + " " + prefix +"TotalProduction: " + val.production
  770. + " " + prefix +"Difference: " + val.difference;
  771. }
  772. private String percentage(double numerator , double denominator) {
  773. if((int)denominator == 0) {
  774. return "-%";
  775. }
  776. return Format.doubleTwoPlaces(numerator) + "/" + Format.doubleTwoPlaces(denominator) + " "+ Format.doubleFixedPlaces(2,(float)numerator /(float)denominator * 100) + "%";
  777. }
  778. @Override
  779. public JPanel getPanel() {
  780. return content;
  781. }
  782. @Override
  783. public void setController(Control control) {
  784. this.control = control;
  785. }
  786. private class RunProgressBar{
  787. //progressbar
  788. private JProgressBar progressBar = new JProgressBar();
  789. private int count = 0;
  790. private boolean isActive = false;
  791. public void step() {
  792. if(isActive) progressBar.setValue(count++);
  793. }
  794. public void start() {
  795. progressBar.setIndeterminate(false);
  796. count = 0;
  797. isActive = true;
  798. progressBar.setValue(0);
  799. progressBar.setMaximum(getProgressBarMaxCount());
  800. }
  801. public void cancel() {
  802. isActive = false;
  803. progressBar.setIndeterminate(true);
  804. }
  805. public void finishedCancel() {
  806. progressBar.setIndeterminate(false);
  807. progressBar.setValue(0);
  808. }
  809. public JProgressBar getJProgressBar(){
  810. return progressBar;
  811. }
  812. }
  813. protected abstract int getProgressBarMaxCount();
  814. protected abstract String algoInformationToPrint();
  815. protected abstract String plottFileName();
  816. public class Printer{
  817. private JFileChooser fileChooser = new JFileChooser();
  818. private BufferedWriter out;
  819. public Printer(String filename){
  820. fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
  821. fileChooser.setSelectedFile(new File(filename));
  822. }
  823. public void openStream() {
  824. File file = fileChooser.getSelectedFile();
  825. try {
  826. file.createNewFile();
  827. out = new BufferedWriter(new OutputStreamWriter(
  828. new FileOutputStream(file, true), "UTF-8"));
  829. } catch (IOException e) {
  830. System.out.println(e.getMessage());
  831. }
  832. }
  833. public void println(String stringToPrint) {
  834. try {
  835. out.write(stringToPrint);
  836. out.newLine();
  837. } catch (IOException e) {
  838. System.out.println(e.getMessage());
  839. }
  840. }
  841. public void closeStream() {
  842. try {
  843. out.close();
  844. } catch (IOException e) {
  845. System.out.println(e.getMessage());
  846. }
  847. }
  848. }
  849. private class RunValues{
  850. public double result;
  851. public double executionTime;
  852. public double objects;
  853. public double passiv;
  854. public double consumer;
  855. public double supplied;
  856. public double producer;
  857. public double unsupplied;
  858. public double partiallySupplied;
  859. public double overSupplied;
  860. public double partiallyMin;
  861. public double partiallyMax;
  862. public double partiallyAverage;
  863. public double overMin;
  864. public double overMax;
  865. public double overAverage;
  866. public double activeElements;
  867. public double elements;
  868. public double essentialFlex;
  869. public double highFlex;
  870. public double mediumFlex;
  871. public double lowFlex;
  872. public double flexebilities;
  873. public double switches;
  874. public double activeSwitches;
  875. public double holon;
  876. public double consumption;
  877. public double production;
  878. public double difference;
  879. }
  880. private class RunAverage{
  881. private int runCount = 0;
  882. //Values
  883. private RunValues sum = new RunValues();
  884. public void addRun(RunValues val) {
  885. sum.result += val.result;
  886. sum.executionTime += val.executionTime;
  887. sum.passiv += val.passiv;
  888. sum.consumer += val.consumer;
  889. sum.producer += val.producer;
  890. sum.unsupplied += val.unsupplied;
  891. sum.partiallySupplied += val.partiallySupplied;
  892. sum.overSupplied += val.overSupplied;
  893. sum.activeElements += val.activeElements;
  894. sum.elements += val.elements;
  895. sum.essentialFlex += val.essentialFlex;
  896. sum.highFlex += val.highFlex;
  897. sum.mediumFlex += val.mediumFlex;
  898. sum.lowFlex += val.lowFlex;
  899. sum.flexebilities += val.flexebilities;
  900. sum.holon += val.holon;
  901. sum.switches += val.switches;
  902. sum.activeSwitches += val.activeSwitches;
  903. sum.consumption += val.consumption;
  904. sum.production += val.production;
  905. sum.difference += val.difference;
  906. sum.objects += val.objects;
  907. sum.supplied += val.supplied;
  908. sum.partiallyMin += val.partiallyMin;
  909. sum.partiallyMax += val.partiallyMax;
  910. sum.partiallyAverage += val.partiallyAverage;
  911. sum.overMin += val.overMin;
  912. sum.overMax += val.overMax;
  913. sum.overAverage += val.overAverage;
  914. runCount++;
  915. }
  916. public RunValues getAverage() {
  917. RunValues avg = new RunValues();
  918. if(runCount == 0) {
  919. return avg;
  920. }
  921. avg.result = sum.result / runCount;
  922. avg.executionTime = sum.executionTime / runCount;
  923. avg.passiv = sum.passiv / runCount;
  924. avg.consumer = sum.consumer / runCount;
  925. avg.producer = sum.producer / runCount;
  926. avg.unsupplied = sum.unsupplied / runCount;
  927. avg.partiallySupplied = sum.partiallySupplied / runCount;
  928. avg.overSupplied = sum.overSupplied / runCount;
  929. avg.activeElements = sum.activeElements / runCount;
  930. avg.elements = sum.elements / runCount;
  931. avg.essentialFlex = sum.essentialFlex / runCount;
  932. avg.highFlex = sum.highFlex / runCount;
  933. avg.mediumFlex = sum.mediumFlex / runCount;
  934. avg.lowFlex = sum.lowFlex / runCount;
  935. avg.flexebilities = sum.flexebilities / runCount;
  936. avg.holon = sum.holon / runCount;
  937. avg.switches = sum.switches / runCount;
  938. avg.activeSwitches = sum.activeSwitches / runCount;
  939. avg.consumption = sum.consumption / runCount;
  940. avg.production = sum.production / runCount;
  941. avg.difference = sum.difference / runCount;
  942. avg.objects = sum.objects / runCount;
  943. avg.supplied = sum.supplied / runCount;
  944. avg.supplied = sum.supplied / runCount;
  945. avg.partiallyMin = sum.partiallyMin / runCount;
  946. avg.partiallyMax = sum.partiallyMax / runCount;
  947. avg.partiallyAverage = sum.partiallyAverage / runCount;
  948. avg.overMin = sum.overMin / runCount;
  949. avg.overMax = sum.overMax / runCount;
  950. avg.overAverage = sum.overAverage / runCount;
  951. return avg;
  952. }
  953. }
  954. private enum AccessType {None, HolonElement, Switch, Flexibility, KillSwitch};
  955. /**
  956. * A Wrapper Class for Access HolonElement and HolonSwitch in one Element and not have to split the List.
  957. */
  958. private class AccessWrapper {
  959. private AccessType type;
  960. private List<Boolean> intialStatesOfElementForKilllSwitch;
  961. private HolonObject hObject;
  962. private HolonSwitch hSwitch;
  963. private HolonElement hElement;
  964. private Flexibility flex;
  965. private AccessWrapper correspondingKillSwitch;
  966. private boolean lastState;
  967. public AccessWrapper(HolonObject hObject){
  968. type = AccessType.KillSwitch;
  969. this.hObject = hObject;
  970. intialStatesOfElementForKilllSwitch = new ArrayList<Boolean>();
  971. hObject.getElements().forEach(hE -> {
  972. intialStatesOfElementForKilllSwitch.add(hE.active);
  973. });
  974. }
  975. public AccessWrapper(HolonSwitch hSwitch){
  976. type = AccessType.Switch;
  977. this.hSwitch = hSwitch;
  978. }
  979. public AccessWrapper(HolonElement hElement, AccessWrapper correspondingKillSwitch){
  980. type = AccessType.HolonElement;
  981. this.hElement = hElement;
  982. this.correspondingKillSwitch = correspondingKillSwitch;
  983. }
  984. public AccessWrapper(Flexibility flex, AccessWrapper correspondingKillSwitch){
  985. type = AccessType.Flexibility;
  986. this.flex = flex;
  987. this.correspondingKillSwitch = correspondingKillSwitch;
  988. }
  989. public void setState(boolean state) {
  990. lastState = state;
  991. switch(type) {
  992. case HolonElement:
  993. if(!algoUseKillSwitch || (algoUseKillSwitch && !correspondingKillSwitch.getLastState())) {
  994. hElement.active = state;
  995. }
  996. break;
  997. case Switch:
  998. hSwitch.setMode(SwitchMode.Manual);
  999. hSwitch.setManualState(state ? SwitchState.Closed: SwitchState.Open);
  1000. break;
  1001. case Flexibility:
  1002. if(state && (!algoUseKillSwitch || (algoUseKillSwitch && !correspondingKillSwitch.getLastState()))) {
  1003. flex.order();
  1004. }
  1005. break;
  1006. case KillSwitch:
  1007. if(state) {
  1008. hObject.getElements().forEach(hE -> {
  1009. hE.active = false;
  1010. });
  1011. }else {
  1012. List<HolonElement> eleList = hObject.getElements().toList();
  1013. for(int i = 0; i < eleList.size(); i++) {
  1014. eleList.get(i).active = intialStatesOfElementForKilllSwitch.get(i);
  1015. }
  1016. }
  1017. break;
  1018. default:
  1019. break;
  1020. }
  1021. }
  1022. public boolean getLastState() {
  1023. return lastState;
  1024. }
  1025. public String typeString() {
  1026. switch(type) {
  1027. case HolonElement:
  1028. return "HolonElement";
  1029. case Switch:
  1030. return "Switch";
  1031. case Flexibility:
  1032. return "Flexibility";
  1033. case KillSwitch:
  1034. return "KillSwitch";
  1035. default:
  1036. return "unknown";
  1037. }
  1038. }
  1039. public String toString() {
  1040. return "[" + typeString() + "]";
  1041. }
  1042. }
  1043. /**
  1044. * To create Random and maybe switch the random generation in the future.
  1045. */
  1046. protected static class Random{
  1047. private static java.util.Random random = new java.util.Random();
  1048. /**
  1049. * True or false
  1050. * @return the random boolean.
  1051. */
  1052. public static boolean nextBoolean(){
  1053. return random.nextBoolean();
  1054. }
  1055. /**
  1056. * Between 0.0(inclusive) and 1.0 (exclusive)
  1057. * @return the random double.
  1058. */
  1059. public static double nextDouble() {
  1060. return random.nextDouble();
  1061. }
  1062. /**
  1063. * Random Int in Range [min;max[ with UniformDistirbution
  1064. * @param min
  1065. * @param max
  1066. * @return
  1067. */
  1068. public static int nextIntegerInRange(int min, int max) {
  1069. int result = min;
  1070. try {
  1071. result = min + random.nextInt(max - min);
  1072. }catch(java.lang.IllegalArgumentException e){
  1073. System.err.println("min : " + min + " max : " + max);
  1074. System.err.println("max should be more then min");
  1075. }
  1076. return result;
  1077. }
  1078. }
  1079. private class Handle<T>{
  1080. public T object;
  1081. Handle(T object){
  1082. this.object = object;
  1083. }
  1084. public String toString() {
  1085. return object.toString();
  1086. }
  1087. }
  1088. public class Individual {
  1089. public double fitness;
  1090. public List<Boolean> position;
  1091. public Individual(){};
  1092. /**
  1093. * Copy Constructor
  1094. */
  1095. public Individual(Individual c){
  1096. position = c.position.stream().collect(Collectors.toList());
  1097. fitness = c.fitness;
  1098. }
  1099. String positionToString() {
  1100. return position.stream().map(bool -> (bool?"1":"0")).collect(Collectors.joining());
  1101. }
  1102. }
  1103. protected class ParameterStepping<T>{
  1104. boolean useThisParameter = false;
  1105. String paramaterName;
  1106. private int count = 0;
  1107. int stepps;
  1108. T stepSize;
  1109. T startValue;
  1110. Consumer<T> setter;
  1111. Supplier<T> getter;
  1112. BiFunction<Integer,T,T> multyply;
  1113. BiFunction<T,T,T> add;
  1114. ParameterStepping(Consumer<T> setter, Supplier<T> getter, BiFunction<T,T,T> add, BiFunction<Integer,T,T> multyply, T stepSize, int stepps){
  1115. this.setter = setter;
  1116. this.getter = getter;
  1117. this.multyply = multyply;
  1118. this.add = add;
  1119. this.stepSize = stepSize;
  1120. this.stepps = stepps;
  1121. }
  1122. void init() {
  1123. startValue = getter.get();
  1124. }
  1125. boolean canUpdate() {
  1126. return count < stepps;
  1127. }
  1128. void update(){
  1129. if(canUpdate()) {
  1130. setter.accept(add.apply(startValue, multyply.apply(count + 1, stepSize)));
  1131. count ++;
  1132. }
  1133. }
  1134. void reset() {
  1135. setter.accept(startValue);
  1136. count = 0;
  1137. }
  1138. }
  1139. }