GaAlgorithm.java 9.4 KB

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