KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > examples > distinctGenes > SampleFitnessFunction


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 examples.distinctGenes;
11
12 import org.jgap.*;
13 import org.jgap.impl.*;
14
15 /**
16  * Fitness function for our example. It's without sense, it's just to
17  * demonstrate how to evaluate a chromosome with 40 4-field-genes and one
18  * 3-field gene. Each toplevel-gene is a CompositeGene, each "field" within
19  * a CompositeGene is a BooleanGene here (arbitrarily chosen).
20  *
21  * @author Klaus Meffert
22  * @since 3.0
23  */

24 public class SampleFitnessFunction
25     extends FitnessFunction {
26   /** String containing the CVS revision. Read out via reflection!*/
27   private final static String JavaDoc CVS_REVISION = "$Revision: 1.2 $";
28
29   /**
30    * Calculate the fitness value of a Chromosome.
31    * @param a_subject the Chromosome to be evaluated
32    * @return defect rate of our problem (the smaller the better)
33    *
34    * @author Klaus Meffert
35    * @since 3.0
36    */

37   public double evaluate(IChromosome a_subject) {
38     int total = 0;
39     // Process the first 40 genes with 4 fields per gene
40
for (int i = 0; i < a_subject.size() - 1; i++) {
41       CompositeGene gene = (CompositeGene) a_subject.getGene(i);
42       for (int j = 0; j < 4; j++) {
43         // Now evaluate the fields within the gene somehow (here: just an
44
// example without sense).
45
// --------------------------------------------------------------
46
BooleanGene field = (BooleanGene) gene.geneAt(j);
47         if (field.booleanValue() == true) {
48           // A field with value true is seen as defect
49
total++;
50         }
51       }
52     }
53     // Process the last gene with 3 fields. Here, a field with value false
54
// is seen as defect (in opposition to the other genes)
55
CompositeGene gene = (CompositeGene) a_subject.getGene(a_subject.size() - 1);
56     for (int j = 0; j < 3; j++) {
57       BooleanGene field = (BooleanGene) gene.geneAt(j);
58       if (field.booleanValue() == false) {
59         // A field with value false is seen as defect
60
total++;
61       }
62     }
63     return total;
64   }
65 }
66
Popular Tags