1 10 package examples.simpleBoolean; 11 12 import org.jgap.*; 13 import org.jgap.impl.*; 14 15 22 public class SimpleExample { 23 24 private static final String CVS_REVISION = "$Revision: 1.8 $"; 25 26 35 public static void main(String [] args) { 36 int numEvolutions = 500; 37 Configuration gaConf = new DefaultConfiguration(); 38 gaConf.setPreservFittestIndividual(true); 39 gaConf.setKeepPopulationSizeConstant(false); 40 Genotype genotype = null; 41 int chromeSize; 42 if (args.length > 0) { 43 chromeSize = Integer.parseInt(args[0]); 44 } 45 else { 46 chromeSize = 16; 47 } 48 double maxFitness = Math.pow(2.0, (double) chromeSize) - 1; 49 if (chromeSize > 32) { 50 System.err.println("This example does not handle " + 51 "Chromosomes greater than 32 bits in length."); 52 System.exit( -1); 53 } 54 try { 55 IChromosome sampleChromosome = new Chromosome(gaConf, 56 new BooleanGene(gaConf), chromeSize); 57 gaConf.setSampleChromosome(sampleChromosome); 58 gaConf.setPopulationSize(20); 59 gaConf.setFitnessFunction(new MaxFunction()); 60 genotype = Genotype.randomInitialGenotype(gaConf); 61 } 62 catch (InvalidConfigurationException e) { 63 e.printStackTrace(); 64 System.exit( -2); 65 } 66 int progress = 0; 67 int percentEvolution = numEvolutions / 100; 68 for (int i = 0; i < numEvolutions; i++) { 69 genotype.evolve(); 70 if (percentEvolution > 0 && i % percentEvolution == 0) { 73 progress++; 74 IChromosome fittest = genotype.getFittestChromosome(); 75 double fitness = fittest.getFitnessValue(); 76 System.out.println("Currently fittest Chromosome has fitness " + 77 fitness); 78 if (fitness >= maxFitness) { 79 break; 80 } 81 } 82 } 83 IChromosome fittest = genotype.getFittestChromosome(); 86 System.out.println("Fittest Chromosome has fitness " + 87 fittest.getFitnessValue()); 88 } 89 } 90 | Popular Tags |