KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jgap > GenotypeTest


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;
11
12 import java.util.*;
13 import org.jgap.impl.*;
14 import org.jgap.util.*;
15 import junit.framework.*;
16
17 /**
18  * Tests the Genotype class.
19  *
20  * @author Klaus Meffert
21  * @since 1.1
22  */

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

44   public void testConstruct_0()
45       throws Exception JavaDoc {
46     try {
47       new Genotype(null, new Population(conf, 0));
48       fail();
49     }
50     catch (IllegalArgumentException JavaDoc invex) {
51       ; //this is OK
52
}
53   }
54
55   /**
56    * Unproper Configuration (e.g. fitness function not set)
57    * @throws Exception
58    *
59    * @author Klaus Meffert
60    * @since 3.0
61    */

62   public void testConstruct_02()
63       throws Exception JavaDoc {
64     conf = new DefaultConfiguration();
65     try {
66       new Genotype(conf, new Population(conf, 0));
67       fail();
68     }
69     catch (InvalidConfigurationException invex) {
70       ; //this is OK
71
}
72   }
73
74   /**
75    * @throws Exception
76    *
77    * @author Klaus Meffert
78    * @since 2.0
79    */

80   public void testConstruct_1()
81       throws Exception JavaDoc {
82     try {
83       Population pop = null;
84       new Genotype(new DefaultConfiguration(), pop);
85       fail();
86     }
87     catch (IllegalArgumentException JavaDoc invex) {
88       ; //this is OK
89
}
90   }
91
92   /**
93    * @throws Exception
94    *
95    * @author Klaus Meffert
96    * @since 2.0
97    */

98   public void testConstruct_2()
99       throws Exception JavaDoc {
100     Chromosome[] chroms = new Chromosome[1];
101     chroms[0] = new Chromosome(new ConfigurationForTest(), new Gene[] {
102       new IntegerGene(new ConfigurationForTest(), 1, 5)
103     });
104     try {
105       new Genotype(null, chroms);
106       fail();
107     }
108     catch (InvalidConfigurationException invex) {
109       ; //this is OK
110
}
111     catch (IllegalArgumentException JavaDoc invex) {
112       ; //this is OK
113
}
114   }
115
116   /**
117    * @throws Exception
118    *
119    * @author Klaus Meffert
120    * @since 2.0
121    */

122   public void testConstruct_3()
123       throws Exception JavaDoc {
124     Chromosome[] chroms = new Chromosome[1];
125     chroms[0] = new Chromosome(conf, new Gene[] {
126       new IntegerGene(conf, 1, 5)
127     });
128     try {
129       new Genotype(new DefaultConfiguration(), chroms);
130       fail();
131     }
132     catch (InvalidConfigurationException invex) {
133       ; //this is OK
134
}
135   }
136
137   /**
138    * @throws Exception
139    *
140    * @author Klaus Meffert
141    * @since 2.0
142    */

143   public void testConstruct_4()
144       throws Exception JavaDoc {
145     Configuration conf = new DefaultConfiguration();
146     Chromosome[] chroms = new Chromosome[1];
147     chroms[0] = new Chromosome(conf, new Gene[] {
148                                new IntegerGene(conf, 1, 5)});
149     conf.setFitnessFunction(new StaticFitnessFunction(5));
150     try {
151       new Genotype(conf, chroms);
152       fail();
153     }
154     catch (InvalidConfigurationException invex) {
155       ; //this is OK
156
}
157   }
158
159   /**
160    * @throws Exception
161    *
162    * @author Klaus Meffert
163    * @since 2.0
164    */

165   public void testConstruct_5()
166       throws Exception JavaDoc {
167     Configuration conf = new DefaultConfiguration();
168     Chromosome[] chroms = new Chromosome[1];
169     chroms[0] = new Chromosome(conf, new Gene[] {
170                                new IntegerGene(conf, 1, 5)});
171     conf.setFitnessFunction(new StaticFitnessFunction(5));
172     conf.setSampleChromosome(new Chromosome(conf, new BooleanGene(conf), 9));
173     try {
174       new Genotype(conf, chroms);
175       fail();
176     }
177     catch (InvalidConfigurationException invex) {
178       ; //this is OK
179
}
180   }
181
182   /**
183    * @throws Exception
184    *
185    * @author Klaus Meffert
186    * @since 2.0
187    */

188   public void testConstruct_6()
189       throws Exception JavaDoc {
190     Configuration conf = new DefaultConfiguration();
191     Chromosome[] chroms = new Chromosome[1];
192     chroms[0] = new Chromosome(conf, new Gene[] {
193                                new IntegerGene(conf, 1, 5)});
194     conf.setFitnessFunction(new StaticFitnessFunction(5));
195     conf.setSampleChromosome(new Chromosome(conf, new BooleanGene(conf), 9));
196     conf.setPopulationSize(7);
197     Genotype genotype = new Genotype(conf, chroms);
198     assertTrue(genotype.getConfiguration().getFitnessEvaluator()
199                instanceof DefaultFitnessEvaluator);
200     assertSame(conf, genotype.getConfiguration());
201   }
202
203   /**
204    * @throws Exception
205    *
206    * @author Klaus Meffert
207    * @since 2.0
208    */

