GaAlgorithm.java 8.9 KB

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