TopologieAlgorithmFramework.java 44 KB

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