TopologieAlgorithmFramework.java 43 KB

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