PSOAlgotihm.java 33 KB

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