GaAlgorithm.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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 "GaAlgo"+ " Rounds:" + rounds
  93. + " maxGenerations:" + maxGenerations
  94. + " popsize:" + popsize
  95. + " tournamentSize:" + tournamentSize
  96. + (useFixedSpawProbability? " fixedSwapProbability:" + fixedSwapProbability:" swapProbability:" + "1.0f/problemsize")
  97. + (useIntervalMutation?
  98. (" mutateProbabilityInterval:" + mutateProbabilityInterval
  99. + " maxMutationPercent:" + maxMutationPercent)
  100. :
  101. (useFixedMutateProbability? " fixedMutateProbability:" + fixedMutateProbability:" mutateProbability:" + "1.0f/problemsize"));
  102. }
  103. @Override
  104. protected String plottFileName() {
  105. return "ga-topologie.txt";
  106. }
  107. /**
  108. * Initialize the Population with Individuals that have a random Position.
  109. */
  110. private List<Individual> initPopuluationRandom(int problemSize, Individual startIndidual){
  111. List<Individual> population = new ArrayList<Individual>();
  112. for(int i = 0; i < popsize -1; i++) {
  113. population.add(createRandomIndividualWithoutFitness(problemSize));
  114. }
  115. //Add Start Position
  116. population.add(new Individual(startIndidual));
  117. return population;
  118. }
  119. private Individual createRandomIndividualWithoutFitness(int problemSize) {
  120. //create Random Individual Without Fitness
  121. Individual result = new Individual();
  122. result.position = new ArrayList<Integer>();
  123. for (int index = 0; index < problemSize; index++){
  124. result.position.add(Random.nextIntegerInRange(0, this.getMaximumIndexObjects(index) + 1));
  125. }
  126. //console.println("[" +result.position.stream().map(Object::toString).collect(Collectors.joining(", ")) + "]");
  127. return result;
  128. }
  129. /**
  130. * Algorithm 32 Tournament Selection.
  131. * The fitnessValues are calculated for the Population List.
  132. * PseudoCode
  133. */
  134. private Individual selectAParent(List<Individual> population,int popsize) {
  135. Individual tournamentBest = population.get(Random.nextIntegerInRange(0, popsize));
  136. double participants;
  137. for(participants = tournamentSize ; participants >= 2; participants -= 1.0) {
  138. Individual next = population.get(Random.nextIntegerInRange(0, popsize));
  139. if(next.fitness < tournamentBest.fitness) tournamentBest = next;
  140. }
  141. //if tournament size is not a whole number like 2.5 or 3.6
  142. //the remaining part is the chance to fight another time; 2.7 -> 70% chance to fight a second time
  143. if( participants > 1) {
  144. if(Random.nextDouble() < participants - 1.0) {
  145. //println("Chance to find a match");
  146. Individual next = population.get(Random.nextIntegerInRange(0, popsize));
  147. if(next.fitness < tournamentBest.fitness) tournamentBest = next;
  148. }
  149. }
  150. return tournamentBest;
  151. }
  152. /**
  153. * Algorithm 25 Uniform Crossover.
  154. * Probability is set to 1/Problemsize when not changed.
  155. */
  156. private void crossover(Individual childA, Individual childB, int problemSize) {
  157. double probability = (this.useFixedSpawProbability) ? this.fixedSwapProbability : 1.0/(double)problemSize;
  158. ListIterator<Integer> iterA = childA.position.listIterator();
  159. ListIterator<Integer> iterB = childB.position.listIterator();
  160. for(int i= 0; i < problemSize; i++) {
  161. int intA = iterA.next();
  162. int intB = iterB.next();
  163. if(Random.nextDouble() <= probability ) {
  164. //Swap
  165. iterA.set(intB);
  166. iterB.set(intA);
  167. }
  168. }
  169. }
  170. /**
  171. * Algorithm 22 Bit-Flip Mutation.
  172. *
  173. */
  174. private void mutate(Individual child, int problemSize) {
  175. double probability = (this.useFixedMutateProbability) ? this.fixedMutateProbability : 1.0/(double)problemSize;
  176. ListIterator<Integer> iter = child.position.listIterator();
  177. while(iter.hasNext()) {
  178. int index = iter.nextIndex();
  179. Integer intValue = iter.next();
  180. if(Random.nextDouble() <= probability) {
  181. iter.set(Random.nextIntegerInRangeExcept(0, this.getMaximumIndexObjects(index), intValue));
  182. }
  183. }
  184. }
  185. /**
  186. * Algorithm rolf
  187. *
  188. */
  189. private void mutateInterval(Individual child, int problemSize) {
  190. //If not mutate skip
  191. if(Random.nextDouble() > this.mutateProbabilityInterval) {
  192. return;
  193. }
  194. //println("problemSize:" + problemSize + " maxMutationPercent:" + maxMutationPercent);
  195. int maximumAmountOfMutatedBits = Math.max(1, (int)Math.round(((double) problemSize) * this.maxMutationPercent));
  196. int randomUniformAmountOfMutatedValues = Random.nextIntegerInRange(1,maximumAmountOfMutatedBits + 1);
  197. //println("max:" + maximumAmountOfMutatedBits + " actual:" + randomUniformAmountOfMutatedValues);
  198. TreeSet<Integer> mutationLocation = new TreeSet<Integer>(); //sortedSet
  199. //Choose the location to mutate
  200. for(int i = 0; i< randomUniformAmountOfMutatedValues; i++) {
  201. boolean success = mutationLocation.add(Random.nextIntegerInRange(0, problemSize));
  202. if(!success) i--; //can be add up to some series long loops if maximumAmountOfMutatedBits get closed to problemsize.
  203. }
  204. //println("Set:" + mutationLocation);
  205. ListIterator<Integer> iter = child.position.listIterator();
  206. if(mutationLocation.isEmpty()) return;
  207. int firstindex = mutationLocation.pollFirst();
  208. while(iter.hasNext()) {
  209. int index = iter.nextIndex();
  210. int intValue = iter.next();
  211. if(index == firstindex) {
  212. iter.set(Random.nextIntegerInRangeExcept(0, this.getMaximumIndexObjects(index), intValue));
  213. //println("changed Value["+ index +"]");
  214. if(mutationLocation.isEmpty()) break;
  215. firstindex = mutationLocation.pollFirst();
  216. }
  217. }
  218. }
  219. }