PSOAlgotihm.java 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  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.addActionListener(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.getPassivNoEnergyList().stream().map(con -> 1000.0).reduce(0.0, (a, b) -> (a + b));
  535. object_fitness += net.getSupplierList().stream().map(sup -> inactiveHolonElementPenalty(sup.getModel())).reduce(0.0, (a, b) -> (a + b));
  536. object_fitness += net.getConsumerSelfSuppliedList().stream().map(con -> inactiveHolonElementPenalty(con.getModel())).reduce(0.0, (a, b) -> (a + b));
  537. }
  538. fitness = nw_fitness + object_fitness;
  539. return fitness;
  540. }
  541. /**
  542. * Untouched:
  543. * Function that returns the fitness depending on the number of elements deactivated in a single holon object
  544. * @param obj Holon Object that contains Holon Elements
  545. * @return fitness value for that object depending on the number of deactivated holon elements
  546. */
  547. private double inactiveHolonElementPenalty(HolonObject obj) {
  548. float result = 0;
  549. int activeElements = obj.getNumberOfActiveElements();
  550. int maxElements = obj.getElements().size();
  551. if(activeElements == maxElements)
  552. result =0;
  553. else result = (float) Math.pow((maxElements -activeElements),2)*100;
  554. return result;
  555. }
  556. /**
  557. * Untouched:
  558. * Calculates a penalty value based on the HOs current supply percentage
  559. * @param supplyPercentage
  560. * @return
  561. */
  562. private double holonObjectSupplyPenaltyFunction(float supplyPercentage) {
  563. float result = 0;
  564. if(supplyPercentage == 1)
  565. return result;
  566. else if(supplyPercentage < 1 && supplyPercentage >= 0.25) // undersupplied inbetween 25% and 100%
  567. result = (float) Math.pow(1/supplyPercentage, 2);
  568. else if (supplyPercentage < 0.25) //undersupplied with less than 25%
  569. result = (float) Math.pow(1/supplyPercentage,2);
  570. else if (supplyPercentage < 1.25) //Oversupplied less than 25%
  571. result = (float) Math.pow(supplyPercentage,3) ;
  572. else result = (float) Math.pow(supplyPercentage,4); //Oversupplied more than 25%
  573. if(Float.isInfinite(result) || Float.isNaN(result))
  574. result = 1000;
  575. return result;
  576. }
  577. /**
  578. * If you want to get in touch with a reliable state? Working function not in use currently.
  579. * @param state
  580. * @return
  581. */
  582. private double StateToDouble(HolonObjectState state) {
  583. switch (state) {
  584. case NOT_SUPPLIED:
  585. return 10.0;
  586. case NO_ENERGY:
  587. return 15.0;
  588. case OVER_SUPPLIED:
  589. return 5.0;
  590. case PARTIALLY_SUPPLIED:
  591. return 3.0;
  592. case PRODUCER:
  593. return 2.0;
  594. case SUPPLIED:
  595. return 0;
  596. default:
  597. return 0;
  598. }
  599. }
  600. /**
  601. * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
  602. * Also initialize the Access Hashmap to swap faster positions.
  603. * @param model
  604. * @return
  605. */
  606. private List<Boolean> extractPositionAndAccess(Model model) {
  607. initialState = new ArrayList<Boolean>();
  608. access= new HashMap<Integer, AccessWrapper>();
  609. rollOutNodes((useGroupNode && (dGroupNode != null))? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurIteration());
  610. return initialState;
  611. }
  612. /**
  613. * Method to extract the Informations recursively out of the Model.
  614. * @param nodes
  615. * @param positionToInit
  616. * @param timeStep
  617. */
  618. private void rollOutNodes(List<AbstractCpsObject> nodes, List<Boolean> positionToInit, int timeStep) {
  619. for(AbstractCpsObject aCps : nodes) {
  620. if (aCps instanceof HolonObject) {
  621. for (HolonElement hE : ((HolonObject) aCps).getElements()) {
  622. positionToInit.add(hE.isActive());
  623. access.put(positionToInit.size() - 1 , new AccessWrapper(hE));
  624. }
  625. }
  626. else if (aCps instanceof HolonSwitch) {
  627. HolonSwitch sw = (HolonSwitch) aCps;
  628. positionToInit.add(sw.getState(timeStep));
  629. access.put(positionToInit.size() - 1 , new AccessWrapper(sw));
  630. }
  631. else if(aCps instanceof CpsUpperNode) {
  632. rollOutNodes(((CpsUpperNode)aCps).getNodes(), positionToInit ,timeStep );
  633. }
  634. }
  635. }
  636. /**
  637. * To let the User See the current state without touching the Canvas.
  638. */
  639. private void updateVisual() {
  640. control.calculateStateForCurrentTimeStep();
  641. control.updateCanvas();
  642. }
  643. /**
  644. * Sets the Model back to its original State before the LAST run.
  645. */
  646. private void resetState() {
  647. setState(initialState);
  648. }
  649. /**
  650. * Sets the State out of the given position for calculation or to show the user.
  651. * @param position
  652. */
  653. private void setState(List<Boolean> position) {
  654. for(int i = 0;i<position.size();i++) {
  655. access.get(i).setState(position.get(i));
  656. }
  657. }
  658. /**
  659. * A Database for all Global Best(G<sub>Best</sub>) Values in a execution of a the Algo. For Easy Printing.
  660. */
  661. private class RunDataBase {
  662. List<List<Double>> allRuns;
  663. RunDataBase(){
  664. allRuns = new ArrayList<List<Double>>();
  665. }
  666. /**
  667. * Initialize The Stream before you can write to a File.
  668. */
  669. public void initFileStream() {
  670. File file = fileChooser.getSelectedFile();
  671. try {
  672. file.createNewFile();
  673. BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
  674. new FileOutputStream(file, append), "UTF-8"));
  675. printToStream(out);
  676. out.close();
  677. } catch (IOException e) {
  678. println(e.getMessage());
  679. }
  680. }
  681. /**
  682. *
  683. * TODO: Rolf Change this method to suit your Python script respectively.
  684. * A run have maxIterations + 2 values. As described: First is the InitialState Value,
  685. * Second is The best Value after the swarm is Initialized not have moved jet, and then comes the Iterations that described
  686. * each step of movement from the swarm.
  687. */
  688. public void printToStream(BufferedWriter out) throws IOException {
  689. allRuns.forEach(run -> {
  690. try {
  691. out.write( run.stream().map(Object::toString).collect(Collectors.joining(", ")));
  692. out.newLine();
  693. } catch (IOException e) {
  694. println(e.getMessage());
  695. }
  696. } );
  697. out.write("AverageRun:");
  698. out.newLine();
  699. out.write(calculateAverageRun().stream().map(Object::toString).collect(Collectors.joining(", ")));
  700. out.newLine();
  701. }
  702. private List<Double> calculateAverageRun(){
  703. int amountOfRuns = allRuns.size();
  704. List<Double> newAverageRun = new ArrayList<Double>();
  705. for(int iteration = 0; iteration < maxIterations + 2; iteration++) {
  706. final int currentIter = iteration;
  707. double sum = 0.0;
  708. sum = allRuns.stream().map(run -> run.get(currentIter)).reduce(0.0, (a, b) -> a + b);
  709. newAverageRun.add(sum / amountOfRuns);
  710. }
  711. return newAverageRun;
  712. }
  713. public List<Double> insertNewRun(){
  714. List<Double> newRun = new ArrayList<Double>();
  715. allRuns.add(newRun);
  716. return newRun;
  717. }
  718. }
  719. /**
  720. * 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.
  721. */
  722. private class Best{
  723. public double value;
  724. public List<Boolean> position;
  725. public Best(){
  726. }
  727. }
  728. /**
  729. * A Wrapper Class for Access HolonElement and HolonSwitch in one Element and not have to split the List.
  730. */
  731. private class AccessWrapper {
  732. public static final int HOLONELEMENT = 0;
  733. public static final int SWITCH = 1;
  734. private int type;
  735. private HolonSwitch hSwitch;
  736. private HolonElement hElement;
  737. public AccessWrapper(HolonSwitch hSwitch){
  738. type = SWITCH;
  739. this.hSwitch = hSwitch;
  740. }
  741. public AccessWrapper(HolonElement hElement){
  742. type = HOLONELEMENT;
  743. this.hElement = hElement;
  744. }
  745. public void setState(boolean state) {
  746. if(type == HOLONELEMENT) {
  747. hElement.setActive(state);
  748. }else{//is switch
  749. hSwitch.setManualMode(true);
  750. hSwitch.setManualState(state);
  751. }
  752. }
  753. public boolean getState(int timeStep) {
  754. return (type == HOLONELEMENT)?hElement.isActive():hSwitch.getState(timeStep);
  755. }
  756. }
  757. /**
  758. * Class to represent a Particle.
  759. */
  760. private class Particle{
  761. /**
  762. * The velocity of a particle.
  763. */
  764. public List<Double> velocity;
  765. /**
  766. * The positions genotype.
  767. */
  768. public List<Double> xGenotype;
  769. /**
  770. * The positions phenotype. Alias the current position.
  771. */
  772. public List<Boolean> xPhenotype;
  773. public Best localBest;
  774. Particle(List<Boolean> position){
  775. this.xPhenotype = position;
  776. //Init velocity, xGenotype with 0.0 values.
  777. this.velocity = position.stream().map(bool -> 0.0).collect(Collectors.toList());
  778. this.xGenotype = position.stream().map(bool -> 0.0).collect(Collectors.toList());
  779. localBest = new Best();
  780. localBest.value = Double.MAX_VALUE;
  781. }
  782. public void checkNewEvaluationValue(double newEvaluationValue) {
  783. if(newEvaluationValue < localBest.value) {
  784. localBest.value = newEvaluationValue;
  785. localBest.position = xPhenotype.stream().map(bool -> bool).collect(Collectors.toList());
  786. }
  787. }
  788. public String toString() {
  789. return "Particle with xPhenotype(Position), xGenotype, velocity:["
  790. + listToString(xPhenotype) + "],[" + listToString(xGenotype) + "],["
  791. + listToString(velocity) + "]";
  792. }
  793. private <Type> String listToString(List<Type> list) {
  794. return list.stream().map(Object::toString).collect(Collectors.joining(", "));
  795. }
  796. }
  797. /**
  798. * To create Random and maybe switch the random generation in the future.
  799. */
  800. private static class Random{
  801. /**
  802. * True or false
  803. * @return the random boolean.
  804. */
  805. public static boolean nextBoolean(){
  806. return (Math.random() < 0.5);
  807. }
  808. /**
  809. * Between 0.0 and 1.0
  810. * @return the random double.
  811. */
  812. public static double nextDouble(){
  813. return Math.random();
  814. }
  815. }
  816. private class Handle<T>{
  817. public T object;
  818. Handle(T object){
  819. this.object = object;
  820. }
  821. public String toString() {
  822. return object.toString();
  823. }
  824. }
  825. }