209   public void testConstruct_7()
210       throws Exception JavaDoc {
211     Configuration conf = new DefaultConfiguration();
212     conf.setFitnessFunction(new StaticFitnessFunction(5));
213     conf.setSampleChromosome(new Chromosome(conf, new BooleanGene(conf), 9));
214     conf.setPopulationSize(7);
215     try {
216       new Genotype(conf, new Chromosome[] {null});
217       fail();
218     }
219     catch (IllegalArgumentException JavaDoc illex) {
220       ; //this is OK
221
}
222   }
223
224   /**
225    * Tests that construction is possible without exception. Here, the sample
226    * chromosome is of a different type than the chromosome(s) making up the
227    * population. This is possible because the sample chromosome comes into play
228    * just with Genotype.randomInitialGenotype.
229    *
230    * @throws Exception
231    *
232    * @author Klaus Meffert
233    * @since 2.0
234    */

235   public void testConstruct_8()
236       throws Exception JavaDoc {
237     Chromosome[] chroms = new Chromosome[1];
238     chroms[0] = new Chromosome(conf, new Gene[] {
239                                new IntegerGene(conf, 1, 5)});
240     conf.setFitnessFunction(new StaticFitnessFunction(5));
241     conf.setSampleChromosome(new Chromosome(conf, new BooleanGene(conf), 9));
242     conf.setPopulationSize(7);
243     new Genotype(conf, chroms);
244   }
245
246   /**
247    * @throws Exception
248    *
249    * @author Klaus Meffert
250    * @since 2.0
251    */

252   public void testConstruct_9()
253       throws Exception JavaDoc {
254     Chromosome[] chroms = new Chromosome[1];
255     Configuration conf = new DefaultConfiguration();
256     conf.setFitnessFunction(new StaticFitnessFunction(5));
257     conf.setSampleChromosome(new Chromosome(conf, new BooleanGene(conf), 9));
258     conf.setPopulationSize(7);
259     try {
260       new Genotype(conf, chroms);
261       fail();
262     }
263     catch (IllegalArgumentException JavaDoc iex) {
264       ; //this is OK
265
}
266   }
267
268   /**
269    * @throws Exception
270    *
271    * @author Klaus Meffert
272    * @since 2.0
273    */

274   public void testGetChromosomes_0()
275       throws Exception JavaDoc {
276     Configuration conf = new DefaultConfiguration();
277     conf.setFitnessFunction(new StaticFitnessFunction(5));
278     Chromosome[] chroms = new Chromosome[1];
279     Chromosome chrom = new Chromosome(conf, new Gene[] {
280                                       new IntegerGene(conf, 1, 5)});
281     chroms[0] = chrom;
282     conf.setSampleChromosome(chrom);
283     conf.setPopulationSize(7);
284     Genotype genotype = new Genotype(conf, chroms);
285     assertEquals(1, genotype.getChromosomes().length);
286     assertEquals(chrom, genotype.getChromosomes()[0]);
287   }
288
289   /**
290    * @throws Exception
291    *
292    * @author Klaus Meffert
293    * @since 2.0
294    */

295   public void testGetFittestChromosome_0()
296       throws Exception JavaDoc {
297     Configuration conf = new DefaultConfiguration();
298     conf.setFitnessFunction(new StaticFitnessFunction(5));
299     Chromosome[] chroms = new Chromosome[1];
300     Chromosome chrom = new Chromosome(conf, new Gene[] {
301                                       new IntegerGene(conf, 1, 5)});
302     chroms[0] = chrom;
303     conf.setSampleChromosome(chrom);
304     conf.setPopulationSize(7);
305     Genotype genotype = new Genotype(conf, chroms);
306     privateAccessor.setField(genotype, "m_population", new Population(conf, 1));
307     assertEquals(null, genotype.getFittestChromosome());
308   }
309
310   /**
311    * @throws Exception
312    *
313    * @author Klaus Meffert
314    * @since 2.0
315    */

316   public void testGetFittestChromosome_1()
317       throws Exception JavaDoc {
318     Configuration conf = new DefaultConfiguration();
319     conf.setFitnessFunction(new StaticFitnessFunction(5));
320     IChromosome[] chroms = new Chromosome[1];
321     IChromosome chrom = new Chromosome(conf, new Gene[] {
322                                        new IntegerGene(conf, 1, 5)});
323     chroms[0] = chrom;
324     conf.setSampleChromosome(chrom);
325     conf.setPopulationSize(7);
326     Genotype genotype = new Genotype(conf, chroms);
327     IChromosome chrom2 = genotype.getFittestChromosome();
328     assertEquals(chrom, chrom2);
329   }
330
331   /**
332    * @throws Exception
333    *
334    * @author Klaus Meffert
335    * @since 2.6
336    */

337   public void testGetFittestChromosomes_0()
338       throws Exception JavaDoc {
339     Configuration conf = new DefaultConfiguration();
340     conf.setFitnessFunction(new StaticFitnessFunction(5));
341     Chromosome[] chroms = new Chromosome[1];
342     Chromosome chrom = new Chromosome(conf, new Gene[] {
343                                       new IntegerGene(conf, 1, 5)});
344     chroms[0] = chrom;
345     conf.setSampleChromosome(chrom);
346     conf.setPopulationSize(7);
347     Genotype genotype = new Genotype(conf, chroms);
348     List l = genotype.getFittestChromosomes(1);
349     Chromosome chrom2 = (Chromosome) l.get(0);
350     assertEquals(chrom, chrom2);
351   }
352
353   /**
354    * Assert population size shrinks when using special configuration and by
355    * overwriting default setting for keeping population size constant
356    * @throws Exception
357    *
358    * @author Klaus Meffert
359    * @since 2.3
360    */

