TopologieAlgorithmFramework.java 43 KB

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