TopologieAlgorithmFramework.java 44 KB

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