KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > examples > equalDistribution > 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.equalDistribution;
11
12 import org.jgap.*;
13 import org.jgap.impl.*;
14
15 /**
16  * Fitness function for our example. See method evaluate(..).
17  *
18  * @author Klaus Meffert
19  * @since 3.2
20  */

21 public class SampleFitnessFunction
22     extends FitnessFunction {
23   /** String containing the CVS revision. Read out via reflection!*/
24   private final static String JavaDoc CVS_REVISION = "$Revision: 1.1 $";
25
26   private Vent[] m_vents;
27
28   public SampleFitnessFunction(Vent[] a_vents) {
29     m_vents = a_vents;
30   }
31
32   /**
33    * Calculates the difference in weight between the 8 groups of vents. The
34    * lower the different the better the solution.
35    *
36    * @param a_subject the Chromosome to be evaluated
37    * @return fitness of our problem (smaller is better here)
38    *
39    * @author Klaus Meffert
40    * @since 3.2
41    */

42   public double evaluate(IChromosome a_subject) {
43     double[] groupWeights = new double[8];
44     double squaredDiff = 0.0d;
45     for (int i = 0; i < 8; i++) {
46       double groupWeight = 0.0d;
47       for (int j = 0; j < 8; j++) {
48         IntegerGene ventIndex = (IntegerGene) a_subject.getGene( (i * 8 + j));
49         Vent vent = (Vent) m_vents[ventIndex.intValue()];
50         groupWeight += vent.getWeight();
51       }
52       if (i > 0) {
53         for (int k = 0; k < i; k++) {
54           double diff = Math.abs(groupWeight - groupWeights[k]);
55           squaredDiff += diff * diff;
56         }
57       }
58       groupWeights[i] = groupWeight;
59     }
60     return squaredDiff;
61   }
62 }
63
Popular Tags