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.simpleBooleanThreaded;
11:
12: import org.jgap.*;
13: import org.jgap.impl.*;
14: import org.jgap.event.*;
15:
16: /**
17: * Simple class that demonstrates the basic usage of JGAP together with
18: * multithreaded processing.
19: *
20: * @author Klaus Meffert
21: * @since 3.01
22: */
23: public class SimpleExample {
24: /** String containing the CVS revision. Read out via reflection!*/
25: private static final String CVS_REVISION = "$Revision: 1.2 $";
26:
27: /**
28: * Starts the example.
29: * @param args ignored here
30: *
31: * @throws Exception
32: *
33: * @author Klaus Meffert
34: * @since 3.01
35: */
36: public static void main(String[] args) throws Exception {
37: final int numEvolutions = 500;
38: final int numThreads = 5;
39: int chromeSize = 20;
40: if (chromeSize > 32) {
41: System.err.println("This example does not handle "
42: + "Chromosomes greater than 32 bits in length.");
43: System.exit(-1);
44: }
45: for (int i = 0; i < numThreads; i++) {
46: final int j = i;
47: Configuration gaConf = new DefaultConfiguration(i + "",
48: "no name");
49: gaConf.setPreservFittestIndividual(i % 2 == 0);
50: gaConf.setKeepPopulationSizeConstant(i % 2 != 0);
51: IChromosome sampleChromosome = new Chromosome(gaConf,
52: new BooleanGene(gaConf), chromeSize);
53: gaConf.setSampleChromosome(sampleChromosome);
54: gaConf.setPopulationSize(gaConf.getRandomGenerator()
55: .nextInt(500));
56: gaConf.setFitnessFunction(new MaxFunction());
57: Genotype genotype = null;
58: try {
59: genotype = Genotype.randomInitialGenotype(gaConf);
60: } catch (InvalidConfigurationException e) {
61: e.printStackTrace();
62: System.exit(-2);
63: }
64: final Thread t1 = new Thread(genotype);
65: gaConf.getEventManager().addEventListener(
66: GeneticEvent.GENOTYPE_EVOLVED_EVENT,
67: new GeneticEventListener() {
68: public void geneticEventFired(
69: GeneticEvent a_firedEvent) {
70: Genotype genotype = (Genotype) a_firedEvent
71: .getSource();
72: int evno = genotype.getConfiguration()
73: .getGenerationNr();
74: if (evno % 10 == 0) {
75: double bestFitness = genotype
76: .getFittestChromosome()
77: .getFitnessValue();
78: System.out.println(t1.getName()
79: + ": Evolving generation "
80: + evno + ", best fitness: "
81: + bestFitness);
82: }
83: if (evno > numEvolutions) {
84: t1.stop();
85: } else {
86: try {
87: t1.sleep((j + 1) * 3);
88: } catch (InterruptedException iex) {
89: iex.printStackTrace();
90: System.exit(1);
91: }
92: }
93: }
94: });
95: t1.setPriority((i % 2) + 1);
96: t1.start();
97: }
98: }
99: }
|