TopologieAlgorithmFramework.java 45 KB

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