361   public void testEvolve_0()
362       throws Exception JavaDoc {
363     Configuration config = new ConfigurationForTest();
364     // Remove all natural selectors
365
config.removeNaturalSelectors(false);
366     config.removeNaturalSelectors(true);
367     config.setKeepPopulationSizeConstant(false);
368     // Add new NaturalSelector
369
config.addNaturalSelector(new WeightedRouletteSelector(config), true);
370     Genotype genotype = Genotype.randomInitialGenotype(config);
371     int popSize = config.getPopulationSize()
372         * config.getSampleChromosome().getGenes().length;
373     genotype.evolve(1);
374     assertTrue(popSize >= genotype.getPopulation().size());
375   }
376
377   /**
378    * Test evolve with BulkFitnessFunction.
379    *
380    * @throws Exception
381    *
382    * @author Klaus Meffert
383    * @since 2.3
384    */

385   public void testEvolve_1()
386       throws Exception JavaDoc {
387     // override setFF in order to set the BulkFitnessFunction although
388
// ConfigurationForTest set an ordinary FF beforehand
389
Configuration config = new ConfigurationForTest() {
390       public synchronized void setFitnessFunction(FitnessFunction
391                                                   a_functionToSet)
392           throws InvalidConfigurationException {
393         setBulkFitnessFunction(new BulkFitnessOffsetRemover(a_functionToSet));
394       }
395     };
396     Genotype genotype = Genotype.randomInitialGenotype(config);
397     // Just test that the following runs without error by trusting exception
398
// handling
399
genotype.evolve();
400   }
401
402   /**
403    * Test that population size remains constant when the configuration contains
404    * a BCS as postselector.
405    *
406    * @throws Exception
407    *
408    * @author Klaus Meffert
409    * @since 2.3
410    */

411   public void testEvolve_2_1()
412       throws Exception JavaDoc {
413     Configuration config = new ConfigurationForTest();
414     config.setKeepPopulationSizeConstant(false);
415     // Remove all natural selectors
416
config.removeNaturalSelectors(false);
417     config.removeNaturalSelectors(true);
418     BestChromosomesSelector bcs = new BestChromosomesSelector(config);
419     bcs.setOriginalRate(1);
420     bcs.setDoubletteChromosomesAllowed(true);
421     config.addNaturalSelector(bcs, false);
422     Genotype genotype = Genotype.randomInitialGenotype(config);
423     int popSize = config.getPopulationSize();
424     genotype.evolve();
425     assertEquals(popSize, genotype.getPopulation().size());
426   }
427
428   /**
429    * Test that multiple NaturalSelector's work without error
430    * @throws Exception
431    *
432    * @author Klaus Meffert
433    * @since 2.3
434    */

435   public void testEvolve_2_2()
436       throws Exception JavaDoc {
437     Configuration config = new ConfigurationForTest();
438     // Add another NaturalSelector (others already exist within
439
// ConfigurationForTest)
440
BestChromosomesSelector bcs = new BestChromosomesSelector(config);
441     bcs.setOriginalRate(1);
442     bcs.setDoubletteChromosomesAllowed(true);
443     config.addNaturalSelector(bcs, false);
444     Genotype genotype = Genotype.randomInitialGenotype(config);
445     int popSize = config.getPopulationSize();
446     genotype.evolve();
447     assertEquals(popSize, genotype.getPopulation().size());
448   }
449
450   /**
451    * Test that population size remains constant with default settings.
452    *
453    * @throws Exception
454    *
455    * @author Klaus Meffert
456    * @since 2.4
457    */

458   public void testEvolve_3_1()
459       throws Exception JavaDoc {
460     Configuration config = new ConfigurationForTest();
461     config.setKeepPopulationSizeConstant(true);
462     Genotype genotype = Genotype.randomInitialGenotype(config);
463     int popSize = config.getPopulationSize();
464     genotype.evolve(2);
465     assertEquals(popSize, genotype.getPopulation().size());
466   }
467
468   /**
469    * Test that population size grows with default settings overwritten.
470    *
471    * @throws Exception
472    *
473    * @author Klaus Meffert
474    * @since 2.4
475    */

476   public void testEvolve_3_2()
477       throws Exception JavaDoc {
478     Configuration config = new ConfigurationForTest();
479     // Overwrite default setting
480
config.setKeepPopulationSizeConstant(!true);
481     Genotype genotype = Genotype.randomInitialGenotype(config);
482     int popSize = config.getPopulationSize();
483     genotype.evolve();
484     assertTrue(popSize < genotype.getPopulation().size());
485   }
486
487   /**
488    * Expect exception when no natural selectors are provided.
489    *
490    * @throws Exception
491    *
492    * @author Klaus Meffert
493    * @since 3.3
494    */

495   public void testEvolve_3_3()
496       throws Exception JavaDoc {
497     Configuration config = new ConfigurationForTest();
498     // Remove all natural selectors
499
config.removeNaturalSelectors(false);
500     config.removeNaturalSelectors(true);
501     try {
502       Genotype.randomInitialGenotype(config);
503       fail();
504     } catch (InvalidConfigurationException iex) {
505       ; //this is OK
506
}
507   }
508
509   /**
510    * Test that for new chromosomes (e.g. mutated ones) their fitness value
511    * will be recomputed. Reveals bug 1368072.
512    *
513    * @throws Exception
514    *
515    * @author Klaus Meffert
516    * @since 2.5
517    */

