GaAlgorithm.java 10 KB

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