TopologieAlgorithmFramework.java 42 KB

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