GaAlgorithm.java 9.3 KB

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