PSO.java 13 KB

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