AlgorithmFrameworkFlex.java 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359
  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.HashMap;
  17. import java.util.Iterator;
  18. import java.util.LinkedList;
  19. import java.util.List;
  20. import java.util.Locale;
  21. import java.util.Optional;
  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.preferences.ImagePreference;
  51. import holeg.model.Flexibility.FlexState;
  52. import holeg.model.GroupNode;
  53. import holeg.model.HolonSwitch.SwitchMode;
  54. import holeg.model.HolonSwitch.SwitchState;
  55. import holeg.ui.controller.Control;
  56. import holeg.model.Model;
  57. import holeg.ui.view.component.Console;
  58. import holeg.ui.view.image.Import;
  59. import holeg.utility.math.decimal.Format;
  60. public abstract class AlgorithmFrameworkFlex implements AddOn{
  61. //Algo
  62. protected int rounds = 1;
  63. //Panel
  64. private JPanel content = new JPanel();
  65. protected Console console = new Console();
  66. private JPanel borderPanel = new JPanel();
  67. //Settings groupNode
  68. private Optional<GroupNode> groupNode = Optional.empty();
  69. //access
  70. private ArrayList<AccessWrapper> access;
  71. private HashMap<HolonObject, AccessWrapper> accessKillSwitch = new HashMap<HolonObject, AccessWrapper>();
  72. LinkedList<List<Boolean>> resetChain = new LinkedList<List<Boolean>>();
  73. boolean algoUseElements = false, algoUseSwitches = true, algoUseFlexes = true, algoUseKillSwitch = true;
  74. //time
  75. private long startTime;
  76. private RunProgressBar runProgressbar = new RunProgressBar();
  77. //concurrency
  78. private Thread runThread = new Thread();
  79. protected boolean cancel = false;
  80. //holeg interaction
  81. protected Control control;
  82. //printing
  83. private Printer runPrinter = new Printer(plottFileName());
  84. protected List<Double> runList = new LinkedList<Double>();
  85. private RunAverage avg = new RunAverage();
  86. //Parameter
  87. @SuppressWarnings("rawtypes")
  88. LinkedList<ParameterStepping> parameterSteppingList= new LinkedList<ParameterStepping>();
  89. protected boolean useStepping = false;
  90. //Email
  91. private boolean useEmailNotification = false;
  92. //ObjectiveFunction
  93. enum ObjectiveFunction {Normal, Switch};
  94. ObjectiveFunction evaluationFunction = ObjectiveFunction.Normal;
  95. public AlgorithmFrameworkFlex(){
  96. content.setLayout(new BorderLayout());
  97. JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
  98. createOptionPanel() , console);
  99. splitPane.setResizeWeight(0.0);
  100. content.add(splitPane, BorderLayout.CENTER);
  101. content.setPreferredSize(new Dimension(1200,800));
  102. }
  103. private JPanel createOptionPanel() {
  104. JPanel optionPanel = new JPanel(new BorderLayout());
  105. JScrollPane scrollPane = new JScrollPane(createParameterPanel());
  106. scrollPane.setBorder(BorderFactory.createTitledBorder("Parameter"));
  107. optionPanel.add(scrollPane, BorderLayout.CENTER);
  108. optionPanel.add(createButtonPanel(), BorderLayout.PAGE_END);
  109. return optionPanel;
  110. }
  111. private Component createParameterPanel() {
  112. JPanel parameterPanel = new JPanel(null);
  113. parameterPanel.setPreferredSize(new Dimension(510,300));
  114. borderPanel.setLayout(new BoxLayout(borderPanel, BoxLayout.PAGE_AXIS));
  115. addIntParameter("Rounds", rounds, intInput -> rounds = intInput, () -> rounds, 1);
  116. JScrollPane scrollPane = new JScrollPane(borderPanel);
  117. scrollPane.setBounds(10, 0, 850, 292);
  118. scrollPane.setBorder(BorderFactory.createEmptyBorder());
  119. parameterPanel.add(scrollPane);
  120. JButton selectGroupNodeButton = new JButton("Select GroupNode");
  121. selectGroupNodeButton.setBounds(900, 0, 185, 30);
  122. selectGroupNodeButton.addActionListener(actionEvent -> selectGroupNode());
  123. parameterPanel.add(selectGroupNodeButton);
  124. JProgressBar progressBar = runProgressbar.getJProgressBar();
  125. progressBar.setBounds(900, 35, 185, 20);
  126. progressBar.setStringPainted(true);
  127. parameterPanel.add(progressBar);
  128. JCheckBox useElements = new JCheckBox("Elements");
  129. useElements.setSelected(algoUseElements);
  130. useElements.setBounds(900, 70, 185, 20);
  131. useElements.addActionListener(actionEvent -> algoUseElements = useElements.isSelected());
  132. parameterPanel.add(useElements);
  133. JCheckBox useSwitches = new JCheckBox("Switches");
  134. useSwitches.setSelected(algoUseSwitches);
  135. useSwitches.setBounds(900, 90, 185, 20);
  136. useSwitches.addActionListener(actionEvent -> algoUseSwitches = useSwitches.isSelected());
  137. parameterPanel.add(useSwitches);
  138. JCheckBox useFlexes = new JCheckBox("Flexibilities");
  139. useFlexes.setSelected(algoUseFlexes);
  140. useFlexes.setBounds(900, 110, 185, 20);
  141. useFlexes.addActionListener(actionEvent -> algoUseFlexes = useFlexes.isSelected());
  142. parameterPanel.add(useFlexes);
  143. JCheckBox useSmartMeter = new JCheckBox("SmartMeter");
  144. useSmartMeter.setSelected(algoUseFlexes);
  145. useSmartMeter.setBounds(900, 130, 185, 20);
  146. useSmartMeter.addActionListener(actionEvent ->
  147. {
  148. cancel();
  149. reset();
  150. algoUseKillSwitch = useSmartMeter.isSelected();
  151. });
  152. parameterPanel.add(useSmartMeter);
  153. String[] objectiveFunctionStrings = { "Normal", "Switch"};
  154. JLabel fitnessLabel = new JLabel("FitnessFunction:");
  155. fitnessLabel.setBounds(910, 160, 90, 20);
  156. parameterPanel.add(fitnessLabel);
  157. JComboBox<String> ofBox = new JComboBox<String>(objectiveFunctionStrings);
  158. ofBox.addActionListener(actionEvent ->
  159. {
  160. boolean pickNormal = ((String)ofBox.getSelectedItem()).equals("Normal");
  161. evaluationFunction = pickNormal?ObjectiveFunction.Normal:ObjectiveFunction.Switch;
  162. });
  163. ofBox.setBounds(1000, 160, 70, 20);
  164. parameterPanel.add(ofBox);
  165. JCheckBox emailNotificationCheckbox = new JCheckBox("EmailNotification");
  166. emailNotificationCheckbox.setSelected(this.useEmailNotification);
  167. emailNotificationCheckbox.setBounds(900, 200, 130, 20);
  168. emailNotificationCheckbox.addActionListener(actionEvent -> useEmailNotification = emailNotificationCheckbox.isSelected());
  169. parameterPanel.add(emailNotificationCheckbox);
  170. JButton emailSettingsButton = new JButton("", new ImageIcon(Import.loadImage(ImagePreference.Button.Settings, 16,16)));
  171. emailSettingsButton.setBounds(1030, 200, 20, 20);
  172. emailSettingsButton.addActionListener(event -> {
  173. EmailNotification.OpenEmailSettings(content);
  174. });
  175. parameterPanel.add(emailSettingsButton);
  176. return parameterPanel;
  177. }
  178. private JPanel createButtonPanel() {
  179. JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
  180. JButton resetButton = new JButton("Reset");
  181. resetButton.setToolTipText("Resets the state to the initial grid configuration.");
  182. resetButton.addActionListener(actionEvent -> reset());
  183. buttonPanel.add(resetButton);
  184. JButton cancelButton = new JButton("Cancel Run");
  185. cancelButton.addActionListener(actionEvent -> cancel());
  186. buttonPanel.add(cancelButton);
  187. JButton fitnessButton = new JButton("Evaluate");
  188. fitnessButton.setToolTipText("Evaluate the current grid configuration.");
  189. fitnessButton.addActionListener(actionEvent -> fitness());
  190. buttonPanel.add(fitnessButton);
  191. JButton runButton = new JButton("Run");
  192. runButton.addActionListener(actionEvent -> {
  193. Runnable task = () -> run();
  194. runThread = new Thread(task);
  195. runThread.start();
  196. });
  197. buttonPanel.add(runButton);
  198. return buttonPanel;
  199. }
  200. //ParameterImports
  201. //int
  202. protected void addIntParameter(String parameterName, int parameterValue, Consumer<Integer> setter, Supplier<Integer> getter) {
  203. this.addIntParameter(parameterName, parameterValue, setter, getter, Integer.MIN_VALUE, Integer.MAX_VALUE);
  204. }
  205. protected void addIntParameter(String parameterName, int parameterValue, Consumer<Integer> setter, Supplier<Integer> getter, int parameterMinValue) {
  206. this.addIntParameter(parameterName, parameterValue, setter, getter, parameterMinValue, Integer.MAX_VALUE);
  207. }
  208. protected void addIntParameter(String parameterName, int parameterValue, Consumer<Integer> setter, Supplier<Integer> getter, int parameterMinValue, int parameterMaxValue) {
  209. JPanel singleParameterPanel = new JPanel();
  210. singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
  211. singleParameterPanel.setAlignmentX(0.0f);
  212. singleParameterPanel.add(new JLabel(parameterName + ": "));
  213. singleParameterPanel.add(Box.createHorizontalGlue());
  214. NumberFormat format = NumberFormat.getIntegerInstance();
  215. format.setGroupingUsed(false);
  216. format.setParseIntegerOnly(true);
  217. NumberFormatter integerFormatter = new NumberFormatter(format);
  218. integerFormatter.setMinimum(parameterMinValue);
  219. integerFormatter.setMaximum(parameterMaxValue);
  220. integerFormatter.setCommitsOnValidEdit(true);
  221. JFormattedTextField singleParameterTextField = new JFormattedTextField(integerFormatter);
  222. singleParameterTextField.setValue(parameterValue);
  223. String minValue = (parameterMinValue == Integer.MIN_VALUE)?"Integer.MIN_VALUE":String.valueOf(parameterMinValue);
  224. String maxValue = (parameterMaxValue == Integer.MAX_VALUE)?"Integer.MAX_VALUE":String.valueOf(parameterMaxValue);
  225. singleParameterTextField.setToolTipText("Only integer \u2208 [" + minValue + "," + maxValue + "]");
  226. singleParameterTextField.addPropertyChangeListener(actionEvent -> setter.accept(Integer.parseInt(singleParameterTextField.getValue().toString())));
  227. singleParameterTextField.setMaximumSize(new Dimension(200, 30));
  228. singleParameterTextField.setPreferredSize(new Dimension(200, 30));
  229. singleParameterPanel.add(singleParameterTextField);
  230. ParameterStepping<Integer> intParameterStepping = new ParameterStepping<Integer>(setter, getter, Integer::sum , (a,b) -> a * b, 1, 1);
  231. intParameterStepping.useThisParameter = false;
  232. parameterSteppingList.add(intParameterStepping);
  233. JCheckBox useSteppingCheckBox = new JCheckBox();
  234. useSteppingCheckBox.setSelected(false);
  235. singleParameterPanel.add(useSteppingCheckBox);
  236. JLabel stepsLabel = new JLabel("Steps: ");
  237. stepsLabel.setEnabled(false);
  238. singleParameterPanel.add(stepsLabel);
  239. NumberFormatter stepFormatter = new NumberFormatter(format);
  240. stepFormatter.setMinimum(1);
  241. stepFormatter.setMaximum(Integer.MAX_VALUE);
  242. stepFormatter.setCommitsOnValidEdit(true);
  243. JFormattedTextField stepsTextField = new JFormattedTextField(stepFormatter);
  244. stepsTextField.setEnabled(false);
  245. stepsTextField.setValue(1);
  246. stepsTextField.setToolTipText("Only integer \u2208 [" + 1 + "," + Integer.MAX_VALUE + "]");
  247. stepsTextField.addPropertyChangeListener(actionEvent -> intParameterStepping.stepps = Integer.parseInt(stepsTextField.getValue().toString()));
  248. stepsTextField.setMaximumSize(new Dimension(40, 30));
  249. stepsTextField.setPreferredSize(new Dimension(40, 30));
  250. singleParameterPanel.add(stepsTextField);
  251. JLabel stepsSizeLabel = new JLabel("Step size: ");
  252. stepsSizeLabel.setEnabled(false);
  253. singleParameterPanel.add(stepsSizeLabel);
  254. JFormattedTextField stepsSizeTextField = new JFormattedTextField(stepFormatter);
  255. stepsSizeTextField.setEnabled(false);
  256. stepsSizeTextField.setValue(1);
  257. stepsSizeTextField.setToolTipText("Only integer \u2208 [" + 1 + "," + Integer.MAX_VALUE + "]");
  258. stepsSizeTextField.addPropertyChangeListener(actionEvent -> intParameterStepping.stepSize = Integer.parseInt(stepsSizeTextField.getValue().toString()));
  259. stepsSizeTextField.setMaximumSize(new Dimension(40, 30));
  260. stepsSizeTextField.setPreferredSize(new Dimension(40, 30));
  261. singleParameterPanel.add(stepsSizeTextField);
  262. useSteppingCheckBox.addActionListener(actionEvent -> {
  263. boolean enabled = useSteppingCheckBox.isSelected();
  264. intParameterStepping.useThisParameter = enabled;
  265. this.useStepping = this.parameterSteppingList.stream().anyMatch(parameter -> parameter.useThisParameter);
  266. stepsLabel.setEnabled(enabled);
  267. stepsTextField.setEnabled(enabled);
  268. stepsSizeLabel.setEnabled(enabled);
  269. stepsSizeTextField.setEnabled(enabled);
  270. });
  271. borderPanel.add(singleParameterPanel);
  272. }
  273. //double
  274. protected void addDoubleParameter(String parameterName, double parameterValue, Consumer<Double> setter, Supplier<Double> getter) {
  275. this.addDoubleParameter(parameterName, parameterValue, setter, getter, Double.MIN_VALUE, Double.MAX_VALUE);
  276. }
  277. protected void addDoubleParameter(String parameterName, double parameterValue, Consumer<Double> setter, Supplier<Double> getter, double parameterMinValue) {
  278. this.addDoubleParameter(parameterName, parameterValue, setter, getter, parameterMinValue, Double.MAX_VALUE);
  279. }
  280. protected void addDoubleParameter(String parameterName, double parameterValue, Consumer<Double> setter, Supplier<Double> getter, double parameterMinValue, double parameterMaxValue) {
  281. JPanel singleParameterPanel = new JPanel();
  282. singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
  283. singleParameterPanel.setAlignmentX(0.0f);
  284. singleParameterPanel.add(new JLabel(parameterName + ": "));
  285. singleParameterPanel.add(Box.createHorizontalGlue());
  286. NumberFormat doubleFormat = NumberFormat.getNumberInstance(Locale.US);
  287. doubleFormat.setMinimumFractionDigits(1);
  288. doubleFormat.setMaximumFractionDigits(10);
  289. doubleFormat.setRoundingMode(RoundingMode.HALF_UP);
  290. NumberFormatter doubleFormatter = new NumberFormatter(doubleFormat);
  291. doubleFormatter.setMinimum(parameterMinValue);
  292. doubleFormatter.setMaximum(parameterMaxValue);
  293. doubleFormatter.setCommitsOnValidEdit(true);
  294. JFormattedTextField singleParameterTextField = new JFormattedTextField(doubleFormatter);
  295. singleParameterTextField.setValue(parameterValue);
  296. String minValue = (parameterMinValue == Double.MIN_VALUE)?"Double.MIN_VALUE":String.valueOf(parameterMinValue);
  297. String maxValue = (parameterMaxValue == Double.MAX_VALUE)?"Double.MAX_VALUE":String.valueOf(parameterMaxValue);
  298. singleParameterTextField.setToolTipText("Only double \u2208 [" + minValue + "," + maxValue + "]");
  299. singleParameterTextField.addPropertyChangeListener(actionEvent -> setter.accept(Double.parseDouble(singleParameterTextField.getValue().toString())));
  300. singleParameterTextField.setMaximumSize(new Dimension(200, 30));
  301. singleParameterTextField.setPreferredSize(new Dimension(200, 30));
  302. singleParameterPanel.add(singleParameterTextField);
  303. ParameterStepping<Double> doubleParameterStepping = new ParameterStepping<Double>(setter, getter, (a,b) -> a+b , (a,b) -> a * b, 1.0, 1);
  304. doubleParameterStepping.useThisParameter = false;
  305. parameterSteppingList.add(doubleParameterStepping);
  306. JCheckBox useSteppingCheckBox = new JCheckBox();
  307. useSteppingCheckBox.setSelected(false);
  308. singleParameterPanel.add(useSteppingCheckBox);
  309. JLabel stepsLabel = new JLabel("Steps: ");
  310. stepsLabel.setEnabled(false);
  311. singleParameterPanel.add(stepsLabel);
  312. NumberFormat format = NumberFormat.getIntegerInstance();
  313. format.setGroupingUsed(false);
  314. format.setParseIntegerOnly(true);
  315. NumberFormatter integerFormatter = new NumberFormatter(format);
  316. integerFormatter.setMinimum(1);
  317. integerFormatter.setMaximum(Integer.MAX_VALUE);
  318. integerFormatter.setCommitsOnValidEdit(true);
  319. JFormattedTextField stepsTextField = new JFormattedTextField(integerFormatter);
  320. stepsTextField.setEnabled(false);
  321. stepsTextField.setValue(1);
  322. stepsTextField.setToolTipText("Only integer \u2208 [" + 1 + "," + Integer.MAX_VALUE + "]");
  323. stepsTextField.addPropertyChangeListener(actionEvent -> doubleParameterStepping.stepps = Integer.parseInt(stepsTextField.getValue().toString()));
  324. stepsTextField.setMaximumSize(new Dimension(40, 30));
  325. stepsTextField.setPreferredSize(new Dimension(40, 30));
  326. singleParameterPanel.add(stepsTextField);
  327. JLabel stepsSizeLabel = new JLabel("Step size: ");
  328. stepsSizeLabel.setEnabled(false);
  329. singleParameterPanel.add(stepsSizeLabel);
  330. NumberFormatter doubleFormatterForStepping = new NumberFormatter(doubleFormat);
  331. doubleFormatterForStepping.setCommitsOnValidEdit(true);
  332. JFormattedTextField stepsSizeTextField = new JFormattedTextField(doubleFormatterForStepping);
  333. stepsSizeTextField.setEnabled(false);
  334. stepsSizeTextField.setValue(1.0);
  335. stepsSizeTextField.setToolTipText("Only double");
  336. stepsSizeTextField.addPropertyChangeListener(actionEvent -> doubleParameterStepping.stepSize = Double.parseDouble(stepsSizeTextField.getValue().toString()));
  337. stepsSizeTextField.setMaximumSize(new Dimension(40, 30));
  338. stepsSizeTextField.setPreferredSize(new Dimension(40, 30));
  339. singleParameterPanel.add(stepsSizeTextField);
  340. useSteppingCheckBox.addActionListener(actionEvent -> {
  341. boolean enabled = useSteppingCheckBox.isSelected();
  342. doubleParameterStepping.useThisParameter = enabled;
  343. this.useStepping = this.parameterSteppingList.stream().anyMatch(parameter -> parameter.useThisParameter);
  344. stepsLabel.setEnabled(enabled);
  345. stepsTextField.setEnabled(enabled);
  346. stepsSizeLabel.setEnabled(enabled);
  347. stepsSizeTextField.setEnabled(enabled);
  348. });
  349. borderPanel.add(singleParameterPanel);
  350. }
  351. //boolean
  352. protected void addBooleanParameter(String parameterName, boolean parameterValue, Consumer<Boolean> setter){
  353. JPanel singleParameterPanel = new JPanel();
  354. singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
  355. singleParameterPanel.setAlignmentX(0.0f);
  356. singleParameterPanel.add(new JLabel(parameterName + ": "));
  357. singleParameterPanel.add(Box.createHorizontalGlue());
  358. JCheckBox useGroupNodeCheckBox = new JCheckBox();
  359. useGroupNodeCheckBox.setSelected(parameterValue);
  360. useGroupNodeCheckBox.addActionListener(actionEvent -> setter.accept(useGroupNodeCheckBox.isSelected()));
  361. singleParameterPanel.add(useGroupNodeCheckBox);
  362. borderPanel.add(singleParameterPanel);
  363. }
  364. private void startTimer(){
  365. startTime = System.currentTimeMillis();
  366. }
  367. private long printElapsedTime(){
  368. long elapsedMilliSeconds = System.currentTimeMillis() - startTime;
  369. console.println("Execution Time in Milliseconds:" + elapsedMilliSeconds);
  370. return elapsedMilliSeconds;
  371. }
  372. private void cancel() {
  373. if(runThread.isAlive()) {
  374. console.println("Cancel run.");
  375. cancel = true;
  376. runProgressbar.cancel();
  377. } else {
  378. console.println("Nothing to cancel.");
  379. }
  380. }
  381. private void fitness() {
  382. if(runThread.isAlive()) {
  383. console.println("Run have to be cancelled first.");
  384. return;
  385. }
  386. double currentFitness = evaluatePosition(extractPositionAndAccess());
  387. resetChain.removeLast();
  388. console.println("Actual Fitnessvalue: " + currentFitness);
  389. }
  390. private void selectGroupNode() {
  391. Object[] possibilities = control.getModel().getCanvas().getAllGroupNodeObjectsRecursive().toArray();
  392. @SuppressWarnings("unchecked")
  393. GroupNode selected = (GroupNode) JOptionPane.showInputDialog(content, "Select GroupNode:", "GroupNode?", JOptionPane.OK_OPTION,new ImageIcon(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)) , possibilities, "");
  394. if(selected != null) {
  395. console.println("Selected: " + selected);
  396. groupNode = Optional.of(selected);
  397. }
  398. }
  399. protected double evaluatePosition(List<Boolean> positionToEvaluate) {
  400. runProgressbar.step();
  401. setState(positionToEvaluate); // execution time critical
  402. double result = evaluateState();
  403. return result;
  404. }
  405. private double evaluateState() {
  406. switch(this.evaluationFunction) {
  407. case Switch:
  408. return SwitchObjectiveFunction.getFitnessValueForState(control.getModel());
  409. case Normal:
  410. default:
  411. return ObjectiveFunctionByCarlos.getFitnessValueForState(control.getModel());
  412. }
  413. }
  414. private void run() {
  415. cancel = false;
  416. control.guiSetEnabled(false);
  417. runPrinter.openStream();
  418. runPrinter.println("");
  419. runPrinter.println("Start:" + stringStatFromRunValues(getRunValuesFromActualState()));
  420. runPrinter.closeStream();
  421. if(this.useStepping) {
  422. initParameterStepping();
  423. do {
  424. executeAlgoWithParameter();
  425. if(cancel) break;
  426. resetState();
  427. }while(updateOneParameter());
  428. resetParameterStepping();
  429. }else {
  430. executeAlgoWithParameter();
  431. }
  432. updateVisual();
  433. runProgressbar.finishedCancel();
  434. control.guiSetEnabled(true);
  435. if(this.useEmailNotification && !cancel) {
  436. EmailNotification.sendEmail(this.getClass().getName() + " finished", "Execution done.");
  437. }
  438. }
  439. @SuppressWarnings("rawtypes")
  440. private void initParameterStepping() {
  441. for(ParameterStepping param :this.parameterSteppingList) {
  442. param.init();
  443. }
  444. }
  445. @SuppressWarnings("rawtypes")
  446. private void resetParameterStepping() {
  447. for(ParameterStepping param :this.parameterSteppingList) {
  448. param.reset();
  449. }
  450. }
  451. @SuppressWarnings("rawtypes")
  452. private boolean updateOneParameter() {
  453. List<ParameterStepping> parameterInUseList = this.parameterSteppingList.stream().filter(param -> param.useThisParameter).collect(Collectors.toList());
  454. Collections.reverse(parameterInUseList);
  455. int lastParameter = parameterInUseList.size() - 1 ;
  456. int actualParameter = 0;
  457. for(ParameterStepping param : parameterInUseList) {
  458. if(param.canUpdate()) {
  459. param.update();
  460. return true;
  461. }else {
  462. if(actualParameter == lastParameter) break;
  463. param.reset();
  464. }
  465. actualParameter++;
  466. }
  467. //No Param can be updated
  468. return false;
  469. }
  470. private void executeAlgoWithParameter(){
  471. double startFitness = evaluatePosition(extractPositionAndAccess());
  472. console.println("BitLength: " + access.size());
  473. resetChain.removeLast();
  474. runPrinter.openStream();
  475. runPrinter.println(algoInformationToPrint());
  476. console.println(algoInformationToPrint());
  477. runPrinter.closeStream();
  478. runProgressbar.start();
  479. Individual runBest = new Individual();
  480. runBest.fitness = Double.MAX_VALUE;
  481. this.avg = new RunAverage();
  482. for(int r = 0; r < rounds; r++)
  483. {
  484. startTimer();
  485. Individual roundBest = executeAlgo();
  486. if(cancel)return;
  487. long executionTime = printElapsedTime();
  488. setState(roundBest.position);
  489. runPrinter.openStream();
  490. runPrinter.println(runList.stream().map(value -> Format.doubleFixedPlaces(2,value)).collect(Collectors.joining(", ")));
  491. RunValues val = getRunValuesFromActualState();
  492. val.result = roundBest.fitness;
  493. val.executionTime = executionTime;
  494. avg.addRun(val);
  495. runPrinter.println("Result: " + Format.doubleFixedPlaces(2,roundBest.fitness) + " ExecutionTime:" + executionTime + " " + stringStatFromRunValues(val));
  496. runPrinter.closeStream();
  497. resetState();
  498. if(roundBest.fitness < runBest.fitness) runBest = roundBest;
  499. }
  500. this.extractPositionAndAccess();
  501. setState(runBest.position);
  502. updateVisual();
  503. console.println("Start: " + Format.doubleFixedPlaces(2,startFitness));
  504. console.println("AlgoResult: " + Format.doubleFixedPlaces(2,runBest.fitness));
  505. if(this.algoUseFlexes)calculateAndPrintFlexInfos();
  506. runPrinter.openStream();
  507. if(rounds > 1) {
  508. RunValues avgRun = avg.getAverage();
  509. runPrinter.println("Average.Result: " + Format.doubleFixedPlaces(2, avgRun.result) + " Average.ExecutionTime:" + avgRun.executionTime + " " + this.stringStatFromRunValues(avg.getAverage(), "Average."));
  510. }
  511. runPrinter.println("");
  512. runPrinter.closeStream();
  513. }
  514. private void calculateAndPrintFlexInfos() {
  515. int amountOfUsedFlex = 0;
  516. List<Flexibility> allFlex = control.getModel().getAllFlexibilities();
  517. int amountOfFlex = allFlex.size();
  518. float cost = 0;
  519. int consumingFlex = 0;
  520. float consumingFlexEnergy = 0.0f;
  521. int producingFlex = 0;
  522. float producingFlexEnergy = 0.0f;
  523. int maxCooldown = 0;
  524. int amountEssential = 0;
  525. int amountHigh = 0;
  526. int amountMedium = 0;
  527. int amountLow = 0;
  528. Stream<Flexibility> allFlexInUse = allFlex.stream().filter(flex -> flex.getState().equals(FlexState.IN_USE));
  529. Iterator<Flexibility> iterInUseFlex = allFlexInUse.iterator();
  530. while(iterInUseFlex.hasNext()) {
  531. Flexibility flex = iterInUseFlex.next();
  532. amountOfUsedFlex++;
  533. cost += flex.cost;
  534. float energy = flex.energyReleased();
  535. if(energy < 0) {
  536. consumingFlex++;
  537. consumingFlexEnergy += -energy;
  538. }else {
  539. producingFlex++;
  540. producingFlexEnergy += energy;
  541. }
  542. if(flex.getCooldown() > maxCooldown) maxCooldown = flex.getCooldown();
  543. switch(flex.getElement().getPriority()) {
  544. case Essential:
  545. amountEssential++;
  546. break;
  547. case High:
  548. amountHigh++;
  549. break;
  550. case Low:
  551. amountLow++;
  552. break;
  553. case Medium:
  554. amountMedium++;
  555. break;
  556. default:
  557. break;
  558. }
  559. }
  560. //Total Flexibilities:
  561. //Used Flexibilities:
  562. console.println("Used Flex [" + amountOfUsedFlex + "/" + amountOfFlex + "]");
  563. //Consuming Flexibilities:
  564. console.println(consumingFlex + " consuimg flexibilities that consumed " + consumingFlexEnergy + "Energy.");
  565. //Producing Flexibilities
  566. console.println(producingFlex + " producing flexibilities that produce " + producingFlexEnergy + "Energy.");
  567. console.println("Flex in use:\t" + "Low= " + amountLow + "\tMedium= " + amountMedium + "\tHigh= " + amountHigh + "\tEssential= " + amountEssential);
  568. //Total cost:
  569. console.println("Total Cost: "+ cost);
  570. //Longest Cooldown
  571. console.println("Max Cooldown: "+ maxCooldown);
  572. //
  573. }
  574. protected abstract Individual executeAlgo();
  575. private void reset() {
  576. if(runThread.isAlive()) {
  577. console.println("Run have to be cancelled First.");
  578. return;
  579. }
  580. if(!resetChain.isEmpty()) {
  581. console.println("Resetting..");
  582. setState(resetChain.getFirst());
  583. resetChain.clear();
  584. control.resetSimulation();
  585. control.getModel().setCurrentIteration(0);
  586. updateVisual();
  587. }else {
  588. console.println("No run inistialized.");
  589. }
  590. }
  591. /**
  592. * To let the User See the current state without touching the Canvas.
  593. */
  594. private void updateVisual() {
  595. control.calculateStateAndVisualForCurrentTimeStep();
  596. }
  597. /**
  598. * Sets the Model back to its original State before the LAST run.
  599. */
  600. private void resetState() {
  601. setState(resetChain.getLast());
  602. }
  603. /**
  604. * Sets the State out of the given position for calculation or to show the user.
  605. * @param position
  606. */
  607. private void setState(List<Boolean> position) {
  608. control.resetSimulation();
  609. int i = 0;
  610. for(Boolean bool: position) {
  611. access.get(i++).setState(bool);
  612. }
  613. control.calculateStateOnlyForCurrentTimeStep();
  614. }
  615. /**
  616. * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
  617. * Also initialize the Access Hashmap to swap faster positions.
  618. * @return
  619. */
  620. protected List<Boolean> extractPositionAndAccess() {
  621. Model model = control.getModel();
  622. this.accessKillSwitch = new HashMap<HolonObject, AccessWrapper>();
  623. access= new ArrayList<AccessWrapper>();
  624. List<Boolean> initialState = new ArrayList<Boolean>();
  625. rollOutNodes(initialState);
  626. resetChain.add(initialState);
  627. if(algoUseFlexes) {
  628. List<Flexibility> flexList = model.getAllFlexibilities();
  629. List<Flexibility> allOfferedFLex = flexList.stream().filter(flex -> flex.getState() == FlexState.OFFERED).toList();
  630. for(Flexibility flex :allOfferedFLex){
  631. //flex.getFlex().getElement().parentObject;
  632. AccessWrapper killSwitchAccess = this.algoUseKillSwitch ? this.accessKillSwitch.get(flex.getElement().parentObject): null;;
  633. access.add(new AccessWrapper(flex, killSwitchAccess));
  634. initialState.add(false);
  635. }
  636. List<Flexibility> allInUseFLex = flexList.stream().filter(flex -> flex.getState() == FlexState.IN_USE).toList();
  637. for(Flexibility flex : allInUseFLex){
  638. AccessWrapper killSwitchAccess = this.algoUseKillSwitch ? this.accessKillSwitch.get(flex.getElement().parentObject): null;
  639. access.add(new AccessWrapper(flex, killSwitchAccess));
  640. initialState.add(true);
  641. }
  642. }
  643. //console.println(access.stream().map(Object::toString).collect(Collectors.joining(", ")));
  644. return initialState;
  645. }
  646. private void rollOutNodes(List<Boolean> positionToInit) {
  647. boolean groupNodeSelected = groupNode.isPresent();
  648. int timeStep = control.getModel().getCurrentIteration();
  649. Stream<HolonObject> holonObjects = groupNodeSelected ? groupNode.get().getAllHolonObjectsRecursive() : control.getModel().getCanvas().getAllHolonObjectsRecursive();
  650. Stream<HolonSwitch> holonSwitches = groupNodeSelected ? groupNode.get().getAllSwitchObjectsRecursive(): control.getModel().getCanvas().getAllSwitchObjectsRecursive();
  651. holonObjects.forEach(hObject -> {
  652. AccessWrapper killSwitchAccess = new AccessWrapper(hObject);
  653. if(this.algoUseKillSwitch) {
  654. positionToInit.add(false);
  655. access.add(killSwitchAccess);
  656. accessKillSwitch.put(hObject, killSwitchAccess);
  657. }
  658. if(this.algoUseElements) {
  659. hObject.elementsStream().forEach(hE -> {
  660. positionToInit.add(hE.active);
  661. access.add(new AccessWrapper(hE, killSwitchAccess));
  662. });
  663. }
  664. });
  665. holonSwitches.forEach(sw -> {
  666. positionToInit.add(sw.getState().isClosed());
  667. access.add(new AccessWrapper(sw));
  668. });
  669. }
  670. //TODO(Tom2022-01-13) fix print
  671. private RunValues getRunValuesFromActualState() {
  672. RunValues val = new RunValues();
  673. //TODO(Tom2021-12-1) what should be printed happen when only groupNode are selected
  674. groupNode.ifPresent(groupnode -> {
  675. // val.producer = dGroupNode.getAmountOfSupplier();
  676. // val.consumer = dGroupNode.getAmountOfConsumer();
  677. // val.passiv = dGroupNode.getAmountOfPassiv();
  678. // val.objects = val.producer + val.consumer + val.passiv;
  679. // val.unsupplied = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
  680. // val.partiallySupplied = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
  681. // val.supplied = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
  682. // val.overSupplied = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
  683. //
  684. //
  685. // val.activeElements = dGroupNode.getAmountOfAktiveElemntsFromHolonObjects();
  686. // val.elements = dGroupNode.getAmountOfElemntsFromHolonObjects();
  687. });
  688. // for(DecoratedNetwork net : state.getNetworkList()) {
  689. // val.consumer += net.getAmountOfConsumer();
  690. // val.producer += net.getAmountOfSupplier();
  691. // val.passiv += net.getAmountOfPassiv();
  692. // val.unsupplied += net.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
  693. // val.partiallySupplied += net.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
  694. // val.supplied += net.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
  695. // val.overSupplied += net.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
  696. // val.elements += net.getAmountOfElements();
  697. // val.activeElements += net.getAmountOfActiveElements();
  698. // val.consumption += net.getTotalConsumption();
  699. // val.production += net.getTotalProduction();
  700. // }
  701. // val.objects = val.consumer + val.producer + val.passiv;
  702. // val.difference= Math.abs(val.production - val.consumption);
  703. //
  704. //
  705. // List<Flexibility> flexList = control.getModel().getAllFlexibilities();
  706. // List<Flexibility> flexActiveList = flexList.stream().filter(flex -> flex.getState().equals(FlexState.IN_USE)).toList();
  707. //
  708. // val.essentialFlex = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Essential).count();
  709. // val.highFlex = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.High).count();
  710. // val.mediumFlex = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Medium).count();
  711. // val.lowFlex = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Low).count();
  712. // val.flexebilities = val.essentialFlex + val.highFlex + val.mediumFlex + val.lowFlex;
  713. // val.holon = state.getNetworkList().size();
  714. // val.switches = state.getDecoratedSwitches().size();
  715. // val.activeSwitches = (int)state.getDecoratedSwitches().stream().filter(dswitch -> (dswitch.getState() == SwitchState.Closed)).count();
  716. //
  717. // DoubleSummaryStatistics overStat = state.getNetworkList().stream().flatMap(net -> {
  718. // return net.getConsumerList().stream().filter(con -> con.getState() == HolonObjectState.OVER_SUPPLIED);
  719. // }).mapToDouble(con -> con.getSupplyBarPercentage()).summaryStatistics();
  720. //
  721. // DoubleSummaryStatistics partiallyStat = state.getNetworkList().stream().flatMap(net -> {
  722. // return net.getConsumerList().stream().filter(con -> con.getState() == HolonObjectState.PARTIALLY_SUPPLIED);
  723. // }).mapToDouble(con -> con.getSupplyBarPercentage()).summaryStatistics();
  724. //
  725. // val.partiallyMin = filterInf(partiallyStat.getMin());
  726. // val.partiallyMax = filterInf(partiallyStat.getMax());
  727. // val.partiallyAverage = filterInf(partiallyStat.getAverage());
  728. //
  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.elementsStream().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.setMode(SwitchMode.Manual);
  996. hSwitch.setManualState(state ? SwitchState.Closed: SwitchState.Open);
  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.elementsStream().forEach(hE -> {
  1006. hE.active = false;
  1007. });
  1008. }else {
  1009. List<HolonElement> eleList = hObject.elementsStream().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. }