TopologieAlgorithmFramework.java 45 KB

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