518   public void testEvolve_5_1()
519       throws Exception JavaDoc {
520     Configuration config = new ConfigurationForTest();
521     Gene[] genes = new Gene[] {
522         new BooleanGene(conf)};
523     Configuration.resetProperty(Configuration.PROPERTY_SAMPLE_CHROM_INST);
524     config.setSampleChromosome(new ChromosomeForTest(config, genes));
525     config.setPreservFittestIndividual(true);
526     config.setKeepPopulationSizeConstant(true);
527     BestChromosomesSelector sel = (BestChromosomesSelector) config.
528         getNaturalSelector(true, 0);
529     sel.setDoubletteChromosomesAllowed(true);
530     config.getGeneticOperators().clear();
531     SwappingMutationOperator op = new SwappingMutationOperator(config, 1);
532     op.setStartOffset(0); // because size is 1
533
config.addGeneticOperator(op);
534     assertTrue(doTestEvolve_5(config) > 0);
535   }
536
537   /**
538    * Test that for new chromosomes (e.g. mutated ones) their fitness value
539    * will be recomputed. Reveals bug 1368072.
540    *
541    * @throws Exception
542    *
543    * @author Klaus Meffert
544    * @since 2.5
545    */

546   public void testEvolve_5_2()
547       throws Exception JavaDoc {
548     Configuration config = new ConfigurationForTest();
549     Gene[] genes = new Gene[] {
550         new BooleanGene(conf)};
551     Configuration.resetProperty(Configuration.PROPERTY_SAMPLE_CHROM_INST);
552     config.setSampleChromosome(new ChromosomeForTest(config, genes));
553     config.setPreservFittestIndividual(true);
554     config.setKeepPopulationSizeConstant(true);
555     BestChromosomesSelector sel = (BestChromosomesSelector) config.
556         getNaturalSelector(true, 0);
557     sel.setDoubletteChromosomesAllowed(true);
558     config.getGeneticOperators().clear();
559     config.addGeneticOperator(new MutationOperator(config, 1));
560     assertTrue(doTestEvolve_5(config) > 0);
561   }
562
563   /**
564    * Test that for new chromosomes (e.g. mutated ones) their fitness value
565    * will only be recomputed if necessary. Special case in which bug 1368072
566    * does not apply.
567    *
568    * @throws Exception
569    *
570    * @author Klaus Meffert
571    * @since 2.5
572    */

573   public void testEvolve_5_3()
574       throws Exception JavaDoc {
575     Configuration config = new ConfigurationForTest();
576     Gene[] genes = new Gene[] {
577         new BooleanGene(conf)};
578     Configuration.resetProperty(Configuration.PROPERTY_SAMPLE_CHROM_INST);
579     config.setSampleChromosome(new ChromosomeForTest(config, genes));
580     config.setPreservFittestIndividual(true);
581     config.setKeepPopulationSizeConstant(true);
582     BestChromosomesSelector sel = (BestChromosomesSelector) config.
583         getNaturalSelector(true, 0);
584     sel.setDoubletteChromosomesAllowed(true);
585     config.getGeneticOperators().clear();
586     config.addGeneticOperator(new MutationOperator(config, 0));
587     assertEquals(0, doTestEvolve_5(config));
588   }
589
590   /**
591    * Helper: used in tests for evolve method
592    * @param config Configuration
593    * @throws Exception
594    * @return number of times the fitness value has been computed for the first
595    * chromosome
596    *
597    * @author Klaus Meffert
598    * @since 2.5
599    */

600   private int doTestEvolve_5(Configuration config)
601       throws Exception JavaDoc {
602     Genotype genotype = Genotype.randomInitialGenotype(config);
603     genotype.evolve(2);
604     // Reset counter. Because of static state holder we only need to do this
605
// for one chromosome referencing the same global state holder as well as
606
// all other chromosomes (of class ChromosomeForTest) do.
607
ChromosomeForTest chrom = (ChromosomeForTest) genotype.getPopulation().
608         getChromosome(0);
609     chrom.resetComputedTimes();
610     // Mark any chromosome as original (that is not cloned)
611
for (int i = 0; i < genotype.getPopulation().size(); i++) {
612       chrom = (ChromosomeForTest) genotype.getPopulation().getChromosome(i);
613       chrom.resetIsCloned();
614     }
615     // Now do the test evolution --> new fitness values must be recomputed!
616
genotype.evolve(2);
617     // Check if global state holder indicates that getFitnessValue() has been
618
// called at least once for a cloned (e.g. mutated) chromosome and that for
619
// this call the to date fitness value is initial (i.e. not set).
620
chrom = (ChromosomeForTest) genotype.getPopulation().
621         getChromosome(0);
622     return chrom.getComputedTimes();
623   }
624
625   /**
626    * Population is null.
627    *
628    * @throws Exception
629    *
630    * @author Klaus Meffert
631    * @since 2.6
632    */

633   public void testEvolve_6()
634       throws Exception JavaDoc {
635     Configuration config = new ConfigurationForTest();
636     Genotype genotype = Genotype.randomInitialGenotype(config);
637     genotype.setPopulation(null);
638     try {
639       genotype.evolve();
640       fail();
641     }
642     catch (NullPointerException JavaDoc iex) {
643       ; // this is OK
644
}
645   }
646
647   /**
648    * minimumPopSizePercent > 0.
649    *
650    * @throws Exception
651    *
652    * @author Klaus Meffert
653    * @since 2.6
654    */

