TopologieAlgorithmFramework.java 44 KB

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