PSOAlgotihm.java 28 KB

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