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