TopologieAlgorithmFramework.java 42 KB

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