GaAlgorithm.java 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  1. package exampleAlgorithms;
  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.math.RoundingMode;
  8. import java.text.NumberFormat;
  9. import java.util.ArrayList;
  10. import java.util.HashMap;
  11. import java.util.LinkedList;
  12. import java.util.List;
  13. import java.util.ListIterator;
  14. import java.util.Locale;
  15. import java.util.stream.Collectors;
  16. import javax.swing.BorderFactory;
  17. import javax.swing.ImageIcon;
  18. import javax.swing.JButton;
  19. import javax.swing.JCheckBox;
  20. import javax.swing.JFormattedTextField;
  21. import javax.swing.JFrame;
  22. import javax.swing.JLabel;
  23. import javax.swing.JOptionPane;
  24. import javax.swing.JPanel;
  25. import javax.swing.JProgressBar;
  26. import javax.swing.JScrollPane;
  27. import javax.swing.JSplitPane;
  28. import javax.swing.JTextArea;
  29. import javax.swing.text.NumberFormatter;
  30. import api.Algorithm;
  31. import classes.AbstractCpsObject;
  32. import classes.CpsUpperNode;
  33. import classes.HolonElement;
  34. import classes.HolonObject;
  35. import classes.HolonSwitch;
  36. import ui.controller.Control;
  37. import ui.model.DecoratedGroupNode;
  38. import ui.model.DecoratedState;
  39. import ui.model.Model;
  40. import ui.model.DecoratedHolonObject.HolonObjectState;
  41. public class GaAlgorithm implements Algorithm {
  42. //Parameter for Algo with default Values:
  43. /**
  44. * Should be even.
  45. */
  46. private int popsize = 20;
  47. private int maxGenerations = 100;
  48. private int tournamentSize = 2;
  49. private double fixedSwapProbability = 0.02;
  50. private boolean useFixedSpawProbability = false;
  51. private double fixedMutateProbability = 0.02;
  52. private boolean useFixedMutateProbability = false;
  53. private int rounds = 2;
  54. //Settings For GroupNode using and cancel
  55. private boolean useGroupNode = false;
  56. private DecoratedGroupNode dGroupNode = null;
  57. private boolean cancel = false;
  58. //Parameter defined by Algo
  59. private HashMap<Integer, AccessWrapper> access;
  60. LinkedList<List<Boolean>> resetChain = new LinkedList<List<Boolean>>();
  61. private List<Boolean> initialState;
  62. private List<HolonSwitch> switchList;
  63. private List<HolonObject> objectList;
  64. //Gui Part:
  65. private Control control;
  66. private JTextArea textArea;
  67. private JPanel content = new JPanel();
  68. //ProgressBar
  69. private JProgressBar progressBar = new JProgressBar();
  70. private int progressBarCount = 0;
  71. private long startTime;
  72. private Thread runThread;
  73. public static void main(String[] args)
  74. {
  75. JFrame newFrame = new JFrame("exampleWindow");
  76. GaAlgorithm instance = new GaAlgorithm();
  77. newFrame.setContentPane(instance.getAlgorithmPanel());
  78. newFrame.pack();
  79. newFrame.setVisible(true);
  80. newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  81. }
  82. public GaAlgorithm() {
  83. content.setLayout(new BorderLayout());
  84. textArea = new JTextArea();
  85. textArea.setEditable(false);
  86. JScrollPane scrollPane = new JScrollPane(textArea);
  87. JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
  88. createOptionPanel() , scrollPane);
  89. splitPane.setResizeWeight(0.0);
  90. content.add(splitPane, BorderLayout.CENTER);
  91. content.setPreferredSize(new Dimension(800,800));
  92. }
  93. public JPanel createOptionPanel() {
  94. JPanel optionPanel = new JPanel(new BorderLayout());
  95. JScrollPane scrollPane = new JScrollPane(createParameterPanel());
  96. scrollPane.setBorder(BorderFactory.createTitledBorder("Parameter"));
  97. optionPanel.add(scrollPane, BorderLayout.CENTER);
  98. optionPanel.add(createButtonPanel(), BorderLayout.PAGE_END);
  99. return optionPanel;
  100. }
  101. private Component createParameterPanel() {
  102. JPanel parameterPanel = new JPanel(null);
  103. parameterPanel.setPreferredSize(new Dimension(510,300));
  104. JLabel maxGenerationsLabel = new JLabel("Max. Generations:");
  105. maxGenerationsLabel.setBounds(20, 60, 150, 20);
  106. parameterPanel.add(maxGenerationsLabel);
  107. JLabel populationLabel = new JLabel("Population Size:");
  108. populationLabel.setBounds(20, 85, 150, 20);
  109. parameterPanel.add(populationLabel);
  110. JLabel roundLabel = new JLabel("Rounds:");
  111. roundLabel.setBounds(20, 110, 150, 20);
  112. parameterPanel.add(roundLabel);
  113. JLabel mutationLabel = new JLabel("FixedMutation:");
  114. mutationLabel.setBounds(50, 135, 150, 20);
  115. mutationLabel.setEnabled(useFixedMutateProbability);
  116. parameterPanel.add(mutationLabel);
  117. JLabel swapLabel = new JLabel("FixedSwap:");
  118. swapLabel.setBounds(50, 160, 150, 20);
  119. swapLabel.setEnabled(this.useFixedSpawProbability);
  120. parameterPanel.add(swapLabel);
  121. JLabel progressLabel = new JLabel("Progress:");
  122. progressLabel.setBounds(350, 135, 170, 20);
  123. parameterPanel.add(progressLabel);
  124. progressBar.setBounds(350, 155, 185, 20);
  125. progressBar.setStringPainted(true);
  126. parameterPanel.add(progressBar);
  127. JPanel borderPanel = new JPanel(null);
  128. borderPanel.setBounds(350, 85, 185, 50);
  129. borderPanel.setBorder(BorderFactory.createTitledBorder(""));
  130. parameterPanel.add(borderPanel);
  131. JLabel showGroupNodeLabel = new JLabel("Use Group Node:");
  132. showGroupNodeLabel.setBounds(10, 1, 170, 20);
  133. borderPanel.add(showGroupNodeLabel);
  134. JButton selectGroupNodeButton = new JButton("Select GroupNode");
  135. selectGroupNodeButton.setEnabled(false);
  136. selectGroupNodeButton.setBounds(10, 25, 165, 20);
  137. selectGroupNodeButton.addActionListener(actionEvent -> selectGroupNode());
  138. borderPanel.add(selectGroupNodeButton);
  139. JCheckBox useGroupNodeCheckBox = new JCheckBox();
  140. useGroupNodeCheckBox.setSelected(false);
  141. useGroupNodeCheckBox.setBounds(155, 1, 25, 20);
  142. useGroupNodeCheckBox.addActionListener(actionEvent -> {
  143. useGroupNode = useGroupNodeCheckBox.isSelected();
  144. selectGroupNodeButton.setEnabled(useGroupNode);
  145. });
  146. borderPanel.add(useGroupNodeCheckBox);
  147. //Integer formatter
  148. NumberFormat format = NumberFormat.getIntegerInstance();
  149. format.setGroupingUsed(false);
  150. format.setParseIntegerOnly(true);
  151. NumberFormatter integerFormatter = new NumberFormatter(format);
  152. integerFormatter.setMinimum(1);
  153. integerFormatter.setCommitsOnValidEdit(true);
  154. JFormattedTextField maxGenerationsTextField = new JFormattedTextField(integerFormatter);
  155. maxGenerationsTextField.setValue(this.maxGenerations);
  156. maxGenerationsTextField.setToolTipText("Only positive Integer.");
  157. maxGenerationsTextField.addPropertyChangeListener(actionEvent -> this.maxGenerations = Integer.parseInt(maxGenerationsTextField.getValue().toString()));
  158. maxGenerationsTextField.setBounds(160, 60, 50, 20);
  159. parameterPanel.add(maxGenerationsTextField);
  160. JFormattedTextField popSizeTextField = new JFormattedTextField(integerFormatter);
  161. popSizeTextField.setValue(this.popsize);
  162. popSizeTextField.setToolTipText("Only positive Integer.");
  163. popSizeTextField.addPropertyChangeListener(propertyChange -> this.popsize = Integer.parseInt(popSizeTextField.getValue().toString()));
  164. popSizeTextField.setBounds(160, 85, 50, 20);
  165. parameterPanel.add(popSizeTextField);
  166. JFormattedTextField roundsTextField = new JFormattedTextField(integerFormatter);
  167. roundsTextField.setValue(this.rounds);
  168. roundsTextField.setToolTipText("Only positive Integer.");
  169. roundsTextField.addPropertyChangeListener(propertyChange -> this.rounds = Integer.parseInt(roundsTextField.getValue().toString()));
  170. roundsTextField.setBounds(160, 110, 50, 20);
  171. parameterPanel.add(roundsTextField);
  172. //Double Format:
  173. NumberFormat doubleFormat = NumberFormat.getNumberInstance(Locale.US);
  174. doubleFormat.setMinimumFractionDigits(1);
  175. doubleFormat.setMaximumFractionDigits(3);
  176. doubleFormat.setRoundingMode(RoundingMode.HALF_UP);
  177. //Limit Formatter:
  178. NumberFormatter limitFormatter = new NumberFormatter(doubleFormat);
  179. limitFormatter.setMinimum(0.0);
  180. limitFormatter.setMaximum(1.0);
  181. JFormattedTextField mutateTextField = new JFormattedTextField(limitFormatter);
  182. mutateTextField.setValue(this.fixedMutateProbability);
  183. mutateTextField.setEnabled(this.useFixedMutateProbability);
  184. mutateTextField.setToolTipText("Only Double in range [0.0, 1.0] with DecimalSeperator Point('.').");
  185. mutateTextField.addPropertyChangeListener(propertyChange -> fixedMutateProbability = Double.parseDouble(mutateTextField.getValue().toString()));
  186. mutateTextField.setBounds(160, 135, 50, 20);
  187. parameterPanel.add(mutateTextField);
  188. JCheckBox useFixMutateCheckBox = new JCheckBox();
  189. useFixMutateCheckBox.setSelected(this.useFixedMutateProbability);
  190. useFixMutateCheckBox.setToolTipText("If not checked its 1/ProblemSize");
  191. useFixMutateCheckBox.setBounds(20, 135, 25, 20);
  192. useFixMutateCheckBox.addActionListener(actionEvent -> {
  193. boolean state = useFixMutateCheckBox.isSelected();
  194. this.useFixedMutateProbability = state;
  195. mutateTextField.setEnabled(state);
  196. mutationLabel.setEnabled(state);
  197. });
  198. parameterPanel.add(useFixMutateCheckBox);
  199. JFormattedTextField swapTextField = new JFormattedTextField(limitFormatter);
  200. swapTextField.setValue(this.fixedSwapProbability);
  201. swapTextField.setEnabled(this.useFixedMutateProbability);
  202. swapTextField.setToolTipText("Only Double in range [0.0, 1.0] with DecimalSeperator Point('.').");
  203. swapTextField.addPropertyChangeListener(propertyChange -> this.fixedSwapProbability = Double.parseDouble(swapTextField.getValue().toString()));
  204. swapTextField.setBounds(160, 160, 50, 20);
  205. parameterPanel.add(swapTextField);
  206. JCheckBox useFixSwapCheckBox = new JCheckBox();
  207. useFixSwapCheckBox.setSelected(this.useFixedSpawProbability);
  208. useFixSwapCheckBox.setToolTipText("If not checked its 1/ProblemSize");
  209. useFixSwapCheckBox.setBounds(20, 160, 25, 20);
  210. useFixSwapCheckBox.addActionListener(actionEvent -> {
  211. boolean state = useFixSwapCheckBox.isSelected();
  212. this.useFixedSpawProbability = state;
  213. swapTextField.setEnabled(state);
  214. swapLabel.setEnabled(state);
  215. });
  216. parameterPanel.add(useFixSwapCheckBox);
  217. return parameterPanel;
  218. }
  219. public JPanel createButtonPanel() {
  220. JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
  221. JButton resetButton = new JButton("ResetAll");
  222. resetButton.setToolTipText("Resets the State to before the Algorithm has runed.");
  223. resetButton.addActionListener(actionEvent -> resetAll());
  224. buttonPanel.add(resetButton);
  225. JButton cancelButton = new JButton("Cancel Run");
  226. cancelButton.addActionListener(actionEvent -> cancel());
  227. buttonPanel.add(cancelButton);
  228. JButton clearButton = new JButton("Clear Console");
  229. clearButton.addActionListener(actionEvent -> clear());
  230. buttonPanel.add(clearButton);
  231. JButton undoButton = new JButton("Undo");
  232. undoButton.setToolTipText("One Algo Step Back.");
  233. undoButton.addActionListener(actionEvent -> resetLast());
  234. buttonPanel.add(undoButton);
  235. JButton runButton = new JButton("Run");
  236. runButton.addActionListener(actionEvent -> {
  237. Runnable task = () -> run();
  238. runThread = new Thread(task);
  239. runThread.start();
  240. });
  241. buttonPanel.add(runButton);
  242. return buttonPanel;
  243. }
  244. private void cancel() {
  245. if(runThread.isAlive()) {
  246. println("");
  247. println("Cancel run.");
  248. cancel = true;
  249. progressBar.setValue(0);
  250. } else {
  251. println("Nothing to cancel.");
  252. }
  253. }
  254. private void run() {
  255. cancel = false;
  256. disableGuiInput(true);
  257. executeAlgoWithParameter();
  258. updateVisual();
  259. disableGuiInput(false);
  260. }
  261. private void resetLast() {
  262. if(!resetChain.isEmpty()) {
  263. println("Resetting..");
  264. resetState();
  265. resetChain.removeLast();
  266. control.resetSimulation();
  267. updateVisual();
  268. }else {
  269. println("No run inistialized.");
  270. }
  271. }
  272. private void resetAll() {
  273. if(!resetChain.isEmpty()) {
  274. println("Resetting..");
  275. setState(resetChain.getFirst());
  276. resetChain.clear();
  277. control.resetSimulation();
  278. control.setCurIteration(0);
  279. updateVisual();
  280. }else {
  281. println("No run inistialized.");
  282. }
  283. }
  284. private void disableGuiInput(boolean bool) {
  285. control.guiDiable(bool);
  286. }
  287. @Override
  288. public JPanel getAlgorithmPanel() {
  289. return content;
  290. }
  291. @Override
  292. public void setController(Control control) {
  293. this.control = control;
  294. }
  295. private void clear() {
  296. textArea.setText("");
  297. }
  298. private void println(String message) {
  299. textArea.append(message + "\n");
  300. }
  301. private void selectGroupNode() {
  302. Object[] possibilities = control.getSimManager().getActualVisualRepresentationalState().getCreatedGroupNodes().values().stream().map(aCps -> new Handle<DecoratedGroupNode>(aCps)).toArray();
  303. @SuppressWarnings("unchecked")
  304. Handle<DecoratedGroupNode> selected = (Handle<DecoratedGroupNode>) JOptionPane.showInputDialog(content, "Select GroupNode:", "GroupNode?", JOptionPane.OK_OPTION,new ImageIcon(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)) , possibilities, "");
  305. if(selected != null) {
  306. println("Selected: " + selected);
  307. dGroupNode = selected.object;
  308. }
  309. }
  310. private void progressBarStep(){
  311. progressBar.setValue(++progressBarCount);
  312. }
  313. private void calculateProgressBarParameter() {
  314. int max = this.maxGenerations * this.popsize * this.rounds;
  315. progressBarCount = 0;
  316. progressBar.setValue(0);
  317. progressBar.setMaximum(max);
  318. }
  319. private void startTimer(){
  320. startTime = System.currentTimeMillis();
  321. }
  322. private void printElapsedTime(){
  323. long elapsedMilliSeconds = System.currentTimeMillis() - startTime;
  324. println("Execution Time of Algo in Milliseconds:" + elapsedMilliSeconds);
  325. }
  326. private void executeAlgoWithParameter(){
  327. int actualIteration = control.getModel().getCurIteration();
  328. println("TimeStep:" + actualIteration);
  329. calculateProgressBarParameter();
  330. startTimer();
  331. Individual runBest = new Individual();
  332. runBest.fitness = Double.MAX_VALUE;
  333. for(int r = 0; r < rounds; r++)
  334. {
  335. Individual roundBest = executeGaAlgo();
  336. if(cancel)return;
  337. resetState();
  338. if(roundBest.fitness < runBest.fitness) runBest = roundBest;
  339. }
  340. printElapsedTime();
  341. setState(runBest.position);
  342. updateVisual();
  343. println("AlgoResult:" + runBest.fitness);
  344. }
  345. //Algo Part:
  346. /**
  347. * Algorithm 20 !! Fitness is better when smaller.:
  348. * PseudoCode:
  349. * Best <- actual;
  350. * population = initPopulationRandom();
  351. * for(maxGeneration times){
  352. * for(each Individual i from population){
  353. * fitness <- evaluatePosition(i);
  354. * if(fitness < best.fitnessValue) Best <- i;
  355. * }
  356. * childList <- {};
  357. * for(popsize/2 times){
  358. * parentA <- selectAParent(population);
  359. * parentB <- selectAParent(population);
  360. * childA,childB <- crossover(Copy(parentA ), Copy(parentB));
  361. * mutate(childA);
  362. * mutate(childB);
  363. * childList.add(childA);
  364. * childList.add(childB);
  365. * }
  366. * population = childList;
  367. *
  368. * }
  369. * @return
  370. */
  371. private Individual executeGaAlgo() {
  372. Individual best = new Individual();
  373. best.position = extractPositionAndAccess();
  374. best.fitness = evaluatePosition(best.position, false);
  375. println("Start with Fitness: " + best.fitness);
  376. int problemSize = best.position.size();
  377. List<Individual> population = initPopuluationRandom(problemSize);
  378. println("Size To Test:" + population.size());
  379. for(int generation = 0; generation< maxGenerations; generation++) {
  380. println("Generation" + generation + " start with Fitness: " + best.fitness);
  381. for(Individual i : population) {
  382. i.fitness = evaluatePosition(i.position, true);
  383. println("Fitness" + i.fitness);
  384. if(i.fitness < best.fitness) best = i;
  385. }
  386. List<Individual> childList = new ArrayList<Individual>();
  387. for(int k = 0; k<popsize/2; k++) {
  388. Individual parentA = selectAParent(population, popsize);
  389. Individual parentB = selectAParent(population, popsize);
  390. Individual childA = new Individual(parentA);
  391. Individual childB = new Individual(parentB);
  392. crossover(childA, childB, problemSize);
  393. mutate(childA, problemSize);
  394. mutate(childB, problemSize);
  395. childList.add(childA);
  396. childList.add(childB);
  397. }
  398. population = childList;
  399. println("________________");
  400. }
  401. println("RoundResult:" + best.fitness);
  402. return best;
  403. }
  404. /**
  405. * Algorithm 22 Bit-Flip Mutation.
  406. *
  407. */
  408. private void mutate(Individual child, int problemSize) {
  409. double probability = (this.useFixedMutateProbability) ? this.fixedMutateProbability : 1.0/(double)problemSize;
  410. ListIterator<Boolean> iter = child.position.listIterator();
  411. while(iter.hasNext()) {
  412. boolean boolValue = iter.next();
  413. if(Random.nextDouble() <= probability) {
  414. iter.set(!boolValue);
  415. }
  416. }
  417. }
  418. /**
  419. * Algorithm 25 Uniform Crossover.
  420. * Probability is set to 1/Problemsize when not changed.
  421. */
  422. private void crossover(Individual childA, Individual childB, int problemSize) {
  423. double probability = (this.useFixedSpawProbability) ? this.fixedSwapProbability : 1.0/(double)problemSize;
  424. ListIterator<Boolean> iterA = childA.position.listIterator();
  425. ListIterator<Boolean> iterB = childB.position.listIterator();
  426. for(int i= 0; i < problemSize; i++) {
  427. boolean boolA = iterA.next();
  428. boolean boolB = iterB.next();
  429. if(Random.nextDouble() <= probability ) {
  430. //Swap
  431. iterA.set(boolB);
  432. iterB.set(boolA);
  433. }
  434. }
  435. }
  436. /**
  437. * Algorithm 32 Tournament Selection.
  438. * The fitnessValues are calculated for the Population List.
  439. * PseudoCode
  440. */
  441. private Individual selectAParent(List<Individual> population,int popsize) {
  442. Individual tournamentBest = population.get(Random.nextIntegerInRange(0, popsize));
  443. for(int i = 2 ; i <= tournamentSize; i++) {
  444. Individual next = population.get(Random.nextIntegerInRange(0, popsize));
  445. if(next.fitness < tournamentBest.fitness) tournamentBest = next;
  446. }
  447. return tournamentBest;
  448. }
  449. /**
  450. * Initialize the Population with Individuals that have a random Position.
  451. */
  452. private List<Individual> initPopuluationRandom(int problemSize){
  453. List<Individual> population = new ArrayList<Individual>();
  454. for(int i = 0; i < popsize; i++) {
  455. population.add(createRandomIndividualWithoutFitness(problemSize));
  456. }
  457. return population;
  458. }
  459. /**
  460. * Algorithm 21 The BooleanVeator initialization.
  461. * @param problemSize
  462. * @return
  463. */
  464. private Individual createRandomIndividualWithoutFitness(int problemSize) {
  465. //create Random Individual Without Fitness
  466. Individual result = new Individual();
  467. result.position = new ArrayList<Boolean>();
  468. for (int index = 0; index < problemSize; index++){
  469. result.position.add(Random.nextBoolean());
  470. }
  471. return result;
  472. }
  473. /**
  474. * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
  475. * Also initialize the Access Hashmap to swap faster positions.
  476. * @param model
  477. * @return
  478. */
  479. private List<Boolean> extractPositionAndAccess() {
  480. Model model = control.getModel();
  481. switchList = new ArrayList<HolonSwitch>();
  482. objectList = new ArrayList<HolonObject>();
  483. initialState = new ArrayList<Boolean>();
  484. access= new HashMap<Integer, AccessWrapper>();
  485. rollOutNodes((useGroupNode && (dGroupNode != null))? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurIteration());
  486. resetChain.add(initialState);
  487. return initialState;
  488. }
  489. /**
  490. * Method to extract the Informations recursively out of the Model.
  491. * @param nodes
  492. * @param positionToInit
  493. * @param timeStep
  494. */
  495. private void rollOutNodes(List<AbstractCpsObject> nodes, List<Boolean> positionToInit, int timeStep) {
  496. for(AbstractCpsObject aCps : nodes) {
  497. if (aCps instanceof HolonObject) {
  498. for (HolonElement hE : ((HolonObject) aCps).getElements()) {
  499. positionToInit.add(hE.isActive());
  500. access.put(positionToInit.size() - 1 , new AccessWrapper(hE));
  501. }
  502. objectList.add((HolonObject) aCps);
  503. }
  504. else if (aCps instanceof HolonSwitch) {
  505. HolonSwitch sw = (HolonSwitch) aCps;
  506. positionToInit.add(sw.getState(timeStep));
  507. switchList.add(sw);
  508. access.put(positionToInit.size() - 1 , new AccessWrapper(sw));
  509. }
  510. else if(aCps instanceof CpsUpperNode) {
  511. rollOutNodes(((CpsUpperNode)aCps).getNodes(), positionToInit ,timeStep );
  512. }
  513. }
  514. }
  515. private double evaluatePosition(List<Boolean> position, boolean doIncreaseCounter) {
  516. setState(position);
  517. if(doIncreaseCounter)progressBarStep();
  518. control.calculateStateOnlyForCurrentTimeStep();
  519. DecoratedState actualstate = control.getSimManager().getActualDecorState();
  520. return PSOAlgorithm.getFitnessValueForState(actualstate);
  521. }
  522. /**
  523. * To let the User See the current state without touching the Canvas.
  524. */
  525. private void updateVisual() {
  526. control.calculateStateAndVisualForCurrentTimeStep();
  527. //control.updateCanvas();
  528. //control.getGui().triggerUpdateController(null);
  529. }
  530. /**
  531. * Sets the Model back to its original State before the LAST run.
  532. */
  533. private void resetState() {
  534. setState(resetChain.getLast());
  535. }
  536. /**
  537. * Sets the State out of the given position for calculation or to show the user.
  538. * @param position
  539. */
  540. private void setState(List<Boolean> position) {
  541. for(int i = 0;i<position.size();i++) {
  542. access.get(i).setState(position.get(i));
  543. }
  544. }
  545. private class Individual {
  546. public double fitness;
  547. public List<Boolean> position;
  548. Individual(){};
  549. /**
  550. * Copy Constructor
  551. */
  552. Individual(Individual c){
  553. position = c.position.stream().collect(Collectors.toList());
  554. fitness = c.fitness;
  555. }
  556. }
  557. /**
  558. * A Wrapper Class for Access HolonElement and HolonSwitch in one Element and not have to split the List.
  559. */
  560. private class AccessWrapper {
  561. public static final int HOLONELEMENT = 0;
  562. public static final int SWITCH = 1;
  563. private int type;
  564. private HolonSwitch hSwitch;
  565. private HolonElement hElement;
  566. public AccessWrapper(HolonSwitch hSwitch){
  567. type = SWITCH;
  568. this.hSwitch = hSwitch;
  569. }
  570. public AccessWrapper(HolonElement hElement){
  571. type = HOLONELEMENT;
  572. this.hElement = hElement;
  573. }
  574. public void setState(boolean state) {
  575. if(type == HOLONELEMENT) {
  576. hElement.setActive(state);
  577. }else{//is switch
  578. hSwitch.setManualMode(true);
  579. hSwitch.setManualState(state);
  580. }
  581. }
  582. public boolean getState(int timeStep) {
  583. return (type == HOLONELEMENT)?hElement.isActive():hSwitch.getState(timeStep);
  584. }
  585. public int getType() {
  586. return type;
  587. }
  588. }
  589. private class RunResult {
  590. public int activatedFlex = 0;
  591. public int deactivatedElements = 0;
  592. public float totalCost = 0;
  593. public LinkedList<TimeStepStateResult> timeStepList = new LinkedList<TimeStepStateResult>();
  594. public TimeStepStateResult addTimeStepStateResult(){
  595. TimeStepStateResult aResult = new TimeStepStateResult();
  596. timeStepList.add(aResult);
  597. return aResult;
  598. }
  599. public class TimeStepStateResult{
  600. public int amountOfProducer = 0;
  601. public int amountOfConsumer = 0;
  602. public int amountOfPassiv = 0;
  603. public int amountOfConsumerOverSupplied = 0;
  604. public int amountOfConsumerSupplied = 0;
  605. public int amountOfConsumerPartiallySupplied = 0;
  606. public int amountOfConsumerUnSupplied= 0;
  607. public float getProportionWithState(HolonObjectState state) {
  608. float amountOfObjects = amountOfProducer + amountOfConsumer + amountOfPassiv;
  609. switch(state) {
  610. case NOT_SUPPLIED:
  611. return (float) amountOfConsumerUnSupplied / amountOfObjects;
  612. case NO_ENERGY:
  613. return (float) amountOfPassiv / amountOfObjects;
  614. case OVER_SUPPLIED:
  615. return (float) amountOfConsumerOverSupplied / amountOfObjects;
  616. case PARTIALLY_SUPPLIED:
  617. return (float) amountOfConsumerPartiallySupplied / amountOfObjects;
  618. case PRODUCER:
  619. return (float) amountOfProducer / amountOfObjects;
  620. case SUPPLIED:
  621. return (float) amountOfConsumerSupplied / amountOfObjects;
  622. default:
  623. return 0.f;
  624. }
  625. }
  626. }
  627. public float getAvergaeProportionWithState(HolonObjectState state) {
  628. return timeStepList.stream().map(step -> step.getProportionWithState(state)).reduce((a,b) -> (a + b)).orElse(0.f) / (float) 100;
  629. }
  630. }
  631. /**
  632. * To create Random and maybe switch the random generation in the future.
  633. */
  634. private static class Random{
  635. private static java.util.Random random = new java.util.Random();
  636. /**
  637. * True or false
  638. * @return the random boolean.
  639. */
  640. public static boolean nextBoolean(){
  641. return random.nextBoolean();
  642. }
  643. /**
  644. * Between 0.0(inclusive) and 1.0 (exclusive)
  645. * @return the random double.
  646. */
  647. public static double nextDouble() {
  648. return random.nextDouble();
  649. }
  650. /**
  651. * Random Int in Range [min;max[ with UniformDistirbution
  652. * @param min
  653. * @param max
  654. * @return
  655. */
  656. public static int nextIntegerInRange(int min, int max) {
  657. return min + random.nextInt(max - min);
  658. }
  659. }
  660. private class Handle<T>{
  661. public T object;
  662. Handle(T object){
  663. this.object = object;
  664. }
  665. public String toString() {
  666. return object.toString();
  667. }
  668. }
  669. }