TopologieAlgorithmFramework.java 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  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.AbstractCpsObject;
  43. import classes.Category;
  44. import classes.CpsEdge;
  45. import classes.CpsUpperNode;
  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, AbstractCpsObject> accessIntToObject = new HashMap<Integer, AbstractCpsObject>();
  77. private HashMap<AbstractCpsObject, Integer> accessObjectToInt = new HashMap<AbstractCpsObject, Integer>();
  78. private HashMap<Integer, AbstractCpsObject> accessIntegerToWildcard = new HashMap<Integer, AbstractCpsObject>();
  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<CpsEdge> edgeList = new ArrayList<CpsEdge>();
  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. getCables(model.getObjectsOnCanvas());
  543. //New Cables
  544. for(int i = 0; i < this.amountOfNewCables; i++) {
  545. initialState.add(0);
  546. initialState.add(0);
  547. }
  548. //switch in new Cables
  549. for(int i = 0; i < this.amountOfNewCables; i++) {
  550. initialState.add(0);
  551. }
  552. //Switch in initial Cable
  553. cableSet.stream().forEach(indexCale -> initialState.add(0));
  554. amountOfExistingCables = cableSet.size();
  555. //wildcards
  556. for(int i = 0; i < accessWildcards.size(); i++) {
  557. initialState.add(0);
  558. }
  559. resetChain.add(initialState);
  560. //console.println(accessIntToObject.values().stream().map(hO -> hO.getName()).collect(Collectors.joining(", ")));
  561. //console.println(cableSet.stream().map(Object::toString).collect(Collectors.f(", ")));
  562. return initialState;
  563. }
  564. /**
  565. * Method to extract the Informations recursively out of the Model.
  566. * @param nodes
  567. * @param positionToInit
  568. * @param timeStep
  569. */
  570. private void generateAccess(List<AbstractCpsObject> nodes) {
  571. for(AbstractCpsObject aCps : nodes) {
  572. if(aCps instanceof HolonObject) {
  573. HolonObject hO = (HolonObject) aCps;
  574. accessIntToObject.put(++countForAccessMap, hO);
  575. accessObjectToInt.put(hO, countForAccessMap);
  576. if(hO.getName().equals("Wildcard")) {
  577. accessWildcards.add(new AccessWrapper(hO));
  578. }
  579. }
  580. else if(aCps instanceof CpsUpperNode) {
  581. generateAccess(((CpsUpperNode)aCps).getNodes());
  582. }
  583. }
  584. }
  585. private void getCables(List<AbstractCpsObject> nodes) {
  586. for(AbstractCpsObject aCps : nodes) {
  587. if(aCps instanceof CpsUpperNode) {
  588. CpsUpperNode aUpperNode = (CpsUpperNode)aCps;
  589. addCables(aUpperNode.getNodeEdges());
  590. addCables(aUpperNode.getOldEdges());
  591. aUpperNode.getNodeEdges().clear();
  592. aUpperNode.getOldEdges().clear();
  593. getCables(((CpsUpperNode)aCps).getNodes());
  594. }
  595. }
  596. }
  597. protected void resetWildcards() {
  598. this.accessWildcards.forEach(wrapper -> wrapper.resetState());
  599. }
  600. /**
  601. * All Nodes have to be in the access map !!
  602. * @param cables
  603. */
  604. private void addCables(List<CpsEdge> edges) {
  605. for (CpsEdge edge : edges) {
  606. edge.setUnlimitedCapacity(true);
  607. edgeList.add(edge);
  608. //console.println("Cable from " + edge.getA().getName() + " to " + edge.getB().getName());
  609. if(!accessObjectToInt.containsKey(edge.getA())) {
  610. console.println("Node A from Edge[" + edge + "] not exist");
  611. continue;
  612. } else if (!accessObjectToInt.containsKey(edge.getB())) {
  613. console.println("Node B from Edge[" + edge + "] not exist");
  614. continue;
  615. }
  616. IndexCable cable = new IndexCable(accessObjectToInt.get(edge.getA()), accessObjectToInt.get(edge.getB()));
  617. boolean success = cableSet.add(cable);
  618. if(success) {
  619. cableList.add(cable);
  620. }
  621. }
  622. }
  623. private void generateCable(int index0, int index1, boolean switchBetween) {
  624. //If cable isnt valid
  625. if(index0 == 0 || index1 == 0 || index0 == index1) {
  626. //console.println("Cable("+index1+","+index2+ ") isn't valid");
  627. return;
  628. }
  629. IndexCable cable = new IndexCable(index0, index1);
  630. //if cable is in existing cables
  631. if(cableSet.contains(cable) || addedIndexCable.contains(cable)) {
  632. return;
  633. }
  634. generateEdgeFromIndexCable(cable, switchBetween);
  635. addedIndexCable.add(cable);
  636. }
  637. private void generateEdgeFromIndexCable(IndexCable cable, boolean switchBetween){
  638. if(switchBetween) {
  639. //generate Switch
  640. AbstractCpsObject fromObject = accessIntToObject.get(cable.first);
  641. AbstractCpsObject toObject = accessIntToObject.get(cable.second);
  642. int middleX = (fromObject.getPosition().x + toObject.getPosition().x)/2;
  643. int middleY = (fromObject.getPosition().y + toObject.getPosition().y)/2;
  644. HolonSwitch newSwitch = new HolonSwitch("Switch12368");
  645. newSwitch.setPosition(middleX, middleY);
  646. control.getModel().getObjectsOnCanvas().add(newSwitch);
  647. this.switchList.add(newSwitch);
  648. //Generate Cable From Object A To Switch
  649. CpsEdge edge1 = new CpsEdge(fromObject, newSwitch);
  650. edge1.setUnlimitedCapacity(true);
  651. control.getModel().getEdgesOnCanvas().add(edge1);
  652. edgeList.add(edge1);
  653. //Generate Cable From Object B To Switch
  654. CpsEdge edge = new CpsEdge(newSwitch, toObject);
  655. edge.setUnlimitedCapacity(true);
  656. control.getModel().getEdgesOnCanvas().add(edge);
  657. edgeList.add(edge);
  658. }else {
  659. CpsEdge edge = new CpsEdge(accessIntToObject.get(cable.first), accessIntToObject.get(cable.second));
  660. edge.setUnlimitedCapacity(true);
  661. control.getModel().getEdgesOnCanvas().add(edge);
  662. edgeList.add(edge);
  663. }
  664. }
  665. private void removeAllAddedObjects() {
  666. control.getModel().getEdgesOnCanvas().removeAll(edgeList);
  667. addedIndexCable.clear();
  668. control.getModel().getObjectsOnCanvas().removeAll(switchList);
  669. switchList.clear();
  670. edgeList.clear();
  671. }
  672. private String stringStatFromActualState() {
  673. if(dGroupNode != null)
  674. {
  675. //GetActualDecoratedGroupNode
  676. dGroupNode = control.getSimManager().getActualVisualRepresentationalState().getCreatedGroupNodes().get(dGroupNode.getModel());
  677. int amountOfSupplier = dGroupNode.getAmountOfSupplier();
  678. int amountOfConsumer = dGroupNode.getAmountOfConsumer();
  679. int amountOfPassiv = dGroupNode.getAmountOfPassiv();
  680. int amountOfObjects = amountOfSupplier + amountOfConsumer + amountOfPassiv;
  681. int unSuppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
  682. int partiallySuppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
  683. int suppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
  684. int overSuppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
  685. int activeElements = dGroupNode.getAmountOfAktiveElemntsFromHolonObjects();
  686. int elements = dGroupNode.getAmountOfElemntsFromHolonObjects();
  687. return "HolonObjects["
  688. + " Producer: " + amountOfSupplier + "/" + amountOfObjects + "("+ (float)amountOfSupplier/(float)amountOfObjects * 100 + "%)"
  689. + " Unsupplied: " + unSuppliedConsumer + "/" + amountOfObjects + "("+ (float)unSuppliedConsumer/(float)amountOfObjects * 100 + "%)"
  690. + " PartiallySupplied: " + partiallySuppliedConsumer + "/" + amountOfObjects + "("+ (float)partiallySuppliedConsumer/(float)amountOfObjects * 100 + "%)"
  691. + " Supplied: " + suppliedConsumer + "/" + amountOfObjects + "("+ (float)suppliedConsumer/(float)amountOfObjects * 100 + "%)"
  692. + " Passiv: " + overSuppliedConsumer + "/" + amountOfObjects + "("+ (float)overSuppliedConsumer/(float)amountOfObjects * 100 + "%)"
  693. + "]" + " HolonElemnts["
  694. + " Active: " + activeElements + "/" + elements + "("+ (float)activeElements/(float)elements * 100 + "%)"
  695. + "]";
  696. }
  697. DecoratedState state = control.getSimManager().getActualDecorState();
  698. int amountOfSupplier = 0, amountOfConsumer = 0, amountOfPassiv = 0, unSuppliedConsumer = 0, partiallySuppliedConsumer = 0, suppliedConsumer = 0, overSuppliedConsumer = 0;
  699. int activeElements = 0, amountOfelements = 0;
  700. int totalConsumption = 0, totalProduction = 0;
  701. for(DecoratedNetwork net : state.getNetworkList()) {
  702. amountOfConsumer += net.getAmountOfConsumer();
  703. amountOfSupplier += net.getAmountOfSupplier();
  704. amountOfPassiv += net.getAmountOfPassiv();
  705. unSuppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
  706. partiallySuppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
  707. suppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
  708. overSuppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
  709. amountOfelements += net.getAmountOfElements();
  710. activeElements += net.getAmountOfActiveElements();
  711. totalConsumption += net.getTotalConsumption();
  712. totalProduction += net.getTotalProduction();
  713. }
  714. int amountOfObjects = amountOfSupplier + amountOfConsumer + amountOfPassiv;
  715. int difference = Math.abs(totalProduction - totalConsumption);
  716. List<Flexibility> flexActiveList = control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.IN_USE).stream().map(flex -> flex.getFlex()).collect(Collectors.toList());
  717. int amountActiveEssential = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Essential).count();
  718. int amountActiveHigh = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.High).count();
  719. int amountActiveMedium = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Medium).count();
  720. int amountActiveLow = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Low).count();
  721. int amountActiveFlexibilities = amountActiveEssential + amountActiveHigh + amountActiveMedium + amountActiveLow;
  722. int amountHolons = state.getNetworkList().size();
  723. int amountSwitch = state.getDecoratedSwitches().size();
  724. int amountActiveSwitch = (int)state.getDecoratedSwitches().stream().filter(dswitch -> (dswitch.getState() == SwitchState.Closed)).count();
  725. return "HolonObjects["
  726. + " Passiv: " + percentage(amountOfPassiv, amountOfObjects)
  727. + " Producer: " + percentage(amountOfSupplier, amountOfObjects)
  728. + " Consumer: " + percentage(amountOfConsumer, amountOfObjects)
  729. + " Unsupplied: " + percentage(unSuppliedConsumer, amountOfConsumer)
  730. + " PartiallySupplied: " + percentage(partiallySuppliedConsumer, amountOfObjects)
  731. + " Supplied: " + percentage(suppliedConsumer, amountOfConsumer)
  732. + " Over: " + percentage(overSuppliedConsumer, amountOfConsumer)
  733. + "]" + " HolonElemnts["
  734. + " Active: " + percentage(activeElements, amountOfelements)
  735. + "]" + "Flexibilities_active["
  736. + " Essential: " + percentage(amountActiveEssential, amountActiveFlexibilities)
  737. + " High: " + percentage(amountActiveHigh, amountActiveFlexibilities)
  738. + " Medium: " + percentage(amountActiveMedium, amountActiveFlexibilities)
  739. + " Low: " + percentage(amountActiveLow, amountActiveFlexibilities)
  740. + "]" + " activeSwitches:" + percentage(amountActiveSwitch,amountSwitch)
  741. + " Holons: " + amountHolons
  742. + " totalConsumption: " + totalConsumption
  743. + " totalProduction: " + totalProduction
  744. + " difference: " + difference;
  745. }
  746. private String percentage(int actual, int max) {
  747. return actual + "/" + max + "("+ (float)actual/(float)max * 100 + "%)";
  748. }
  749. @Override
  750. public JPanel getPanel() {
  751. return content;
  752. }
  753. @Override
  754. public void setController(Control control) {
  755. this.control = control;
  756. }
  757. // | New Cable | Switches | Wildcards |
  758. //return index: | countForAccessMap | 1 | accessWildcards.size()|
  759. public int getMaximumIndexObjects(int index) {
  760. int maximumIndex = -1;
  761. //New Cables
  762. if(index < 2 * amountOfNewCables) {
  763. maximumIndex = this.countForAccessMap;
  764. }
  765. //Switches in existing and in new Cables
  766. else if (index < 3 * amountOfNewCables + this.amountOfExistingCables) {
  767. maximumIndex = 1;
  768. }
  769. //wildcards
  770. else {
  771. maximumIndex = accessWildcards.size();
  772. }
  773. return maximumIndex;
  774. }
  775. private class RunProgressBar{
  776. //progressbar
  777. private JProgressBar progressBar = new JProgressBar();
  778. private int count = 0;
  779. private boolean isActive = false;
  780. public void step() {
  781. if(isActive) progressBar.setValue(count++);
  782. }
  783. public void start() {
  784. progressBar.setIndeterminate(false);
  785. count = 0;
  786. isActive = true;
  787. progressBar.setValue(0);
  788. progressBar.setMaximum(getProgressBarMaxCount());
  789. }
  790. public void cancel() {
  791. isActive = false;
  792. progressBar.setIndeterminate(true);
  793. }
  794. public void finishedCancel() {
  795. progressBar.setIndeterminate(false);
  796. progressBar.setValue(0);
  797. }
  798. public JProgressBar getJProgressBar(){
  799. return progressBar;
  800. }
  801. }
  802. protected abstract int getProgressBarMaxCount();
  803. protected abstract String algoInformationToPrint();
  804. protected abstract String plottFileName();
  805. public class Printer{
  806. private JFileChooser fileChooser = new JFileChooser();
  807. private BufferedWriter out;
  808. public Printer(String filename){
  809. fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
  810. fileChooser.setSelectedFile(new File(filename));
  811. }
  812. public void openStream() {
  813. File file = fileChooser.getSelectedFile();
  814. try {
  815. file.createNewFile();
  816. out = new BufferedWriter(new OutputStreamWriter(
  817. new FileOutputStream(file, true), "UTF-8"));
  818. } catch (IOException e) {
  819. System.out.println(e.getMessage());
  820. }
  821. }
  822. public void println(String stringToPrint) {
  823. try {
  824. out.write(stringToPrint);
  825. out.newLine();
  826. } catch (IOException e) {
  827. System.out.println(e.getMessage());
  828. }
  829. }
  830. public void closeStream() {
  831. try {
  832. out.close();
  833. } catch (IOException e) {
  834. System.out.println(e.getMessage());
  835. }
  836. }
  837. }
  838. /**
  839. * A Wrapper Class for Access HolonElement and HolonSwitch in one Element and not have to split the List.
  840. */
  841. private class AccessWrapper {
  842. int state = 0;
  843. HolonObject wildcard;
  844. public AccessWrapper(HolonObject wildcard) {
  845. this.wildcard = wildcard;
  846. }
  847. public void setState(int state) {
  848. if(this.state != state) {
  849. this.state = state;
  850. wildcard.getElements().clear();
  851. if(state > 0) {
  852. HolonObject hO = (HolonObject)accessIntegerToWildcard.get(state);
  853. if(hO == null) {
  854. console.println("null set state(" + state + ")");
  855. }else {
  856. wildcard.getElements().addAll(hO.getElements());
  857. }
  858. }
  859. }
  860. }
  861. public void resetState() {
  862. state = 0;
  863. wildcard.getElements().clear();
  864. }
  865. public String toString() {
  866. return wildcard + "have state: " + state;
  867. }
  868. }
  869. /**
  870. * To create Random and maybe switch the random generation in the future.
  871. */
  872. protected static class Random{
  873. private static java.util.Random random = new java.util.Random();
  874. /**
  875. * True or false
  876. * @return the random boolean.
  877. */
  878. public static boolean nextBoolean(){
  879. return random.nextBoolean();
  880. }
  881. /**
  882. * Between 0.0(inclusive) and 1.0 (exclusive)
  883. * @return the random double.
  884. */
  885. public static double nextDouble() {
  886. return random.nextDouble();
  887. }
  888. /**
  889. * Random Int in Range [min;max[ with UniformDistirbution
  890. * @param min
  891. * @param max
  892. * @return
  893. */
  894. public static int nextIntegerInRange(int min, int max) {
  895. int result = min;
  896. try {
  897. result = min + random.nextInt(max - min);
  898. }catch(java.lang.IllegalArgumentException e){
  899. System.err.println("min : " + min + " max : " + max);
  900. System.err.println("max should be more then min");
  901. }
  902. return result;
  903. }
  904. /**
  905. * Random Int in Range [min;max[ with UniformDistirbution
  906. * @param min
  907. * @param max
  908. * @param valueBetween a value between min and max
  909. * @return
  910. */
  911. public static int nextIntegerInRangeExcept(int min, int max,int valueBetween) {
  912. int result = min;
  913. if(max - min == 1) {
  914. return (valueBetween == min)? max:min;
  915. }
  916. try {
  917. result = min + random.nextInt((max - 1) - min);
  918. if(result >= valueBetween) {
  919. result++;
  920. }
  921. }catch(java.lang.IllegalArgumentException e){
  922. System.err.println("min : " + min + " max : " + max + " valueBetween:" + valueBetween);
  923. System.err.println("Except max should be more then min");
  924. }
  925. return result;
  926. }
  927. }
  928. private class Handle<T>{
  929. public T object;
  930. Handle(T object){
  931. this.object = object;
  932. }
  933. public String toString() {
  934. return object.toString();
  935. }
  936. }
  937. public class Individual {
  938. public double fitness;
  939. public List<Integer> position;
  940. public Individual(){};
  941. /**
  942. * Copy Constructor
  943. */
  944. public Individual(Individual c){
  945. position = c.position.stream().collect(Collectors.toList());
  946. fitness = c.fitness;
  947. }
  948. }
  949. protected class ParameterStepping<T>{
  950. boolean useThisParameter = false;
  951. String paramaterName;
  952. private int count = 0;
  953. int stepps;
  954. T stepSize;
  955. T startValue;
  956. Consumer<T> setter;
  957. Supplier<T> getter;
  958. BiFunction<Integer,T,T> multyply;
  959. BiFunction<T,T,T> add;
  960. ParameterStepping(Consumer<T> setter, Supplier<T> getter, BiFunction<T,T,T> add, BiFunction<Integer,T,T> multyply, T stepSize, int stepps){
  961. this.setter = setter;
  962. this.getter = getter;
  963. this.multyply = multyply;
  964. this.add = add;
  965. this.stepSize = stepSize;
  966. this.stepps = stepps;
  967. }
  968. void init() {
  969. startValue = getter.get();
  970. }
  971. boolean canUpdate() {
  972. return count < stepps;
  973. }
  974. void update(){
  975. if(canUpdate()) {
  976. setter.accept(add.apply(startValue, multyply.apply(count + 1, stepSize)));
  977. count ++;
  978. }
  979. }
  980. void reset() {
  981. setter.accept(startValue);
  982. count = 0;
  983. }
  984. }
  985. public class IndexCable{
  986. public final Integer first;
  987. public final Integer second;
  988. public IndexCable(Integer first, Integer second) {
  989. if(first.compareTo(second) == 0) {
  990. throw new IllegalArgumentException("(" + first + "==" + second + ")"
  991. + "Two ends of the cable are at the same Object");
  992. } else if(first.compareTo(second) < 0) {
  993. this.first = first;
  994. this.second = second;
  995. }else {
  996. this.first = second;
  997. this.second = first;
  998. }
  999. }
  1000. @Override
  1001. public boolean equals(Object o) {
  1002. if (!(o instanceof IndexCable)) {
  1003. return false;
  1004. }
  1005. IndexCable p = (IndexCable) o;
  1006. return Objects.equals(p.first, first) && Objects.equals(p.second, second);
  1007. }
  1008. @Override
  1009. public int hashCode() {
  1010. return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode());
  1011. }
  1012. @Override
  1013. public String toString() {
  1014. return "{" + first + "," + second + "}";
  1015. }
  1016. }
  1017. }