655   public void testEvolve_7()
656       throws Exception JavaDoc {
657     Configuration config = new ConfigurationForTest();
658     config.setMinimumPopSizePercent(290);
659     // Overwrite default setting
660
config.setKeepPopulationSizeConstant(!true);
661     config.setPopulationSize(10);
662     config.setPreservFittestIndividual(false);
663     Genotype genotype = Genotype.randomInitialGenotype(config);
664     genotype.evolve(1);
665     assertEquals( (int) (10 * 290.0 / 100), genotype.getPopulation().size());
666   }
667
668   /**
669    * Preserve fittest Chromosome.
670    *
671    * @throws Exception
672    *
673    * @author Klaus Meffert
674    * @since 2.6
675    */

676   public void testEvolve_8()
677       throws Exception JavaDoc {
678     Configuration config = new ConfigurationForTest();
679     config.setMinimumPopSizePercent(290);
680     // Overwrite default setting
681
config.setKeepPopulationSizeConstant(!true);
682     config.setPopulationSize(10);
683     config.setPreservFittestIndividual(true);
684     Genotype genotype = Genotype.randomInitialGenotype(config);
685     genotype.evolve(1);
686     IChromosome fittest = genotype.getFittestChromosome();
687     genotype.evolve(1);
688     assertEquals(fittest, genotype.getFittestChromosome());
689   }
690
691   /**
692    * Preserve fittest Chromosome.
693    *
694    * @throws Exception
695    *
696    * @author Klaus Meffert
697    * @since 3.0
698    */

699   public void testEvolve_9()
700       throws Exception JavaDoc {
701     Configuration config = new ConfigurationForTest();
702     config.setMinimumPopSizePercent(290);
703     // Overwrite default setting
704
config.setKeepPopulationSizeConstant(!true);
705     config.setPopulationSize(10);
706     config.setPreservFittestIndividual(true);
707     Genotype genotype = Genotype.randomInitialGenotype(config);
708     genotype.evolve(1);
709   }
710
711   /**
712    * @throws Exception
713    *
714    * @author Klaus Meffert
715    * @since 2.0
716    */

717   public void testToString_0()
718       throws Exception JavaDoc {
719     Configuration conf = new DefaultConfiguration();
720     conf.setFitnessFunction(new StaticFitnessFunction(5));
721     Chromosome[] chroms = new Chromosome[1];
722     Chromosome chrom = new Chromosome(conf, new Gene[] {
723                                       new IntegerGene(conf, 1, 55)});
724     chroms[0] = chrom;
725     conf.setSampleChromosome(chrom);
726     conf.setPopulationSize(7);
727     Genotype genotype = new Genotype(conf, chroms);
728     assertTrue(genotype.toString() != null);
729     assertTrue(genotype.toString().length() > 0);
730     assertEquals(IChromosome.S_SIZE + ":1, "
731                  + IChromosome.S_FITNESS_VALUE + ":"
732                  + FitnessFunction.NO_FITNESS_VALUE
733                  + ", "
734                  + IChromosome.S_ALLELES + ":[IntegerGene(1,55)=null], "
735                  + IChromosome.S_APPLICATION_DATA + ":null"
736                  + " ["
737                  + FitnessFunction.NO_FITNESS_VALUE
738                  + "]\n", genotype.toString());
739   }
740
741   /**
742    * Same as testToString_0 except that fitness value is computed
743    * @throws Exception
744    *
745    * @author Klaus Meffert
746    * @since 2.6
747    */

748   public void testToString_1()
749       throws Exception JavaDoc {
750     final double fitnessvalue = 5.0d;
751     Configuration conf = new DefaultConfiguration();
752     conf.setFitnessFunction(new StaticFitnessFunction(fitnessvalue));
753     Chromosome[] chroms = new Chromosome[1];
754     Chromosome chrom = new Chromosome(conf, new Gene[] {
755                                       new IntegerGene(conf, 1, 55)});
756     chroms[0] = chrom;
757     conf.setSampleChromosome(chrom);
758     conf.setPopulationSize(7);
759     Genotype genotype = new Genotype(conf, chroms);
760     assertTrue(genotype.toString() != null);
761     assertTrue(genotype.toString().length() > 0);
762     // compute fitness of Genotype thus of all contained chromosomes
763
genotype.getFittestChromosome();
764     assertEquals(IChromosome.S_SIZE + ":1, "
765                  + IChromosome.S_FITNESS_VALUE + ":"
766                  + fitnessvalue
767                  + ", "
768                  + IChromosome.S_ALLELES + ":[IntegerGene(1,55)=null], "
769                  + IChromosome.S_APPLICATION_DATA + ":null"
770                  + " ["
771                  + fitnessvalue
772                  + "]\n", genotype.toString());
773   }
774
775   /**
776    * @throws Exception
777    *
778    * @author Klaus Meffert
779    * @since 2.0
780    */

781   public void testRandomInitialGenotype_0()
782       throws Exception JavaDoc {
783     try {
784       Genotype.randomInitialGenotype(null);
785       fail();
786     }
787     catch (IllegalArgumentException JavaDoc illex) {
788       ; //this is OK
789
}
790   }
791
792   /**
793    * @throws Exception
794    *
795    * @author Klaus Meffert
796    * @since 2.0
797    */

798   public void testRandomInitialGenotype_1()
799       throws Exception JavaDoc {
800     Configuration conf = new DefaultConfiguration();
801     Chromosome chrom = new Chromosome(conf, new Gene[] {
802                                       new IntegerGene(conf, 1, 9999)});
803     conf.setPopulationSize(7777);
804     conf.setFitnessFunction(new StaticFitnessFunction(5));
805     conf.setSampleChromosome(chrom);
806     Genotype genotype = Genotype.randomInitialGenotype(conf);
807     assertEquals(7777, genotype.getChromosomes().length);
808   }
809
810   /**
811    * Test for a Chromosome class not equal to org.jgap.Chromosome
812    * @throws Exception
813    *
814    * @author Klaus Meffert
815    * @since 2.6
816    */

