PsoAlgorithm2.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. package exampleAlgorithms;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.util.TreeSet;
  5. import java.util.stream.Collectors;
  6. import javax.swing.JFrame;
  7. import api.AlgorithmFramework;
  8. import api.AlgorithmFrameworkFlex;
  9. import ui.model.DecoratedState;
  10. public class PsoAlgorithm2 extends AlgorithmFrameworkFlex{
  11. //Parameter for Algo with default Values:
  12. private int swarmSize = 20;
  13. private int maxIterations = 100;
  14. private double limit = 0.01;
  15. private double dependency = 2.07;
  16. private int mutationInterval = 1;
  17. private boolean useIntervalMutation = true;
  18. private double mutateProbabilityInterval = 0.01;
  19. private double maxMutationPercent = 0.01;
  20. private double c1, c2, w;
  21. public static void main(String[] args)
  22. {
  23. JFrame newFrame = new JFrame("exampleWindow");
  24. PsoAlgorithm2 instance = new PsoAlgorithm2();
  25. newFrame.setContentPane(instance.getPanel());
  26. newFrame.pack();
  27. newFrame.setVisible(true);
  28. newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  29. }
  30. public PsoAlgorithm2() {
  31. super();
  32. addIntParameter("swarmSize", swarmSize, intValue -> swarmSize = intValue, 1);
  33. addIntParameter("maxIterations", maxIterations, intValue -> maxIterations = intValue, 1);
  34. addIntParameter("mutationInterval", mutationInterval, intValue -> mutationInterval = intValue, 0);
  35. addDoubleParameter("dependency", dependency, doubleValue -> dependency = doubleValue, 2.001, 2.4);
  36. addDoubleParameter("limit", limit, doubleValue -> limit = doubleValue, 0.0, 1.0);
  37. addBooleanParameter("useIntervalMutation", useIntervalMutation, booleanValue -> useIntervalMutation = booleanValue);
  38. addDoubleParameter("mutateProbabilityInterval", mutateProbabilityInterval, doubleValue -> mutateProbabilityInterval = doubleValue, 0.0, 1.0);
  39. addDoubleParameter("maxMutationPercent", maxMutationPercent, doubleValue -> maxMutationPercent = doubleValue, 0.0, 1.0);
  40. }
  41. @Override
  42. protected double evaluateState(DecoratedState actualstate) {
  43. return Evaluation.getFitnessValueForState(actualstate);
  44. }
  45. @Override
  46. protected int getProgressBarMaxCount() {
  47. return swarmSize * (maxIterations + 1)* rounds + rounds;
  48. }
  49. /**
  50. * <p>Algo from Paper:</p><font size="3"><pre>
  51. *
  52. * Begin
  53. * t = 0; {t: generation index}
  54. * initialize particles x<sub>p,i,j</sub>(t);
  55. * evaluation x<sub>p,i,j</sub>(t);
  56. * while (termination condition &ne; true) do
  57. * v<sub>i,j</sub>(t) = update v<sub>i,j</sub>(t); {by Eq. (6)}
  58. * x<sub>g,i,j</sub>(t) = update x<sub>g,i,j</sub>(t); {by Eq. (7)}
  59. * x<sub>g,i,j</sub>(t) = mutation x<sub>g,i,j</sub>(t); {by Eq. (11)}
  60. * x<sub>p,i,j</sub>(t) = decode x<sub>g,i,j</sub>(t); {by Eqs. (8) and (9)}
  61. * evaluate x<sub>p,i,j</sub>(t);
  62. * t = t + 1;
  63. * end while
  64. * End</pre></font>
  65. * <p>with:</p><font size="3">
  66. *
  67. * x<sub>g,i,j</sub>: genotype ->genetic information -> in continuous space<br>
  68. * x<sub>p,i,j</sub>: phenotype -> observable characteristics-> in binary space<br>
  69. * X<sub>g,max</sub>: is the Maximum here set to 4.<br>
  70. * 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>
  71. * 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>
  72. * 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>
  73. * 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>
  74. * 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>
  75. * <p>Parameter:</p>
  76. * w inertia, calculated from phi(Variable:{@link #dependency})<br>
  77. * c1: influence, calculated from phi(Variable:{@link #dependency}) <br>
  78. * c2: influence, calculated from phi(Variable:{@link #dependency})<br>
  79. * r<sub>mu</sub>: probability that the proposed operation is conducted defined by limit(Variable:{@link #limit})<br>
  80. *
  81. *
  82. */
  83. @Override
  84. protected Individual executeAlgo() {
  85. initDependentParameter();
  86. Individual globalBest = new Individual();
  87. globalBest.position = extractPositionAndAccess();
  88. globalBest.fitness = evaluatePosition(globalBest.position);
  89. console.println("Start Value:" + globalBest.fitness);
  90. int dimensions = globalBest.position.size();
  91. List<Particle> swarm= initializeParticles(dimensions);
  92. List<Double> runList = new ArrayList<Double>();
  93. runList.add(globalBest.fitness);
  94. evaluation(globalBest, swarm);
  95. runList.add(globalBest.fitness);
  96. for (int iteration = 0; iteration < maxIterations ; iteration++) {
  97. int mutationAllowed = iteration % mutationInterval;
  98. for (int particleNumber = 0; particleNumber < swarmSize; particleNumber++) {
  99. Particle particle = swarm.get(particleNumber);
  100. if(this.useIntervalMutation) {
  101. boolean allowMutation = (Random.nextDouble() < this.mutateProbabilityInterval);
  102. TreeSet<Integer> mutationLocation = null;
  103. if(allowMutation)mutationLocation = locationsToMutate(dimensions);
  104. for(int index = 0; index < dimensions; index++) {
  105. updateVelocity(particle, index, globalBest);
  106. updateGenotype(particle, index);
  107. if(allowMutation &&mutationAllowed == 0 && iteration != 0 && mutationLocation.contains(index))mutation(particle, index);
  108. decode(particle, index);
  109. }
  110. }else {
  111. for(int index = 0; index < dimensions; index++) {
  112. updateVelocity(particle, index, globalBest);
  113. updateGenotype(particle, index);
  114. if(mutationAllowed == 0 && iteration != 0)mutation(particle, index);
  115. decode(particle, index);
  116. }
  117. }
  118. }
  119. if(cancel)return null;
  120. evaluation(globalBest, swarm);
  121. runList.add(globalBest.fitness);
  122. }
  123. console.println(" End Value:" + globalBest.fitness);
  124. db.insertNewRun(runList);
  125. return globalBest;
  126. }
  127. /**
  128. *
  129. * @param j maximum index of position in the particle
  130. * @return
  131. */
  132. private List<Particle> initializeParticles(int j) {
  133. List<Particle> swarm = new ArrayList<Particle>();
  134. //Create The Particle
  135. for (int particleNumber = 0; particleNumber < swarmSize; particleNumber++){
  136. //Create a Random position
  137. List<Boolean> aRandomPosition = new ArrayList<Boolean>();
  138. for (int index = 0; index < j; index++){
  139. aRandomPosition.add(Random.nextBoolean());
  140. }
  141. swarm.add(new Particle(aRandomPosition));
  142. }
  143. return swarm;
  144. }
  145. /**
  146. * Calculate w, c1, c2
  147. */
  148. private void initDependentParameter() {
  149. w = 1.0 / (dependency - 1 + Math.sqrt(dependency * dependency - 2 * dependency));
  150. c1 = c2 = dependency * w;
  151. }
  152. /**
  153. * Evaluate each particle and update the global Best position;
  154. * @param globalBest
  155. * @param swarm
  156. */
  157. private void evaluation(Individual globalBest, List<Particle> swarm) {
  158. for(Particle p: swarm) {
  159. double localEvaluationValue = evaluatePosition(p.xPhenotype);
  160. p.checkNewEvaluationValue(localEvaluationValue);
  161. if(localEvaluationValue < globalBest.fitness) {
  162. globalBest.fitness = localEvaluationValue;
  163. globalBest.position = p.localBest.position;
  164. }
  165. }
  166. }
  167. /**
  168. * 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>
  169. * @param particle
  170. * @param index
  171. * @param globalBest
  172. */
  173. private void updateVelocity(Particle particle, int index, Individual globalBest) {
  174. double r1 = Random.nextDouble();
  175. double r2 = Random.nextDouble();
  176. double posValue = particle.xPhenotype.get(index)?1.0:0.0;
  177. 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)) );
  178. }
  179. /**
  180. * 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>
  181. * @param particle
  182. * @param index
  183. */
  184. private void updateGenotype(Particle particle, int index) {
  185. particle.xGenotype.set(index, clamp(particle.xGenotype.get(index) + particle.velocity.get(index)));
  186. }
  187. /**
  188. * 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>
  189. * @param particle
  190. * @param index
  191. */
  192. private void mutation(Particle particle, int index) {
  193. if(Random.nextDouble() < limit) particle.xGenotype.set(index, -particle.xGenotype.get(index));
  194. }
  195. /**
  196. * 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>
  197. * @param particle
  198. * @param index
  199. */
  200. private void decode(Particle particle, int index) {
  201. particle.xPhenotype.set(index, Random.nextDouble() < Sigmoid(particle.xGenotype.get(index)));
  202. }
  203. /**
  204. * 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>
  205. * @param value
  206. * @return
  207. */
  208. private double Sigmoid(double value) {
  209. return 1.0 / (1.0 + Math.exp(-value));
  210. }
  211. /**
  212. * 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}
  213. * @param value
  214. * @return
  215. */
  216. private double clamp(double value) {
  217. return Math.max(-4.0, Math.min(4.0, value));
  218. }
  219. private TreeSet<Integer> locationsToMutate(int dimensions) {
  220. TreeSet<Integer> mutationLocation = new TreeSet<Integer>(); //sortedSet
  221. int maximumAmountOfMutatedBits = Math.max(1, (int)Math.round(((double) dimensions) * this.maxMutationPercent));
  222. int randomUniformAmountOfMutatedValues = Random.nextIntegerInRange(1,maximumAmountOfMutatedBits + 1);
  223. for(int i = 0; i< randomUniformAmountOfMutatedValues; i++) {
  224. boolean success = mutationLocation.add(Random.nextIntegerInRange(0, dimensions));
  225. if(!success) i--; //can be add up to some series long loops if maximumAmountOfMutatedBits get closed to problemsize.
  226. }
  227. //console.println(mutationLocation.toString());
  228. return mutationLocation;
  229. }
  230. /**
  231. * Class to represent a Particle.
  232. */
  233. private class Particle{
  234. /**
  235. * The velocity of a particle.
  236. */
  237. public List<Double> velocity;
  238. /**
  239. * The positions genotype.
  240. */
  241. public List<Double> xGenotype;
  242. /**
  243. * The positions phenotype. Alias the current position.
  244. */
  245. public List<Boolean> xPhenotype;
  246. public Individual localBest;
  247. Particle(List<Boolean> position){
  248. this.xPhenotype = position;
  249. //Init velocity, xGenotype with 0.0 values.
  250. this.velocity = position.stream().map(bool -> 0.0).collect(Collectors.toList());
  251. this.xGenotype = position.stream().map(bool -> 0.0).collect(Collectors.toList());
  252. localBest = new Individual();
  253. localBest.fitness = Double.MAX_VALUE;
  254. }
  255. public void checkNewEvaluationValue(double newEvaluationValue) {
  256. if(newEvaluationValue < localBest.fitness) {
  257. localBest.fitness = newEvaluationValue;
  258. localBest.position = xPhenotype.stream().map(bool -> bool).collect(Collectors.toList());
  259. }
  260. }
  261. public String toString() {
  262. return "Particle with xPhenotype(Position), xGenotype, velocity:["
  263. + listToString(xPhenotype) + "],[" + listToString(xGenotype) + "],["
  264. + listToString(velocity) + "]";
  265. }
  266. private <Type> String listToString(List<Type> list) {
  267. return list.stream().map(Object::toString).collect(Collectors.joining(", "));
  268. }
  269. }
  270. }