GaAlgorithm.java 9.3 KB

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