817   public void testRandomInitialGenotype_2()
818       throws Exception JavaDoc {
819     Configuration conf = new DefaultConfiguration();
820     Gene aGene = new IntegerGene(conf, 1, 9999);
821     aGene.setEnergy(22.3d);
822     Chromosome chrom = new ChromosomeForTest2(conf, new Gene[] {aGene});
823     conf.setPopulationSize(7777);
824     conf.setFitnessFunction(new StaticFitnessFunction(5));
825     conf.setSampleChromosome(chrom);
826     Genotype genotype = Genotype.randomInitialGenotype(conf);
827     assertEquals(7777, genotype.getPopulation().size());
828     Chromosome c = (Chromosome) genotype.getPopulation().getChromosome(0);
829     Gene g = c.getGene(0);
830     assertEquals(aGene.getEnergy(), g.getEnergy(), DELTA);
831   }
832
833   /**
834    * @throws Exception
835    *
836    * @author Klaus Meffert
837    * @since 2.6
838    */

839   public void testRandomInitialGenotype_3()
840       throws Exception JavaDoc {
841     Configuration conf = new DefaultConfiguration();
842     IChromosome chrom = new MyChromosome(conf);
843     conf.setPopulationSize(7777);
844     conf.setFitnessFunction(new StaticFitnessFunction(5));
845     conf.setSampleChromosome(chrom);
846     try {
847       Genotype.randomInitialGenotype(conf);
848       fail();
849     }
850     catch (IllegalStateException JavaDoc iex) {
851       ; //this is OK
852
}
853   }
854
855   /**
856    * GeneticOperators missing
857    * @throws Exception
858    *
859    * @author Klaus Meffert
860    * @since 2.3
861    */

862   public void testRandomInitialGenotype_4()
863       throws Exception JavaDoc {
864     Configuration config = new ConfigurationForTest();
865     // Remove all genetic operators
866
config.getGeneticOperators().clear();
867     config.addNaturalSelector(new WeightedRouletteSelector(), true);
868     try {
869       Genotype.randomInitialGenotype(config);
870       fail();
871     }
872     catch (InvalidConfigurationException iex) {
873       ; //this is OK
874
}
875   }
876
877   /**
878    * @throws Exception
879    *
880    * @author Klaus Meffert
881    * @since 2.0
882    */

883   public void testEquals_0()
884       throws Exception JavaDoc {
885     Configuration conf = new DefaultConfiguration();
886     conf.setFitnessFunction(new StaticFitnessFunction(5));
887     conf.setSampleChromosome(new Chromosome(conf, new BooleanGene(conf), 9));
888     conf.setPopulationSize(99999);
889     Chromosome[] chroms = new Chromosome[1];
890     chroms[0] = new Chromosome(conf, new Gene[] {new IntegerGene(conf, 1, 5)});
891     Genotype genotype = new Genotype(conf, chroms);
892     assertNotNull(genotype);
893     Genotype genotype2 = new Genotype(conf, chroms);
894     assertTrue(genotype.equals(genotype2));
895     assertEquals(genotype.toString(), genotype2.toString());
896     assertEquals(genotype.toString(), genotype2.toString());
897     assertFalse(genotype.equals(new Chromosome(conf)));
898   }
899
900   /**
901    * @throws Exception
902    *
903    * @author Klaus Meffert
904    * @since 2.6
905    */

906   public void testEquals_1()
907       throws Exception JavaDoc {
908     Configuration conf = new DefaultConfiguration();
909     conf.setFitnessFunction(new StaticFitnessFunction(5));
910     conf.setSampleChromosome(new Chromosome(conf, new BooleanGene(conf), 9));
911     conf.setPopulationSize(99999);
912     Chromosome[] chroms = new Chromosome[1];
913     chroms[0] = new Chromosome(conf, new Gene[] {
914                                new IntegerGene(conf, 1, 5)});
915     Genotype genotype = new Genotype(conf, chroms);
916     Chromosome[] chroms2 = new Chromosome[2];
917     chroms2[0] = new Chromosome(conf, new Gene[] {new IntegerGene(conf, 1, 5)});
918     chroms2[1] = new Chromosome(conf, new Gene[] {new IntegerGene(conf, 2, 4)});
919     Genotype genotype2 = new Genotype(conf, chroms2);
920     assertFalse(genotype.equals(genotype2));
921   }
922
923   /**
924    * @throws Exception
925    *
926    * @author Klaus Meffert
927    * @since 2.6
928    */

929   public void testEquals_2()
930       throws Exception JavaDoc {
931     Configuration conf = new DefaultConfiguration();
932     conf.setFitnessFunction(new StaticFitnessFunction(5));
933     conf.setSampleChromosome(new Chromosome(conf, new BooleanGene(conf), 9));
934     conf.setPopulationSize(99999);
935     Chromosome[] chroms = new Chromosome[1];
936     chroms[0] = new Chromosome(conf, new Gene[] {
937                                new IntegerGene(conf, 1, 5)});
938     Genotype genotype = new Genotype(conf, chroms);
939     assertFalse(genotype.equals(null));
940   }
941
942   /**
943    * Test if hashcode working in general.
944    *
945    * @throws Exception
946    *
947    * @author Klaus Meffert
948    * @author John Serri
949    * @since 2.1
950    */

