TopologieAlgorithmFramework.java 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266
  1. package holeg.api;
  2. import java.awt.BorderLayout;
  3. import java.awt.Dimension;
  4. import java.awt.FlowLayout;
  5. import java.io.BufferedWriter;
  6. import java.io.File;
  7. import java.io.FileOutputStream;
  8. import java.io.IOException;
  9. import java.io.OutputStreamWriter;
  10. import java.math.RoundingMode;
  11. import java.text.NumberFormat;
  12. import java.util.ArrayList;
  13. import java.util.Collections;
  14. import java.util.HashMap;
  15. import java.util.HashSet;
  16. import java.util.LinkedList;
  17. import java.util.List;
  18. import java.util.Locale;
  19. import java.util.Objects;
  20. import java.util.Optional;
  21. import java.util.function.BiFunction;
  22. import java.util.function.Consumer;
  23. import java.util.function.Supplier;
  24. import java.util.stream.Collectors;
  25. import java.util.stream.Stream;
  26. import javax.swing.BorderFactory;
  27. import javax.swing.Box;
  28. import javax.swing.BoxLayout;
  29. import javax.swing.JButton;
  30. import javax.swing.JCheckBox;
  31. import javax.swing.JFileChooser;
  32. import javax.swing.JFormattedTextField;
  33. import javax.swing.JLabel;
  34. import javax.swing.JPanel;
  35. import javax.swing.JProgressBar;
  36. import javax.swing.JScrollPane;
  37. import javax.swing.JSeparator;
  38. import javax.swing.JSplitPane;
  39. import javax.swing.text.NumberFormatter;
  40. import holeg.algorithm.objective_function.TopologieObjectiveFunction;
  41. import holeg.model.AbstractCanvasObject;
  42. import holeg.model.Edge;
  43. import holeg.model.GroupNode;
  44. import holeg.model.HolonObject;
  45. import holeg.model.HolonSwitch;
  46. import holeg.model.Node;
  47. import holeg.model.HolonSwitch.SwitchMode;
  48. import holeg.model.HolonSwitch.SwitchState;
  49. import holeg.preferences.ImagePreference;
  50. import holeg.ui.controller.Control;
  51. import holeg.ui.model.Model;
  52. import holeg.ui.view.component.Console;
  53. import holeg.ui.view.main.Category;
  54. public abstract class TopologieAlgorithmFramework implements AddOn{
  55. //Algo
  56. protected int rounds = 1;
  57. protected int amountOfNewCables = 20;
  58. //Panel
  59. private JPanel content = new JPanel();
  60. protected Console console = new Console();
  61. private JPanel borderPanel = new JPanel();
  62. private HashMap<String, JPanel> panelMap = new HashMap<String, JPanel>();
  63. //Settings groupNode
  64. private Optional<GroupNode> groupNode = Optional.empty();
  65. //access
  66. private ArrayList<AccessWrapper> accessWildcards = new ArrayList<AccessWrapper>();
  67. LinkedList<List<Integer>> resetChain = new LinkedList<List<Integer>>();
  68. private HashMap<Integer, AbstractCanvasObject> accessIntToObject = new HashMap<Integer, AbstractCanvasObject>();
  69. private HashMap<AbstractCanvasObject, Integer> accessObjectToInt = new HashMap<AbstractCanvasObject, Integer>();
  70. private HashMap<Integer, AbstractCanvasObject> accessIntegerToWildcard = new HashMap<Integer, AbstractCanvasObject>();
  71. private HashMap<AbstractCanvasObject, GroupNode> accessGroupNode = new HashMap<AbstractCanvasObject, GroupNode>();
  72. private HashSet<IndexCable> cableSet = new HashSet<IndexCable>();
  73. private ArrayList<IndexCable> cableList = new ArrayList<IndexCable>();
  74. private HashMap<IndexCable, Double> addedIndexCable = new HashMap<IndexCable, Double>();
  75. private int countForAccessMap = 0;
  76. private int amountOfExistingCables = 0;
  77. private ArrayList<HolonSwitch> switchList = new ArrayList<HolonSwitch>();
  78. private HashMap<HolonSwitch, GroupNode> accessSwitchGroupNode = new HashMap<HolonSwitch, GroupNode>();
  79. private ArrayList<Edge> edgeList = new ArrayList<Edge>();
  80. boolean algoUseElements = false, algoUseSwitches = true, algoUseFlexes = true;
  81. //time
  82. private long startTime;
  83. private RunProgressBar runProgressbar = new RunProgressBar();
  84. //concurrency
  85. private Thread runThread = new Thread();
  86. protected boolean cancel = false;
  87. //holeg interaction
  88. protected Control control;
  89. //printing
  90. private Printer runPrinter = new Printer(plottFileName());
  91. protected List<Double> runList = new LinkedList<Double>();
  92. //Parameter
  93. @SuppressWarnings("rawtypes")
  94. LinkedList<ParameterStepping> parameterSteppingList= new LinkedList<ParameterStepping>();
  95. protected boolean useStepping = false;
  96. //SwitchButton
  97. public TopologieAlgorithmFramework(){
  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("Parameters"));
  109. optionPanel.add(scrollPane, BorderLayout.CENTER);
  110. optionPanel.add(createButtonPanel(), BorderLayout.PAGE_END);
  111. return optionPanel;
  112. }
  113. private JPanel 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("Number of New Cables", amountOfNewCables, intInput -> amountOfNewCables = intInput, () -> amountOfNewCables, 0);
  118. addSeperator();
  119. addIntParameter("Repetitions", rounds, intInput -> rounds = intInput, () -> rounds, 1);
  120. JScrollPane scrollPane = new JScrollPane(borderPanel);
  121. scrollPane.setBounds(10, 0, 850, 292);
  122. scrollPane.setBorder(BorderFactory.createEmptyBorder());
  123. parameterPanel.add(scrollPane);
  124. JProgressBar progressBar = runProgressbar.getJProgressBar();
  125. progressBar.setBounds(900, 35, 185, 20);
  126. progressBar.setStringPainted(true);
  127. parameterPanel.add(progressBar);
  128. JButton addCategoryButton = new JButton("Add Category");
  129. addCategoryButton.setBounds(900, 65, 185, 30);
  130. addCategoryButton.addActionListener(clicked -> createWildcardsCategory());
  131. parameterPanel.add(addCategoryButton);
  132. return parameterPanel;
  133. }
  134. private JPanel createButtonPanel() {
  135. JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
  136. JButton toggleSwitchesButton = new JButton("Toggle Switches");
  137. toggleSwitchesButton.setToolTipText("Set all switches active or inactive.");
  138. toggleSwitchesButton.addActionListener(actionEvent -> toggleSwitches());
  139. buttonPanel.add(toggleSwitchesButton);
  140. JButton resetButton = new JButton("Reset");
  141. resetButton.setToolTipText("Resets the State to before the Algorithm has runed.");
  142. resetButton.addActionListener(actionEvent -> reset());
  143. buttonPanel.add(resetButton);
  144. JButton cancelButton = new JButton("Cancel Run");
  145. cancelButton.addActionListener(actionEvent -> cancel());
  146. buttonPanel.add(cancelButton);
  147. JButton fitnessButton = new JButton("Fitness");
  148. fitnessButton.setToolTipText("Fitness for the current state.");
  149. fitnessButton.addActionListener(actionEvent -> fitness());
  150. buttonPanel.add(fitnessButton);
  151. JButton runButton = new JButton("Run");
  152. runButton.addActionListener(actionEvent -> {
  153. if(runThread.isAlive()) {
  154. return;
  155. }
  156. reset();
  157. this.resetAllList();
  158. resetChain.clear();
  159. Runnable task = () -> run();
  160. runThread = new Thread(task);
  161. runThread.start();
  162. });
  163. buttonPanel.add(runButton);
  164. return buttonPanel;
  165. }
  166. //ParameterImports
  167. private void toggleSwitches() {
  168. List<HolonSwitch> allSwitchList = control.getModel().getCanvas().getAllSwitchObjectsRecursive().toList();
  169. if(allSwitchList.isEmpty()) return;
  170. SwitchState set = allSwitchList.get(0).getManualState();
  171. allSwitchList.forEach(hSwitch -> {
  172. hSwitch.setMode(SwitchMode.Manual);
  173. hSwitch.setManualState(SwitchState.opposite(set));
  174. });
  175. updateVisual();
  176. }
  177. //addSeperator
  178. protected void addSeperator() {
  179. borderPanel.add(Box.createRigidArea(new Dimension(5, 5)));
  180. borderPanel.add(new JSeparator());
  181. borderPanel.add(Box.createRigidArea(new Dimension(5, 5)));
  182. }
  183. //int
  184. protected void addIntParameter(String parameterName, int parameterValue, Consumer<Integer> setter, Supplier<Integer> getter) {
  185. this.addIntParameter(parameterName, parameterValue, setter, getter, true, Integer.MIN_VALUE, Integer.MAX_VALUE);
  186. }
  187. protected void addIntParameter(String parameterName, int parameterValue, Consumer<Integer> setter, Supplier<Integer> getter, int parameterMinValue) {
  188. this.addIntParameter(parameterName, parameterValue, setter, getter, true, parameterMinValue, Integer.MAX_VALUE);
  189. }
  190. protected void addIntParameter(String parameterName, int parameterValue, Consumer<Integer> setter, Supplier<Integer> getter, boolean visible, int parameterMinValue, int parameterMaxValue) {
  191. JPanel singleParameterPanel = new JPanel();
  192. singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
  193. singleParameterPanel.setAlignmentX(0.0f);
  194. singleParameterPanel.add(new JLabel(parameterName + ": "));
  195. singleParameterPanel.add(Box.createHorizontalGlue());
  196. NumberFormat format = NumberFormat.getIntegerInstance();
  197. format.setGroupingUsed(false);
  198. format.setParseIntegerOnly(true);
  199. NumberFormatter integerFormatter = new NumberFormatter(format);
  200. integerFormatter.setMinimum(parameterMinValue);
  201. integerFormatter.setMaximum(parameterMaxValue);
  202. integerFormatter.setCommitsOnValidEdit(true);
  203. JFormattedTextField singleParameterTextField = new JFormattedTextField(integerFormatter);
  204. singleParameterTextField.setValue(parameterValue);
  205. String minValue = (parameterMinValue == Integer.MIN_VALUE)?"Integer.MIN_VALUE":String.valueOf(parameterMinValue);
  206. String maxValue = (parameterMaxValue == Integer.MAX_VALUE)?"Integer.MAX_VALUE":String.valueOf(parameterMaxValue);
  207. singleParameterTextField.setToolTipText("Only integer \u2208 [" + minValue + "," + maxValue + "]");
  208. singleParameterTextField.addPropertyChangeListener(actionEvent -> setter.accept(Integer.parseInt(singleParameterTextField.getValue().toString())));
  209. singleParameterTextField.setMaximumSize(new Dimension(200, 30));
  210. singleParameterTextField.setPreferredSize(new Dimension(200, 30));
  211. singleParameterPanel.add(singleParameterTextField);
  212. ParameterStepping<Integer> intParameterStepping = new ParameterStepping<Integer>(setter, getter, Integer::sum , (a,b) -> a * b, 1, 1);
  213. intParameterStepping.useThisParameter = false;
  214. parameterSteppingList.add(intParameterStepping);
  215. JCheckBox useSteppingCheckBox = new JCheckBox();
  216. useSteppingCheckBox.setSelected(false);
  217. singleParameterPanel.add(useSteppingCheckBox);
  218. JLabel stepsLabel = new JLabel("Steps: ");
  219. stepsLabel.setEnabled(false);
  220. singleParameterPanel.add(stepsLabel);
  221. NumberFormatter stepFormatter = new NumberFormatter(format);
  222. stepFormatter.setMinimum(1);
  223. stepFormatter.setMaximum(Integer.MAX_VALUE);
  224. stepFormatter.setCommitsOnValidEdit(true);
  225. JFormattedTextField stepsTextField = new JFormattedTextField(stepFormatter);
  226. stepsTextField.setEnabled(false);
  227. stepsTextField.setValue(1);
  228. stepsTextField.setToolTipText("Only integer \u2208 [" + 1 + "," + Integer.MAX_VALUE + "]");
  229. stepsTextField.addPropertyChangeListener(actionEvent -> intParameterStepping.stepps = Integer.parseInt(stepsTextField.getValue().toString()));
  230. stepsTextField.setMaximumSize(new Dimension(40, 30));
  231. stepsTextField.setPreferredSize(new Dimension(40, 30));
  232. singleParameterPanel.add(stepsTextField);
  233. JLabel stepsSizeLabel = new JLabel("StepsSize: ");
  234. stepsSizeLabel.setEnabled(false);
  235. singleParameterPanel.add(stepsSizeLabel);
  236. JFormattedTextField stepsSizeTextField = new JFormattedTextField(stepFormatter);
  237. stepsSizeTextField.setEnabled(false);
  238. stepsSizeTextField.setValue(1);
  239. stepsSizeTextField.setToolTipText("Only integer \u2208 [" + 1 + "," + Integer.MAX_VALUE + "]");
  240. stepsSizeTextField.addPropertyChangeListener(actionEvent -> intParameterStepping.stepSize = Integer.parseInt(stepsSizeTextField.getValue().toString()));
  241. stepsSizeTextField.setMaximumSize(new Dimension(40, 30));
  242. stepsSizeTextField.setPreferredSize(new Dimension(40, 30));
  243. singleParameterPanel.add(stepsSizeTextField);
  244. useSteppingCheckBox.addActionListener(actionEvent -> {
  245. boolean enabled = useSteppingCheckBox.isSelected();
  246. intParameterStepping.useThisParameter = enabled;
  247. this.useStepping = this.parameterSteppingList.stream().anyMatch(parameter -> parameter.useThisParameter);
  248. stepsLabel.setEnabled(enabled);
  249. stepsTextField.setEnabled(enabled);
  250. stepsSizeLabel.setEnabled(enabled);
  251. stepsSizeTextField.setEnabled(enabled);
  252. });
  253. panelMap.put(parameterName, singleParameterPanel);
  254. singleParameterPanel.setVisible(visible);
  255. borderPanel.add(singleParameterPanel);
  256. }
  257. //double
  258. protected void addDoubleParameter(String parameterName, double parameterValue, Consumer<Double> setter, Supplier<Double> getter) {
  259. this.addDoubleParameter(parameterName, parameterValue, setter, getter, true, Double.MIN_VALUE, Double.MAX_VALUE);
  260. }
  261. protected void addDoubleParameter(String parameterName, double parameterValue, Consumer<Double> setter, Supplier<Double> getter, double parameterMinValue) {
  262. this.addDoubleParameter(parameterName, parameterValue, setter, getter, true, parameterMinValue, Double.MAX_VALUE);
  263. }
  264. protected void addDoubleParameter(String parameterName, double parameterValue, Consumer<Double> setter, Supplier<Double> getter, boolean visible, double parameterMinValue, double parameterMaxValue) {
  265. JPanel singleParameterPanel = new JPanel();
  266. singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
  267. singleParameterPanel.setAlignmentX(0.0f);
  268. singleParameterPanel.add(new JLabel(parameterName + ": "));
  269. singleParameterPanel.add(Box.createHorizontalGlue());
  270. NumberFormat doubleFormat = NumberFormat.getNumberInstance(Locale.US);
  271. doubleFormat.setMinimumFractionDigits(1);
  272. doubleFormat.setMaximumFractionDigits(10);
  273. doubleFormat.setRoundingMode(RoundingMode.HALF_UP);
  274. NumberFormatter doubleFormatter = new NumberFormatter(doubleFormat);
  275. doubleFormatter.setMinimum(parameterMinValue);
  276. doubleFormatter.setMaximum(parameterMaxValue);
  277. doubleFormatter.setCommitsOnValidEdit(true);
  278. JFormattedTextField singleParameterTextField = new JFormattedTextField(doubleFormatter);
  279. singleParameterTextField.setValue(parameterValue);
  280. String minValue = (parameterMinValue == Double.MIN_VALUE)?"Double.MIN_VALUE":String.valueOf(parameterMinValue);
  281. String maxValue = (parameterMaxValue == Double.MAX_VALUE)?"Double.MAX_VALUE":String.valueOf(parameterMaxValue);
  282. singleParameterTextField.setToolTipText("Only double \u2208 [" + minValue + "," + maxValue + "]");
  283. singleParameterTextField.addPropertyChangeListener(actionEvent -> setter.accept(Double.parseDouble(singleParameterTextField.getValue().toString())));
  284. singleParameterTextField.setMaximumSize(new Dimension(200, 30));
  285. singleParameterTextField.setPreferredSize(new Dimension(200, 30));
  286. singleParameterPanel.add(singleParameterTextField);
  287. ParameterStepping<Double> doubleParameterStepping = new ParameterStepping<Double>(setter, getter, (a,b) -> a+b , (a,b) -> a * b, 1.0, 1);
  288. doubleParameterStepping.useThisParameter = false;
  289. parameterSteppingList.add(doubleParameterStepping);
  290. JCheckBox useSteppingCheckBox = new JCheckBox();
  291. useSteppingCheckBox.setSelected(false);
  292. singleParameterPanel.add(useSteppingCheckBox);
  293. JLabel stepsLabel = new JLabel("Steps: ");
  294. stepsLabel.setEnabled(false);
  295. singleParameterPanel.add(stepsLabel);
  296. NumberFormat format = NumberFormat.getIntegerInstance();
  297. format.setGroupingUsed(false);
  298. format.setParseIntegerOnly(true);
  299. NumberFormatter integerFormatter = new NumberFormatter(format);
  300. integerFormatter.setMinimum(1);
  301. integerFormatter.setMaximum(Integer.MAX_VALUE);
  302. integerFormatter.setCommitsOnValidEdit(true);
  303. JFormattedTextField stepsTextField = new JFormattedTextField(integerFormatter);
  304. stepsTextField.setEnabled(false);
  305. stepsTextField.setValue(1);
  306. stepsTextField.setToolTipText("Only integer \u2208 [" + 1 + "," + Integer.MAX_VALUE + "]");
  307. stepsTextField.addPropertyChangeListener(actionEvent -> doubleParameterStepping.stepps = Integer.parseInt(stepsTextField.getValue().toString()));
  308. stepsTextField.setMaximumSize(new Dimension(40, 30));
  309. stepsTextField.setPreferredSize(new Dimension(40, 30));
  310. singleParameterPanel.add(stepsTextField);
  311. JLabel stepsSizeLabel = new JLabel("StepsSize: ");
  312. stepsSizeLabel.setEnabled(false);
  313. singleParameterPanel.add(stepsSizeLabel);
  314. NumberFormatter doubleFormatterForStepping = new NumberFormatter(doubleFormat);
  315. doubleFormatterForStepping.setCommitsOnValidEdit(true);
  316. JFormattedTextField stepsSizeTextField = new JFormattedTextField(doubleFormatterForStepping);
  317. stepsSizeTextField.setEnabled(false);
  318. stepsSizeTextField.setValue(1.0);
  319. stepsSizeTextField.setToolTipText("Only double");
  320. stepsSizeTextField.addPropertyChangeListener(actionEvent -> doubleParameterStepping.stepSize = Double.parseDouble(stepsSizeTextField.getValue().toString()));
  321. stepsSizeTextField.setMaximumSize(new Dimension(40, 30));
  322. stepsSizeTextField.setPreferredSize(new Dimension(40, 30));
  323. singleParameterPanel.add(stepsSizeTextField);
  324. useSteppingCheckBox.addActionListener(actionEvent -> {
  325. boolean enabled = useSteppingCheckBox.isSelected();
  326. doubleParameterStepping.useThisParameter = enabled;
  327. this.useStepping = this.parameterSteppingList.stream().anyMatch(parameter -> parameter.useThisParameter);
  328. stepsLabel.setEnabled(enabled);
  329. stepsTextField.setEnabled(enabled);
  330. stepsSizeLabel.setEnabled(enabled);
  331. stepsSizeTextField.setEnabled(enabled);
  332. });
  333. panelMap.put(parameterName, singleParameterPanel);
  334. singleParameterPanel.setVisible(visible);
  335. borderPanel.add(singleParameterPanel);
  336. }
  337. //boolean
  338. protected void addBooleanParameter(String parameterName, boolean parameterValue, Consumer<Boolean> setter, List<String> showParameterNames, List<String> hideParameterNames){
  339. JPanel singleParameterPanel = new JPanel();
  340. panelMap.put(parameterName, singleParameterPanel);
  341. singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
  342. singleParameterPanel.setAlignmentX(0.0f);
  343. singleParameterPanel.add(new JLabel(parameterName + ": "));
  344. singleParameterPanel.add(Box.createHorizontalGlue());
  345. JCheckBox useGroupNodeCheckBox = new JCheckBox();
  346. useGroupNodeCheckBox.addActionListener(actionEvent -> {
  347. setter.accept(useGroupNodeCheckBox.isSelected());
  348. showParameterNames.forEach(string -> panelMap.get(string).setVisible(useGroupNodeCheckBox.isSelected()));
  349. hideParameterNames.forEach(string -> panelMap.get(string).setVisible(!useGroupNodeCheckBox.isSelected()));
  350. });
  351. useGroupNodeCheckBox.setSelected(parameterValue);
  352. singleParameterPanel.add(useGroupNodeCheckBox);
  353. borderPanel.add(singleParameterPanel);
  354. }
  355. private void startTimer(){
  356. startTime = System.currentTimeMillis();
  357. }
  358. private long printElapsedTime(){
  359. long elapsedMilliSeconds = System.currentTimeMillis() - startTime;
  360. console.println("Execution Time of Algo in Milliseconds:" + elapsedMilliSeconds);
  361. return elapsedMilliSeconds;
  362. }
  363. private void cancel() {
  364. if(runThread.isAlive()) {
  365. console.println("Cancel run.");
  366. cancel = true;
  367. runProgressbar.cancel();
  368. } else {
  369. console.println("Nothing to cancel.");
  370. }
  371. }
  372. private void createWildcardsCategory() {
  373. Optional<Category> category = control.findCategoryWithName("Wildcards");
  374. if(category.isEmpty()) {
  375. control.createCategoryWithName("Wildcards");
  376. }
  377. }
  378. private void fitness() {
  379. if(runThread.isAlive()) {
  380. console.println("Run have to be cancelled First.");
  381. return;
  382. }
  383. // reset();
  384. // this.extractPositionAndAccess();
  385. double currentFitness = evaluateNetworkAndPrint();
  386. console.println("Actual Fitnessvalue: " + currentFitness);
  387. }
  388. protected double evaluatePosition(List<Integer> positionToEvaluate) {
  389. setState(positionToEvaluate); // execution time critical
  390. return evaluateNetwork();
  391. }
  392. private double evaluateNetwork() {
  393. runProgressbar.step();
  394. return evaluateState(control.getModel(), calculateAmountOfAddedSwitches(), addedCableMeter(), false);
  395. }
  396. private double evaluateNetworkAndPrint() {
  397. runProgressbar.step();
  398. openAllSwitchInSwitchList();
  399. control.calculateStateOnlyForCurrentTimeStep();
  400. return evaluateState(control.getModel() ,calculateAmountOfAddedSwitches(), addedCableMeter(), true);
  401. }
  402. private void openAllSwitchInSwitchList() {
  403. for(HolonSwitch hSwitch: switchList) {
  404. hSwitch.setMode(SwitchMode.Manual);
  405. hSwitch.setManualState(SwitchState.Open);
  406. }
  407. }
  408. private double addedCableMeter() {
  409. return addedIndexCable.values().stream().reduce(0.0, Double::sum);
  410. }
  411. private int calculateAmountOfAddedSwitches() {
  412. return (int)this.switchList.stream().filter(sw -> sw.getName().contains("AddedSwitch")).count();
  413. }
  414. protected abstract double evaluateState(Model model, int amountOfAddedSwitch, double addedCableMeter, boolean moreInfromation);
  415. private void run() {
  416. cancel = false;
  417. control.guiSetEnabled(true);
  418. runPrinter.openStream();
  419. runPrinter.println("");
  420. runPrinter.println("Start:" + stringStatFromActualState());
  421. runPrinter.closeStream();
  422. if(this.useStepping) {
  423. initParameterStepping();
  424. do {
  425. executeAlgoWithParameter();
  426. if(cancel) break;
  427. resetState();
  428. }while(updateOneParameter());
  429. resetParameterStepping();
  430. }else {
  431. executeAlgoWithParameter();
  432. }
  433. TopologieObjectiveFunction.averageLog.clear();
  434. updateVisual();
  435. runProgressbar.finishedCancel();
  436. control.guiSetEnabled(false);
  437. }
  438. @SuppressWarnings("rawtypes")
  439. private void initParameterStepping() {
  440. for(ParameterStepping param :this.parameterSteppingList) {
  441. param.init();
  442. }
  443. }
  444. @SuppressWarnings("rawtypes")
  445. private void resetParameterStepping() {
  446. for(ParameterStepping param :this.parameterSteppingList) {
  447. param.reset();
  448. }
  449. }
  450. @SuppressWarnings("rawtypes")
  451. private boolean updateOneParameter() {
  452. List<ParameterStepping> parameterInUseList = this.parameterSteppingList.stream().filter(param -> param.useThisParameter).collect(Collectors.toList());
  453. Collections.reverse(parameterInUseList);
  454. int lastParameter = parameterInUseList.size() - 1 ;
  455. int actualParameter = 0;
  456. for(ParameterStepping param : parameterInUseList) {
  457. if(param.canUpdate()) {
  458. param.update();
  459. return true;
  460. }else {
  461. if(actualParameter == lastParameter) break;
  462. param.reset();
  463. }
  464. actualParameter++;
  465. }
  466. //No Param can be updated
  467. return false;
  468. }
  469. private void executeAlgoWithParameter(){
  470. double startFitness = evaluatePosition(extractPositionAndAccess());
  471. resetChain.removeLast();
  472. runPrinter.openStream();
  473. runPrinter.println("");
  474. runPrinter.println(algoInformationToPrint());
  475. runPrinter.closeStream();
  476. console.println(algoInformationToPrint());
  477. runProgressbar.start();
  478. Individual runBest = new Individual();
  479. runBest.fitness = Double.MAX_VALUE;
  480. for(int r = 0; r < rounds; r++)
  481. {
  482. resetState();
  483. startTimer();
  484. Individual roundBest = executeAlgo();
  485. if(cancel)return;
  486. long executionTime = printElapsedTime();
  487. setState(roundBest.position);
  488. runPrinter.openStream();
  489. runPrinter.println(runList.stream().map(Object::toString).collect(Collectors.joining(", ")));
  490. runPrinter.println(stringStatFromActualState());
  491. runPrinter.println("Result: " + roundBest.fitness + " ExecutionTime:" + executionTime);
  492. runPrinter.closeStream();
  493. if(roundBest.fitness < runBest.fitness) runBest = roundBest;
  494. }
  495. setState(runBest.position);
  496. openAllSwitchInSwitchList();
  497. updateVisual();
  498. evaluateNetworkAndPrint();
  499. console.println("Start: " + startFitness);
  500. console.println("AlgoResult: " + runBest.fitness);
  501. }
  502. protected abstract Individual executeAlgo();
  503. private void reset() {
  504. if(runThread.isAlive()) {
  505. console.println("Run have to be cancelled First.");
  506. return;
  507. }
  508. if(!resetChain.isEmpty()) {
  509. console.println("Resetting..");
  510. setState(resetChain.getFirst());
  511. resetChain.clear();
  512. control.resetSimulation();
  513. control.getModel().setCurrentIteration(0);
  514. updateVisual();
  515. }else {
  516. console.println("No run inistialized.");
  517. }
  518. }
  519. /**
  520. * To let the User See the current state without touching the Canvas.
  521. */
  522. private void updateVisual() {
  523. control.calculateStateAndVisualForCurrentTimeStep();
  524. }
  525. /**
  526. * Sets the Model back to its original State before the LAST run.
  527. */
  528. private void resetState() {
  529. if(!resetChain.isEmpty()) {
  530. setState(resetChain.removeLast());
  531. }
  532. resetAllList();
  533. }
  534. /**
  535. * Sets the State out of the given position for calculation or to show the user.
  536. * @param position
  537. */
  538. private void setState(List<Integer> position) {
  539. this.removeAllAddedObjects();
  540. for(int i = 0; i < this.amountOfNewCables; i++) {
  541. generateCable(position.get(2 * i), position.get(2 * i + 1), position.get(2 * amountOfNewCables + i) == 1);
  542. }
  543. //Switches new Cable
  544. //Switches existing cable
  545. int count = 0;
  546. for(int i = 3 * amountOfNewCables; i < 3 * this.amountOfNewCables + this.amountOfExistingCables; i++) {
  547. generateEdgeFromIndexCable(cableList.get(count++), position.get(i) == 1);
  548. }
  549. //WildCards
  550. count = 0;
  551. for(int i = 3 * amountOfNewCables + amountOfExistingCables; i < position.size(); i++) {
  552. accessWildcards.get(count++).setState(position.get(i));
  553. }
  554. openAllSwitchInSwitchList();
  555. control.calculateStateOnlyForCurrentTimeStep();
  556. }
  557. /**
  558. * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
  559. * Also initialize the Access Hashmap to swap faster positions.
  560. */
  561. protected List<Integer> extractPositionAndAccess() {
  562. Model model = control.getModel();
  563. resetAllList();
  564. Optional<Category> category = control.findCategoryWithName("Wildcards");
  565. category.ifPresentOrElse(cat -> {
  566. int count = 1;
  567. for(AbstractCanvasObject obj : cat.getObjects()) {
  568. accessIntegerToWildcard.put(count, obj);
  569. count++;
  570. }
  571. }, () -> {
  572. console.println("No 'Wildcards' Category");
  573. });
  574. List<Integer> initialState = new ArrayList<Integer>();
  575. generateAccess(model.getCanvas().getObjectsInThisLayer(), null);
  576. addCables(model.getEdgesOnCanvas());
  577. model.getEdgesOnCanvas().clear();
  578. //New Cables
  579. for(int i = 0; i < this.amountOfNewCables; i++) {
  580. initialState.add(0);
  581. initialState.add(0);
  582. }
  583. //switch in new Cables
  584. for(int i = 0; i < this.amountOfNewCables; i++) {
  585. initialState.add(0);
  586. }
  587. //Switch in initial Cable
  588. cableSet.stream().forEach(indexCale -> initialState.add(0));
  589. amountOfExistingCables = cableSet.size();
  590. //wildcards
  591. for(int i = 0; i < accessWildcards.size(); i++) {
  592. initialState.add(0);
  593. }
  594. resetChain.add(initialState);
  595. //console.println(accessIntToObject.values().stream().map(hO -> hO.getName()).collect(Collectors.joining(", ")));
  596. //console.println(cableSet.stream().map(Object::toString).collect(Collectors.f(", ")));
  597. return initialState;
  598. }
  599. private void resetAllList() {
  600. //-->reset
  601. accessWildcards.clear();
  602. this.countForAccessMap = 0;
  603. amountOfExistingCables = 0;
  604. accessIntToObject.clear();
  605. accessObjectToInt.clear();
  606. cableSet.clear();
  607. cableList.clear();
  608. accessGroupNode.clear();
  609. accessIntegerToWildcard.clear();
  610. addedIndexCable.clear();
  611. switchList.clear();
  612. accessSwitchGroupNode.clear();
  613. edgeList.clear();
  614. //<---
  615. }
  616. /**
  617. * Method to extract the Informations recursively out of the Model.
  618. * @param nodes
  619. */
  620. private void generateAccess(Stream<AbstractCanvasObject> nodes, GroupNode groupnode) {
  621. nodes.forEach(aCps -> {
  622. if(aCps instanceof HolonObject hO) {
  623. accessIntToObject.put(++countForAccessMap, hO);
  624. accessObjectToInt.put(hO, countForAccessMap);
  625. if(hO.getName().contains("Wildcard")) {
  626. accessWildcards.add(new AccessWrapper(hO));
  627. }
  628. if(groupnode != null) {
  629. accessGroupNode.put(hO, groupnode);
  630. }
  631. }
  632. if(aCps instanceof HolonSwitch hSwitch) {
  633. accessIntToObject.put(++countForAccessMap, hSwitch);
  634. accessObjectToInt.put(hSwitch, countForAccessMap);
  635. if(groupnode != null) {
  636. accessGroupNode.put(hSwitch, groupnode);
  637. }
  638. }
  639. if(aCps instanceof Node node) {
  640. accessIntToObject.put(++countForAccessMap, node);
  641. accessObjectToInt.put(node, countForAccessMap);
  642. if(groupnode != null) {
  643. accessGroupNode.put(node, groupnode);
  644. }
  645. }
  646. else if(aCps instanceof GroupNode groupNode) {
  647. generateAccess(groupNode.getObjectsInThisLayer(), groupNode);
  648. }
  649. });
  650. }
  651. protected void resetWildcards() {
  652. this.accessWildcards.forEach(wrapper -> wrapper.resetState());
  653. }
  654. /**
  655. * All Nodes have to be in the access map !!
  656. */
  657. private void addCables(List<Edge> edges) {
  658. for (Edge edge : edges) {
  659. edge.mode = Edge.EdgeMode.Unlimited;
  660. edgeList.add(edge);
  661. //console.println("Cable from " + edge.getA().getName() + " to " + edge.getB().getName());
  662. if(!accessObjectToInt.containsKey(edge.getA())) {
  663. console.println("Node A [" + edge.getA() + "] from Edge[" + edge + "] not exist");
  664. continue;
  665. } else if (!accessObjectToInt.containsKey(edge.getB())) {
  666. console.println("Node B [" + edge.getB() + "]from Edge[" + edge + "] not exist");
  667. continue;
  668. }
  669. IndexCable cable = new IndexCable(accessObjectToInt.get(edge.getA()), accessObjectToInt.get(edge.getB()));
  670. boolean success = cableSet.add(cable);
  671. if(success) {
  672. cableList.add(cable);
  673. }
  674. }
  675. }
  676. private void generateCable(int index0, int index1, boolean switchBetween) {
  677. //If cable isnt valid
  678. if(index0 == 0 || index1 == 0 || index0 == index1) {
  679. //console.println("Cable("+index1+","+index2+ ") isn't valid");
  680. return;
  681. }
  682. IndexCable cable = new IndexCable(index0, index1);
  683. //if cable is in existing cables
  684. if(cableSet.contains(cable) || addedIndexCable.keySet().contains(cable)) {
  685. return;
  686. }
  687. generateEdgeFromIndexCable(cable, switchBetween);
  688. addedIndexCable.put(cable, cable.getLength());
  689. }
  690. private void generateEdgeFromIndexCable(IndexCable cable, boolean switchBetween){
  691. if(switchBetween) {
  692. //generate Switch
  693. AbstractCanvasObject fromObject = accessIntToObject.get(cable.first);
  694. AbstractCanvasObject toObject = accessIntToObject.get(cable.second);
  695. int middleX = (fromObject.getPosition().getX() + toObject.getPosition().getX())/2;
  696. int middleY = (fromObject.getPosition().getY() + toObject.getPosition().getY())/2;
  697. HolonSwitch newSwitch = new HolonSwitch("AddedSwitch");
  698. newSwitch.setPosition(middleX, middleY);
  699. //If fromObject is in Group
  700. if(accessGroupNode.containsKey(fromObject)) {
  701. GroupNode groupnode = accessGroupNode.get(fromObject);
  702. groupnode.add(newSwitch);
  703. accessSwitchGroupNode.put(newSwitch, groupnode);
  704. } else if(accessGroupNode.containsKey(toObject)) {
  705. GroupNode groupnode = accessGroupNode.get(toObject);
  706. groupnode.add(newSwitch);
  707. accessSwitchGroupNode.put(newSwitch, groupnode);
  708. }else {
  709. control.getModel().getCanvas().add(newSwitch);
  710. }
  711. //else if toObject is in Group
  712. this.switchList.add(newSwitch);
  713. //Generate Cable From Object A To Switch
  714. Edge edge1 = new Edge(fromObject, newSwitch, 0);
  715. edge1.mode = Edge.EdgeMode.Unlimited;
  716. control.getModel().getEdgesOnCanvas().add(edge1);
  717. edgeList.add(edge1);
  718. //Generate Cable From Object B To Switch
  719. Edge edge = new Edge(newSwitch, toObject, 0);
  720. edge.mode = Edge.EdgeMode.Unlimited;
  721. control.getModel().getEdgesOnCanvas().add(edge);
  722. edgeList.add(edge);
  723. }else {
  724. Edge edge = new Edge(accessIntToObject.get(cable.first), accessIntToObject.get(cable.second), 0);
  725. edge.mode = Edge.EdgeMode.Unlimited;
  726. control.getModel().getEdgesOnCanvas().add(edge);
  727. edgeList.add(edge);
  728. }
  729. }
  730. private void removeAllAddedObjects() {
  731. control.getModel().getEdgesOnCanvas().removeAll(edgeList);
  732. addedIndexCable.clear();
  733. //control.getModel().getObjectsOnCanvas().removeAll(switchList);
  734. for(HolonSwitch hSwitch: switchList) {
  735. if(this.accessSwitchGroupNode.containsKey(hSwitch)) {
  736. accessSwitchGroupNode.get(hSwitch).remove(hSwitch);
  737. }
  738. else {
  739. control.getModel().getCanvas().remove(hSwitch);
  740. }
  741. }
  742. accessSwitchGroupNode.clear();
  743. switchList.clear();
  744. edgeList.clear();
  745. }
  746. //TODO(Tom2022-01-13): Fix print
  747. private String stringStatFromActualState() {
  748. // if(groupNode != null)
  749. // {
  750. // //GetActualDecoratedGroupNode
  751. // int amountOfSupplier = dGroupNode.getAmountOfSupplier();
  752. // int amountOfConsumer = dGroupNode.getAmountOfConsumer();
  753. // int amountOfPassiv = dGroupNode.getAmountOfPassiv();
  754. // int amountOfObjects = amountOfSupplier + amountOfConsumer + amountOfPassiv;
  755. // int unSuppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
  756. // int partiallySuppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
  757. // int suppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
  758. // int overSuppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
  759. //
  760. //
  761. // int activeElements = dGroupNode.getAmountOfAktiveElemntsFromHolonObjects();
  762. // int elements = dGroupNode.getAmountOfElemntsFromHolonObjects();
  763. // return "HolonObjects["
  764. // + " Producer: " + amountOfSupplier + "/" + amountOfObjects + "("+ (float)amountOfSupplier/(float)amountOfObjects * 100 + "%)"
  765. // + " Unsupplied: " + unSuppliedConsumer + "/" + amountOfObjects + "("+ (float)unSuppliedConsumer/(float)amountOfObjects * 100 + "%)"
  766. // + " PartiallySupplied: " + partiallySuppliedConsumer + "/" + amountOfObjects + "("+ (float)partiallySuppliedConsumer/(float)amountOfObjects * 100 + "%)"
  767. // + " Supplied: " + suppliedConsumer + "/" + amountOfObjects + "("+ (float)suppliedConsumer/(float)amountOfObjects * 100 + "%)"
  768. // + " Passiv: " + overSuppliedConsumer + "/" + amountOfObjects + "("+ (float)overSuppliedConsumer/(float)amountOfObjects * 100 + "%)"
  769. // + "]" + " HolonElemnts["
  770. // + " Active: " + activeElements + "/" + elements + "("+ (float)activeElements/(float)elements * 100 + "%)"
  771. // + "]";
  772. // }
  773. // int amountOfSupplier = 0, amountOfConsumer = 0, amountOfPassiv = 0, unSuppliedConsumer = 0, partiallySuppliedConsumer = 0, suppliedConsumer = 0, overSuppliedConsumer = 0;
  774. // int activeElements = 0, amountOfelements = 0;
  775. // int totalConsumption = 0, totalProduction = 0;
  776. // for(DecoratedNetwork net : state.getNetworkList()) {
  777. // amountOfConsumer += net.getAmountOfConsumer();
  778. // amountOfSupplier += net.getAmountOfSupplier();
  779. // amountOfPassiv += net.getAmountOfPassiv();
  780. // unSuppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
  781. // partiallySuppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
  782. // suppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
  783. // overSuppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
  784. // amountOfelements += net.getAmountOfElements();
  785. // activeElements += net.getAmountOfActiveElements();
  786. // totalConsumption += net.getTotalConsumption();
  787. // totalProduction += net.getTotalProduction();
  788. // }
  789. // int amountOfObjects = amountOfSupplier + amountOfConsumer + amountOfPassiv;
  790. // int difference = Math.abs(totalProduction - totalConsumption);
  791. //
  792. //
  793. //
  794. // int amountHolons = state.getNetworkList().size();
  795. // int amountSwitch = state.getDecoratedSwitches().size();
  796. // int amountActiveSwitch = (int)state.getDecoratedSwitches().stream().filter(dswitch -> (dswitch.getState() == SwitchState.Closed)).count();
  797. //
  798. // int addedSwitches = calculateAmountOfAddedSwitches();
  799. // double addedCableMeters = addedCableMeter();
  800. // double wildcardCost = TopologieObjectiveFunction.calculateWildcardCost(state);
  801. // double cableCost = TopologieObjectiveFunction.calculateWildcardCost(state);
  802. // double switchCost = TopologieObjectiveFunction.calculateWildcardCost(state);
  803. // double totalCost = wildcardCost + cableCost + switchCost;
  804. //
  805. // DoubleSummaryStatistics overStat = state.getNetworkList().stream().flatMap(net -> {
  806. // return net.getConsumerList().stream().filter(con -> con.getState() == HolonObjectState.OVER_SUPPLIED);
  807. // }).mapToDouble(con -> con.getSupplyBarPercentage()).summaryStatistics();
  808. //
  809. // DoubleSummaryStatistics partiallyStat = state.getNetworkList().stream().flatMap(net -> {
  810. // return net.getConsumerList().stream().filter(con -> con.getState() == HolonObjectState.PARTIALLY_SUPPLIED);
  811. // }).mapToDouble(con -> con.getSupplyBarPercentage()).summaryStatistics();
  812. //
  813. // return "HolonObjects["
  814. // + " Passiv: " + percentage(amountOfPassiv, amountOfObjects)
  815. // + " Producer: " + percentage(amountOfSupplier, amountOfObjects)
  816. // + " Consumer: " + percentage(amountOfConsumer, amountOfObjects)
  817. // + " Unsupplied: " + percentage(unSuppliedConsumer, amountOfConsumer)
  818. // + " PartiallySupplied: " + percentage(partiallySuppliedConsumer, amountOfObjects)
  819. // + " with SupplyPercentage(Min: " + partiallyStat.getMin()
  820. // + " Max: "+ partiallyStat.getMax()
  821. // + " Average: " +partiallyStat.getAverage() + ")"
  822. // + " Supplied: " + percentage(suppliedConsumer, amountOfConsumer)
  823. // + " Over: " + percentage(overSuppliedConsumer, amountOfConsumer)
  824. // + " with SupplyPercentage(Min: " + overStat.getMin()
  825. // + " Max: "+ overStat.getMax()
  826. // + " Average: " + overStat.getAverage() + ")"
  827. // + "]" + " HolonElemnts["
  828. // + " Active: " + percentage(activeElements, amountOfelements)
  829. // + "]"
  830. // + " activeSwitches:" + percentage(amountActiveSwitch,amountSwitch)
  831. // + " Holons: " + amountHolons
  832. // + " totalConsumption: " + totalConsumption
  833. // + " totalProduction: " + totalProduction
  834. // + " difference: " + difference
  835. // + " Topologie["
  836. // + " addedCableMeters:" + addedCableMeters
  837. // + " addedSwitches: " + addedSwitches
  838. // + " totalCost: " + totalCost + "("
  839. // + " wildcardCost: " + wildcardCost
  840. // + " cableCost: " + cableCost
  841. // + " switchCost: " + switchCost
  842. // + ")]"
  843. // ;
  844. //
  845. return "";
  846. }
  847. private String percentage(int actual, int max) {
  848. return actual + "/" + max + "("+ (float)actual/(float)max * 100 + "%)";
  849. }
  850. @Override
  851. public JPanel getPanel() {
  852. return content;
  853. }
  854. @Override
  855. public void setController(Control control) {
  856. this.control = control;
  857. }
  858. // | New Cable | Switches | Wildcards |
  859. //return index: | countForAccessMap | 1 | accessWildcards.size()|
  860. public int getMaximumIndexObjects(int index) {
  861. int maximumIndex = -1;
  862. //New Cables
  863. if(index < 2 * amountOfNewCables) {
  864. maximumIndex = this.countForAccessMap;
  865. }
  866. //Switches in existing and in new Cables
  867. else if (index < 3 * amountOfNewCables + this.amountOfExistingCables) {
  868. maximumIndex = 1;
  869. }
  870. //wildcards
  871. else {
  872. maximumIndex = this.accessIntegerToWildcard.size();
  873. }
  874. return maximumIndex;
  875. }
  876. private class RunProgressBar{
  877. //progressbar
  878. private JProgressBar progressBar = new JProgressBar();
  879. private int count = 0;
  880. private boolean isActive = false;
  881. public void step() {
  882. if(isActive) progressBar.setValue(count++);
  883. }
  884. public void start() {
  885. progressBar.setIndeterminate(false);
  886. count = 0;
  887. isActive = true;
  888. progressBar.setValue(0);
  889. progressBar.setMaximum(getProgressBarMaxCount());
  890. }
  891. public void cancel() {
  892. isActive = false;
  893. progressBar.setIndeterminate(true);
  894. }
  895. public void finishedCancel() {
  896. progressBar.setIndeterminate(false);
  897. progressBar.setValue(0);
  898. }
  899. public JProgressBar getJProgressBar(){
  900. return progressBar;
  901. }
  902. }
  903. protected abstract int getProgressBarMaxCount();
  904. protected abstract String algoInformationToPrint();
  905. protected abstract String plottFileName();
  906. public class Printer{
  907. private JFileChooser fileChooser = new JFileChooser();
  908. private BufferedWriter out;
  909. public Printer(String filename){
  910. fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
  911. fileChooser.setSelectedFile(new File(filename));
  912. }
  913. public void openStream() {
  914. File file = fileChooser.getSelectedFile();
  915. try {
  916. file.createNewFile();
  917. out = new BufferedWriter(new OutputStreamWriter(
  918. new FileOutputStream(file, true), "UTF-8"));
  919. } catch (IOException e) {
  920. System.out.println(e.getMessage());
  921. }
  922. }
  923. public void println(String stringToPrint) {
  924. try {
  925. out.write(stringToPrint);
  926. out.newLine();
  927. } catch (IOException e) {
  928. System.out.println(e.getMessage());
  929. }
  930. }
  931. public void closeStream() {
  932. try {
  933. out.close();
  934. } catch (IOException e) {
  935. System.out.println(e.getMessage());
  936. }
  937. }
  938. }
  939. /**
  940. * A Wrapper Class to access wildcards
  941. */
  942. private class AccessWrapper {
  943. int state = 0;
  944. HolonObject wildcard;
  945. public AccessWrapper(HolonObject wildcard) {
  946. this.wildcard = wildcard;
  947. }
  948. public void setState(int state) {
  949. if(this.state != state) {
  950. this.state = state;
  951. if(state > 0) {
  952. wildcard.clearElements();
  953. HolonObject hO = (HolonObject)accessIntegerToWildcard.get(state);
  954. if(hO == null) {
  955. console.println("null set state(" + state + ")");
  956. }else {
  957. if(hO.getName().contains(":")) {
  958. wildcard.setName("Wildcard" + hO.getName().substring(hO.getName().lastIndexOf(":")));
  959. }else {
  960. wildcard.setName("Wildcard");
  961. }
  962. wildcard.add(hO.getElements().toList());
  963. wildcard.setImage(hO.getImage());
  964. }
  965. }else {
  966. resetState();
  967. }
  968. }
  969. }
  970. public void resetState() {
  971. state = 0;
  972. wildcard.setName("Wildcard");
  973. wildcard.setImage(ImagePreference.Canvas.DefaultObject.House);
  974. wildcard.clearElements();
  975. }
  976. public String toString() {
  977. return wildcard + "have state: " + state;
  978. }
  979. }
  980. public class Individual {
  981. public double fitness;
  982. public List<Integer> position;
  983. public Individual(){};
  984. /**
  985. * Copy Constructor
  986. */
  987. public Individual(Individual c){
  988. position = c.position.stream().collect(Collectors.toList());
  989. fitness = c.fitness;
  990. }
  991. }
  992. protected class ParameterStepping<T>{
  993. boolean useThisParameter = false;
  994. String paramaterName;
  995. private int count = 0;
  996. int stepps;
  997. T stepSize;
  998. T startValue;
  999. Consumer<T> setter;
  1000. Supplier<T> getter;
  1001. BiFunction<Integer,T,T> multyply;
  1002. BiFunction<T,T,T> add;
  1003. ParameterStepping(Consumer<T> setter, Supplier<T> getter, BiFunction<T,T,T> add, BiFunction<Integer,T,T> multyply, T stepSize, int stepps){
  1004. this.setter = setter;
  1005. this.getter = getter;
  1006. this.multyply = multyply;
  1007. this.add = add;
  1008. this.stepSize = stepSize;
  1009. this.stepps = stepps;
  1010. }
  1011. void init() {
  1012. startValue = getter.get();
  1013. }
  1014. boolean canUpdate() {
  1015. return count < stepps;
  1016. }
  1017. void update(){
  1018. if(canUpdate()) {
  1019. setter.accept(add.apply(startValue, multyply.apply(count + 1, stepSize)));
  1020. count ++;
  1021. }
  1022. }
  1023. void reset() {
  1024. setter.accept(startValue);
  1025. count = 0;
  1026. }
  1027. }
  1028. public class IndexCable{
  1029. public final Integer first;
  1030. public final Integer second;
  1031. public IndexCable(Integer first, Integer second) {
  1032. if(first.equals(second)) {
  1033. throw new IllegalArgumentException("(" + first + "==" + second + ")"
  1034. + "Two ends of the cable are at the same Object");
  1035. } else if(first.compareTo(second) < 0) {
  1036. this.first = first;
  1037. this.second = second;
  1038. }else {
  1039. this.first = second;
  1040. this.second = first;
  1041. }
  1042. }
  1043. @Override
  1044. public boolean equals(Object o) {
  1045. if(o instanceof IndexCable cable) {
  1046. return Objects.equals(cable.first, first) && Objects.equals(cable.second, second);
  1047. }
  1048. return false;
  1049. }
  1050. @Override
  1051. public int hashCode() {
  1052. return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode());
  1053. }
  1054. @Override
  1055. public String toString() {
  1056. return "{" + first + "," + second + "}";
  1057. }
  1058. public double getLength() {
  1059. return accessIntToObject.get(first).getPosition().getDistance(accessIntToObject.get(second).getPosition());
  1060. }
  1061. }
  1062. }