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