PSOAlgotihm.java 32 KB

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