TopologieAlgorithmFramework.java 43 KB

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