PSOAlgotihm.java 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  1. package exampleAlgorithms;
  2. import java.awt.BorderLayout;
  3. import java.awt.Component;
  4. import java.awt.Cursor;
  5. import java.awt.Dimension;
  6. import java.awt.FlowLayout;
  7. import java.awt.Font;
  8. import java.awt.image.BufferedImage;
  9. import java.io.BufferedWriter;
  10. import java.io.File;
  11. import java.io.FileOutputStream;
  12. import java.io.IOException;
  13. import java.io.OutputStreamWriter;
  14. import java.math.RoundingMode;
  15. import java.text.NumberFormat;
  16. import java.util.ArrayList;
  17. import java.util.HashMap;
  18. import java.util.List;
  19. import java.util.Locale;
  20. import java.util.stream.Collectors;
  21. import javax.swing.BorderFactory;
  22. import javax.swing.ImageIcon;
  23. import javax.swing.JButton;
  24. import javax.swing.JCheckBox;
  25. import javax.swing.JFileChooser;
  26. import javax.swing.JFormattedTextField;
  27. import javax.swing.JFrame;
  28. import javax.swing.JLabel;
  29. import javax.swing.JOptionPane;
  30. import javax.swing.JPanel;
  31. import javax.swing.JProgressBar;
  32. import javax.swing.JScrollPane;
  33. import javax.swing.JSplitPane;
  34. import javax.swing.JTextArea;
  35. import javax.swing.filechooser.FileNameExtensionFilter;
  36. import javax.swing.text.NumberFormatter;
  37. import api.Algorithm;
  38. import classes.AbstractCpsObject;
  39. import classes.CpsUpperNode;
  40. import classes.HolonElement;
  41. import classes.HolonObject;
  42. import classes.HolonSwitch;
  43. import ui.controller.Control;
  44. import ui.model.Model;
  45. import ui.model.DecoratedHolonObject.HolonObjectState;
  46. import ui.model.DecoratedGroupNode;
  47. import ui.model.DecoratedNetwork;
  48. import ui.model.DecoratedState;
  49. public class PSOAlgotihm implements Algorithm {
  50. //Parameter for Algo with default Values:
  51. private int swarmSize = 20;
  52. private int maxIterations = 100;
  53. private double limit = 0.01;
  54. private double dependency = 2.07;
  55. private int rounds = 20;
  56. //Settings For GroupNode using and plotting
  57. private boolean append = false;
  58. private boolean useGroupNode = false;
  59. private DecoratedGroupNode dGroupNode = null;
  60. //Parameter defined by Algo
  61. private HashMap<Integer, AccessWrapper> access;
  62. private List<Boolean> initialState;
  63. private double c1, c2, w;
  64. private RunDataBase db;
  65. //Parameter for Plotting (Default Directory in Constructor)
  66. private JFileChooser fileChooser = new JFileChooser();
  67. //Gui Part:
  68. private Control control;
  69. private JTextArea textArea;
  70. private JPanel content = new JPanel();
  71. //ProgressBar
  72. private JProgressBar progressBar = new JProgressBar();
  73. private int progressBarCount = 0;
  74. private long startTime;
  75. public static void main(String[] args)
  76. {
  77. JFrame newFrame = new JFrame("exampleWindow");
  78. PSOAlgotihm instance = new PSOAlgotihm();
  79. newFrame.setContentPane(instance.getAlgorithmPanel());
  80. newFrame.pack();
  81. newFrame.setVisible(true);
  82. newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  83. }
  84. public PSOAlgotihm() {
  85. content.setLayout(new BorderLayout());
  86. textArea = new JTextArea();
  87. textArea.setEditable(false);
  88. JScrollPane scrollPane = new JScrollPane(textArea);
  89. JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
  90. createOptionPanel() , scrollPane);
  91. splitPane.setResizeWeight(0.0);
  92. content.add(splitPane, BorderLayout.CENTER);
  93. content.setPreferredSize(new Dimension(800,800));
  94. //Default Directory
  95. fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
  96. fileChooser.setSelectedFile(new File("plott.txt"));
  97. }
  98. public JPanel createOptionPanel() {
  99. JPanel optionPanel = new JPanel(new BorderLayout());
  100. JScrollPane scrollPane = new JScrollPane(createParameterPanel());
  101. scrollPane.setBorder(BorderFactory.createTitledBorder("Parameter"));
  102. optionPanel.add(scrollPane, BorderLayout.CENTER);
  103. optionPanel.add(createButtonPanel(), BorderLayout.PAGE_END);
  104. return optionPanel;
  105. }
  106. private Component createParameterPanel() {
  107. JPanel parameterPanel = new JPanel(null);
  108. parameterPanel.setPreferredSize(new Dimension(510,300));
  109. JLabel info = new JLabel("Tune the variables of the PSO algorithm in order to reach better results.");
  110. info.setBounds(10, 10, 480, 15);
  111. parameterPanel.add(info);
  112. JLabel swarmSizeLabel = new JLabel("Swarm Size:");
  113. swarmSizeLabel.setBounds(20, 60, 100, 20);
  114. parameterPanel.add(swarmSizeLabel);
  115. JLabel maxIterLabel = new JLabel("Max. Iterations:");
  116. maxIterLabel.setBounds(20, 85, 100, 20);
  117. parameterPanel.add(maxIterLabel);
  118. JLabel limitLabel = new JLabel("Limit:");
  119. limitLabel.setBounds(20, 110, 100, 20);
  120. parameterPanel.add(limitLabel);
  121. JLabel dependecyLabel = new JLabel("Dependency:");
  122. dependecyLabel.setBounds(20, 135, 100, 20);
  123. parameterPanel.add(dependecyLabel);
  124. JLabel roundsLabel = new JLabel("Round:");
  125. roundsLabel.setBounds(20, 160, 100, 20);
  126. parameterPanel.add(roundsLabel);
  127. JLabel cautionLabel = new JLabel(
  128. "Caution: High values in the fields of 'Swarm Size' and 'Max. Iteration' may take some time to calculate.");
  129. cautionLabel.setFont(new Font("Serif", Font.ITALIC, 12));
  130. JLabel showDiagnosticsLabel = new JLabel("Append Plott on existing File:");
  131. showDiagnosticsLabel.setBounds(200, 60, 170, 20);
  132. parameterPanel.add(showDiagnosticsLabel);
  133. JPanel borderPanel = new JPanel(null);
  134. borderPanel.setBounds(200, 85, 185, 50);
  135. borderPanel.setBorder(BorderFactory.createTitledBorder(""));
  136. parameterPanel.add(borderPanel);
  137. JLabel showGroupNodeLabel = new JLabel("Use Group Node:");
  138. showGroupNodeLabel.setBounds(10, 1, 170, 20);
  139. borderPanel.add(showGroupNodeLabel);
  140. JButton selectGroupNodeButton = new JButton("Select GroupNode");
  141. selectGroupNodeButton.setEnabled(false);
  142. selectGroupNodeButton.setBounds(10, 25, 165, 20);
  143. selectGroupNodeButton.addActionListener(actionEvent -> selectGroupNode());
  144. borderPanel.add(selectGroupNodeButton);
  145. JCheckBox useGroupNodeCheckBox = new JCheckBox();
  146. useGroupNodeCheckBox.setSelected(false);
  147. useGroupNodeCheckBox.setBounds(155, 1, 25, 20);
  148. useGroupNodeCheckBox.addActionListener(actionEvent -> {
  149. useGroupNode = useGroupNodeCheckBox.isSelected();
  150. selectGroupNodeButton.setEnabled(useGroupNode);
  151. });
  152. borderPanel.add(useGroupNodeCheckBox);
  153. JLabel progressLabel = new JLabel("Progress:");
  154. progressLabel.setBounds(200, 135, 170, 20);
  155. parameterPanel.add(progressLabel);
  156. progressBar.setBounds(200, 155, 185, 20);
  157. progressBar.setStringPainted(true);
  158. parameterPanel.add(progressBar);
  159. cautionLabel.setBounds(10, 210, 500, 15);
  160. parameterPanel.add(cautionLabel);
  161. JCheckBox diagnosticsCheckBox = new JCheckBox();
  162. diagnosticsCheckBox.setSelected(false);
  163. diagnosticsCheckBox.setBounds(370, 60, 25, 20);
  164. diagnosticsCheckBox.addActionListener(actionEvent -> append = diagnosticsCheckBox.isSelected());
  165. parameterPanel.add(diagnosticsCheckBox);
  166. //Integer formatter
  167. NumberFormat format = NumberFormat.getIntegerInstance();
  168. format.setGroupingUsed(false);
  169. format.setParseIntegerOnly(true);
  170. NumberFormatter integerFormatter = new NumberFormatter(format);
  171. integerFormatter.setMinimum(0);
  172. integerFormatter.setCommitsOnValidEdit(true);
  173. JFormattedTextField swarmSizeTextField = new JFormattedTextField(integerFormatter);
  174. swarmSizeTextField.setValue(swarmSize);
  175. swarmSizeTextField.setToolTipText("Only positive Integer.");
  176. swarmSizeTextField.addPropertyChangeListener(actionEvent -> swarmSize = Integer.parseInt(swarmSizeTextField.getValue().toString()));
  177. swarmSizeTextField.setBounds(125, 60, 50, 20);
  178. parameterPanel.add(swarmSizeTextField);
  179. JFormattedTextField maxIterTextField = new JFormattedTextField(integerFormatter);
  180. maxIterTextField.setValue(maxIterations);
  181. maxIterTextField.setToolTipText("Only positive Integer.");
  182. maxIterTextField.addPropertyChangeListener(propertyChange -> maxIterations = Integer.parseInt(maxIterTextField.getValue().toString()));
  183. maxIterTextField.setBounds(125, 85, 50, 20);
  184. parameterPanel.add(maxIterTextField);
  185. //Double Format:
  186. NumberFormat doubleFormat = NumberFormat.getNumberInstance(Locale.US);
  187. doubleFormat.setMinimumFractionDigits(1);
  188. doubleFormat.setMaximumFractionDigits(3);
  189. doubleFormat.setRoundingMode(RoundingMode.HALF_UP);
  190. //Limit Formatter:
  191. NumberFormatter limitFormatter = new NumberFormatter(doubleFormat);
  192. limitFormatter.setMinimum(0.0);
  193. limitFormatter.setMaximum(1.0);
  194. JFormattedTextField limitTextField = new JFormattedTextField(limitFormatter);
  195. limitTextField.setValue(limit);
  196. limitTextField.setToolTipText("Only Double in range [0.0, 1.0] with DecimalSeperator Point('.').");
  197. limitTextField.addPropertyChangeListener(propertyChange -> limit = Double.parseDouble(limitTextField.getValue().toString()));
  198. limitTextField.setBounds(125, 110, 50, 20);
  199. parameterPanel.add(limitTextField);
  200. //Limit Formatter:
  201. NumberFormatter dependencyFormatter = new NumberFormatter(doubleFormat);
  202. dependencyFormatter.setMinimum(2.001);
  203. dependencyFormatter.setMaximum(2.4);
  204. JFormattedTextField dependencyTextField = new JFormattedTextField(dependencyFormatter);
  205. dependencyTextField.setValue(dependency);
  206. dependencyTextField.setToolTipText("Only Double in range [2.001, 2.4] with DecimalSeperator Point('.').");
  207. dependencyTextField.addPropertyChangeListener(propertyChange -> dependency = Double.parseDouble(dependencyTextField.getValue().toString()));
  208. dependencyTextField.setBounds(125, 135, 50, 20);
  209. parameterPanel.add(dependencyTextField);
  210. NumberFormatter roundsFormatter = new NumberFormatter(format);
  211. roundsFormatter.setMinimum(1);
  212. roundsFormatter.setCommitsOnValidEdit(true);
  213. JFormattedTextField roundsTextField = new JFormattedTextField(roundsFormatter);
  214. roundsTextField.setValue(rounds);
  215. roundsTextField.setToolTipText("Amount of rounds to be runed with the same starting ");
  216. roundsTextField.addPropertyChangeListener(propertyChange -> rounds = Integer.parseInt((roundsTextField.getValue().toString())));
  217. roundsTextField.setBounds(125, 160, 50, 20);
  218. parameterPanel.add(roundsTextField);
  219. return parameterPanel;
  220. }
  221. public JPanel createButtonPanel() {
  222. JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
  223. JButton clearButton = new JButton("Clear Console");
  224. clearButton.addActionListener(actionEvent -> clear());
  225. buttonPanel.add(clearButton);
  226. JButton folderButton = new JButton("Change Plott-File");
  227. folderButton.addActionListener(actionEvent -> setSaveFile());
  228. buttonPanel.add(folderButton);
  229. JButton fitnessButton = new JButton("Actual Fitness");
  230. fitnessButton.addActionListener(actionEvent -> fitness());
  231. buttonPanel.add(fitnessButton);
  232. JButton plottButton = new JButton("Plott");
  233. plottButton.addActionListener(actionEvent -> plott());
  234. buttonPanel.add(plottButton);
  235. JButton resetButton = new JButton("Reset");
  236. resetButton.setToolTipText("Resets the State to before the Algorithm has runed.");
  237. resetButton.addActionListener(actionEvent -> reset());
  238. buttonPanel.add(resetButton);
  239. JButton runButton = new JButton("Run");
  240. runButton.addActionListener(actionEvent -> {
  241. Runnable task = () -> {
  242. startTimer();
  243. executePsoAlgoWithCurrentParameters();
  244. printElapsedTime();
  245. };
  246. Thread thread = new Thread(task);
  247. thread.start();
  248. });
  249. buttonPanel.add(runButton);
  250. return buttonPanel;
  251. }
  252. private void fitness() {
  253. initDependentParameter();
  254. double currentFitness = evaluatePosition(extractPositionAndAccess(control.getModel()));
  255. println("Actual Fitnessvalue: " + currentFitness);
  256. }
  257. private void setSaveFile() {
  258. fileChooser.setFileFilter(new FileNameExtensionFilter("File", "txt"));
  259. fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
  260. int result = fileChooser.showSaveDialog(content);
  261. if(result == JFileChooser.APPROVE_OPTION) {
  262. println("Set save File to:" + fileChooser.getSelectedFile().getAbsolutePath());
  263. }
  264. }
  265. private void plott() {
  266. if(db!=null) {
  267. println("Plott..");
  268. db.initFileStream();
  269. }else {
  270. println("No run inistialized.");
  271. }
  272. }
  273. private void reset() {
  274. if(initialState != null) {
  275. println("Resetting..");
  276. resetState();
  277. updateVisual();
  278. }else {
  279. println("No run inistialized.");
  280. }
  281. }
  282. private void printParameter() {
  283. println("SwarmSize:" + swarmSize + ", MaxIter:" + maxIterations + ", Limit:" + limit + ", Dependency:" + dependency + ", Rounds:" + rounds +", DependentParameter: w:"+ w + ", c1:" + c1 + ", c2:" + c2 );
  284. }
  285. @Override
  286. public JPanel getAlgorithmPanel() {
  287. return content;
  288. }
  289. @Override
  290. public void setController(Control control) {
  291. this.control = control;
  292. }
  293. private void clear() {
  294. textArea.setText("");
  295. }
  296. private void print(String message) {
  297. textArea.append(message);
  298. }
  299. private void println(String message) {
  300. textArea.append(message + "\n");
  301. }
  302. private void selectGroupNode() {
  303. Object[] possibilities = control.getSimManager().getActualVisualRepresentationalState().getCreatedGroupNodes().values().stream().map(aCps -> new Handle<DecoratedGroupNode>(aCps)).toArray();
  304. @SuppressWarnings("unchecked")
  305. 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, "");
  306. if(selected != null) {
  307. println("Selected: " + selected);
  308. dGroupNode = selected.object;
  309. }
  310. }
  311. private void progressBarStep(){
  312. progressBar.setValue(++progressBarCount);
  313. }
  314. private void calculateProgressBarParameter() {
  315. int max = swarmSize * (maxIterations + 1)* rounds + rounds;
  316. progressBarCount = 0;
  317. progressBar.setValue(0);
  318. progressBar.setMaximum(max);
  319. }
  320. private void startTimer(){
  321. startTime = System.currentTimeMillis();
  322. }
  323. private void printElapsedTime(){
  324. long elapsedMilliSeconds = System.currentTimeMillis() - startTime;
  325. println("Execution Time of Algo in Milliseconds:" + elapsedMilliSeconds);
  326. }
  327. //Algo Part:
  328. /**
  329. * The Execution of the Algo its initialize the missing parameter and execute single Algo runs successively.
  330. */
  331. private void executePsoAlgoWithCurrentParameters() {
  332. initDependentParameter();
  333. calculateProgressBarParameter();
  334. printParameter();
  335. Best runBest = new Best();
  336. runBest.value = Double.MAX_VALUE;
  337. db = new RunDataBase();
  338. for(int r = 0; r < rounds; r++)
  339. {
  340. List<Double> runList = db.insertNewRun();
  341. Best lastRunBest = executePSOoneTime(runList);
  342. resetState();
  343. if(lastRunBest.value < runBest.value) runBest = lastRunBest;
  344. }
  345. println("AlgoResult:" + runBest.value);
  346. //println("[" + lastRunBest.position.stream().map(Object::toString).collect(Collectors.joining(", ")) + "]");
  347. setState(runBest.position);
  348. updateVisual();
  349. }
  350. /**
  351. * Calculate w, c1, c2
  352. */
  353. private void initDependentParameter() {
  354. w = 1.0 / (dependency - 1 + Math.sqrt(dependency * dependency - 2 * dependency));
  355. c1 = c2 = dependency * w;
  356. }
  357. /**
  358. * <p>Algo from Paper:</p><font size="3"><pre>
  359. *
  360. * Begin
  361. * t = 0; {t: generation index}
  362. * initialize particles x<sub>p,i,j</sub>(t);
  363. * evaluation x<sub>p,i,j</sub>(t);
  364. * while (termination condition &ne; true) do
  365. * v<sub>i,j</sub>(t) = update v<sub>i,j</sub>(t); {by Eq. (6)}
  366. * x<sub>g,i,j</sub>(t) = update x<sub>g,i,j</sub>(t); {by Eq. (7)}
  367. * x<sub>g,i,j</sub>(t) = mutation x<sub>g,i,j</sub>(t); {by Eq. (11)}
  368. * x<sub>p,i,j</sub>(t) = decode x<sub>g,i,j</sub>(t); {by Eqs. (8) and (9)}
  369. * evaluate x<sub>p,i,j</sub>(t);
  370. * t = t + 1;
  371. * end while
  372. * End</pre></font>
  373. * <p>with:</p><font size="3">
  374. *
  375. * x<sub>g,i,j</sub>: genotype ->genetic information -> in continuous space<br>
  376. * x<sub>p,i,j</sub>: phenotype -> observable characteristics-> in binary space<br>
  377. * X<sub>g,max</sub>: is the Maximum here set to 4.<br>
  378. * Eq. (6):v<sub>i,j</sub>(t + 1) = wv<sub>i,j</sub>+c<sub>1</sub>R<sub>1</sub>(P<sub>best,i,j</sub>-x<sub>p,i,j</sub>(t))+c<sub>2</sub>R<sub>2</sub>(g<sub>best,i,j</sub>-x<sub>p,i,j</sub>(t))<br>
  379. * Eq. (7):x<sub>g,i,j</sub>(t + 1) = x<sub>g,i,j</sub>(t) + v<sub>i,j</sub>(t + 1)<br>
  380. * Eq. (11):<b>if(</b>rand()&lt;r<sub>mu</sub><b>)then</b> x<sub>g,i,j</sub>(t + 1) = -x<sub>g,i,j</sub>(t + 1)<br>
  381. * Eq. (8):x<sub>p,i,j</sub>(t + 1) = <b>(</b>rand() &lt; S(x<sub>g,i,j</sub>(t + 1))<b>) ?</b> 1 <b>:</b> 0<br>
  382. * Eq. (9) Sigmoid:S(x<sub>g,i,j</sub>(t + 1)) := 1/(1 + e<sup>-x<sub>g,i,j</sub>(t + 1)</sup>)<br></font>
  383. * <p>Parameter:</p>
  384. * w inertia, calculated from phi(Variable:{@link #dependency})<br>
  385. * c1: influence, calculated from phi(Variable:{@link #dependency}) <br>
  386. * c2: influence, calculated from phi(Variable:{@link #dependency})<br>
  387. * r<sub>mu</sub>: probability that the proposed operation is conducted defined by limit(Variable:{@link #limit})<br>
  388. *
  389. *
  390. */
  391. private Best executePSOoneTime(List<Double> runList) {
  392. Best globalBest = new Best();
  393. globalBest.position = extractPositionAndAccess(control.getModel());
  394. globalBest.value = evaluatePosition(globalBest.position);
  395. print("Start Value:" + globalBest.value);
  396. int dimensions = globalBest.position.size();
  397. List<Particle> swarm= initializeParticles(dimensions);
  398. runList.add(globalBest.value);
  399. evaluation(globalBest, swarm);
  400. runList.add(globalBest.value);
  401. for (int iteration = 0; iteration < maxIterations ; iteration++) {
  402. for (int particleNumber = 0; particleNumber < swarmSize; particleNumber++) {
  403. Particle particle = swarm.get(particleNumber);
  404. for(int index = 0; index < dimensions; index++) {
  405. updateVelocity(particle, index, globalBest);
  406. updateGenotype(particle, index);
  407. mutation(particle, index);
  408. decode(particle, index);
  409. }
  410. }
  411. evaluation(globalBest, swarm);
  412. runList.add(globalBest.value);
  413. }
  414. println(" End Value:" + globalBest.value);
  415. return globalBest;
  416. }
  417. /**
  418. * Eq. (6):v<sub>i,j</sub>(t + 1) = wv<sub>i,j</sub>+c<sub>1</sub>R<sub>1</sub>(P<sub>best,i,j</sub>-x<sub>p,i,j</sub>(t))+c<sub>2</sub>R<sub>2</sub>(g<sub>best,i,j</sub>-x<sub>p,i,j</sub>(t))<br>
  419. * @param particle
  420. * @param index
  421. * @param globalBest
  422. */
  423. private void updateVelocity(Particle particle, int index, Best globalBest) {
  424. double r1 = Random.nextDouble();
  425. double r2 = Random.nextDouble();
  426. double posValue = particle.xPhenotype.get(index)?1.0:0.0;
  427. particle.velocity.set(index, clamp(w*particle.velocity.get(index) + c1*r1*((particle.localBest.position.get(index)?1.0:0.0) - posValue) + c2*r2*((globalBest.position.get(index)?1.0:0.0)- posValue)) );
  428. }
  429. /**
  430. * Eq. (7):x<sub>g,i,j</sub>(t + 1) = x<sub>g,i,j</sub>(t) + v<sub>i,j</sub>(t + 1)<br>
  431. * @param particle
  432. * @param index
  433. */
  434. private void updateGenotype(Particle particle, int index) {
  435. particle.xGenotype.set(index, clamp(particle.xGenotype.get(index) + particle.velocity.get(index)));
  436. }
  437. /**
  438. * Eq. (11):<b>if(</b>rand()&lt;r<sub>mu</sub><b>)then</b> x<sub>g,i,j</sub>(t + 1) = -x<sub>g,i,j</sub>(t + 1)<br>
  439. * @param particle
  440. * @param index
  441. */
  442. private void mutation(Particle particle, int index) {
  443. if(Random.nextDouble() < limit) particle.xGenotype.set(index, -particle.xGenotype.get(index));
  444. }
  445. /**
  446. * Eq. (8):x<sub>p,i,j</sub>(t + 1) = <b>(</b>rand() &lt; S(x<sub>g,i,j</sub>(t + 1))<b>) ?</b> 1 <b>:</b> 0<br>
  447. * @param particle
  448. * @param index
  449. */
  450. private void decode(Particle particle, int index) {
  451. particle.xPhenotype.set(index, Random.nextDouble() < Sigmoid(particle.xGenotype.get(index)));
  452. }
  453. /**
  454. * Eq. (9) Sigmoid:S(x<sub>g,i,j</sub>(t + 1)) := 1/(1 + e<sup>-x<sub>g,i,j</sub>(t + 1)</sup>)<br></font>
  455. * @param value
  456. * @return
  457. */
  458. private double Sigmoid(double value) {
  459. return 1.0 / (1.0 + Math.exp(-value));
  460. }
  461. /**
  462. * To clamp X<sub>g,j,i</sub> and v<sub>i,j</sub> in Range [-X<sub>g,max</sub>|+X<sub>g,max</sub>] with {X<sub>g,max</sub>= 4}
  463. * @param value
  464. * @return
  465. */
  466. private double clamp(double value) {
  467. return Math.max(-4.0, Math.min(4.0, value));
  468. }
  469. /**
  470. *
  471. * @param j maximum index of position in the particle
  472. * @return
  473. */
  474. private List<Particle> initializeParticles(int j) {
  475. List<Particle> swarm = new ArrayList<Particle>();
  476. //Create The Particle
  477. for (int particleNumber = 0; particleNumber < swarmSize; particleNumber++){
  478. //Create a Random position
  479. List<Boolean> aRandomPosition = new ArrayList<Boolean>();
  480. for (int index = 0; index < j; index++){
  481. aRandomPosition.add(Random.nextBoolean());
  482. }
  483. swarm.add(new Particle(aRandomPosition));
  484. }
  485. return swarm;
  486. }
  487. /**
  488. * Evaluate each particle and update the global Best position;
  489. * @param globalBest
  490. * @param swarm
  491. */
  492. private void evaluation(Best globalBest, List<Particle> swarm) {
  493. for(Particle p: swarm) {
  494. double localEvaluationValue = evaluatePosition(p.xPhenotype);
  495. p.checkNewEvaluationValue(localEvaluationValue);
  496. if(localEvaluationValue < globalBest.value) {
  497. globalBest.value = localEvaluationValue;
  498. globalBest.position = p.localBest.position;
  499. }
  500. }
  501. }
  502. /**
  503. * Evaluate a position.
  504. * @param position
  505. * @return
  506. */
  507. private double evaluatePosition(List<Boolean> position) {
  508. setState(position);
  509. progressBarStep();
  510. control.calculateStateForCurrentTimeStep();
  511. DecoratedState actualstate = control.getSimManager().getActualDecorState();
  512. return getFitnessValueForState(actualstate);
  513. }
  514. /**
  515. * Calculate the Fitness(Penelty) Value for a state (alias the calculated Position).
  516. * TODO: Make me better Rolf.
  517. * @param state
  518. * @return
  519. */
  520. private double getFitnessValueForState(DecoratedState state) {
  521. double fitness = 0.0;
  522. double nw_fitness =0.0;
  523. double object_fitness = 0.0;
  524. // calculate network_fitness
  525. for(DecoratedNetwork net : state.getNetworkList()) {
  526. float production = net.getSupplierList().stream().map(supplier -> supplier.getEnergyToSupplyNetwork()).reduce(0.0f, (a, b) -> a + b);
  527. float consumption = net.getConsumerList().stream().map(con -> con.getEnergyNeededFromNetwork()).reduce(0.0f, (a, b) -> a + b);
  528. nw_fitness += Math.abs(production - consumption); //Energy is now everywhere positive
  529. }
  530. // calculate object_fitness
  531. for(DecoratedNetwork net : state.getNetworkList()) {
  532. object_fitness += net.getConsumerList().stream().map(con -> holonObjectSupplyPenaltyFunction(con.getSupplyBarPercentage()) + inactiveHolonElementPenalty(con.getModel())).reduce(0.0, (a, b) -> (a + b));
  533. //warum war das im network fitness und nicht hier im Object fitness??
  534. object_fitness += net.getConsumerList().stream().map(con -> StateToDouble(con.getState())).reduce(0.0, (a,b) -> (a+b));
  535. //System.out.println("objectfitness for statestuff: " + object_fitness);
  536. object_fitness += net.getPassivNoEnergyList().stream().map(con -> 1000.0).reduce(0.0, (a, b) -> (a + b));
  537. object_fitness += net.getSupplierList().stream().map(sup -> inactiveHolonElementPenalty(sup.getModel())).reduce(0.0, (a, b) -> (a + b));
  538. object_fitness += net.getConsumerSelfSuppliedList().stream().map(con -> inactiveHolonElementPenalty(con.getModel())).reduce(0.0, (a, b) -> (a + b));
  539. }
  540. fitness = nw_fitness + object_fitness;
  541. return fitness;
  542. }
  543. /**
  544. * Untouched:
  545. * Function that returns the fitness depending on the number of elements deactivated in a single holon object
  546. * @param obj Holon Object that contains Holon Elements
  547. * @return fitness value for that object depending on the number of deactivated holon elements
  548. */
  549. private double inactiveHolonElementPenalty(HolonObject obj) {
  550. float result = 0;
  551. int activeElements = obj.getNumberOfActiveElements();
  552. int maxElements = obj.getElements().size();
  553. //result = (float) Math.pow((maxElements -activeElements),2)*10;
  554. result = (float) Math.pow(5, 4* ( (float) maxElements - (float) activeElements)/ (float) maxElements) - 1;
  555. //System.out.println("max: " + maxElements + " active: " + activeElements + " results in penalty: " + result);
  556. return result;
  557. }
  558. /**
  559. * Untouched:
  560. * Calculates a penalty value based on the HOs current supply percentage
  561. * @param supplyPercentage
  562. * @return
  563. */
  564. private double holonObjectSupplyPenaltyFunction(float supplyPercentage) {
  565. double result = 0;
  566. /*if(supplyPercentage == 1)
  567. return result;
  568. else if(supplyPercentage < 1 && supplyPercentage >= 0.25) // undersupplied inbetween 25% and 100%
  569. result = (float) Math.pow(1/supplyPercentage, 2);
  570. else if (supplyPercentage < 0.25) //undersupplied with less than 25%
  571. result = (float) Math.pow(1/supplyPercentage,2);
  572. else if (supplyPercentage < 1.25) //Oversupplied less than 25%
  573. result = (float) Math.pow(supplyPercentage,3) ;
  574. else result = (float) Math.pow(supplyPercentage,4); //Oversupplied more than 25%
  575. if(Float.isInfinite(result) || Float.isNaN(result))
  576. result = 1000;
  577. */
  578. if(supplyPercentage <= 1.0) {
  579. result = Math.pow(5,((100 - (supplyPercentage*100))/50 + 2)) - Math.pow(5, 2);
  580. }
  581. else {
  582. result = Math.pow(6,((100 - (supplyPercentage*100))/50 + 2)) - Math.pow(6, 2);
  583. }
  584. return result;
  585. }
  586. /**
  587. * If you want to get in touch with a reliable state? Working function not in use currently.
  588. * @param state
  589. * @return
  590. */
  591. private double StateToDouble(HolonObjectState state) {
  592. switch (state) {
  593. case NOT_SUPPLIED:
  594. return 300.0;
  595. case NO_ENERGY:
  596. return 100.0;
  597. case OVER_SUPPLIED:
  598. return 200.0;
  599. case PARTIALLY_SUPPLIED:
  600. return 100.0;
  601. case PRODUCER:
  602. return 0;
  603. case SUPPLIED:
  604. return 0;
  605. default:
  606. return 0;
  607. }
  608. }
  609. /**
  610. * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
  611. * Also initialize the Access Hashmap to swap faster positions.
  612. * @param model
  613. * @return
  614. */
  615. private List<Boolean> extractPositionAndAccess(Model model) {
  616. initialState = new ArrayList<Boolean>();
  617. access= new HashMap<Integer, AccessWrapper>();
  618. rollOutNodes((useGroupNode && (dGroupNode != null))? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurIteration());
  619. return initialState;
  620. }
  621. /**
  622. * Method to extract the Informations recursively out of the Model.
  623. * @param nodes
  624. * @param positionToInit
  625. * @param timeStep
  626. */
  627. private void rollOutNodes(List<AbstractCpsObject> nodes, List<Boolean> positionToInit, int timeStep) {
  628. for(AbstractCpsObject aCps : nodes) {
  629. if (aCps instanceof HolonObject) {
  630. for (HolonElement hE : ((HolonObject) aCps).getElements()) {
  631. positionToInit.add(hE.isActive());
  632. access.put(positionToInit.size() - 1 , new AccessWrapper(hE));
  633. }
  634. }
  635. else if (aCps instanceof HolonSwitch) {
  636. HolonSwitch sw = (HolonSwitch) aCps;
  637. positionToInit.add(sw.getState(timeStep));
  638. access.put(positionToInit.size() - 1 , new AccessWrapper(sw));
  639. }
  640. else if(aCps instanceof CpsUpperNode) {
  641. rollOutNodes(((CpsUpperNode)aCps).getNodes(), positionToInit ,timeStep );
  642. }
  643. }
  644. }
  645. /**
  646. * To let the User See the current state without touching the Canvas.
  647. */
  648. private void updateVisual() {
  649. control.calculateStateForCurrentTimeStep();
  650. control.updateCanvas();
  651. }
  652. /**
  653. * Sets the Model back to its original State before the LAST run.
  654. */
  655. private void resetState() {
  656. setState(initialState);
  657. }
  658. /**
  659. * Sets the State out of the given position for calculation or to show the user.
  660. * @param position
  661. */
  662. private void setState(List<Boolean> position) {
  663. for(int i = 0;i<position.size();i++) {
  664. access.get(i).setState(position.get(i));
  665. }
  666. }
  667. /**
  668. * A Database for all Global Best(G<sub>Best</sub>) Values in a execution of a the Algo. For Easy Printing.
  669. */
  670. private class RunDataBase {
  671. List<List<Double>> allRuns;
  672. RunDataBase(){
  673. allRuns = new ArrayList<List<Double>>();
  674. }
  675. /**
  676. * Initialize The Stream before you can write to a File.
  677. */
  678. public void initFileStream() {
  679. File file = fileChooser.getSelectedFile();
  680. try {
  681. file.createNewFile();
  682. BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
  683. new FileOutputStream(file, append), "UTF-8"));
  684. printToStream(out);
  685. out.close();
  686. } catch (IOException e) {
  687. println(e.getMessage());
  688. }
  689. }
  690. /**
  691. *
  692. * TODO: Rolf Change this method to suit your Python script respectively.
  693. * A run have maxIterations + 2 values. As described: First is the InitialState Value,
  694. * Second is The best Value after the swarm is Initialized not have moved jet, and then comes the Iterations that described
  695. * each step of movement from the swarm.
  696. */
  697. public void printToStream(BufferedWriter out) throws IOException {
  698. try {
  699. out.write(maxIterations + 2 + "," + allRuns.size() + "," + swarmSize);
  700. out.newLine();
  701. }
  702. catch(IOException e) {
  703. println(e.getMessage());
  704. }
  705. allRuns.forEach(run -> {
  706. try {
  707. out.write( run.stream().map(Object::toString).collect(Collectors.joining(", ")));
  708. out.newLine();
  709. } catch (IOException e) {
  710. println(e.getMessage());
  711. }
  712. } );
  713. /* out.write("AverageRun:");
  714. out.newLine();
  715. out.write(calculateAverageRun().stream().map(Object::toString).collect(Collectors.joining(", ")));
  716. out.newLine();
  717. */
  718. }
  719. private List<Double> calculateAverageRun(){
  720. int amountOfRuns = allRuns.size();
  721. List<Double> newAverageRun = new ArrayList<Double>();
  722. for(int iteration = 0; iteration < maxIterations + 2; iteration++) {
  723. final int currentIter = iteration;
  724. double sum = 0.0;
  725. sum = allRuns.stream().map(run -> run.get(currentIter)).reduce(0.0, (a, b) -> a + b);
  726. newAverageRun.add(sum / amountOfRuns);
  727. }
  728. return newAverageRun;
  729. }
  730. public List<Double> insertNewRun(){
  731. List<Double> newRun = new ArrayList<Double>();
  732. allRuns.add(newRun);
  733. return newRun;
  734. }
  735. }
  736. /**
  737. * To give the Local Best of a Partice(P<sub>Best</sub>) or the Global Best(G<sub>Best</sub>) a Wrapper to have Position And Evaluation Value in one Place.
  738. */
  739. private class Best{
  740. public double value;
  741. public List<Boolean> position;
  742. public Best(){
  743. }
  744. }
  745. /**
  746. * A Wrapper Class for Access HolonElement and HolonSwitch in one Element and not have to split the List.
  747. */
  748. private class AccessWrapper {
  749. public static final int HOLONELEMENT = 0;
  750. public static final int SWITCH = 1;
  751. private int type;
  752. private HolonSwitch hSwitch;
  753. private HolonElement hElement;
  754. public AccessWrapper(HolonSwitch hSwitch){
  755. type = SWITCH;
  756. this.hSwitch = hSwitch;
  757. }
  758. public AccessWrapper(HolonElement hElement){
  759. type = HOLONELEMENT;
  760. this.hElement = hElement;
  761. }
  762. public void setState(boolean state) {
  763. if(type == HOLONELEMENT) {
  764. hElement.setActive(state);
  765. }else{//is switch
  766. hSwitch.setManualMode(true);
  767. hSwitch.setManualState(state);
  768. }
  769. }
  770. public boolean getState(int timeStep) {
  771. return (type == HOLONELEMENT)?hElement.isActive():hSwitch.getState(timeStep);
  772. }
  773. }
  774. /**
  775. * Class to represent a Particle.
  776. */
  777. private class Particle{
  778. /**
  779. * The velocity of a particle.
  780. */
  781. public List<Double> velocity;
  782. /**
  783. * The positions genotype.
  784. */
  785. public List<Double> xGenotype;
  786. /**
  787. * The positions phenotype. Alias the current position.
  788. */
  789. public List<Boolean> xPhenotype;
  790. public Best localBest;
  791. Particle(List<Boolean> position){
  792. this.xPhenotype = position;
  793. //Init velocity, xGenotype with 0.0 values.
  794. this.velocity = position.stream().map(bool -> 0.0).collect(Collectors.toList());
  795. this.xGenotype = position.stream().map(bool -> 0.0).collect(Collectors.toList());
  796. localBest = new Best();
  797. localBest.value = Double.MAX_VALUE;
  798. }
  799. public void checkNewEvaluationValue(double newEvaluationValue) {
  800. if(newEvaluationValue < localBest.value) {
  801. localBest.value = newEvaluationValue;
  802. localBest.position = xPhenotype.stream().map(bool -> bool).collect(Collectors.toList());
  803. }
  804. }
  805. public String toString() {
  806. return "Particle with xPhenotype(Position), xGenotype, velocity:["
  807. + listToString(xPhenotype) + "],[" + listToString(xGenotype) + "],["
  808. + listToString(velocity) + "]";
  809. }
  810. private <Type> String listToString(List<Type> list) {
  811. return list.stream().map(Object::toString).collect(Collectors.joining(", "));
  812. }
  813. }
  814. /**
  815. * To create Random and maybe switch the random generation in the future.
  816. */
  817. private static class Random{
  818. /**
  819. * True or false
  820. * @return the random boolean.
  821. */
  822. public static boolean nextBoolean(){
  823. return (Math.random() < 0.5);
  824. }
  825. /**
  826. * Between 0.0 and 1.0
  827. * @return the random double.
  828. */
  829. public static double nextDouble(){
  830. return Math.random();
  831. }
  832. }
  833. private class Handle<T>{
  834. public T object;
  835. Handle(T object){
  836. this.object = object;
  837. }
  838. public String toString() {
  839. return object.toString();
  840. }
  841. }
  842. }