GaAlgorithm2.java 8.8 KB

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