TournamentSelector.java
001 /*
002  * Java Genetic Algorithm Library (jenetics-4.1.0).
003  * Copyright (c) 2007-2018 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@gmail.com)
019  */
020 package io.jenetics;
021 
022 import static java.lang.String.format;
023 import static java.util.Objects.requireNonNull;
024 
025 import java.util.Random;
026 import java.util.stream.Stream;
027 
028 import io.jenetics.internal.util.Equality;
029 import io.jenetics.internal.util.Hash;
030 import io.jenetics.util.ISeq;
031 import io.jenetics.util.MSeq;
032 import io.jenetics.util.RandomRegistry;
033 import io.jenetics.util.Seq;
034 
035 /**
036  * In tournament selection the best individual from a random sample of <i>s</i>
037  * individuals is chosen from the population <i>P<sub>g</sub></i>. The samples
038  * are drawn with replacement. An individual will win a tournament only if its
039  * fitness is greater than the fitness of the other <i>s-1</i>  competitors.
040  * Note that the worst individual never survives, and the best individual wins
041  * in all the tournaments it participates. The selection pressure can be varied
042  * by changing the tournament size <i>s</i> . For large values of <i>s</i>, weak
043  * individuals have less chance being selected.
044  *
045  @see <a href="http://en.wikipedia.org/wiki/Tournament_selection">Tournament selection</a>
046  *
047  @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
048  @since 1.0
049  @version 4.0
050  */
051 public class TournamentSelector<
052     extends Gene<?, G>,
053     extends Comparable<? super C>
054 >
055     implements Selector<G, C>
056 {
057 
058     private final int _sampleSize;
059 
060     /**
061      * Create a tournament selector with the give sample size. The sample size
062      * must be greater than one.
063      *
064      @param sampleSize the number of individuals involved in one tournament
065      @throws IllegalArgumentException if the sample size is smaller than two.
066      */
067     public TournamentSelector(final int sampleSize) {
068         if (sampleSize < 2) {
069             throw new IllegalArgumentException(
070                 "Sample size must be greater than one, but was " + sampleSize
071             );
072         }
073         _sampleSize = sampleSize;
074     }
075 
076     /**
077      * Create a tournament selector with sample size two.
078      */
079     public TournamentSelector() {
080         this(2);
081     }
082 
083     @Override
084     public ISeq<Phenotype<G, C>> select(
085         final Seq<Phenotype<G, C>> population,
086         final int count,
087         final Optimize opt
088     ) {
089         requireNonNull(population, "Population");
090         requireNonNull(opt, "Optimization");
091         if (count < 0) {
092             throw new IllegalArgumentException(format(
093                 "Selection count must be greater or equal then zero, but was %s",
094                 count
095             ));
096         }
097 
098         final Random random = RandomRegistry.getRandom();
099         return population.isEmpty()
100             ? ISeq.empty()
101             : MSeq.<Phenotype<G, C>>ofLength(count)
102                 .fill(() -> select(population, opt, _sampleSize, random))
103                 .toISeq();
104     }
105 
106     private Phenotype<G, C> select(
107         final Seq<Phenotype<G, C>> population,
108         final Optimize opt,
109         final int sampleSize,
110         final Random random
111     ) {
112         final int N = population.size();
113         return Stream.generate(() -> population.get(random.nextInt(N)))
114             .limit(sampleSize)
115             .max(opt.ascending())
116             .orElseThrow(IllegalStateException::new);
117     }
118 
119     @Override
120     public int hashCode() {
121         return Hash.of(getClass()).and(_sampleSize).value();
122     }
123 
124     @Override
125     public boolean equals(final Object obj) {
126         return Equality.of(this, obj).test(s -> _sampleSize == s._sampleSize);
127     }
128 
129     @Override
130     public String toString() {
131         return format("%s[s=%d]", getClass().getSimpleName(), _sampleSize);
132     }
133 
134 }