1 10 package examples.chromInit; 11 12 import org.jgap.*; 13 import org.jgap.impl.*; 14 15 22 public class ChromosomeInit { 23 24 private static final String CVS_REVISION = "$Revision: 1.6 $"; 25 26 public static void main(String [] args) { 27 int numEvolutions = 500; 28 Configuration gaConf = new DefaultConfiguration(); 32 gaConf.getGeneticOperators().remove(0); 34 gaConf.setPreservFittestIndividual(true); 35 gaConf.setKeepPopulationSizeConstant(false); 36 try { 37 int chromeSize; 38 if (args.length == 0) { 39 chromeSize = 7; 40 } 41 else { 42 chromeSize = Integer.parseInt(args[0]); 43 } 44 if (chromeSize > 15) { 45 System.err.println("This example does not handle " + 46 "Chromosomes greater than 15 bits in length."); 47 System.exit( -1); 48 } 49 IChromosome sampleChromosome = new Chromosome(gaConf, 50 new BooleanGene(gaConf), chromeSize); 51 gaConf.setSampleChromosome(sampleChromosome); 52 gaConf.setPopulationSize(20); 53 gaConf.setFitnessFunction(new MaxFunction()); 54 int populationSize = gaConf.getPopulationSize(); 59 Population pop = new Population(gaConf, populationSize); 60 for (int i = 0; i < populationSize; i++) { 61 int mult; 62 if (i % 2 == 0) { 65 mult = 1; 66 } 67 else { 68 mult = 2; 69 } 70 Gene[] sampleGenes = sampleChromosome.getGenes(); 71 Gene[] newGenes = new Gene[sampleGenes.length * mult]; 72 RandomGenerator generator = gaConf.getRandomGenerator(); 73 for (int j = 0; j < newGenes.length; j = j + mult) { 74 newGenes[j] = sampleGenes[j / mult].newGene(); 81 newGenes[j].setToRandomValue(generator); 84 if (mult > 1) { 85 newGenes[j + 1] = sampleGenes[j / 2].newGene(); 86 newGenes[j + 1].setToRandomValue(generator); 89 } 90 } 91 IChromosome chrom = Chromosome.randomInitialChromosome(gaConf); 92 chrom.setGenes(newGenes); 93 pop.addChromosome(chrom); 94 } 95 Genotype genotype = new Genotype(gaConf, pop); 99 int progress = 0; 100 int percentEvolution = numEvolutions / 100; 101 for (int i = 0; i < numEvolutions; i++) { 102 genotype.evolve(); 103 if (percentEvolution > 0 && i % percentEvolution == 0) { 106 progress++; 107 IChromosome fittest = genotype.getFittestChromosome(); 108 double fitness = fittest.getFitnessValue(); 109 System.out.println("Fittest Chromosome has value " + fitness); 110 } 111 } 112 IChromosome fittest = genotype.getFittestChromosome(); 113 System.out.println("Fittest Chromosome has value " + 114 fittest.getFitnessValue()); 115 } 116 catch (InvalidConfigurationException e) { 117 e.printStackTrace(); 118 System.exit( -2); 119 } 120 } 121 } 122 | Popular Tags |