KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jgap > gp > impl > GPGenotypeTest


1 /*
2  * This file is part of JGAP.
3  *
4  * JGAP offers a dual license model containing the LGPL as well as the MPL.
5  *
6  * For licencing information please see the file license.txt included with JGAP
7  * or have a look at the top of class org.jgap.Chromosome which representatively
8  * includes the JGAP license policy applicable for any file delivered with JGAP.
9  */

10 package org.jgap.gp.impl;
11
12 import junit.framework.*;
13 import org.jgap.*;
14 import org.jgap.impl.*;
15 import org.jgap.gp.terminal.*;
16 import org.jgap.gp.function.*;
17 import org.jgap.gp.*;
18
19 /**
20  * Tests the GPGenotype class.
21  *
22  * @author Klaus Meffert
23  * @since 3.0
24  */

25 public class GPGenotypeTest
26     extends GPTestCase {
27   /** String containing the CVS revision. Read out via reflection!*/
28   private final static String JavaDoc CVS_REVISION = "$Revision: 1.8 $";
29
30   public static Test suite() {
31     TestSuite suite = new TestSuite(GPGenotypeTest.class);
32     return suite;
33   }
34
35   public void setUp() {
36     super.setUp();
37   }
38
39   /**
40    * @throws Exception
41    *
42    * @author Klaus Meffert
43    * @since 3.0
44    */

45   public void testConstruct_0()
46       throws Exception JavaDoc {
47     GPPopulation pop = new GPPopulation(m_gpconf, 5);
48     try {
49       new GPGenotype(m_gpconf, pop, null, null, null, null, null, 1);
50       fail();
51     } catch (IllegalArgumentException JavaDoc iex) {
52       ; //this is OK
53
}
54   }
55
56   /**
57    * @throws Exception
58    *
59    * @author Klaus Meffert
60    * @since 3.0
61    */

62   public void testConstruct_1()
63       throws Exception JavaDoc {
64     GPPopulation pop = new GPPopulation(m_gpconf, 2);
65     GPProgram prog = new GPProgram(m_gpconf, 2);
66     ProgramChromosome chrom = new ProgramChromosome(m_gpconf, 2, prog);
67     prog.setChromosome(0, chrom);
68     prog.setChromosome(1, chrom);
69     pop.setGPProgram(0, prog);
70     pop.setGPProgram(1, prog);
71     GPGenotype gen = new GPGenotype(m_gpconf, pop, null, null, null, null, null,
72                                     1);
73     assertSame(pop, gen.getGPPopulation());
74   }
75
76   public void testRandomInitialize_0()
77       throws Exception JavaDoc {
78     Variable vx;
79     Class JavaDoc[] types = {
80         CommandGene.VoidClass, CommandGene.VoidClass, CommandGene.IntegerClass};
81     Class JavaDoc[][] argTypes = { {}, {}, {}
82     };
83     int[] minDepths = new int[] {3, 4, 1};
84     int[] maxDepths = new int[] {3, 4, 1};
85     CommandGene[][] nodeSets = { {
86         CMD_SUB_V_V, //0
87
CMD_CONST1, //1
88
new StoreTerminal(m_gpconf, "mem0", CommandGene.IntegerClass), //2
89
new StoreTerminal(m_gpconf, "mem1", CommandGene.IntegerClass), //3
90
}, {
91         vx = Variable.create(m_gpconf, "X", CommandGene.IntegerClass), //0
92
new AddAndStore(m_gpconf, CommandGene.IntegerClass, "mem2"), //1
93
CMD_FOR, //2
94
new TransferMemory(m_gpconf, "mem2", "mem1"), //3
95
new TransferMemory(m_gpconf, "mem1", "mem0"), //4
96
new ReadTerminal(m_gpconf, CommandGene.IntegerClass, "mem0"), //5
97
new ReadTerminal(m_gpconf, CommandGene.IntegerClass, "mem1"), //6
98
CMD_SUB_V_V_V, //7
99
new Increment(m_gpconf, CommandGene.IntegerClass, -1), //8
100
}, {
101     }
102     };
103     // Add commands working with internal memory.
104
// ------------------------------------------
105
nodeSets[2] = CommandFactory.createReadOnlyCommands(nodeSets[2], m_gpconf,
106         CommandGene.IntegerClass, "mem", 1, 2, !true);
107     // Execute the functionality to test.
108
// ----------------------------------
109
rn.setNextIntSequence(new int[] {0, 2, 1, 3, 1,
110                           2, 8, 0, 7, 1, 5, 6, 4, 3});
111     m_gpconf.setPopulationSize(1);
112     GPGenotype gen = GPGenotype.randomInitialGenotype(m_gpconf, types, argTypes,
113         nodeSets, minDepths, maxDepths, 200, new boolean[] {true, true, false}, false);
114     GPPopulation pop = gen.getGPPopulation();
115     assertEquals(m_gpconf.getPopulationSize(), pop.size());
116     // Evaluate program 1
117
// ------------------
118
IGPProgram p = pop.getGPProgram(0);
119     assertEquals(5, p.getChromosome(0).size());
120     assertEquals(CMD_SUB_V_V, p.getChromosome(0).getNode(0));
121     assertEquals(StoreTerminal.class, p.getChromosome(0).getNode(1).getClass());
122     assertSame(CMD_CONST1, p.getChromosome(0).getNode(2));
123     assertEquals(StoreTerminal.class, p.getChromosome(0).getNode(3).getClass());
124     assertSame(CMD_CONST1, p.getChromosome(0).getNode(4));
125     // Evaluate program 2
126
// ------------------
127
int node = 0;
128     assertEquals(9, p.getChromosome(1).size());
129     assertSame(CMD_FOR, p.getChromosome(1).getNode(node++));
130     assertEquals(Increment.class, p.getChromosome(1).getNode(node++).getClass());
131     assertEquals(Variable.class, p.getChromosome(1).getNode(node++).getClass());
132     assertEquals(CMD_SUB_V_V_V, p.getChromosome(1).getNode(node++));
133     assertEquals(AddAndStore.class, p.getChromosome(1).getNode(node++).getClass());
134     assertEquals(ReadTerminal.class,
135                  p.getChromosome(1).getNode(node++).getClass());
136     assertEquals(ReadTerminal.class,
137                  p.getChromosome(1).getNode(node++).getClass());
138     assertEquals(TransferMemory.class,
139                  p.getChromosome(1).getNode(node++).getClass());
140     assertEquals(TransferMemory.class,
141                  p.getChromosome(1).getNode(node++).getClass());
142     // Evaluate program 3
143
// ------------------
144
assertEquals(1, p.getChromosome(2).size());
145     assertEquals(ReadTerminal.class, p.getChromosome(2).getNode(0).getClass());
146     assertEquals(0.0, computeFitness(p, vx), DELTA);
147   }
148
149   private double computeFitness(IGPProgram a_program, Variable vx) {
150     double error = 0.0f;
151     Object JavaDoc[] noargs = new Object JavaDoc[0];
152     // Initialize local stores.
153
// ------------------------
154
a_program.getGPConfiguration().clearStack();
155     a_program.getGPConfiguration().clearMemory();
156     // Compute fitness for each program.
157
// ---------------------------------
158
for (int i = 2; i < 15; i++) {
159       for (int j = 0; j < a_program.size(); j++) {
160         vx.set(new Integer JavaDoc(i));
161         try {
162           try {
163             // Only evaluate after whole GP program was run.
164
// ---------------------------------------------
165
if (j == a_program.size() - 1) {
166               double result = a_program.execute_int(j, noargs);
167               error += Math.abs(result - fib_iter(i));
168             }
169             else {
170               a_program.execute_void(j, noargs);
171             }
172           } catch (IllegalStateException JavaDoc iex) {
173             error = Double.MAX_VALUE / 2;
174             break;
175           }
176         } catch (ArithmeticException JavaDoc ex) {
177           System.out.println("x = " + i);
178           System.out.println(a_program.getChromosome(j));
179           throw ex;
180         }
181       }
182     }
183     return error;
184   }
185
186   private int fib_iter(int a_index) {
187     // 1
188
if (a_index == 0 || a_index == 1) {
189       return 1;
190     }
191     // 2
192
int a = 1; //Store("mem0", Constant(1))
193
int b = 1; //Store("mem1", Constant(1))
194
int x = 0; //Store("mem2", Constant(0))
195
// 3
196
for (int i = 2; i <= a_index; i++) { //FORX (Subprogram(A;B;C))
197
x = a + b; // A: AddAndStore(Read("mem0"),Read("mem1"),"mem2")
198
a = b; //B: TransferMemory("mem1","mem0")
199
b = x; //C: TransferMemory("mem2","mem1")
200
}
201     return x; //Read("mem2")
202
}
203
204   /**
205    * @throws Exception
206    *
207    * @author Klaus Meffert
208    * @since 3.0
209    */

210   public void testSerialize_0()
211       throws Exception JavaDoc {
212     GPPopulation pop = new GPPopulation(m_gpconf, 2);
213     GPProgram prog = new GPProgram(m_gpconf, 2);
214     ProgramChromosome chrom = new ProgramChromosome(m_gpconf, 2, prog);
215     prog.setChromosome(0, chrom);
216     prog.setChromosome(1, chrom);
217     pop.setGPProgram(0, prog);
218     pop.setGPProgram(1, prog);
219     GPGenotype gen = new GPGenotype(m_gpconf, pop, null, null, null, null, null,
220                                     1);
221     // Serialize genotype to a file.
222
// -----------------------------
223
assertEquals(gen, doSerialize(gen));
224   }
225
226   /**
227    * Verifies that terminals are passed as clones during evolution and not
228    * as references. Thanx a lot Javier for pointing this out nicely!
229    *
230    * @throws Exception
231    *
232    * @author Klaus Meffert
233    * @since 3.2
234    */

235   public void testReferenceProblem_0()
236       throws Exception JavaDoc {
237     m_gpconf.setPopulationSize(30);
238     m_gpconf.setGPFitnessEvaluator(new DeltaGPFitnessEvaluator());
239     m_gpconf.setFitnessFunction(new TerminalsOnly());
240     m_gpconf.setRandomGenerator(new StockRandomGenerator());
241     //
242
Class JavaDoc[] types = {
243         CommandGene.IntegerClass};
244     Class JavaDoc[][] argTypes = { {}
245     };
246     CommandGene[][] nodeSets = { {
247         new Increment(m_gpconf, CommandGene.IntegerClass, 1),
248         new Terminal(m_gpconf, CommandGene.IntegerClass, 1.0d, 10000.0d),
249     }
250     };
251     GPGenotype gen = GPGenotype.randomInitialGenotype(m_gpconf, types, argTypes,
252         nodeSets, 10, false);
253     gen.getGPPopulation().sort(new TerminalsFirstComparator());
254     IGPProgram prog1 = gen.getGPPopulation().getGPProgram(0);
255     ProgramChromosome chrom1 = prog1.getChromosome(0);
256     Terminal gene1 = (Terminal) chrom1.getGene(0);
257     IGPProgram prog2 = gen.getGPPopulation().getGPProgram(1);
258     ProgramChromosome chrom2 = prog2.getChromosome(0);
259     Terminal gene2 = (Terminal) chrom2.getGene(0);
260     assertNotSame(gene1, gene2);
261   }
262
263   /**
264    * Verifies that for different genotypes different configurations are
265    * possible.
266    * @throws Exception
267    *
268    * @author Klaus Meffert
269    * @since 3.2
270    */

271   public void testConfigurationInstance_0() throws Exception JavaDoc {
272     Class JavaDoc[] types = {
273         CommandGene.IntegerClass};
274     Class JavaDoc[][] argTypes = { {}
275     };
276     CommandGene[][] nodeSets = { {
277         new Increment(m_gpconf, CommandGene.IntegerClass, 1),
278         new Terminal(m_gpconf, CommandGene.IntegerClass, 1.0d, 2.0d),
279     }
280     };
281     m_gpconf.setPopulationSize(30);
282     m_gpconf.setGPFitnessEvaluator(new DeltaGPFitnessEvaluator());
283     m_gpconf.setFitnessFunction(new TerminalsOnly());
284     m_gpconf.setRandomGenerator(new StockRandomGenerator());
285     GPGenotype gen1 = GPGenotype.randomInitialGenotype(m_gpconf, types, argTypes,
286         nodeSets, 10, false);
287     GPConfiguration conf2 = new GPConfiguration(m_gpconf.getId()+"_2","noname");
288     conf2.setPopulationSize(1);
289     conf2.setGPFitnessEvaluator(new DefaultGPFitnessEvaluator());
290     conf2.setFitnessFunction(new TerminalsOnly());
291     conf2.setRandomGenerator(new StockRandomGenerator());
292     GPGenotype gen2 = GPGenotype.randomInitialGenotype(conf2, types, argTypes,
293         nodeSets, 4, false);
294     assertNotSame(gen1, gen2);
295     assertNotSame(gen1.getGPConfiguration(), gen2.getGPConfiguration());
296     assertEquals(30, gen1.getGPConfiguration().getPopulationSize());
297     assertEquals(1, gen2.getGPConfiguration().getPopulationSize());
298   }
299
300   class TerminalsOnly
301       extends GPFitnessFunction {
302     protected double evaluate(IGPProgram a_subject) {
303       ProgramChromosome chrom1 = a_subject.getChromosome(0);
304       CommandGene gene1 = chrom1.getGene(0);
305       if (gene1 instanceof Terminal) {
306         return gene1.execute_double(null, 0, new Object JavaDoc[] {});
307       }
308       else {
309         return 999999.0d;
310       }
311     }
312   }
313   class TerminalsFirstComparator
314       implements java.util.Comparator JavaDoc {
315     public int compare(Object JavaDoc o1, Object JavaDoc o2) {
316       IGPProgram prog1 = (IGPProgram)o1;
317       IGPProgram prog2 = (IGPProgram)o2;
318       CommandGene gene1 = prog1.getChromosome(0).getGene(0);
319       CommandGene gene2 = prog2.getChromosome(0).getGene(0);
320       boolean o1is, o2is;
321       if (gene1 instanceof Terminal) {
322         o1is = true;
323       }
324       else {
325         o1is = false;
326       }
327       if (gene2 instanceof Terminal) {
328         o2is = true;
329       }
330       else {
331         o2is = false;
332       }
333       if (o1is) {
334         if (o2is) {
335           return 0;
336         }
337         else {
338           return -1;
339         }
340       }
341       else {
342         if (o2is) {
343           return 1;
344         }
345         else {
346           return 0;
347         }
348       }
349     }
350
351     public boolean equals(Object JavaDoc obj) {
352       return compare(this, obj) == 0;
353     }
354   }
355 }
356
Popular Tags