PSOAlgotihm.java 33 KB

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