TopologieAlgorithmFramework.java 42 KB

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