GaAlgorithm.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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.ListIterator;
  7. import java.util.TreeSet;
  8. import algorithm.objectiveFunction.TopologieObjectiveFunction;
  9. import api.TopologieAlgorithmFramework;
  10. import ui.model.DecoratedState;
  11. import utility.Random;
  12. public class GaAlgorithm extends TopologieAlgorithmFramework {
  13. private int popsize = 20;
  14. private int maxGenerations = 100;
  15. private double tournamentSize = 2.0;
  16. private double fixedSwapProbability = 0.02;
  17. private boolean useFixedSpawProbability = false;
  18. private double fixedMutateProbability = 0.02;
  19. private boolean useFixedMutateProbability = false;
  20. private boolean useIntervalMutation = false;
  21. private double mutateProbabilityInterval = 0.01;
  22. private double maxMutationPercent = 0.01;
  23. private boolean moreInformation = false;
  24. public GaAlgorithm(){
  25. addIntParameter("popsize", popsize, intValue -> popsize = intValue, () -> popsize, 1);
  26. addIntParameter("maxGenerations", maxGenerations, intValue -> maxGenerations = intValue, () -> maxGenerations, 1);
  27. addDoubleParameter("tournamentSize", tournamentSize, doubleValue -> tournamentSize = doubleValue, () -> tournamentSize, 1.0);
  28. addBooleanParameter("useFixedSpawProbability", useFixedSpawProbability, booleanValue -> useFixedSpawProbability = booleanValue, Arrays.asList("fixedSwapProbability"), new LinkedList<String>());
  29. addDoubleParameter("fixedSwapProbability", fixedSwapProbability, doubleValue -> fixedSwapProbability = doubleValue, () -> fixedSwapProbability, useFixedSpawProbability, 0.0, 1.0);
  30. addSeperator();
  31. addBooleanParameter("Use Interval Mutation", useIntervalMutation, booleanValue -> useIntervalMutation = booleanValue, Arrays.asList("Probability for Frequency Mutation", "Scope of Mutation"), Arrays.asList("Probability for Bit-wise Mutation"));
  32. addDoubleParameter("Probability for Frequency Mutation", mutateProbabilityInterval, doubleValue -> mutateProbabilityInterval = doubleValue, () -> mutateProbabilityInterval, useIntervalMutation, 0.0, 1.0);
  33. addDoubleParameter("Probability for Bit-wise Mutation", fixedMutateProbability, doubleValue -> fixedMutateProbability = doubleValue, () -> fixedMutateProbability, !useIntervalMutation, 0.0, 1.0);
  34. addDoubleParameter("Scope of Mutation", maxMutationPercent, doubleValue -> maxMutationPercent = doubleValue, () -> maxMutationPercent, useIntervalMutation, 0.0, 1.0);
  35. addSeperator();
  36. addBooleanParameter("Print Auxiliary Information", moreInformation, booleanValue -> moreInformation = booleanValue, new LinkedList<String>(), new LinkedList<String>());
  37. }
  38. @Override
  39. protected double evaluateState(DecoratedState actualstate, int amountOfAddedSwitch, double addedCableMeters, boolean moreInformation) {
  40. return TopologieObjectiveFunction.getFitnessValueForState(actualstate, amountOfAddedSwitch, addedCableMeters, moreInformation);
  41. }
  42. @Override
  43. protected Individual executeAlgo() {
  44. resetWildcards();
  45. Individual best = new Individual();
  46. best.position = extractPositionAndAccess();
  47. int problemSize = best.position.size();
  48. best.fitness = evaluatePosition(best.position);
  49. List<Double> runList = new ArrayList<Double>();
  50. runList.add(best.fitness);
  51. console.println("Integer_Array_length: " + best.position.size());
  52. List<Individual> population = initPopuluationRandom(problemSize, best);
  53. for(int generation = 0; generation< maxGenerations; generation++) {
  54. if(moreInformation)console.println("Generation" + generation + " start with Fitness: " + best.fitness);
  55. for(Individual i : population) {
  56. i.fitness = evaluatePosition(i.position);
  57. if(moreInformation)console.println("Fitness" + i.fitness);
  58. if(i.fitness < best.fitness) best = i;
  59. }
  60. runList.add(best.fitness);
  61. List<Individual> childList = new ArrayList<Individual>();
  62. for(int k = 0; k<popsize/2; k++) {
  63. Individual parentA = selectAParent(population, popsize);
  64. Individual parentB = selectAParent(population, popsize);
  65. Individual childA = new Individual(parentA);
  66. Individual childB = new Individual(parentB);
  67. crossover(childA, childB, problemSize);
  68. if(useIntervalMutation)mutateInterval(childA, problemSize);else mutate(childA, problemSize);
  69. if(useIntervalMutation)mutateInterval(childB, problemSize);else mutate(childB, problemSize);
  70. childList.add(childA);
  71. childList.add(childB);
  72. }
  73. population = childList;
  74. if(moreInformation)console.println("________________");
  75. if(cancel)return null;
  76. }
  77. console.println(" End with:" + best.fitness);
  78. this.runList = runList;
  79. return best;
  80. }
  81. @Override
  82. protected int getProgressBarMaxCount() {
  83. return rounds * maxGenerations * popsize + 1;
  84. }
  85. @Override
  86. protected String algoInformationToPrint() {
  87. return "GaAlgo"+ " Rounds:" + rounds
  88. + " maxGenerations:" + maxGenerations
  89. + " popsize:" + popsize
  90. + " tournamentSize:" + tournamentSize
  91. + (useFixedSpawProbability? " fixedSwapProbability:" + fixedSwapProbability:" swapProbability:" + "1.0f/problemsize")
  92. + (useIntervalMutation?
  93. (" mutateProbabilityInterval:" + mutateProbabilityInterval
  94. + " maxMutationPercent:" + maxMutationPercent)
  95. :
  96. (useFixedMutateProbability? " fixedMutateProbability:" + fixedMutateProbability:" mutateProbability:" + "1.0f/problemsize"));
  97. }
  98. @Override
  99. protected String plottFileName() {
  100. return "ga-topologie.txt";
  101. }
  102. /**
  103. * Initialize the Population with Individuals that have a random Position.
  104. */
  105. private List<Individual> initPopuluationRandom(int problemSize, Individual startIndidual){
  106. List<Individual> population = new ArrayList<Individual>();
  107. for(int i = 0; i < popsize -1; i++) {
  108. population.add(createRandomIndividualWithoutFitness(problemSize));
  109. }
  110. //Add Start Position
  111. population.add(new Individual(startIndidual));
  112. return population;
  113. }
  114. private Individual createRandomIndividualWithoutFitness(int problemSize) {
  115. //create Random Individual Without Fitness
  116. Individual result = new Individual();
  117. result.position = new ArrayList<Integer>();
  118. for (int index = 0; index < problemSize; index++){
  119. result.position.add(Random.nextIntegerInRange(0, this.getMaximumIndexObjects(index) + 1));
  120. }
  121. //console.println("[" +result.position.stream().map(Object::toString).collect(Collectors.joining(", ")) + "]");
  122. return result;
  123. }
  124. /**
  125. * Algorithm 32 Tournament Selection.
  126. * The fitnessValues are calculated for the Population List.
  127. * PseudoCode
  128. */
  129. private Individual selectAParent(List<Individual> population,int popsize) {
  130. Individual tournamentBest = population.get(Random.nextIntegerInRange(0, popsize));
  131. double participants;
  132. for(participants = tournamentSize ; participants >= 2; participants -= 1.0) {
  133. Individual next = population.get(Random.nextIntegerInRange(0, popsize));
  134. if(next.fitness < tournamentBest.fitness) tournamentBest = next;
  135. }
  136. //if tournament size is not a whole number like 2.5 or 3.6
  137. //the remaining part is the chance to fight another time; 2.7 -> 70% chance to fight a second time
  138. if( participants > 1) {
  139. if(Random.nextDouble() < participants - 1.0) {
  140. //println("Chance to find a match");
  141. Individual next = population.get(Random.nextIntegerInRange(0, popsize));
  142. if(next.fitness < tournamentBest.fitness) tournamentBest = next;
  143. }
  144. }
  145. return tournamentBest;
  146. }
  147. /**
  148. * Algorithm 25 Uniform Crossover.
  149. * Probability is set to 1/Problemsize when not changed.
  150. */
  151. private void crossover(Individual childA, Individual childB, int problemSize) {
  152. double probability = (this.useFixedSpawProbability) ? this.fixedSwapProbability : 1.0/(double)problemSize;
  153. ListIterator<Integer> iterA = childA.position.listIterator();
  154. ListIterator<Integer> iterB = childB.position.listIterator();
  155. for(int i= 0; i < problemSize; i++) {
  156. int intA = iterA.next();
  157. int intB = iterB.next();
  158. if(Random.nextDouble() <= probability ) {
  159. //Swap
  160. iterA.set(intB);
  161. iterB.set(intA);
  162. }
  163. }
  164. }
  165. /**
  166. * Algorithm 22 Bit-Flip Mutation.
  167. *
  168. */
  169. private void mutate(Individual child, int problemSize) {
  170. double probability = (this.useFixedMutateProbability) ? this.fixedMutateProbability : 1.0/(double)problemSize;
  171. ListIterator<Integer> iter = child.position.listIterator();
  172. while(iter.hasNext()) {
  173. int index = iter.nextIndex();
  174. Integer intValue = iter.next();
  175. if(Random.nextDouble() <= probability) {
  176. iter.set(Random.nextIntegerInRangeExcept(0, this.getMaximumIndexObjects(index), intValue));
  177. }
  178. }
  179. }
  180. /**
  181. * Algorithm rolf
  182. *
  183. */
  184. private void mutateInterval(Individual child, int problemSize) {
  185. //If not mutate skip
  186. if(Random.nextDouble() > this.mutateProbabilityInterval) {
  187. return;
  188. }
  189. //println("problemSize:" + problemSize + " maxMutationPercent:" + maxMutationPercent);
  190. int maximumAmountOfMutatedBits = Math.max(1, (int)Math.round(((double) problemSize) * this.maxMutationPercent));
  191. int randomUniformAmountOfMutatedValues = Random.nextIntegerInRange(1,maximumAmountOfMutatedBits + 1);
  192. //println("max:" + maximumAmountOfMutatedBits + " actual:" + randomUniformAmountOfMutatedValues);
  193. TreeSet<Integer> mutationLocation = new TreeSet<Integer>(); //sortedSet
  194. //Choose the location to mutate
  195. for(int i = 0; i< randomUniformAmountOfMutatedValues; i++) {
  196. boolean success = mutationLocation.add(Random.nextIntegerInRange(0, problemSize));
  197. if(!success) i--; //can be add up to some series long loops if maximumAmountOfMutatedBits get closed to problemsize.
  198. }
  199. //println("Set:" + mutationLocation);
  200. ListIterator<Integer> iter = child.position.listIterator();
  201. if(mutationLocation.isEmpty()) return;
  202. int firstindex = mutationLocation.pollFirst();
  203. while(iter.hasNext()) {
  204. int index = iter.nextIndex();
  205. int intValue = iter.next();
  206. if(index == firstindex) {
  207. iter.set(Random.nextIntegerInRangeExcept(0, this.getMaximumIndexObjects(index), intValue));
  208. //println("changed Value["+ index +"]");
  209. if(mutationLocation.isEmpty()) break;
  210. firstindex = mutationLocation.pollFirst();
  211. }
  212. }
  213. }
  214. }