TopologieAlgorithmFramework.java 42 KB

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