PSOAlgotihm.java 31 KB

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