GaAlgorithm.java 9.2 KB

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