951   public void testHashcode_0()
952       throws Exception JavaDoc {
953     Configuration conf = new DefaultConfiguration();
954     conf.setFitnessFunction(new StaticFitnessFunction(5));
955     conf.setSampleChromosome(new Chromosome(conf, new BooleanGene(conf), 9));
956     conf.setPopulationSize(99999);
957     Chromosome[] chroms = new Chromosome[1];
958     chroms[0] = new Chromosome(conf, new Gene[] {
959                                new IntegerGene(conf, 1, 5)});
960     Genotype genotype = new Genotype(conf, chroms);
961     genotype.hashCode();
962   }
963
964   private final static int MAX_CHROMOSOME_TO_TEST = 1000;
965
966   private final static int MAX_GENES_TO_TEST = 25;
967
968   private final static int MAX_GENES_TYPES = 6;
969
970   public void testHashcode_1()
971       throws Exception JavaDoc {
972     int Count;
973     int NumGenes;
974     int GeneCount;
975     int GeneType;
976     Gene[] genes;
977     Chromosome chrom;
978     TestHashcode thc = new TestHashcode();
979     thc.setVerbose(!true);
980     List UniqueChromosome = new ArrayList();
981     List EqualChromosome = new ArrayList();
982     Genotype geno;
983     //Build random Chromosomes
984
for (Count = 0; Count < MAX_CHROMOSOME_TO_TEST; Count++) {
985       NumGenes = (int) (Math.random() * MAX_GENES_TO_TEST) + 1;
986       genes = new Gene[NumGenes];
987       for (GeneCount = 0; GeneCount < NumGenes; GeneCount++) {
988         GeneType = (int) (Math.random() * MAX_GENES_TYPES);
989         switch (GeneType) {
990           case 0:
991             genes[GeneCount] = new IntegerGene(conf);
992             break;
993           case 1:
994             genes[GeneCount] = new BooleanGene(conf);
995             break;
996           case 2:
997             genes[GeneCount] = new CompositeGene(conf);
998             break;
999           case 3:
1000            genes[GeneCount] = new DoubleGene(conf);
1001            break;
1002          case 4:
1003            genes[GeneCount] = new FixedBinaryGene(conf, 5);
1004            break;
1005          case 5:
1006            genes[GeneCount] = new StringGene(conf);
1007            break;
1008        }
1009      }
1010      Configuration.reset();
1011      Configuration conf = new DefaultConfiguration();
1012      chrom = new Chromosome(conf, genes);
1013      conf.setFitnessFunction(new StaticFitnessFunction(0.5d));
1014      conf.setSampleChromosome(chrom);
1015      conf.setPopulationSize(5);
1016      Population pop = new Population(conf);
1017      pop.addChromosome(chrom);
1018      geno = new Genotype(conf, pop);
1019      // We only want to add unique object, since equal object will return the
1020
// same hashcode
1021
if (UniqueChromosome.contains(geno) == false) {
1022        UniqueChromosome.add(geno);
1023      }
1024    }
1025    //Test to see if enough hashcodes are unique
1026
thc.setFractionUnique(.95);
1027    if (!thc.testHashCodeUniqueness(UniqueChromosome)) {
1028      System.out.println(
1029          "testHashCodeUniqueness failed\n Actual Percent unique = " +
1030          thc.getActualFractionUnique());
1031      fail();
1032    }
1033    //Test mathematical average and dispersion of hashcode
1034
//I am not sure of the value of this test since boundary values are
1035
//pretty much arbitrary
1036
// thc.setAverageMax(16500000);
1037
// thc.setAverageMin(14000);
1038
// thc.setStdDevMax(2100000000);
1039
// thc.setStdDevMin(90000);
1040
// if (thc.testDispersion(UniqueChromosome) == false) {
1041
// fail();
1042
// }
1043

1044    //Build identical Chromosomes
1045
for (Count = 0; Count < 3; Count++) {
1046      genes = new Gene[1];
1047      genes[0] = new IntegerGene(conf);
1048      Configuration.reset();
1049      Configuration conf = new DefaultConfiguration();
1050      chrom = new Chromosome(conf, genes);
1051      conf.setFitnessFunction(new StaticFitnessFunction(0.5d));
1052      conf.setSampleChromosome(chrom);
1053      conf.setPopulationSize(5);
1054      Population pop = new Population(conf);
1055      pop.addChromosome(chrom);
1056      geno = new Genotype(conf, pop);
1057      EqualChromosome.add(geno);
1058    }
1059    //If an object is equal it must have the same hashcode
1060
if (!thc.testHashCodeEquality(EqualChromosome)) {
1061      fail();
1062    }
1063  }
1064
1065  /**
1066   * This test fails and shows the need for revamping configuration object
1067   * handling.
1068   * @throws Exception
1069   *
1070   * @author Klaus Meffert
1071   */

