001 /*
002 * Java Genetic Algorithm Library (jenetics-5.1.0).
003 * Copyright (c) 2007-2019 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.0
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 getSampleSize() {
089 return _sampleSize;
090 }
091
092 @Override
093 public ISeq<Phenotype<G, C>> select(
094 final Seq<Phenotype<G, C>> population,
095 final int count,
096 final Optimize opt
097 ) {
098 requireNonNull(population, "Population");
099 requireNonNull(opt, "Optimization");
100 if (count < 0) {
101 throw new IllegalArgumentException(format(
102 "Selection count must be greater or equal then zero, but was %s",
103 count
104 ));
105 }
106
107 final Random random = RandomRegistry.getRandom();
108 return population.isEmpty()
109 ? ISeq.empty()
110 : MSeq.<Phenotype<G, C>>ofLength(count)
111 .fill(() -> select(population, opt, random))
112 .toISeq();
113 }
114
115 private Phenotype<G, C> select(
116 final Seq<Phenotype<G, C>> population,
117 final Optimize opt,
118 final Random random
119 ) {
120 final int N = population.size();
121
122 assert _sampleSize >= 2;
123 assert N >= 1;
124
125 return Stream.generate(() -> population.get(random.nextInt(N)))
126 .limit(_sampleSize)
127 .max(opt.ascending())
128 .orElseThrow(AssertionError::new);
129 }
130
131 @Override
132 public String toString() {
133 return format("%s[s=%d]", getClass().getSimpleName(), _sampleSize);
134 }
135
136 }
|