TopologieAlgorithmFramework.java 45 KB

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