PsoAlgorithm.java 14 KB

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