TopologieAlgorithmFramework.java 41 KB

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