KickJava   Java API By Example, From Geeks To Geeks.

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


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.io.*;
13 import org.jgap.*;
14 import org.jgap.gp.*;
15
16 /**
17  * A GP tournament selector.
18  *
19  * @author Javier Meseguer
20  * @author Enrique D. Martí
21  * @since 3.2
22  */

23 public class TournamentSelector
24     implements INaturalGPSelector, Serializable {
25   /** String containing the CVS revision. Read out via reflection!*/
26   private final static String JavaDoc CVS_REVISION = "$Revision: 1.1 $";
27
28   private int tournament_size;
29
30   /**
31    * Constructor with default tournament size.
32    *
33    * @since 3.2
34    */

35   public TournamentSelector() {
36     this(5);
37   }
38
39   /**
40    * Preferred Constructor.
41    *
42    * @param a_tournament_size the size of the tournament
43    *
44    * @since 3.2
45    */

46   public TournamentSelector(int a_tournament_size) {
47     tournament_size = a_tournament_size;
48   }
49
50   /**
51    * Does the tournament selection.
52    *
53    * @param a_genotype the genotype containing the competers
54    * @return program that won the tournament
55    *
56    * @author Javier Meseguer
57    * @author Enrique D. Martí
58    * @since 3.2
59    */

60   public IGPProgram select(GPGenotype a_genotype) {
61     GPPopulation pop = a_genotype.getGPPopulation();
62     IGPProgram bestProgram = null;
63     int index = 0;
64     RandomGenerator random = a_genotype.getGPConfiguration().getRandomGenerator();
65     IGPFitnessEvaluator evaluator = a_genotype.getGPConfiguration().
66         getGPFitnessEvaluator();
67     for (int i = 0; i < tournament_size; i++) {
68       index = (int) (random.nextDouble() * pop.getPopSize());
69       if (bestProgram == null) {
70         bestProgram = pop.getGPProgram(index);
71       }
72       else {
73         if (evaluator.isFitter(pop.getGPProgram(index), bestProgram)) {
74           bestProgram = pop.getGPProgram(index);
75         }
76       }
77     }
78     return bestProgram;
79   }
80 }
81
Popular Tags