GaAlgorithm.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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.AlgorithmFrameworkFlex;
  8. import ui.model.DecoratedState;
  9. public class GaAlgorithm extends AlgorithmFrameworkFlex{
  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 GaAlgorithm() {
  25. super();
  26. addIntParameter("popsize", popsize, intValue -> popsize = intValue, () -> popsize, 1);
  27. addIntParameter("maxGenerations", maxGenerations, intValue -> maxGenerations = intValue, () -> maxGenerations, 1);
  28. addDoubleParameter("tournamentSize", tournamentSize, doubleValue -> tournamentSize = doubleValue, () -> tournamentSize, 1.0);
  29. addDoubleParameter("fixedSwapProbability", fixedSwapProbability, doubleValue -> fixedSwapProbability = doubleValue, () -> fixedSwapProbability, 0.0, 1.0);
  30. addBooleanParameter("useFixedSpawProbability", useFixedSpawProbability, booleanValue -> useFixedSpawProbability = booleanValue);
  31. addDoubleParameter("fixedMutateProbability", fixedMutateProbability, doubleValue -> fixedMutateProbability = doubleValue, () -> fixedMutateProbability, 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, () -> mutateProbabilityInterval, 0.0, 1.0);
  35. addDoubleParameter("maxMutationPercent", maxMutationPercent, doubleValue -> maxMutationPercent = doubleValue, () -> maxMutationPercent, 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. GaAlgorithm instance = new GaAlgorithm();
  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 ObjectiveFunctionByCarlos.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. this.runList = runList;
  94. return best;
  95. }
  96. /**
  97. * Algorithm 22 Bit-Flip Mutation.
  98. *
  99. */
  100. private void mutate(Individual child, int problemSize) {
  101. double probability = (this.useFixedMutateProbability) ? this.fixedMutateProbability : 1.0/(double)problemSize;
  102. ListIterator<Boolean> iter = child.position.listIterator();
  103. while(iter.hasNext()) {
  104. boolean boolValue = iter.next();
  105. if(Random.nextDouble() <= probability) {
  106. iter.set(!boolValue);
  107. }
  108. }
  109. }
  110. /**
  111. * Algorithm rolf
  112. *
  113. */
  114. private void mutateInterval(Individual child, int problemSize) {
  115. //If not mutate skip
  116. if(Random.nextDouble() > this.mutateProbabilityInterval) {
  117. return;
  118. }
  119. //println("problemSize:" + problemSize + " maxMutationPercent:" + maxMutationPercent);
  120. int maximumAmountOfMutatedBits = Math.max(1, (int)Math.round(((double) problemSize) * this.maxMutationPercent));
  121. int randomUniformAmountOfMutatedValues = Random.nextIntegerInRange(1,maximumAmountOfMutatedBits + 1);
  122. //println("max:" + maximumAmountOfMutatedBits + " actual:" + randomUniformAmountOfMutatedValues);
  123. TreeSet<Integer> mutationLocation = new TreeSet<Integer>(); //sortedSet
  124. //Choose the location to mutate
  125. for(int i = 0; i< randomUniformAmountOfMutatedValues; i++) {
  126. boolean success = mutationLocation.add(Random.nextIntegerInRange(0, problemSize));
  127. if(!success) i--; //can be add up to some series long loops if maximumAmountOfMutatedBits get closed to problemsize.
  128. }
  129. //println("Set:" + mutationLocation);
  130. ListIterator<Boolean> iter = child.position.listIterator();
  131. if(mutationLocation.isEmpty()) return;
  132. int firstindex = mutationLocation.pollFirst();
  133. while(iter.hasNext()) {
  134. int index = iter.nextIndex();
  135. boolean boolValue = iter.next();
  136. if(index == firstindex) {
  137. iter.set(!boolValue);
  138. //println("changed Value["+ index +"]");
  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/ (float)popsize)
  228. + (useIntervalMutation?
  229. (" mutateProbabilityInterval:" + mutateProbabilityInterval
  230. + " maxMutationPercent:" + maxMutationPercent)
  231. :
  232. (useFixedMutateProbability? " fixedMutateProbability:" + fixedMutateProbability:" mutateProbability:" + 1.0f/ (float)popsize));
  233. }
  234. @Override
  235. protected String plottFileName() {
  236. return "plottGaAlgo.txt";
  237. }
  238. }