TopologieAlgorithmFramework.java 45 KB

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