01: /*
02: * This file is part of JGAP.
03: *
04: * JGAP offers a dual license model containing the LGPL as well as the MPL.
05: *
06: * For licencing information please see the file license.txt included with JGAP
07: * or have a look at the top of class org.jgap.Chromosome which representatively
08: * includes the JGAP license policy applicable for any file delivered with JGAP.
09: */
10: package examples.simpleBoolean;
11:
12: import org.jgap.*;
13: import org.jgap.impl.*;
14:
15: /**
16: * Simple class that demonstrates the basic usage of JGAP.
17: *
18: * @author Neil Rotstan
19: * @author Klaus Meffert
20: * @since 2.0
21: */
22: public class SimpleExample {
23: /** String containing the CVS revision. Read out via reflection!*/
24: private static final String CVS_REVISION = "$Revision: 1.8 $";
25:
26: /**
27: * Starts the example.
28: * @param args if optional first argument provided, it represents the number
29: * of bits to use, but no more than 32
30: *
31: * @author Neil Rotstan
32: * @author Klaus Meffert
33: * @since 2.0
34: */
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: } else {
45: chromeSize = 16;
46: }
47: double maxFitness = Math.pow(2.0, (double) chromeSize) - 1;
48: if (chromeSize > 32) {
49: System.err.println("This example does not handle "
50: + "Chromosomes greater than 32 bits in length.");
51: System.exit(-1);
52: }
53: try {
54: IChromosome sampleChromosome = new Chromosome(gaConf,
55: new BooleanGene(gaConf), chromeSize);
56: gaConf.setSampleChromosome(sampleChromosome);
57: gaConf.setPopulationSize(20);
58: gaConf.setFitnessFunction(new MaxFunction());
59: genotype = Genotype.randomInitialGenotype(gaConf);
60: } catch (InvalidConfigurationException e) {
61: e.printStackTrace();
62: System.exit(-2);
63: }
64: int progress = 0;
65: int percentEvolution = numEvolutions / 100;
66: for (int i = 0; i < numEvolutions; i++) {
67: genotype.evolve();
68: // Print progress.
69: // ---------------
70: if (percentEvolution > 0 && i % percentEvolution == 0) {
71: progress++;
72: IChromosome fittest = genotype.getFittestChromosome();
73: double fitness = fittest.getFitnessValue();
74: System.out
75: .println("Currently fittest Chromosome has fitness "
76: + fitness);
77: if (fitness >= maxFitness) {
78: break;
79: }
80: }
81: }
82: // Print summary.
83: // --------------
84: IChromosome fittest = genotype.getFittestChromosome();
85: System.out.println("Fittest Chromosome has fitness "
86: + fittest.getFitnessValue());
87: }
88: }
|