1072// public void testSetActiveConfiguration_0()
1073
// throws Exception {
1074
// Configuration conf = new ConfigurationForTest();
1075
// Chromosome[] chroms = new Chromosome[1];
1076
// chroms[0] = new Chromosome(conf, new Gene[] {
1077
// new IntegerGene(conf, 1, 5)});
1078
// Genotype genotype = new Genotype(conf, chroms);
1079
// genotype.setActiveConfiguration(conf);
1080
// genotype.setActiveConfiguration(null);
1081
// // If working properly, the next call should return null!
1082
// assertNotNull(genotype.getConfiguration());
1083
// }
1084
//
1085
// public void testSetActiveConfiguration_1()
1086
// throws Exception {
1087
// Configuration conf = new ConfigurationForTest();
1088
// Chromosome[] chroms = new Chromosome[1];
1089
// chroms[0] = new Chromosome(conf, new Gene[] {
1090
// new IntegerGene(conf, 1, 5)});
1091
// Genotype genotype = new Genotype(conf, chroms);
1092
// Genotype.setConfiguration(null);
1093
// try {
1094
// genotype.setActiveConfiguration(null);
1095
// fail();
1096
// }
1097
// catch (InvalidConfigurationException iex) {
1098
// ; //this is OK
1099
// }
1100
// }
1101
//
1102
// /**
1103
// * @throws Exception
1104
// * @author Klaus Meffert
1105
// * @since 2.6
1106
// */
1107
// public void testSetActiveConfiguration_2()
1108
// throws Exception {
1109
// Configuration conf = new ConfigurationForTest();
1110
// Chromosome[] chroms = new Chromosome[1];
1111
// chroms[0] = new Chromosome(conf, new Gene[] {
1112
// new IntegerGene(conf, 1, 5)});
1113
// Genotype genotype = new Genotype(conf, chroms);
1114
// /**@todo following will be obsolete*/
1115
// genotype.setConfiguration(null);
1116
// Configuration conf2 = new ConfigurationForTest();
1117
// genotype.setActiveConfiguration(conf2);
1118
// assertTrue(genotype.getConfiguration().isLocked());
1119
// }
1120

1121  /**
1122   * Ensures Genotype is implementing Serializable.
1123   * @throws Exception
1124   *
1125   * @author Klaus Meffert
1126   * @since 2.3
1127   */

1128  public void testIsSerializable_0()
1129      throws Exception JavaDoc {
1130    Configuration conf = new ConfigurationForTest();
1131    Chromosome[] chroms = new Chromosome[1];
1132    chroms[0] = new Chromosome(conf, new Gene[] {
1133                               new IntegerGene(conf, 1, 5)});
1134    assertTrue(isSerializable(new Genotype(conf, chroms)));
1135  }
1136
1137  /**
1138   * Ensures that Genotype and all objects contained implement Serializable.
1139   * @throws Exception
1140   *
1141   * @author Klaus Meffert
1142   * @since 2.3
1143   */

1144  public void testdoSerialize_0()
1145      throws Exception JavaDoc {
1146    // construct genotype to be serialized
1147
Configuration conf = new ConfigurationForTest();
1148    Chromosome[] chroms = new Chromosome[1];
1149    chroms[0] = new Chromosome(conf, new Gene[] {
1150                               new IntegerGene(conf, 1, 5)});
1151    Genotype genotype = new Genotype(conf, chroms);
1152    // Serialize genotype to a file.
1153
// -----------------------------
1154
assertEquals(genotype, super.doSerialize(genotype));
1155  }
1156
1157  public class ChromosomeForTest2
1158      extends ChromosomeForTest {
1159    public ChromosomeForTest2(Configuration a_config,
1160                              final Gene[] a_initialGenes)
1161        throws InvalidConfigurationException {
1162      super(a_config, a_initialGenes);
1163    }
1164
1165    public boolean isHandlerFor(Class JavaDoc a_class) {
1166      if (a_class == ChromosomeForTest2.class) {
1167        return true;
1168      }
1169      else {
1170        return false;
1171      }
1172    }
1173
1174    public Object JavaDoc perform(Object JavaDoc a_obj, Class JavaDoc a_class, Object JavaDoc a_params)
1175        throws Exception JavaDoc {
1176      return randomInitialChromosome2();
1177    }
1178  }
1179  public class MyChromosome
1180      implements IChromosome {
1181    private transient Configuration m_conf;
1182
1183    public MyChromosome(Configuration a_conf) {
1184      m_conf = a_conf;
1185    }
1186
1187    public Gene getGene(int a_desiredLocus) {
1188      try {
1189        return new IntegerGene(m_conf);
1190      }
1191      catch (InvalidConfigurationException iex) {
1192        throw new IllegalStateException JavaDoc(iex.getMessage());
1193      }
1194    }
1195
1196    public Gene[] getGenes() {
1197      return new Gene[] {};
1198    }
1199
1200    public int size() {
1201      return 1;
1202    }
1203
1204    public void setFitnessValue(double a_newFitnessValue) {
1205    }
1206
1207    public double getFitnessValue() {
1208      return 0;
1209    }
1210
1211    public void setFitnessValueDirectly(double a_newFitnessValue) {
1212    }
1213
1214    public double getFitnessValueDirectly() {
1215      return getFitnessValue();
1216    }
1217
1218    public int compareTo(Object JavaDoc other) {
1219      return 0;
1220    }
1221
1222    public void setGenes(Gene[] a_genes)
1223        throws InvalidConfigurationException {
1224    }
1225
1226    public void setIsSelectedForNextGeneration(boolean a_isSelected) {
1227    }
1228
1229    public boolean isSelectedForNextGeneration() {
1230      return true;
1231    }
1232
1233    public Object JavaDoc clone() {
1234      return null;
1235    }
1236
1237    public void setConstraintChecker(IGeneConstraintChecker a_constraintChecker)
1238        throws InvalidConfigurationException {
1239    }
1240
1241    public void setApplicationData(Object JavaDoc a_newData) {
1242    }
1243
1244    public Object JavaDoc getApplicationData() {
1245      return null;
1246    }
1247
1248    public void cleanup() {
1249    }
1250
1251    public Configuration getConfiguration() {
1252      return m_conf;
1253    }
1254  }
1255}
1256
Popular Tags