TopologieAlgorithmFramework.java 44 KB

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