TopologieAlgorithmFramework.java 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  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. control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
  366. setState(positionToEvaluate); // execution time critical
  367. return evaluateNetwork();
  368. }
  369. private double evaluateNetwork() {
  370. // Not possible due exponentiak growing
  371. // double times = Math.pow(2, switchList.size());
  372. // double sum = 0;
  373. // for(int i = 0; i < times; i++) {
  374. // int positionInBitString = 0;
  375. // for(HolonSwitch hSwitch: switchList) {
  376. // boolean result = ((i >> positionInBitString++) & 1) != 0;
  377. // hSwitch.setManualState(result);
  378. // }
  379. // sum += evaluateNetwork() / times;
  380. // }
  381. System.out.println("-->");
  382. double sum = 0;
  383. double step = 0.1;
  384. int steppsDone = 0;
  385. for(double actual = 0; actual <= 1 ; actual += step) {
  386. for(HolonSwitch hSwitch: switchList) {
  387. hSwitch.setManualMode(true);
  388. hSwitch.setManualState(Random.nextDouble() < actual);
  389. }
  390. control.calculateStateOnlyForCurrentTimeStep();
  391. DecoratedState actualstate = control.getSimManager().getActualDecorState();
  392. sum += evaluateState(actualstate);
  393. steppsDone++;
  394. }
  395. System.out.println("<--");
  396. return sum /(double) steppsDone;
  397. }
  398. protected abstract double evaluateState(DecoratedState actualstate);
  399. private void run() {
  400. cancel = false;
  401. control.guiDisable(true);
  402. runPrinter.openStream();
  403. runPrinter.println("");
  404. runPrinter.println("Start:" + stringStatFromActualState());
  405. runPrinter.closeStream();
  406. if(this.useStepping) {
  407. initParameterStepping();
  408. do {
  409. executeAlgoWithParameter();
  410. if(cancel) break;
  411. resetState();
  412. }while(updateOneParameter());
  413. resetParameterStepping();
  414. }else {
  415. executeAlgoWithParameter();
  416. }
  417. updateVisual();
  418. runProgressbar.finishedCancel();
  419. control.guiDisable(false);
  420. }
  421. @SuppressWarnings("rawtypes")
  422. private void initParameterStepping() {
  423. for(ParameterStepping param :this.parameterSteppingList) {
  424. param.init();
  425. }
  426. }
  427. @SuppressWarnings("rawtypes")
  428. private void resetParameterStepping() {
  429. for(ParameterStepping param :this.parameterSteppingList) {
  430. param.reset();
  431. }
  432. }
  433. @SuppressWarnings("rawtypes")
  434. private boolean updateOneParameter() {
  435. List<ParameterStepping> parameterInUseList = this.parameterSteppingList.stream().filter(param -> param.useThisParameter).collect(Collectors.toList());
  436. Collections.reverse(parameterInUseList);
  437. int lastParameter = parameterInUseList.size() - 1 ;
  438. int actualParameter = 0;
  439. for(ParameterStepping param : parameterInUseList) {
  440. if(param.canUpdate()) {
  441. param.update();
  442. return true;
  443. }else {
  444. if(actualParameter == lastParameter) break;
  445. param.reset();
  446. }
  447. actualParameter++;
  448. }
  449. //No Param can be updated
  450. return false;
  451. }
  452. private void executeAlgoWithParameter(){
  453. double startFitness = evaluatePosition(extractPositionAndAccess());
  454. resetChain.removeLast();
  455. runPrinter.openStream();
  456. runPrinter.println("");
  457. runPrinter.println(algoInformationToPrint());
  458. console.println(algoInformationToPrint());
  459. runPrinter.closeStream();
  460. runProgressbar.start();
  461. Individual runBest = new Individual();
  462. runBest.fitness = Double.MAX_VALUE;
  463. for(int r = 0; r < rounds; r++)
  464. {
  465. startTimer();
  466. Individual roundBest = executeAlgo();
  467. if(cancel)return;
  468. long executionTime = printElapsedTime();
  469. runPrinter.openStream();
  470. runPrinter.println(runList.stream().map(Object::toString).collect(Collectors.joining(", ")));
  471. runPrinter.println(stringStatFromActualState());
  472. runPrinter.println("Result: " + roundBest.fitness + " ExecutionTime:" + executionTime);
  473. runPrinter.closeStream();
  474. //resetState();
  475. if(roundBest.fitness < runBest.fitness) runBest = roundBest;
  476. }
  477. control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
  478. setState(runBest.position);
  479. updateVisual();
  480. console.println("Start: " + startFitness);
  481. console.println("AlgoResult: " + runBest.fitness);
  482. }
  483. protected abstract Individual executeAlgo();
  484. private void reset() {
  485. if(runThread.isAlive()) {
  486. console.println("Run have to be cancelled First.");
  487. return;
  488. }
  489. if(!resetChain.isEmpty()) {
  490. console.println("Resetting..");
  491. setState(resetChain.getFirst());
  492. control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
  493. resetChain.clear();
  494. control.resetSimulation();
  495. control.setCurIteration(0);
  496. updateVisual();
  497. }else {
  498. console.println("No run inistialized.");
  499. }
  500. }
  501. /**
  502. * To let the User See the current state without touching the Canvas.
  503. */
  504. private void updateVisual() {
  505. control.calculateStateAndVisualForCurrentTimeStep();
  506. }
  507. /**
  508. * Sets the Model back to its original State before the LAST run.
  509. */
  510. private void resetState() {
  511. control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
  512. setState(resetChain.getLast());
  513. }
  514. /**
  515. * Sets the State out of the given position for calculation or to show the user.
  516. * @param position
  517. */
  518. private void setState(List<Integer> position) {
  519. this.removeAllAddedObjects();
  520. for(int i = 0; i < this.amountOfNewCables; i++) {
  521. generateCable(position.get(2 * i), position.get(2 * i + 1), position.get(2 * amountOfNewCables + i) == 1);
  522. }
  523. //Switches new Cable
  524. //Switches existing cable
  525. int count = 0;
  526. for(int i = 3 * amountOfNewCables; i < 3 * this.amountOfNewCables + this.amountOfExistingCables; i++) {
  527. generateEdgeFromIndexCable(cableList.get(count++), position.get(i) == 1);
  528. }
  529. //WildCards
  530. count = 0;
  531. for(int i = 3 * amountOfNewCables + amountOfExistingCables; i < position.size(); i++) {
  532. accessWildcards.get(count++).setState(position.get(i));
  533. }
  534. }
  535. /**
  536. * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
  537. * Also initialize the Access Hashmap to swap faster positions.
  538. * @param model
  539. * @return
  540. */
  541. protected List<Integer> extractPositionAndAccess() {
  542. Model model = control.getModel();
  543. //-->reset
  544. accessWildcards.clear();
  545. this.countForAccessMap = 0;
  546. amountOfExistingCables = 0;
  547. accessIntToObject.clear();
  548. accessObjectToInt.clear();
  549. cableSet.clear();
  550. cableList.clear();
  551. accessGroupNode.clear();
  552. //<---
  553. Category category = control.searchCategory("Wildcards");
  554. if(category != null) {
  555. for(int count = 0; count < category.getObjects().size(); count++ ) {
  556. accessIntegerToWildcard.put(count + 1, category.getObjects().get(count));
  557. }
  558. }else {
  559. console.println("No 'Wildcards' Category");
  560. }
  561. List<Integer> initialState = new ArrayList<Integer>();
  562. generateAccess(model.getObjectsOnCanvas(), null);
  563. addCables(model.getEdgesOnCanvas());
  564. model.getEdgesOnCanvas().clear();
  565. //New Cables
  566. for(int i = 0; i < this.amountOfNewCables; i++) {
  567. initialState.add(0);
  568. initialState.add(0);
  569. }
  570. //switch in new Cables
  571. for(int i = 0; i < this.amountOfNewCables; i++) {
  572. initialState.add(0);
  573. }
  574. //Switch in initial Cable
  575. cableSet.stream().forEach(indexCale -> initialState.add(0));
  576. amountOfExistingCables = cableSet.size();
  577. //wildcards
  578. for(int i = 0; i < accessWildcards.size(); i++) {
  579. initialState.add(0);
  580. }
  581. resetChain.add(initialState);
  582. //console.println(accessIntToObject.values().stream().map(hO -> hO.getName()).collect(Collectors.joining(", ")));
  583. //console.println(cableSet.stream().map(Object::toString).collect(Collectors.f(", ")));
  584. return initialState;
  585. }
  586. /**
  587. * Method to extract the Informations recursively out of the Model.
  588. * @param nodes
  589. * @param positionToInit
  590. * @param timeStep
  591. */
  592. private void generateAccess(List<AbstractCanvasObject> nodes, GroupNode groupnode) {
  593. for(AbstractCanvasObject aCps : nodes) {
  594. if(aCps instanceof HolonObject) {
  595. HolonObject hO = (HolonObject) aCps;
  596. accessIntToObject.put(++countForAccessMap, hO);
  597. accessObjectToInt.put(hO, countForAccessMap);
  598. if(hO.getName().equals("Wildcard")) {
  599. accessWildcards.add(new AccessWrapper(hO));
  600. }
  601. if(groupnode != null) {
  602. accessGroupNode.put(hO, groupnode);
  603. }
  604. }
  605. else if(aCps instanceof GroupNode) {
  606. generateAccess(((GroupNode)aCps).getNodes(), (GroupNode) aCps);
  607. }
  608. }
  609. }
  610. protected void resetWildcards() {
  611. this.accessWildcards.forEach(wrapper -> wrapper.resetState());
  612. }
  613. /**
  614. * All Nodes have to be in the access map !!
  615. * @param cables
  616. */
  617. private void addCables(List<Edge> edges) {
  618. for (Edge edge : edges) {
  619. edge.setUnlimitedCapacity(true);
  620. edgeList.add(edge);
  621. //console.println("Cable from " + edge.getA().getName() + " to " + edge.getB().getName());
  622. if(!accessObjectToInt.containsKey(edge.getA())) {
  623. console.println("Node A from Edge[" + edge + "] not exist");
  624. continue;
  625. } else if (!accessObjectToInt.containsKey(edge.getB())) {
  626. console.println("Node B from Edge[" + edge + "] not exist");
  627. continue;
  628. }
  629. IndexCable cable = new IndexCable(accessObjectToInt.get(edge.getA()), accessObjectToInt.get(edge.getB()));
  630. boolean success = cableSet.add(cable);
  631. if(success) {
  632. cableList.add(cable);
  633. }
  634. }
  635. }
  636. private void generateCable(int index0, int index1, boolean switchBetween) {
  637. //If cable isnt valid
  638. if(index0 == 0 || index1 == 0 || index0 == index1) {
  639. //console.println("Cable("+index1+","+index2+ ") isn't valid");
  640. return;
  641. }
  642. IndexCable cable = new IndexCable(index0, index1);
  643. //if cable is in existing cables
  644. if(cableSet.contains(cable) || addedIndexCable.contains(cable)) {
  645. return;
  646. }
  647. generateEdgeFromIndexCable(cable, switchBetween);
  648. addedIndexCable.add(cable);
  649. }
  650. private void generateEdgeFromIndexCable(IndexCable cable, boolean switchBetween){
  651. if(switchBetween) {
  652. //generate Switch
  653. AbstractCanvasObject fromObject = accessIntToObject.get(cable.first);
  654. AbstractCanvasObject toObject = accessIntToObject.get(cable.second);
  655. int middleX = (fromObject.getPosition().x + toObject.getPosition().x)/2;
  656. int middleY = (fromObject.getPosition().y + toObject.getPosition().y)/2;
  657. HolonSwitch newSwitch = new HolonSwitch("AddedSwitch");
  658. newSwitch.setPosition(middleX, middleY);
  659. //If fromObject is in Group
  660. if(accessGroupNode.containsKey(fromObject)) {
  661. GroupNode groupnode = accessGroupNode.get(fromObject);
  662. groupnode.getNodes().add(newSwitch);
  663. accessSwitchGroupNode.put(newSwitch, groupnode);
  664. } else if(accessGroupNode.containsKey(toObject)) {
  665. GroupNode groupnode = accessGroupNode.get(toObject);
  666. groupnode.getNodes().add(newSwitch);
  667. accessSwitchGroupNode.put(newSwitch, groupnode);
  668. }else {
  669. control.getModel().getObjectsOnCanvas().add(newSwitch);
  670. }
  671. //else if toObject is in Group
  672. this.switchList.add(newSwitch);
  673. //Generate Cable From Object A To Switch
  674. Edge edge1 = new Edge(fromObject, newSwitch);
  675. edge1.setUnlimitedCapacity(true);
  676. control.getModel().getEdgesOnCanvas().add(edge1);
  677. edgeList.add(edge1);
  678. //Generate Cable From Object B To Switch
  679. Edge edge = new Edge(newSwitch, toObject);
  680. edge.setUnlimitedCapacity(true);
  681. control.getModel().getEdgesOnCanvas().add(edge);
  682. edgeList.add(edge);
  683. }else {
  684. Edge edge = new Edge(accessIntToObject.get(cable.first), accessIntToObject.get(cable.second));
  685. edge.setUnlimitedCapacity(true);
  686. control.getModel().getEdgesOnCanvas().add(edge);
  687. edgeList.add(edge);
  688. }
  689. }
  690. private void removeAllAddedObjects() {
  691. control.getModel().getEdgesOnCanvas().removeAll(edgeList);
  692. addedIndexCable.clear();
  693. //control.getModel().getObjectsOnCanvas().removeAll(switchList);
  694. for(HolonSwitch hSwitch: switchList) {
  695. if(this.accessSwitchGroupNode.containsKey(hSwitch)) {
  696. accessSwitchGroupNode.get(hSwitch).getNodes().remove(hSwitch);
  697. }
  698. else {
  699. control.getModel().getObjectsOnCanvas().remove(hSwitch);
  700. }
  701. }
  702. accessSwitchGroupNode.clear();
  703. switchList.clear();
  704. edgeList.clear();
  705. }
  706. private String stringStatFromActualState() {
  707. if(dGroupNode != null)
  708. {
  709. //GetActualDecoratedGroupNode
  710. dGroupNode = control.getSimManager().getActualVisualRepresentationalState().getCreatedGroupNodes().get(dGroupNode.getModel());
  711. int amountOfSupplier = dGroupNode.getAmountOfSupplier();
  712. int amountOfConsumer = dGroupNode.getAmountOfConsumer();
  713. int amountOfPassiv = dGroupNode.getAmountOfPassiv();
  714. int amountOfObjects = amountOfSupplier + amountOfConsumer + amountOfPassiv;
  715. int unSuppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
  716. int partiallySuppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
  717. int suppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
  718. int overSuppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
  719. int activeElements = dGroupNode.getAmountOfAktiveElemntsFromHolonObjects();
  720. int elements = dGroupNode.getAmountOfElemntsFromHolonObjects();
  721. return "HolonObjects["
  722. + " Producer: " + amountOfSupplier + "/" + amountOfObjects + "("+ (float)amountOfSupplier/(float)amountOfObjects * 100 + "%)"
  723. + " Unsupplied: " + unSuppliedConsumer + "/" + amountOfObjects + "("+ (float)unSuppliedConsumer/(float)amountOfObjects * 100 + "%)"
  724. + " PartiallySupplied: " + partiallySuppliedConsumer + "/" + amountOfObjects + "("+ (float)partiallySuppliedConsumer/(float)amountOfObjects * 100 + "%)"
  725. + " Supplied: " + suppliedConsumer + "/" + amountOfObjects + "("+ (float)suppliedConsumer/(float)amountOfObjects * 100 + "%)"
  726. + " Passiv: " + overSuppliedConsumer + "/" + amountOfObjects + "("+ (float)overSuppliedConsumer/(float)amountOfObjects * 100 + "%)"
  727. + "]" + " HolonElemnts["
  728. + " Active: " + activeElements + "/" + elements + "("+ (float)activeElements/(float)elements * 100 + "%)"
  729. + "]";
  730. }
  731. DecoratedState state = control.getSimManager().getActualDecorState();
  732. int amountOfSupplier = 0, amountOfConsumer = 0, amountOfPassiv = 0, unSuppliedConsumer = 0, partiallySuppliedConsumer = 0, suppliedConsumer = 0, overSuppliedConsumer = 0;
  733. int activeElements = 0, amountOfelements = 0;
  734. int totalConsumption = 0, totalProduction = 0;
  735. for(DecoratedNetwork net : state.getNetworkList()) {
  736. amountOfConsumer += net.getAmountOfConsumer();
  737. amountOfSupplier += net.getAmountOfSupplier();
  738. amountOfPassiv += net.getAmountOfPassiv();
  739. unSuppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
  740. partiallySuppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
  741. suppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
  742. overSuppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
  743. amountOfelements += net.getAmountOfElements();
  744. activeElements += net.getAmountOfActiveElements();
  745. totalConsumption += net.getTotalConsumption();
  746. totalProduction += net.getTotalProduction();
  747. }
  748. int amountOfObjects = amountOfSupplier + amountOfConsumer + amountOfPassiv;
  749. int difference = Math.abs(totalProduction - totalConsumption);
  750. List<Flexibility> flexActiveList = control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.IN_USE).stream().map(flex -> flex.getFlex()).collect(Collectors.toList());
  751. int amountActiveEssential = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Essential).count();
  752. int amountActiveHigh = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.High).count();
  753. int amountActiveMedium = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Medium).count();
  754. int amountActiveLow = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Low).count();
  755. int amountActiveFlexibilities = amountActiveEssential + amountActiveHigh + amountActiveMedium + amountActiveLow;
  756. int amountHolons = state.getNetworkList().size();
  757. int amountSwitch = state.getDecoratedSwitches().size();
  758. int amountActiveSwitch = (int)state.getDecoratedSwitches().stream().filter(dswitch -> (dswitch.getState() == SwitchState.Closed)).count();
  759. return "HolonObjects["
  760. + " Passiv: " + percentage(amountOfPassiv, amountOfObjects)
  761. + " Producer: " + percentage(amountOfSupplier, amountOfObjects)
  762. + " Consumer: " + percentage(amountOfConsumer, amountOfObjects)
  763. + " Unsupplied: " + percentage(unSuppliedConsumer, amountOfConsumer)
  764. + " PartiallySupplied: " + percentage(partiallySuppliedConsumer, amountOfObjects)
  765. + " Supplied: " + percentage(suppliedConsumer, amountOfConsumer)
  766. + " Over: " + percentage(overSuppliedConsumer, amountOfConsumer)
  767. + "]" + " HolonElemnts["
  768. + " Active: " + percentage(activeElements, amountOfelements)
  769. + "]" + "Flexibilities_active["
  770. + " Essential: " + percentage(amountActiveEssential, amountActiveFlexibilities)
  771. + " High: " + percentage(amountActiveHigh, amountActiveFlexibilities)
  772. + " Medium: " + percentage(amountActiveMedium, amountActiveFlexibilities)
  773. + " Low: " + percentage(amountActiveLow, amountActiveFlexibilities)
  774. + "]" + " activeSwitches:" + percentage(amountActiveSwitch,amountSwitch)
  775. + " Holons: " + amountHolons
  776. + " totalConsumption: " + totalConsumption
  777. + " totalProduction: " + totalProduction
  778. + " difference: " + difference;
  779. }
  780. private String percentage(int actual, int max) {
  781. return actual + "/" + max + "("+ (float)actual/(float)max * 100 + "%)";
  782. }
  783. @Override
  784. public JPanel getPanel() {
  785. return content;
  786. }
  787. @Override
  788. public void setController(Control control) {
  789. this.control = control;
  790. }
  791. // | New Cable | Switches | Wildcards |
  792. //return index: | countForAccessMap | 1 | accessWildcards.size()|
  793. public int getMaximumIndexObjects(int index) {
  794. int maximumIndex = -1;
  795. //New Cables
  796. if(index < 2 * amountOfNewCables) {
  797. maximumIndex = this.countForAccessMap;
  798. }
  799. //Switches in existing and in new Cables
  800. else if (index < 3 * amountOfNewCables + this.amountOfExistingCables) {
  801. maximumIndex = 1;
  802. }
  803. //wildcards
  804. else {
  805. maximumIndex = accessWildcards.size();
  806. }
  807. return maximumIndex;
  808. }
  809. private class RunProgressBar{
  810. //progressbar
  811. private JProgressBar progressBar = new JProgressBar();
  812. private int count = 0;
  813. private boolean isActive = false;
  814. public void step() {
  815. if(isActive) progressBar.setValue(count++);
  816. }
  817. public void start() {
  818. progressBar.setIndeterminate(false);
  819. count = 0;
  820. isActive = true;
  821. progressBar.setValue(0);
  822. progressBar.setMaximum(getProgressBarMaxCount());
  823. }
  824. public void cancel() {
  825. isActive = false;
  826. progressBar.setIndeterminate(true);
  827. }
  828. public void finishedCancel() {
  829. progressBar.setIndeterminate(false);
  830. progressBar.setValue(0);
  831. }
  832. public JProgressBar getJProgressBar(){
  833. return progressBar;
  834. }
  835. }
  836. protected abstract int getProgressBarMaxCount();
  837. protected abstract String algoInformationToPrint();
  838. protected abstract String plottFileName();
  839. public class Printer{
  840. private JFileChooser fileChooser = new JFileChooser();
  841. private BufferedWriter out;
  842. public Printer(String filename){
  843. fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
  844. fileChooser.setSelectedFile(new File(filename));
  845. }
  846. public void openStream() {
  847. File file = fileChooser.getSelectedFile();
  848. try {
  849. file.createNewFile();
  850. out = new BufferedWriter(new OutputStreamWriter(
  851. new FileOutputStream(file, true), "UTF-8"));
  852. } catch (IOException e) {
  853. System.out.println(e.getMessage());
  854. }
  855. }
  856. public void println(String stringToPrint) {
  857. try {
  858. out.write(stringToPrint);
  859. out.newLine();
  860. } catch (IOException e) {
  861. System.out.println(e.getMessage());
  862. }
  863. }
  864. public void closeStream() {
  865. try {
  866. out.close();
  867. } catch (IOException e) {
  868. System.out.println(e.getMessage());
  869. }
  870. }
  871. }
  872. /**
  873. * A Wrapper Class for Access HolonElement and HolonSwitch in one Element and not have to split the List.
  874. */
  875. private class AccessWrapper {
  876. int state = 0;
  877. HolonObject wildcard;
  878. public AccessWrapper(HolonObject wildcard) {
  879. this.wildcard = wildcard;
  880. }
  881. public void setState(int state) {
  882. if(this.state != state) {
  883. this.state = state;
  884. wildcard.getElements().clear();
  885. if(state > 0) {
  886. HolonObject hO = (HolonObject)accessIntegerToWildcard.get(state);
  887. if(hO == null) {
  888. console.println("null set state(" + state + ")");
  889. }else {
  890. wildcard.getElements().addAll(hO.getElements());
  891. }
  892. }
  893. }
  894. }
  895. public void resetState() {
  896. state = 0;
  897. wildcard.getElements().clear();
  898. }
  899. public String toString() {
  900. return wildcard + "have state: " + state;
  901. }
  902. }
  903. /**
  904. * To create Random and maybe switch the random generation in the future.
  905. */
  906. protected static class Random{
  907. private static java.util.Random random = new java.util.Random();
  908. /**
  909. * True or false
  910. * @return the random boolean.
  911. */
  912. public static boolean nextBoolean(){
  913. return random.nextBoolean();
  914. }
  915. /**
  916. * Between 0.0(inclusive) and 1.0 (exclusive)
  917. * @return the random double.
  918. */
  919. public static double nextDouble() {
  920. return random.nextDouble();
  921. }
  922. /**
  923. * Random Int in Range [min;max[ with UniformDistirbution
  924. * @param min
  925. * @param max
  926. * @return
  927. */
  928. public static int nextIntegerInRange(int min, int max) {
  929. int result = min;
  930. try {
  931. result = min + random.nextInt(max - min);
  932. }catch(java.lang.IllegalArgumentException e){
  933. System.err.println("min : " + min + " max : " + max);
  934. System.err.println("max should be more then min");
  935. }
  936. return result;
  937. }
  938. /**
  939. * Random Int in Range [min;max[ with UniformDistirbution
  940. * @param min
  941. * @param max
  942. * @param valueBetween a value between min and max
  943. * @return
  944. */
  945. public static int nextIntegerInRangeExcept(int min, int max,int valueBetween) {
  946. int result = min;
  947. if(max - min == 1) {
  948. return (valueBetween == min)? max:min;
  949. }
  950. try {
  951. result = min + random.nextInt((max - 1) - min);
  952. if(result >= valueBetween) {
  953. result++;
  954. }
  955. }catch(java.lang.IllegalArgumentException e){
  956. System.err.println("min : " + min + " max : " + max + " valueBetween:" + valueBetween);
  957. System.err.println("Except max should be more then min");
  958. }
  959. return result;
  960. }
  961. }
  962. private class Handle<T>{
  963. public T object;
  964. Handle(T object){
  965. this.object = object;
  966. }
  967. public String toString() {
  968. return object.toString();
  969. }
  970. }
  971. public class Individual {
  972. public double fitness;
  973. public List<Integer> position;
  974. public Individual(){};
  975. /**
  976. * Copy Constructor
  977. */
  978. public Individual(Individual c){
  979. position = c.position.stream().collect(Collectors.toList());
  980. fitness = c.fitness;
  981. }
  982. }
  983. protected class ParameterStepping<T>{
  984. boolean useThisParameter = false;
  985. String paramaterName;
  986. private int count = 0;
  987. int stepps;
  988. T stepSize;
  989. T startValue;
  990. Consumer<T> setter;
  991. Supplier<T> getter;
  992. BiFunction<Integer,T,T> multyply;
  993. BiFunction<T,T,T> add;
  994. ParameterStepping(Consumer<T> setter, Supplier<T> getter, BiFunction<T,T,T> add, BiFunction<Integer,T,T> multyply, T stepSize, int stepps){
  995. this.setter = setter;
  996. this.getter = getter;
  997. this.multyply = multyply;
  998. this.add = add;
  999. this.stepSize = stepSize;
  1000. this.stepps = stepps;
  1001. }
  1002. void init() {
  1003. startValue = getter.get();
  1004. }
  1005. boolean canUpdate() {
  1006. return count < stepps;
  1007. }
  1008. void update(){
  1009. if(canUpdate()) {
  1010. setter.accept(add.apply(startValue, multyply.apply(count + 1, stepSize)));
  1011. count ++;
  1012. }
  1013. }
  1014. void reset() {
  1015. setter.accept(startValue);
  1016. count = 0;
  1017. }
  1018. }
  1019. public class IndexCable{
  1020. public final Integer first;
  1021. public final Integer second;
  1022. public IndexCable(Integer first, Integer second) {
  1023. if(first.compareTo(second) == 0) {
  1024. throw new IllegalArgumentException("(" + first + "==" + second + ")"
  1025. + "Two ends of the cable are at the same Object");
  1026. } else if(first.compareTo(second) < 0) {
  1027. this.first = first;
  1028. this.second = second;
  1029. }else {
  1030. this.first = second;
  1031. this.second = first;
  1032. }
  1033. }
  1034. @Override
  1035. public boolean equals(Object o) {
  1036. if (!(o instanceof IndexCable)) {
  1037. return false;
  1038. }
  1039. IndexCable p = (IndexCable) o;
  1040. return Objects.equals(p.first, first) && Objects.equals(p.second, second);
  1041. }
  1042. @Override
  1043. public int hashCode() {
  1044. return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode());
  1045. }
  1046. @Override
  1047. public String toString() {
  1048. return "{" + first + "," + second + "}";
  1049. }
  1050. }
  1051. }