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