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.grid.mathProblemDistributed;
11:
12: import java.util.*;
13:
14: import org.jgap.gp.*;
15: import org.jgap.gp.terminal.*;
16: import org.apache.log4j.*;
17:
18: /**
19: * Fitness function for our example.
20: *
21: * @author Klaus Meffert
22: * @since 3.2
23: */
24: public class SampleFitnessFunction extends GPFitnessFunction {
25: /** String containing the CVS revision. Read out via reflection!*/
26: private final static String CVS_REVISION = "$Revision: 1.5 $";
27:
28: private static Logger log = Logger
29: .getLogger(SampleFitnessFunction.class);
30:
31: static Variable vx;
32:
33: static Float[] x = new Float[20];
34: /**@todo initialize*/
35:
36: static float[] y = new float[20];
37:
38: /**@todo initialize*/
39:
40: public SampleFitnessFunction() {
41: Random random = new Random();
42: // Randomly initialize function data (X-Y table) for x^4+x^3+x^2-x
43: // ---------------------------------------------------------------
44: for (int i = 0; i < 20; i++) {
45: float f = 8.0f * (random.nextFloat() - 0.3f);
46: x[i] = new Float(f);
47: y[i] = f * f * f * f + f * f * f + f * f - f;
48: log.debug(i + ") " + x[i] + " " + y[i]);
49: }
50: }
51:
52: protected double evaluate(final IGPProgram a_subject) {
53: return computeRawFitness(a_subject);
54: }
55:
56: public double computeRawFitness(final IGPProgram ind) {
57: double error = 0.0f;
58: Object[] noargs = new Object[0];
59: Variable vx = ind.getGPConfiguration().getVariable("X");
60: if (vx == null) {
61: log.error("Variable X not initialized correctly!");
62: return GPFitnessFunction.MAX_FITNESS_VALUE;
63: }
64: for (int i = 0; i < 20; i++) {
65: vx.set(x[i]);
66: try {
67: double result = ind.execute_float(0, noargs);
68: error += Math.abs(result - y[i]);
69: } catch (ArithmeticException ex) {
70: System.out.println("x = " + x[i].floatValue());
71: System.out.println(ind);
72: throw ex;
73: }
74: }
75: if (error < 0.000001) {
76: error = 0.0d;
77: }
78: return error;
79: }
80: }
|