GaAlgorithm.java 9.6 KB

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