TopologieAlgorithmFramework.java 44 KB

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