KickJava   Java API By Example, From Geeks To Geeks.

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


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 java.util.Comparator JavaDoc;
13 import org.jgap.*;
14
15 import org.jgap.gp.*;
16
17 /**
18  * Simple comparator to allow the sorting of GPProgram lists with the highest
19  * fitness value in first place of the list.
20  * Usage example:
21  * Arrays.sort(
22  * population.getGPPrograms(),
23  * new GPProgramFitnessComparator() );
24  *
25  * @author Klaus Meffert
26  * @since 3.0
27  */

28 public class GPProgramFitnessComparator
29     implements Comparator JavaDoc {
30   /** String containing the CVS revision. Read out via reflection!*/
31   private final static String JavaDoc CVS_REVISION = "$Revision: 1.3 $";
32
33   private IGPFitnessEvaluator m_fitnessEvaluator;
34
35   /**
36    * Constructs the comparator using the DefaultFitnessEvaluator
37    *
38    * @author Klaus Meffert
39    * @since 3.0
40    */

41   public GPProgramFitnessComparator() {
42     this(new DefaultGPFitnessEvaluator());
43   }
44
45   /**
46    * @param a_evaluator the fitness evaluator to use
47    *
48    * @author Klaus Meffert
49    * @since 3.0
50    */

51   public GPProgramFitnessComparator(IGPFitnessEvaluator a_evaluator) {
52     if (a_evaluator == null) {
53       throw new IllegalArgumentException JavaDoc("Evaluator must not be null");
54     }
55     m_fitnessEvaluator = a_evaluator;
56   }
57
58   /**
59    * Compares two programs by using a FitnessEvaluator.
60    *
61    * @param a_program1 the first program to compare
62    * @param a_program2 the second program to compare
63    * @return -1 if a_program1 is fitter than a_program2, 1 if it is the other
64    * way round and 0 if both are equal
65    *
66    * @author Klaus Meffert
67    * @since 3.0
68    */

69   public int compare(final Object JavaDoc a_program1, final Object JavaDoc a_program2) {
70     IGPProgram progOne = (IGPProgram) a_program1;
71     IGPProgram progTwo = (IGPProgram) a_program2;
72     if (m_fitnessEvaluator.isFitter(progOne, progTwo)) {
73       return -1;
74     }
75     else if (m_fitnessEvaluator.isFitter(progTwo, progOne)) {
76       return 1;
77     }
78     else {
79       return 0;
80     }
81   }
82 }
83
Popular Tags