PsoAlgorithm.java 13 KB

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