TopologieAlgorithmFramework.java 45 KB

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