TournamentSelector.java
001 /*
002  * Java Genetic Algorithm Library (jenetics-2.0.2).
003  * Copyright (c) 2007-2014 Franz Wilhelmstötter
004  *
005  * Licensed under the Apache License, Version 2.0 (the "License");
006  * you may not use this file except in compliance with the License.
007  * You may obtain a copy of the License at
008  *
009  *      http://www.apache.org/licenses/LICENSE-2.0
010  *
011  * Unless required by applicable law or agreed to in writing, software
012  * distributed under the License is distributed on an "AS IS" BASIS,
013  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014  * See the License for the specific language governing permissions and
015  * limitations under the License.
016  *
017  * Author:
018  *    Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)
019  */
020 package org.jenetics;
021 
022 import static java.lang.String.format;
023 import static java.util.Objects.requireNonNull;
024 
025 import java.util.Random;
026 
027 import org.jenetics.internal.util.HashBuilder;
028 
029 import org.jenetics.util.Factory;
030 import org.jenetics.util.RandomRegistry;
031 
032 /**
033  * In tournament selection the best individual from a random sample of <i>s</i>
034  * individuals is chosen from the population <i>P<sub>g</sub></i>. The samples
035  * are drawn with replacement. An individual will win a tournament only if its
036  * fitness is greater than the fitness of the other <i>s-1</i>  competitors.
037  * Note that the worst individual never survives, and the best individual wins
038  * in all the tournaments it participates. The selection pressure can be varied
039  * by changing the tournament size <i>s</i> . For large values of <i>s</i>, weak
040  * individuals have less chance being selected.
041  *
042  @see <a href="http://en.wikipedia.org/wiki/Tournament_selection">Tournament selection</a>
043  *
044  @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
045  @since 1.0
046  @version 2.0 &mdash; <em>$Date: 2014-08-12 $</em>
047  */
048 public class TournamentSelector<
049     extends Gene<?, G>,
050     extends Comparable<? super C>
051 >
052     implements Selector<G, C>
053 {
054 
055     private final int _sampleSize;
056 
057     /**
058      * Create a tournament selector with the give sample size. The sample size
059      * must be greater than one.
060      *
061      @param sampleSize the number of individuals involved in one tournament
062      @throws IllegalArgumentException if the sample size is smaller than two.
063      */
064     public TournamentSelector(final int sampleSize) {
065         if (sampleSize < 2) {
066             throw new IllegalArgumentException(
067                 "Sample size must be greater than one, but was " + sampleSize
068             );
069         }
070         _sampleSize = sampleSize;
071     }
072 
073     /**
074      * Create a tournament selector with sample size two.
075      */
076     public TournamentSelector() {
077         this(2);
078     }
079 
080     @Override
081     public Population<G, C> select(
082         final Population<G, C> population,
083         final int count,
084         final Optimize opt
085     ) {
086         requireNonNull(population, "Population");
087         requireNonNull(opt, "Optimization");
088         if (count < 0) {
089             throw new IllegalArgumentException(format(
090                 "Selection count must be greater or equal then zero, but was %s",
091                 count
092             ));
093         }
094 
095         final Population<G, C> pop = new Population<>(count);
096         final Factory<Phenotype<G, C>> factory = factory(
097             population, opt, _sampleSize, RandomRegistry.getRandom()
098         );
099 
100         return pop.fill(factory, count);
101     }
102 
103     private static <
104         extends Gene<?, G>,
105         extends Comparable<? super C>
106     >
107     Factory<Phenotype<G, C>> factory(
108         final Population<G, C> population,
109         final Optimize opt,
110         final int sampleSize,
111         final Random random
112     ) {
113         return new Factory<Phenotype<G, C>>() {
114             @Override
115             public Phenotype<G, C> newInstance() {
116                 return select(population, opt, sampleSize, random);
117             }
118         };
119     }
120 
121     private static <
122         extends Gene<?, G>,
123         extends Comparable<? super C>
124     >
125     Phenotype<G, C> select(
126         final Population<G, C> population,
127         final Optimize opt,
128         final int sampleSize,
129         final Random random
130     ) {
131         final int N = population.size();
132         Phenotype<G, C> winner = population.get(random.nextInt(N));
133 
134         for (int j = 0; j < sampleSize; ++j) {
135             final Phenotype<G, C> selection = population.get(random.nextInt(N));
136             if (opt.compare(selection, winner0) {
137                 winner = selection;
138             }
139         }
140         assert (winner != null);
141 
142         return winner;
143     }
144 
145     @Override
146     public int hashCode() {
147         return HashBuilder.of(getClass()).and(_sampleSize).value();
148     }
149 
150     @Override
151     public boolean equals(final Object obj) {
152         if (obj == this) {
153             return true;
154         }
155         if (obj == null || obj.getClass() != getClass()) {
156             return false;
157         }
158 
159         final TournamentSelector<?, ?> selector = (TournamentSelector<?, ?>)obj;
160         return _sampleSize == selector._sampleSize;
161     }
162 
163     @Override
164     public String toString() {
165         return format("%s[s=%d]", getClass().getSimpleName(), _sampleSize);
166     }
167 
168 }