PsoAlgorithm.java 13 KB

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