GaAlgorithm.java 25 KB

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