GaAlgorithm.java 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  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.event.ActionListener;
  7. import java.awt.image.BufferedImage;
  8. import java.io.BufferedWriter;
  9. import java.io.File;
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.io.OutputStreamWriter;
  13. import java.math.RoundingMode;
  14. import java.text.NumberFormat;
  15. import java.util.ArrayList;
  16. import java.util.HashMap;
  17. import java.util.HashSet;
  18. import java.util.LinkedList;
  19. import java.util.List;
  20. import java.util.ListIterator;
  21. import java.util.Locale;
  22. import java.util.Set;
  23. import java.util.TreeSet;
  24. import java.util.stream.Collectors;
  25. import javax.swing.BorderFactory;
  26. import javax.swing.ButtonGroup;
  27. import javax.swing.ImageIcon;
  28. import javax.swing.JButton;
  29. import javax.swing.JCheckBox;
  30. import javax.swing.JFileChooser;
  31. import javax.swing.JFormattedTextField;
  32. import javax.swing.JFrame;
  33. import javax.swing.JLabel;
  34. import javax.swing.JOptionPane;
  35. import javax.swing.JPanel;
  36. import javax.swing.JProgressBar;
  37. import javax.swing.JRadioButton;
  38. import javax.swing.JScrollPane;
  39. import javax.swing.JSplitPane;
  40. import javax.swing.JTextArea;
  41. import javax.swing.text.NumberFormatter;
  42. import api.AddOn;
  43. import classes.AbstractCpsObject;
  44. import classes.CpsUpperNode;
  45. import classes.HolonElement;
  46. import classes.HolonObject;
  47. import classes.HolonSwitch;
  48. import exampleAlgorithms.PSOAlgorithm.RunDataBase;
  49. import ui.controller.Control;
  50. import ui.model.DecoratedGroupNode;
  51. import ui.model.DecoratedState;
  52. import ui.model.Model;
  53. import ui.view.Console;
  54. import ui.model.DecoratedHolonObject.HolonObjectState;
  55. public class GaAlgorithm implements AddOn {
  56. //Parameter for Algo with default Values:
  57. /**
  58. * Should be even.
  59. */
  60. private int popsize = 20;
  61. private int maxGenerations = 100;
  62. private double tournamentSize = 2.0;
  63. private double fixedSwapProbability = 0.02;
  64. private boolean useFixedSpawProbability = false;
  65. private double fixedMutateProbability = 0.02;
  66. private boolean useFixedMutateProbability = false;
  67. private boolean useIntervalMutation = true;
  68. private double mutateProbabilityInterval = 0.01;
  69. private double maxMutationPercent = 0.01;
  70. private int rounds = 2;
  71. //Settings For GroupNode using and cancel
  72. private boolean useGroupNode = false;
  73. private DecoratedGroupNode dGroupNode = null;
  74. private boolean cancel = false;
  75. private boolean moreInformation = false;
  76. private boolean append = false;
  77. //Parameter defined by Algo
  78. private HashMap<Integer, AccessWrapper> access;
  79. LinkedList<List<Boolean>> resetChain = new LinkedList<List<Boolean>>();
  80. private List<HolonSwitch> switchList;
  81. private List<HolonObject> objectList;
  82. //Gui Part:
  83. private Control control;
  84. private Console console = new Console();
  85. private JPanel content = new JPanel();
  86. //ProgressBar
  87. private JProgressBar progressBar = new JProgressBar();
  88. private int progressBarCount = 0;
  89. private long startTime;
  90. private Thread runThread = new Thread();
  91. private RunDataBase db;
  92. //Parameter for Plotting (Default Directory in Constructor)
  93. private JFileChooser fileChooser = new JFileChooser();
  94. public static void main(String[] args)
  95. {
  96. JFrame newFrame = new JFrame("exampleWindow");
  97. GaAlgorithm instance = new GaAlgorithm();
  98. newFrame.setContentPane(instance.getPanel());
  99. newFrame.pack();
  100. newFrame.setVisible(true);
  101. newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  102. }
  103. public GaAlgorithm() {
  104. content.setLayout(new BorderLayout());
  105. JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
  106. createOptionPanel() , console);
  107. splitPane.setResizeWeight(0.0);
  108. content.add(splitPane, BorderLayout.CENTER);
  109. content.setPreferredSize(new Dimension(800,800));
  110. fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
  111. fileChooser.setSelectedFile(new File("plott.txt"));
  112. }
  113. public JPanel createOptionPanel() {
  114. JPanel optionPanel = new JPanel(new BorderLayout());
  115. JScrollPane scrollPane = new JScrollPane(createParameterPanel());
  116. scrollPane.setBorder(BorderFactory.createTitledBorder("Parameter"));
  117. optionPanel.add(scrollPane, BorderLayout.CENTER);
  118. optionPanel.add(createButtonPanel(), BorderLayout.PAGE_END);
  119. return optionPanel;
  120. }
  121. private Component createParameterPanel() {
  122. JPanel parameterPanel = new JPanel(null);
  123. parameterPanel.setPreferredSize(new Dimension(510,300));
  124. JLabel maxGenerationsLabel = new JLabel("Max. Generations:");
  125. maxGenerationsLabel.setBounds(20, 60, 150, 20);
  126. parameterPanel.add(maxGenerationsLabel);
  127. JLabel populationLabel = new JLabel("Population Size:");
  128. populationLabel.setBounds(20, 85, 150, 20);
  129. parameterPanel.add(populationLabel);
  130. JLabel roundLabel = new JLabel("Rounds:");
  131. roundLabel.setBounds(20, 110, 150, 20);
  132. parameterPanel.add(roundLabel);
  133. JLabel mutationLabel = new JLabel("FixedMutation:");
  134. mutationLabel.setBounds(50, 255, 150, 20);
  135. mutationLabel.setEnabled(useFixedMutateProbability);
  136. parameterPanel.add(mutationLabel);
  137. JLabel swapLabel = new JLabel("FixedSwap:");
  138. swapLabel.setBounds(50, 160, 150, 20);
  139. swapLabel.setEnabled(this.useFixedSpawProbability);
  140. parameterPanel.add(swapLabel);
  141. JLabel tournamentLabel = new JLabel("TournamentSize:");
  142. tournamentLabel.setBounds(20, 185, 150, 20);
  143. parameterPanel.add(tournamentLabel);
  144. JLabel progressLabel = new JLabel("Progress:");
  145. progressLabel.setBounds(350, 135, 170, 20);
  146. parameterPanel.add(progressLabel);
  147. progressBar.setBounds(350, 155, 185, 20);
  148. progressBar.setStringPainted(true);
  149. parameterPanel.add(progressBar);
  150. JPanel borderPanel = new JPanel(null);
  151. borderPanel.setBounds(350, 85, 185, 50);
  152. borderPanel.setBorder(BorderFactory.createTitledBorder(""));
  153. parameterPanel.add(borderPanel);
  154. JLabel showGroupNodeLabel = new JLabel("Use Group Node:");
  155. showGroupNodeLabel.setBounds(10, 1, 170, 20);
  156. borderPanel.add(showGroupNodeLabel);
  157. JButton selectGroupNodeButton = new JButton("Select GroupNode");
  158. selectGroupNodeButton.setEnabled(false);
  159. selectGroupNodeButton.setBounds(10, 25, 165, 20);
  160. selectGroupNodeButton.addActionListener(actionEvent -> selectGroupNode());
  161. borderPanel.add(selectGroupNodeButton);
  162. JCheckBox useGroupNodeCheckBox = new JCheckBox();
  163. useGroupNodeCheckBox.setSelected(false);
  164. useGroupNodeCheckBox.setBounds(155, 1, 25, 20);
  165. useGroupNodeCheckBox.addActionListener(actionEvent -> {
  166. useGroupNode = useGroupNodeCheckBox.isSelected();
  167. selectGroupNodeButton.setEnabled(useGroupNode);
  168. });
  169. borderPanel.add(useGroupNodeCheckBox);
  170. JCheckBox informationCheckBox = new JCheckBox("More Information");
  171. informationCheckBox.setSelected(this.moreInformation);
  172. informationCheckBox.setBounds(350, 60, 220, 20);
  173. informationCheckBox.addActionListener(actionEvent -> {
  174. moreInformation = informationCheckBox.isSelected();
  175. });
  176. parameterPanel.add(informationCheckBox);
  177. //Integer formatter
  178. NumberFormat format = NumberFormat.getIntegerInstance();
  179. format.setGroupingUsed(false);
  180. format.setParseIntegerOnly(true);
  181. NumberFormatter integerFormatter = new NumberFormatter(format);
  182. integerFormatter.setMinimum(1);
  183. integerFormatter.setCommitsOnValidEdit(true);
  184. JFormattedTextField maxGenerationsTextField = new JFormattedTextField(integerFormatter);
  185. maxGenerationsTextField.setValue(this.maxGenerations);
  186. maxGenerationsTextField.setToolTipText("Only positive Integer.");
  187. maxGenerationsTextField.addPropertyChangeListener(actionEvent -> this.maxGenerations = Integer.parseInt(maxGenerationsTextField.getValue().toString()));
  188. maxGenerationsTextField.setBounds(160, 60, 50, 20);
  189. parameterPanel.add(maxGenerationsTextField);
  190. JFormattedTextField popSizeTextField = new JFormattedTextField(integerFormatter);
  191. popSizeTextField.setValue(this.popsize);
  192. popSizeTextField.setToolTipText("Only positive Integer.");
  193. popSizeTextField.addPropertyChangeListener(propertyChange -> this.popsize = Integer.parseInt(popSizeTextField.getValue().toString()));
  194. popSizeTextField.setBounds(160, 85, 50, 20);
  195. parameterPanel.add(popSizeTextField);
  196. JFormattedTextField roundsTextField = new JFormattedTextField(integerFormatter);
  197. roundsTextField.setValue(this.rounds);
  198. roundsTextField.setToolTipText("Only positive Integer.");
  199. roundsTextField.addPropertyChangeListener(propertyChange -> this.rounds = Integer.parseInt(roundsTextField.getValue().toString()));
  200. roundsTextField.setBounds(160, 110, 50, 20);
  201. parameterPanel.add(roundsTextField);
  202. //Double Format:
  203. NumberFormat doubleFormat = NumberFormat.getNumberInstance(Locale.US);
  204. doubleFormat.setMinimumFractionDigits(1);
  205. doubleFormat.setMaximumFractionDigits(3);
  206. doubleFormat.setRoundingMode(RoundingMode.HALF_UP);
  207. //Limit Formatter:
  208. NumberFormatter limitFormatter = new NumberFormatter(doubleFormat);
  209. limitFormatter.setMinimum(0.0);
  210. limitFormatter.setMaximum(1.0);
  211. JFormattedTextField mutateTextField = new JFormattedTextField(limitFormatter);
  212. mutateTextField.setValue(this.fixedMutateProbability);
  213. mutateTextField.setEnabled(this.useFixedMutateProbability);
  214. mutateTextField.setToolTipText("Only Double in range [0.0, 1.0] with DecimalSeperator Point('.').");
  215. mutateTextField.addPropertyChangeListener(propertyChange -> fixedMutateProbability = Double.parseDouble(mutateTextField.getValue().toString()));
  216. mutateTextField.setBounds(160, 255, 50, 20);
  217. parameterPanel.add(mutateTextField);
  218. JCheckBox useFixMutateCheckBox = new JCheckBox();
  219. useFixMutateCheckBox.setSelected(this.useFixedMutateProbability);
  220. useFixMutateCheckBox.setToolTipText("If not checked its 1/ProblemSize");
  221. useFixMutateCheckBox.setBounds(20, 255, 25, 20);
  222. useFixMutateCheckBox.addActionListener(actionEvent -> {
  223. boolean state = useFixMutateCheckBox.isSelected();
  224. this.useFixedMutateProbability = state;
  225. mutateTextField.setEnabled(state);
  226. mutationLabel.setEnabled(state);
  227. });
  228. parameterPanel.add(useFixMutateCheckBox);
  229. JFormattedTextField swapTextField = new JFormattedTextField(limitFormatter);
  230. swapTextField.setValue(this.fixedSwapProbability);
  231. swapTextField.setEnabled(this.useFixedMutateProbability);
  232. swapTextField.setToolTipText("Only Double in range [0.0, 1.0] with DecimalSeperator Point('.').");
  233. swapTextField.addPropertyChangeListener(propertyChange -> this.fixedSwapProbability = Double.parseDouble(swapTextField.getValue().toString()));
  234. swapTextField.setBounds(160, 160, 50, 20);
  235. parameterPanel.add(swapTextField);
  236. JCheckBox useFixSwapCheckBox = new JCheckBox();
  237. useFixSwapCheckBox.setSelected(this.useFixedSpawProbability);
  238. useFixSwapCheckBox.setToolTipText("If not checked its 1/ProblemSize");
  239. useFixSwapCheckBox.setBounds(20, 160, 25, 20);
  240. useFixSwapCheckBox.addActionListener(actionEvent -> {
  241. boolean state = useFixSwapCheckBox.isSelected();
  242. this.useFixedSpawProbability = state;
  243. swapTextField.setEnabled(state);
  244. swapLabel.setEnabled(state);
  245. });
  246. parameterPanel.add(useFixSwapCheckBox);
  247. NumberFormatter tournamentFormatter = new NumberFormatter(doubleFormat);
  248. tournamentFormatter.setMinimum(1.0);
  249. JFormattedTextField tournamentSizeTextField = new JFormattedTextField(tournamentFormatter);
  250. tournamentSizeTextField.setValue(this.tournamentSize);
  251. tournamentSizeTextField.setToolTipText("Only Double bigger or equal then 1.");
  252. tournamentSizeTextField.addPropertyChangeListener(propertyChange -> this.tournamentSize = Double.parseDouble(tournamentSizeTextField.getValue().toString()));
  253. tournamentSizeTextField.setBounds(160, 185, 50, 20);
  254. parameterPanel.add(tournamentSizeTextField);
  255. JLabel mutationIntervallLabel = new JLabel("MutationRate:");
  256. mutationIntervallLabel.setBounds(220, 255, 150, 20);
  257. mutationIntervallLabel.setEnabled(useIntervalMutation);
  258. parameterPanel.add(mutationIntervallLabel);
  259. JFormattedTextField mutationRateField = new JFormattedTextField(limitFormatter);
  260. mutationRateField.setValue(this.mutateProbabilityInterval);
  261. mutationRateField.setEnabled(this.useIntervalMutation);
  262. mutationRateField.setToolTipText("Only Double in range [0.0, 1.0] with DecimalSeperator Point('.').");
  263. mutationRateField.addPropertyChangeListener(propertyChange -> this.mutateProbabilityInterval = Double.parseDouble(mutationRateField.getValue().toString()));
  264. mutationRateField.setBounds(400, 255, 50, 20);
  265. parameterPanel.add(mutationRateField);
  266. JLabel maxMutationPercentLabel = new JLabel("Max Mutation Percent:");
  267. maxMutationPercentLabel.setBounds(220, 280, 200, 20);
  268. maxMutationPercentLabel.setEnabled(useIntervalMutation);
  269. parameterPanel.add(maxMutationPercentLabel);
  270. JFormattedTextField mutationMaxField = new JFormattedTextField(limitFormatter);
  271. mutationMaxField.setValue(this.maxMutationPercent);
  272. mutationMaxField.setEnabled(this.useIntervalMutation);
  273. mutationMaxField.setToolTipText("Only Double in range [0.0, 1.0] with DecimalSeperator Point('.').");
  274. mutationMaxField.addPropertyChangeListener(propertyChange -> this.maxMutationPercent = Double.parseDouble(mutationMaxField.getValue().toString()));
  275. mutationMaxField.setBounds(400, 280, 50, 20);
  276. parameterPanel.add(mutationMaxField);
  277. JRadioButton jRadioMutate = new JRadioButton("Normal Mutate");
  278. jRadioMutate.setBounds(20, 230, 200, 20);
  279. jRadioMutate.setSelected(!useIntervalMutation);
  280. jRadioMutate.setActionCommand("normal");
  281. parameterPanel.add(jRadioMutate);
  282. JRadioButton jRadioMutateInterval = new JRadioButton("Mutate Interval");
  283. jRadioMutateInterval.setBounds(220, 230, 200, 20);
  284. jRadioMutateInterval.setActionCommand("intervall");
  285. jRadioMutateInterval.setSelected(useIntervalMutation);
  286. parameterPanel.add(jRadioMutateInterval);
  287. ButtonGroup group = new ButtonGroup();
  288. group.add(jRadioMutate);
  289. group.add(jRadioMutateInterval);
  290. ActionListener radioListener = e -> {
  291. if(e.getActionCommand() == "normal") {
  292. this.useIntervalMutation = false;
  293. mutateTextField.setEnabled(true);
  294. useFixMutateCheckBox.setEnabled(true);
  295. mutationLabel.setEnabled(true);
  296. mutationIntervallLabel.setEnabled(false);
  297. mutationRateField.setEnabled(false);
  298. maxMutationPercentLabel.setEnabled(false);
  299. mutationMaxField.setEnabled(false);
  300. }else if(e.getActionCommand() == "intervall") {
  301. this.useIntervalMutation = true;
  302. mutateTextField.setEnabled(false);
  303. useFixMutateCheckBox.setEnabled(false);
  304. mutationLabel.setEnabled(false);
  305. mutationIntervallLabel.setEnabled(true);
  306. mutationRateField.setEnabled(true);
  307. maxMutationPercentLabel.setEnabled(true);
  308. mutationMaxField.setEnabled(true);
  309. }
  310. };
  311. jRadioMutate.addActionListener(radioListener);
  312. jRadioMutateInterval.addActionListener(radioListener);
  313. return parameterPanel;
  314. }
  315. public JPanel createButtonPanel() {
  316. JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
  317. JButton fitnessButton = new JButton("Fitness");
  318. fitnessButton.setToolTipText("Fitness for the current state.");
  319. fitnessButton.addActionListener(actionEvent -> fitness());
  320. buttonPanel.add(fitnessButton);
  321. JButton plottButton = new JButton("Plott");
  322. plottButton.addActionListener(actionEvent -> plott());
  323. buttonPanel.add(plottButton);
  324. JButton resetButton = new JButton("ResetAll");
  325. resetButton.setToolTipText("Resets the State to before the Algorithm has runed.");
  326. resetButton.addActionListener(actionEvent -> resetAll());
  327. buttonPanel.add(resetButton);
  328. JButton cancelButton = new JButton("Cancel Run");
  329. cancelButton.addActionListener(actionEvent -> cancel());
  330. buttonPanel.add(cancelButton);
  331. JButton undoButton = new JButton("Undo");
  332. undoButton.setToolTipText("One Algo Step Back.");
  333. undoButton.addActionListener(actionEvent -> resetLast());
  334. buttonPanel.add(undoButton);
  335. JButton runButton = new JButton("Run");
  336. runButton.addActionListener(actionEvent -> {
  337. Runnable task = () -> run();
  338. runThread = new Thread(task);
  339. runThread.start();
  340. });
  341. buttonPanel.add(runButton);
  342. return buttonPanel;
  343. }
  344. private void cancel() {
  345. if(runThread.isAlive()) {
  346. println("");
  347. println("Cancel run.");
  348. cancel = true;
  349. progressBar.setValue(0);
  350. } else {
  351. println("Nothing to cancel.");
  352. }
  353. }
  354. private void run() {
  355. cancel = false;
  356. disableGuiInput(true);
  357. executeAlgoWithParameter();
  358. updateVisual();
  359. disableGuiInput(false);
  360. }
  361. private void resetLast() {
  362. if(runThread.isAlive()) {
  363. println("Run have to be cancelled First.");
  364. return;
  365. }
  366. if(!resetChain.isEmpty()) {
  367. println("Resetting..");
  368. resetState();
  369. resetChain.removeLast();
  370. control.resetSimulation();
  371. updateVisual();
  372. }else {
  373. println("No run inistialized.");
  374. }
  375. }
  376. private void resetAll() {
  377. if(runThread.isAlive()) {
  378. println("Run have to be cancelled First.");
  379. return;
  380. }
  381. if(!resetChain.isEmpty()) {
  382. println("Resetting..");
  383. setState(resetChain.getFirst());
  384. resetChain.clear();
  385. control.resetSimulation();
  386. control.setCurIteration(0);
  387. updateVisual();
  388. }else {
  389. println("No run inistialized.");
  390. }
  391. }
  392. private void fitness() {
  393. if(runThread.isAlive()) {
  394. println("Run have to be cancelled First.");
  395. return;
  396. }
  397. double currentFitness = evaluatePosition(extractPositionAndAccess(), false);
  398. resetChain.removeLast();
  399. console.println("Actual Fitnessvalue: " + currentFitness);
  400. }
  401. private void disableGuiInput(boolean bool) {
  402. control.guiDisable(bool);
  403. }
  404. private void plott() {
  405. if(db!=null) {
  406. console.println("Plott..");
  407. db.initFileStream();
  408. }else {
  409. console.println("No run inistialized.");
  410. }
  411. }
  412. @Override
  413. public JPanel getPanel() {
  414. return content;
  415. }
  416. @Override
  417. public void setController(Control control) {
  418. this.control = control;
  419. }
  420. private void clear() {
  421. console.clear();
  422. }
  423. private void println(String message) {
  424. console.println(message);
  425. }
  426. private void selectGroupNode() {
  427. Object[] possibilities = control.getSimManager().getActualVisualRepresentationalState().getCreatedGroupNodes().values().stream().map(aCps -> new Handle<DecoratedGroupNode>(aCps)).toArray();
  428. @SuppressWarnings("unchecked")
  429. 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, "");
  430. if(selected != null) {
  431. println("Selected: " + selected);
  432. dGroupNode = selected.object;
  433. }
  434. }
  435. private void progressBarStep(){
  436. progressBar.setValue(++progressBarCount);
  437. }
  438. private void calculateProgressBarParameter() {
  439. int max = this.maxGenerations * this.popsize * this.rounds;
  440. progressBarCount = 0;
  441. progressBar.setValue(0);
  442. progressBar.setMaximum(max);
  443. }
  444. private void startTimer(){
  445. startTime = System.currentTimeMillis();
  446. }
  447. private void printElapsedTime(){
  448. long elapsedMilliSeconds = System.currentTimeMillis() - startTime;
  449. println("Execution Time of Algo in Milliseconds:" + elapsedMilliSeconds);
  450. }
  451. private void executeAlgoWithParameter(){
  452. int actualIteration = control.getModel().getCurIteration();
  453. println("TimeStep:" + actualIteration);
  454. calculateProgressBarParameter();
  455. startTimer();
  456. Individual runBest = new Individual();
  457. runBest.fitness = Double.MAX_VALUE;
  458. db = new RunDataBase();
  459. for(int r = 0; r < rounds; r++)
  460. {
  461. List<Double> runList = db.insertNewRun();
  462. Individual roundBest = executeGaAlgo(runList);
  463. if(cancel)return;
  464. resetState();
  465. if(roundBest.fitness < runBest.fitness) runBest = roundBest;
  466. }
  467. printElapsedTime();
  468. setState(runBest.position);
  469. updateVisual();
  470. println("AlgoResult:" + runBest.fitness);
  471. }
  472. //Algo Part:
  473. /**
  474. * Algorithm 20 !! Fitness is better when smaller.:
  475. * PseudoCode:
  476. * Best <- actual;
  477. * population = initPopulationRandom();
  478. * for(maxGeneration times){
  479. * for(each Individual i from population){
  480. * fitness <- evaluatePosition(i);
  481. * if(fitness < best.fitnessValue) Best <- i;
  482. * }
  483. * childList <- {};
  484. * for(popsize/2 times){
  485. * parentA <- selectAParent(population);
  486. * parentB <- selectAParent(population);
  487. * childA,childB <- crossover(Copy(parentA ), Copy(parentB));
  488. * mutate(childA);
  489. * mutate(childB);
  490. * childList.add(childA);
  491. * childList.add(childB);
  492. * }
  493. * population = childList;
  494. *
  495. * }
  496. * @return
  497. */
  498. private Individual executeGaAlgo(List<Double> runList) {
  499. Individual best = new Individual();
  500. best.position = extractPositionAndAccess();
  501. if(moreInformation)println("Bit-Array_length: " + best.position.size());
  502. best.fitness = evaluatePosition(best.position, false);
  503. runList.add(best.fitness);
  504. console.print("Start with: " + best.fitness);
  505. if(moreInformation)println("");
  506. int problemSize = best.position.size();
  507. List<Individual> population = initPopuluationRandom(problemSize, best);
  508. if(moreInformation)println("Size To Test:" + population.size());
  509. for(int generation = 0; generation< maxGenerations; generation++) {
  510. if(moreInformation)println("Generation" + generation + " start with Fitness: " + best.fitness);
  511. for(Individual i : population) {
  512. i.fitness = evaluatePosition(i.position, true);
  513. if(moreInformation)println("Fitness" + i.fitness);
  514. if(i.fitness < best.fitness) best = i;
  515. }
  516. runList.add(best.fitness);
  517. List<Individual> childList = new ArrayList<Individual>();
  518. for(int k = 0; k<popsize/2; k++) {
  519. Individual parentA = selectAParent(population, popsize);
  520. Individual parentB = selectAParent(population, popsize);
  521. Individual childA = new Individual(parentA);
  522. Individual childB = new Individual(parentB);
  523. crossover(childA, childB, problemSize);
  524. if(useIntervalMutation)mutateInterval(childA, problemSize);else mutate(childA, problemSize);
  525. if(useIntervalMutation)mutateInterval(childB, problemSize);else mutate(childB, problemSize);
  526. childList.add(childA);
  527. childList.add(childB);
  528. }
  529. population = childList;
  530. if(moreInformation)println("________________");
  531. if(cancel)return null;
  532. }
  533. println(" End with:" + best.fitness);
  534. return best;
  535. }
  536. /**
  537. * Algorithm 22 Bit-Flip Mutation.
  538. *
  539. */
  540. private void mutate(Individual child, int problemSize) {
  541. double probability = (this.useFixedMutateProbability) ? this.fixedMutateProbability : 1.0/(double)problemSize;
  542. ListIterator<Boolean> iter = child.position.listIterator();
  543. while(iter.hasNext()) {
  544. boolean boolValue = iter.next();
  545. if(Random.nextDouble() <= probability) {
  546. iter.set(!boolValue);
  547. }
  548. }
  549. }
  550. /**
  551. * Algorithm rolf
  552. *
  553. */
  554. private void mutateInterval(Individual child, int problemSize) {
  555. //If not mutate skip
  556. if(Random.nextDouble() > this.mutateProbabilityInterval) {
  557. return;
  558. }
  559. //println("problemSize:" + problemSize + " maxMutationPercent:" + maxMutationPercent);
  560. int maximumAmountOfMutatedBits = Math.max(1, (int)Math.round(((double) problemSize) * this.maxMutationPercent));
  561. int randomUniformAmountOfMutatedValues = Random.nextIntegerInRange(1,maximumAmountOfMutatedBits + 1);
  562. //println("max:" + maximumAmountOfMutatedBits + " actual:" + randomUniformAmountOfMutatedValues);
  563. TreeSet<Integer> mutationLocation = new TreeSet<Integer>(); //sortedSet
  564. //Choose the location to mutate
  565. for(int i = 0; i< randomUniformAmountOfMutatedValues; i++) {
  566. boolean success = mutationLocation.add(Random.nextIntegerInRange(0, problemSize));
  567. if(!success) i--; //can be add up to some series long loops if maximumAmountOfMutatedBits get closed to problemsize.
  568. }
  569. //println("Set:" + mutationLocation);
  570. ListIterator<Boolean> iter = child.position.listIterator();
  571. if(mutationLocation.isEmpty()) return;
  572. int firstindex = mutationLocation.pollFirst();
  573. while(iter.hasNext()) {
  574. int index = iter.nextIndex();
  575. boolean boolValue = iter.next();
  576. if(index == firstindex) {
  577. iter.set(!boolValue);
  578. //println("changed Value["+ index +"]");
  579. if(mutationLocation.isEmpty()) break;
  580. firstindex = mutationLocation.pollFirst();
  581. }
  582. }
  583. }
  584. /**
  585. * Algorithm 25 Uniform Crossover.
  586. * Probability is set to 1/Problemsize when not changed.
  587. */
  588. private void crossover(Individual childA, Individual childB, int problemSize) {
  589. double probability = (this.useFixedSpawProbability) ? this.fixedSwapProbability : 1.0/(double)problemSize;
  590. ListIterator<Boolean> iterA = childA.position.listIterator();
  591. ListIterator<Boolean> iterB = childB.position.listIterator();
  592. for(int i= 0; i < problemSize; i++) {
  593. boolean boolA = iterA.next();
  594. boolean boolB = iterB.next();
  595. if(Random.nextDouble() <= probability ) {
  596. //Swap
  597. iterA.set(boolB);
  598. iterB.set(boolA);
  599. }
  600. }
  601. }
  602. /**
  603. * Algorithm 32 Tournament Selection.
  604. * The fitnessValues are calculated for the Population List.
  605. * PseudoCode
  606. */
  607. private Individual selectAParent(List<Individual> population,int popsize) {
  608. Individual tournamentBest = population.get(Random.nextIntegerInRange(0, popsize));
  609. double participants;
  610. for(participants = tournamentSize ; participants >= 2; participants -= 1.0) {
  611. Individual next = population.get(Random.nextIntegerInRange(0, popsize));
  612. if(next.fitness < tournamentBest.fitness) tournamentBest = next;
  613. }
  614. //if tournament size is not a whole number like 2.5 or 3.6
  615. //the remaining part is the chance to fight another time; 2.7 -> 70% chance to fight a second time
  616. if( participants > 1) {
  617. if(Random.nextDouble() < participants - 1.0) {
  618. //println("Chance to find a match");
  619. Individual next = population.get(Random.nextIntegerInRange(0, popsize));
  620. if(next.fitness < tournamentBest.fitness) tournamentBest = next;
  621. }
  622. }
  623. return tournamentBest;
  624. }
  625. /**
  626. * Initialize the Population with Individuals that have a random Position.
  627. */
  628. private List<Individual> initPopuluationRandom(int problemSize, Individual startIndidual){
  629. List<Individual> population = new ArrayList<Individual>();
  630. for(int i = 0; i < popsize -1; i++) {
  631. population.add(createRandomIndividualWithoutFitness(problemSize));
  632. }
  633. //Add Start Position
  634. population.add(new Individual(startIndidual));
  635. return population;
  636. }
  637. /**
  638. * Algorithm 21 The BooleanVeator initialization.
  639. * @param problemSize
  640. * @return
  641. */
  642. private Individual createRandomIndividualWithoutFitness(int problemSize) {
  643. //create Random Individual Without Fitness
  644. Individual result = new Individual();
  645. result.position = new ArrayList<Boolean>();
  646. for (int index = 0; index < problemSize; index++){
  647. result.position.add(Random.nextBoolean());
  648. }
  649. return result;
  650. }
  651. /**
  652. * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
  653. * Also initialize the Access Hashmap to swap faster positions.
  654. * @param model
  655. * @return
  656. */
  657. private List<Boolean> extractPositionAndAccess() {
  658. Model model = control.getModel();
  659. switchList = new ArrayList<HolonSwitch>();
  660. objectList = new ArrayList<HolonObject>();
  661. List<Boolean> initialState = new ArrayList<Boolean>();
  662. access= new HashMap<Integer, AccessWrapper>();
  663. rollOutNodes((useGroupNode && (dGroupNode != null))? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurIteration());
  664. resetChain.add(initialState);
  665. return initialState;
  666. }
  667. /**
  668. * Method to extract the Informations recursively out of the Model.
  669. * @param nodes
  670. * @param positionToInit
  671. * @param timeStep
  672. */
  673. private void rollOutNodes(List<AbstractCpsObject> nodes, List<Boolean> positionToInit, int timeStep) {
  674. for(AbstractCpsObject aCps : nodes) {
  675. if (aCps instanceof HolonObject) {
  676. for (HolonElement hE : ((HolonObject) aCps).getElements()) {
  677. positionToInit.add(hE.isActive());
  678. access.put(positionToInit.size() - 1 , new AccessWrapper(hE));
  679. }
  680. objectList.add((HolonObject) aCps);
  681. }
  682. else if (aCps instanceof HolonSwitch) {
  683. HolonSwitch sw = (HolonSwitch) aCps;
  684. positionToInit.add(sw.getState(timeStep));
  685. switchList.add(sw);
  686. access.put(positionToInit.size() - 1 , new AccessWrapper(sw));
  687. }
  688. else if(aCps instanceof CpsUpperNode) {
  689. rollOutNodes(((CpsUpperNode)aCps).getNodes(), positionToInit ,timeStep );
  690. }
  691. }
  692. }
  693. private double evaluatePosition(List<Boolean> position, boolean doIncreaseCounter) {
  694. setState(position);
  695. if(doIncreaseCounter)progressBarStep();
  696. control.calculateStateOnlyForCurrentTimeStep();
  697. DecoratedState actualstate = control.getSimManager().getActualDecorState();
  698. return PSOAlgorithm.getFitnessValueForState(actualstate);
  699. }
  700. /**
  701. * To let the User See the current state without touching the Canvas.
  702. */
  703. private void updateVisual() {
  704. control.calculateStateAndVisualForCurrentTimeStep();
  705. //control.updateCanvas();
  706. //control.getGui().triggerUpdateController(null);
  707. }
  708. /**
  709. * Sets the Model back to its original State before the LAST run.
  710. */
  711. private void resetState() {
  712. setState(resetChain.getLast());
  713. }
  714. /**
  715. * Sets the State out of the given position for calculation or to show the user.
  716. * @param position
  717. */
  718. private void setState(List<Boolean> position) {
  719. for(int i = 0;i<position.size();i++) {
  720. access.get(i).setState(position.get(i));
  721. }
  722. }
  723. private class Individual {
  724. public double fitness;
  725. public List<Boolean> position;
  726. Individual(){};
  727. /**
  728. * Copy Constructor
  729. */
  730. Individual(Individual c){
  731. position = c.position.stream().collect(Collectors.toList());
  732. fitness = c.fitness;
  733. }
  734. }
  735. /**
  736. * A Wrapper Class for Access HolonElement and HolonSwitch in one Element and not have to split the List.
  737. */
  738. private class AccessWrapper {
  739. public static final int HOLONELEMENT = 0;
  740. public static final int SWITCH = 1;
  741. private int type;
  742. private HolonSwitch hSwitch;
  743. private HolonElement hElement;
  744. public AccessWrapper(HolonSwitch hSwitch){
  745. type = SWITCH;
  746. this.hSwitch = hSwitch;
  747. }
  748. public AccessWrapper(HolonElement hElement){
  749. type = HOLONELEMENT;
  750. this.hElement = hElement;
  751. }
  752. public void setState(boolean state) {
  753. if(type == HOLONELEMENT) {
  754. hElement.setActive(state);
  755. }else{//is switch
  756. hSwitch.setManualMode(true);
  757. hSwitch.setManualState(state);
  758. }
  759. }
  760. public boolean getState(int timeStep) {
  761. return (type == HOLONELEMENT)?hElement.isActive():hSwitch.getState(timeStep);
  762. }
  763. public int getType() {
  764. return type;
  765. }
  766. }
  767. /**
  768. * A Database for all Global Best(G<sub>Best</sub>) Values in a execution of a the Algo. For Easy Printing.
  769. */
  770. public class RunDataBase {
  771. List<List<Double>> allRuns = new ArrayList<List<Double>>();
  772. /**
  773. * Initialize The Stream before you can write to a File.
  774. */
  775. public void initFileStream() {
  776. File file = fileChooser.getSelectedFile();
  777. try {
  778. file.createNewFile();
  779. BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
  780. new FileOutputStream(file, append), "UTF-8"));
  781. printToStream(out);
  782. out.close();
  783. } catch (IOException e) {
  784. console.println(e.getMessage());
  785. }
  786. }
  787. public void printToStream(BufferedWriter out) throws IOException {
  788. try {
  789. out.write(maxGenerations + 1 + "," + allRuns.size() + "," + popsize);
  790. out.newLine();
  791. }
  792. catch(IOException e) {
  793. console.println(e.getMessage());
  794. }
  795. allRuns.forEach(run -> {
  796. try {
  797. out.write( run.stream().map(Object::toString).collect(Collectors.joining(", ")));
  798. out.newLine();
  799. } catch (IOException e) {
  800. console.println(e.getMessage());
  801. }
  802. } );
  803. }
  804. public List<Double> insertNewRun(){
  805. List<Double> newRun = new ArrayList<Double>();
  806. allRuns.add(newRun);
  807. return newRun;
  808. }
  809. }
  810. private class RunResult {
  811. public int activatedFlex = 0;
  812. public int deactivatedElements = 0;
  813. public float totalCost = 0;
  814. public LinkedList<TimeStepStateResult> timeStepList = new LinkedList<TimeStepStateResult>();
  815. public TimeStepStateResult addTimeStepStateResult(){
  816. TimeStepStateResult aResult = new TimeStepStateResult();
  817. timeStepList.add(aResult);
  818. return aResult;
  819. }
  820. public class TimeStepStateResult{
  821. public int amountOfProducer = 0;
  822. public int amountOfConsumer = 0;
  823. public int amountOfPassiv = 0;
  824. public int amountOfConsumerOverSupplied = 0;
  825. public int amountOfConsumerSupplied = 0;
  826. public int amountOfConsumerPartiallySupplied = 0;
  827. public int amountOfConsumerUnSupplied= 0;
  828. public float getProportionWithState(HolonObjectState state) {
  829. float amountOfObjects = amountOfProducer + amountOfConsumer + amountOfPassiv;
  830. switch(state) {
  831. case NOT_SUPPLIED:
  832. return (float) amountOfConsumerUnSupplied / amountOfObjects;
  833. case NO_ENERGY:
  834. return (float) amountOfPassiv / amountOfObjects;
  835. case OVER_SUPPLIED:
  836. return (float) amountOfConsumerOverSupplied / amountOfObjects;
  837. case PARTIALLY_SUPPLIED:
  838. return (float) amountOfConsumerPartiallySupplied / amountOfObjects;
  839. case PRODUCER:
  840. return (float) amountOfProducer / amountOfObjects;
  841. case SUPPLIED:
  842. return (float) amountOfConsumerSupplied / amountOfObjects;
  843. default:
  844. return 0.f;
  845. }
  846. }
  847. }
  848. public float getAvergaeProportionWithState(HolonObjectState state) {
  849. return timeStepList.stream().map(step -> step.getProportionWithState(state)).reduce((a,b) -> (a + b)).orElse(0.f) / (float) 100;
  850. }
  851. }
  852. /**
  853. * To create Random and maybe switch the random generation in the future.
  854. */
  855. private static class Random{
  856. private static java.util.Random random = new java.util.Random();
  857. /**
  858. * True or false
  859. * @return the random boolean.
  860. */
  861. public static boolean nextBoolean(){
  862. return random.nextBoolean();
  863. }
  864. /**
  865. * Between 0.0(inclusive) and 1.0 (exclusive)
  866. * @return the random double.
  867. */
  868. public static double nextDouble() {
  869. return random.nextDouble();
  870. }
  871. /**
  872. * Random Int in Range [min;max[ with UniformDistirbution
  873. * @param min
  874. * @param max
  875. * @return
  876. */
  877. public static int nextIntegerInRange(int min, int max) {
  878. return min + random.nextInt(max - min);
  879. }
  880. }
  881. private class Handle<T>{
  882. public T object;
  883. Handle(T object){
  884. this.object = object;
  885. }
  886. public String toString() {
  887. return object.toString();
  888. }
  889. }
  890. }