PSO.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. package psoAlgoCode;
  2. import java.awt.BorderLayout;
  3. import java.awt.Color;
  4. import java.awt.FlowLayout;
  5. import java.awt.Font;
  6. import java.awt.event.ActionEvent;
  7. import java.awt.event.ActionListener;
  8. import java.awt.event.KeyEvent;
  9. import java.awt.event.KeyListener;
  10. import java.io.File;
  11. import java.io.FileOutputStream;
  12. import java.io.FileWriter;
  13. import java.io.IOException;
  14. import java.io.PrintWriter;
  15. import java.util.ArrayList;
  16. import java.util.Vector;
  17. import javax.swing.JButton;
  18. import javax.swing.JCheckBox;
  19. import javax.swing.JDialog;
  20. import javax.swing.JLabel;
  21. import javax.swing.JPanel;
  22. import javax.swing.JTextField;
  23. import javax.swing.border.EmptyBorder;
  24. import api.CpsAlgorithm;
  25. import classes.AbstractCpsObject;
  26. import classes.CpsUpperNode;
  27. import classes.HolonElement;
  28. import classes.HolonObject;
  29. import classes.HolonSwitch;
  30. import ui.controller.Control;
  31. import ui.model.Model;
  32. public class PSO implements CpsAlgorithm {
  33. static Coordinate<Vector<Object>> startPos;
  34. static SimplePSO pso;
  35. @Override
  36. public void runAlgorithm(Model model, Control controller) {
  37. startPos = extractInfo(model, controller);
  38. pso = new SimplePSO(model, controller, startPos);
  39. callPopUp(model, controller);
  40. }
  41. /**
  42. * Returns a binary representation of the current state of the network based on the state of the switches and holon elements
  43. * @param model the overall model of the network
  44. * @param controller the general controller
  45. * @return Coordinate<Vector<Object>> where the first coordinate contains all switches states and the second coordinate all states of holon elements
  46. */
  47. public static Coordinate<Vector<Object>> extractInfo(Model model, Control controller) {
  48. Coordinate<Vector<Object>> information = new Coordinate<Vector<Object>>();
  49. // First only for Switches configuration
  50. Vector<Object> temp = new Vector<Object>();
  51. for (int i = 0; i < model.getSwitches().size(); i++) {
  52. temp.add(model.getSwitches().get(i).getState());
  53. }
  54. information.setCoord(temp, 0);
  55. temp = new Vector<Object>();
  56. ArrayList<AbstractCpsObject> canvas_objects = model.getObjectsOnCanvas();
  57. for (int i = 0; i < canvas_objects.size(); i++) {
  58. if (canvas_objects.get(i) instanceof HolonObject) {
  59. HolonObject obj = ((HolonObject) canvas_objects.get(i));
  60. ArrayList<HolonElement> obj_elements = obj.getElements();
  61. for (int j = 0; j < obj_elements.size(); j++) {
  62. temp.add(obj_elements.get(j).isActive());
  63. }
  64. }
  65. else {
  66. if(canvas_objects.get(i) instanceof CpsUpperNode) {
  67. CpsUpperNode tmp = (CpsUpperNode) canvas_objects.get(i);
  68. ArrayList<AbstractCpsObject> upperNodecontent = tmp.getNodes();
  69. for( int j = 0; j < upperNodecontent.size(); j++) {
  70. //Does not work for recursiveness of more than two levels!!!!
  71. if (upperNodecontent.get(j) instanceof HolonObject) {
  72. HolonObject obj = ((HolonObject) upperNodecontent.get(j));
  73. for (int k = 0; k < obj.getElements().size(); k++) {
  74. temp.add(obj.getElements().get(k).isActive());
  75. }
  76. }
  77. }
  78. }
  79. }
  80. }
  81. information.setCoord(temp, 1);
  82. System.out.println("Information received: " + information.toString());
  83. return information;
  84. }
  85. /**
  86. * Applies the best configuration of the run on the model to make it visible on the canvas
  87. * @param bestConfig
  88. * @param model
  89. * @param controller
  90. */
  91. public static void applyBestConfig(Coordinate<Vector<Object>> bestConfig, Model model, Control controller) {
  92. System.out.println("Applying configuration: " + bestConfig.toString());
  93. System.out.println("Config size: " + bestConfig.getCoord(1).size());
  94. Vector<Object> switchstates = bestConfig.getCoord(0);
  95. Vector<Object> elementstates = bestConfig.getCoord(1);
  96. for (int i = 0; i < model.getSwitches().size(); i++) {
  97. model.getSwitches().get(i).setManualMode(true);
  98. model.getSwitches().get(i).setManualState((boolean) switchstates.get(i));
  99. }
  100. int position = 0;
  101. for (int j = 0; j < model.getObjectsOnCanvas().size(); j++) {
  102. if (model.getObjectsOnCanvas().get(j) instanceof HolonObject) {
  103. for (int h = 0; h < ((HolonObject) model.getObjectsOnCanvas().get(j)).getElements().size(); h++) {
  104. ((HolonObject) model.getObjectsOnCanvas().get(j)).getElements().get(h)
  105. .setActive((boolean) elementstates.get(position));
  106. position++;
  107. }
  108. }
  109. else {
  110. //Does not work for more than two recursive levels... seperate function recommended
  111. if(model.getObjectsOnCanvas().get(j) instanceof CpsUpperNode) {
  112. CpsUpperNode tmp = (CpsUpperNode) model.getObjectsOnCanvas().get(j);
  113. for( int k = 0; k < tmp.getNodes().size(); k++) {
  114. if (tmp.getNodes().get(k) instanceof HolonObject) {
  115. HolonObject obj = ((HolonObject) tmp.getNodes().get(k));
  116. for (int l = 0; l < obj.getElements().size(); l++) {
  117. obj.getElements().get(l).setActive((boolean) elementstates.get(position));
  118. position++;
  119. }
  120. }
  121. }
  122. }
  123. }
  124. }
  125. controller.calculateStateForCurrentTimeStep();
  126. }
  127. /*
  128. * Write stuff to file. Needs to get completely restructured.
  129. */
  130. public static void printChart(SimplePSO pso, PrintWriter out) {
  131. int rounds = Constants.ROUNDS;
  132. Vector<Double> record = null;
  133. String name = "";
  134. // while (rounds <= Constants.ROUNDS) {
  135. //name = pso.getNameOfFunc();
  136. record = pso.getGBRecord();
  137. out.println(record.toString());
  138. //System.out.println("Global best of the round " + rounds + " is " + record.lastElement());
  139. //chart.createDataSet(record, rounds);
  140. out.flush();
  141. //rounds++;
  142. //}
  143. out.close();
  144. //chart.setTitle("Simple PSO - " + name);
  145. //chart.plotStuff("Iterations: " + Constants.MAX_ITERATION);
  146. //chart.setVisible(true);
  147. }
  148. /**
  149. * Unnecessary popup that is currently used to control the PSO runs, but should be replaced in the future
  150. * @param model
  151. * @param controller
  152. */
  153. public static void callPopUp(Model model, Control controller) {
  154. System.out.println("Repeat");
  155. // Declaration
  156. JDialog popUp = new JDialog();
  157. JPanel panel = new JPanel();
  158. JPanel buttonPanel = new JPanel();
  159. // Setup
  160. popUp.setTitle("Particle Swarm Optimization (PSO)");
  161. popUp.setBounds(100, 100, 500, 300);
  162. popUp.setModal(true);
  163. popUp.getContentPane().setLayout(new BorderLayout());
  164. panel.setBorder(new EmptyBorder(5, 5, 5, 5));
  165. popUp.getContentPane().add(panel, BorderLayout.CENTER);
  166. panel.setLayout(null);
  167. buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
  168. popUp.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
  169. // Names and Labels
  170. JLabel title1 = new JLabel("Tune the variables of the PSO algorithm in order to reach better results.");
  171. title1.setBounds(10, 10, 480, 15);
  172. JLabel swarmSizeText = new JLabel("Swarm Size:");
  173. swarmSizeText.setBounds(20, 60, 100, 20);
  174. JLabel maxItText = new JLabel("Max. Iterations:");
  175. maxItText.setBounds(20, 85, 100, 20);
  176. JLabel rmuText = new JLabel("Limit:");
  177. rmuText.setBounds(20, 110, 100, 20);
  178. JLabel phiText = new JLabel("Dependency:");
  179. phiText.setBounds(20, 135, 100, 20);
  180. final JLabel iteration = new JLabel();
  181. iteration.setBounds(20, 185, 110, 20);
  182. JLabel counterIt = new JLabel("Repetitions:");
  183. counterIt.setBounds(20, 155, 110, 20);
  184. JLabel infoGraph = new JLabel("Show Diagnostic:");
  185. infoGraph.setBounds(200, 60, 110, 20);
  186. JLabel infoText1 = new JLabel(
  187. "Caution: High values in the fields of 'Swarm Size' and 'Max. Iteration' may take some time to calculate.");
  188. infoText1.setFont(new Font("Serif", Font.ITALIC, 10));
  189. infoText1.setBounds(10, 210, 480, 15);
  190. // Input boxes
  191. JTextField swarmSizeIn = new JTextField();
  192. swarmSizeIn.setText("" + Constants.SWARM_SIZE);
  193. swarmSizeIn.addKeyListener(new KeyListener() {
  194. @Override
  195. public void keyPressed(KeyEvent arg0) {
  196. }
  197. @Override
  198. public void keyReleased(KeyEvent e) {
  199. }
  200. @Override
  201. public void keyTyped(KeyEvent e) {
  202. swarmSizeIn.setBackground(Color.WHITE);
  203. }
  204. });
  205. swarmSizeIn.setBounds(125, 60, 50, 20);
  206. swarmSizeIn.setColumns(10);
  207. JTextField maxItIn = new JTextField();
  208. maxItIn.setText("" + Constants.MAX_ITERATION);
  209. maxItIn.addKeyListener(new KeyListener() {
  210. @Override
  211. public void keyPressed(KeyEvent arg0) {
  212. }
  213. @Override
  214. public void keyReleased(KeyEvent e) {
  215. }
  216. @Override
  217. public void keyTyped(KeyEvent e) {
  218. maxItIn.setBackground(Color.WHITE);
  219. }
  220. });
  221. maxItIn.setBounds(125, 85, 50, 20);
  222. maxItIn.setColumns(10);
  223. JTextField rmuIn = new JTextField();
  224. rmuIn.setText("" + Constants.RMU);
  225. rmuIn.addKeyListener(new KeyListener() {
  226. @Override
  227. public void keyPressed(KeyEvent arg0) {
  228. }
  229. @Override
  230. public void keyReleased(KeyEvent e) {
  231. }
  232. @Override
  233. public void keyTyped(KeyEvent e) {
  234. rmuIn.setBackground(Color.WHITE);
  235. }
  236. });
  237. rmuIn.setBounds(125, 110, 50, 20);
  238. rmuIn.setColumns(10);
  239. JTextField phiIn = new JTextField();
  240. phiIn.setText("" + Constants.PHI);
  241. phiIn.addKeyListener(new KeyListener() {
  242. @Override
  243. public void keyPressed(KeyEvent arg0) {
  244. }
  245. @Override
  246. public void keyReleased(KeyEvent e) {
  247. }
  248. @Override
  249. public void keyTyped(KeyEvent e) {
  250. phiIn.setBackground(Color.WHITE);
  251. }
  252. });
  253. phiIn.setBounds(125, 135, 50, 20);
  254. phiIn.setColumns(10);
  255. JTextField runs = new JTextField();
  256. runs.setText("");
  257. runs.addKeyListener(new KeyListener() {
  258. @Override
  259. public void keyPressed(KeyEvent arg0) {
  260. }
  261. @Override
  262. public void keyReleased(KeyEvent e) {
  263. }
  264. @Override
  265. public void keyTyped(KeyEvent e) {
  266. phiIn.setBackground(Color.WHITE);
  267. }
  268. });
  269. runs.setBounds(125, 155, 50, 20);
  270. runs.setColumns(10);
  271. // Buttons
  272. JButton run = new JButton("Run");
  273. run.setActionCommand("Run");
  274. JButton nextIt = new JButton("Reset");
  275. nextIt.setActionCommand("Next It.");
  276. JCheckBox graph = new JCheckBox();
  277. graph.setSelected(true);
  278. graph.setBounds(320, 60, 25, 20);
  279. // Buttons action
  280. run.addActionListener(new ActionListener() {
  281. @Override
  282. public void actionPerformed(ActionEvent e) {
  283. Constants.setSwarmSize(Integer.parseInt(swarmSizeIn.getText()));
  284. Constants.setMaxIt(Integer.parseInt(maxItIn.getText()));
  285. Constants.setRMU(Double.parseDouble(rmuIn.getText()));
  286. Constants.setPhi(Double.parseDouble(phiIn.getText()));
  287. int nr_runs = Integer.parseInt(runs.getText());
  288. double overallRecord= Float.MAX_VALUE;
  289. Coordinate<Vector<Object>> currentBestConfig = startPos;
  290. File f = new File("gb_singlerun.txt");
  291. PrintWriter out = null;
  292. try {
  293. if(f.exists() && !f.isDirectory()) {
  294. out = new PrintWriter(new FileOutputStream(new File("gb_singlerun.txt"),true));
  295. }else out = new PrintWriter("gb_singlerun.txt");
  296. //printChart(pso, out);
  297. out.println(""+ Constants.MAX_ITERATION +"," + nr_runs +"," + Constants.SWARM_SIZE);
  298. out.close();
  299. } catch (IOException e1) {
  300. // TODO Auto-generated catch block
  301. e1.printStackTrace();
  302. }
  303. for(int i =0; i<nr_runs; i++) {
  304. //applyBestConfig(startPos, model, controller);
  305. System.out.println("Startpos size:" + startPos.getCoord(1).size() + " in " + i + " : " + startPos.toString() );
  306. pso = new SimplePSO(model, controller, startPos);
  307. long startTime = System.currentTimeMillis();
  308. pso.caclSimplePSO(model, controller, startPos);
  309. long endTime = System.currentTimeMillis();
  310. System.out.println("Computation time is: " + (endTime - startTime));
  311. //HelpFunctions.runRepairConnections(model);
  312. controller.addTextToConsole("Global best is " + pso.getGBRecord().get(Constants.MAX_ITERATION - 1));
  313. //applyBestConfig(pso.getBestConfig(), model, controller);
  314. if(pso.getGBRecord().get(Constants.MAX_ITERATION-1) < overallRecord) {
  315. overallRecord = pso.getGBRecord().get(Constants.MAX_ITERATION-1);
  316. currentBestConfig = pso.getBestConfig();
  317. }
  318. try {
  319. if(f.exists() && !f.isDirectory()) {
  320. out = new PrintWriter(new FileOutputStream(new File("gb_singlerun.txt"),true));
  321. }else out = new PrintWriter("gb_singlerun.txt");
  322. //printChart(pso, out);
  323. out.close();
  324. } catch (IOException e1) {
  325. // TODO Auto-generated catch block
  326. e1.printStackTrace();
  327. }
  328. //if (graph.isSelected()) {
  329. applyBestConfig(startPos, model, controller);
  330. }
  331. applyBestConfig(currentBestConfig, model, controller);
  332. controller.addTextToConsole(
  333. "Best of all is " + overallRecord);
  334. //popUp.dispose();
  335. }
  336. });
  337. nextIt.addActionListener(new ActionListener() {
  338. @Override
  339. public void actionPerformed(ActionEvent e) {
  340. applyBestConfig(startPos, model, controller);
  341. /* iteration.setText("Current Iteration:");
  342. Constants.setSwarmSize(Integer.parseInt(swarmSizeIn.getText()));
  343. Constants.setMaxIt(Integer.parseInt(maxItIn.getText()));
  344. Constants.setRMU(Double.parseDouble(rmuIn.getText()));
  345. Constants.setPhi(Double.parseDouble(phiIn.getText()));
  346. PrintWriter out;
  347. pso.caclNextItSimplePSO(model, controller, startPos);
  348. counterIt.setText("" + pso.getIteration());
  349. HelpFunctions.runRepairConnections(model);
  350. controller.addTextToConsole(
  351. "Best of this " + pso.getIteration() + " is " + pso.getGBRecord().get(pso.getIteration() - 1));
  352. applyBestConfig(pso.getBestConfig(), model, controller);
  353. //PrintWriter out;
  354. try {
  355. out = new PrintWriter(new FileWriter("gb_singlerun.txt"));
  356. printChart(pso, out);
  357. } catch (IOException e1) {
  358. // TODO Auto-generated catch block
  359. e1.printStackTrace();
  360. }
  361. popUp.dispose();*/
  362. }
  363. });
  364. // Add to the panel
  365. panel.add(title1);
  366. panel.add(swarmSizeText);
  367. panel.add(maxItText);
  368. panel.add(rmuText);
  369. panel.add(phiText);
  370. buttonPanel.add(run);
  371. buttonPanel.add(nextIt);
  372. panel.add(swarmSizeIn);
  373. panel.add(maxItIn);
  374. panel.add(infoText1);
  375. panel.add(iteration);
  376. panel.add(counterIt);
  377. panel.add(infoGraph);
  378. panel.add(graph);
  379. panel.add(phiIn);
  380. panel.add(rmuIn);
  381. panel.add(runs);
  382. popUp.setVisible(true);
  383. }
  384. }