TopologieAlgorithmFramework.java 45 KB

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