GaAlgorithm.java 10 KB

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