GaAlgorithm.java 9.0 KB

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