TopologieAlgorithmFramework.java 45 KB

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