01 package org.jenetics.ext;
02
03 import static java.lang.String.format;
04 import static java.util.Objects.requireNonNull;
05
06 import org.jenetics.Gene;
07 import org.jenetics.Optimize;
08 import org.jenetics.Phenotype;
09 import org.jenetics.Population;
10 import org.jenetics.Selector;
11 import org.jenetics.stat.MinMax;
12
13 /**
14 * Selector implementation which is part of the
15 * <a href="https://en.wikipedia.org/wiki/Weasel_program">Weasel program</a>
16 * algorithm. The <i>Weasel program</i> is an thought experiment by Richard
17 * Dawkins to illustrate the functioning of the evolution: random <i>mutation</i>
18 * combined with non-random cumulative <i>selection</i>.
19 * <p>
20 * The selector always returns populations which only contains "{@code count}"
21 * instances of the <i>best</i> {@link Phenotype}.
22 * </p>
23 * {@link org.jenetics.engine.Engine} setup for the <i>Weasel program:</i>
24 * <pre>{@code
25 * final Engine<CharacterGene, Integer> engine = Engine
26 * .builder(fitness, gtf)
27 * // Set the 'WeaselSelector'.
28 * .selector(new WeaselSelector<>())
29 * // Disable survivors selector.
30 * .offspringFraction(1)
31 * // Set the 'WeaselMutator'.
32 * .alterers(new WeaselMutator<>(0.05))
33 * .build();
34 * }</pre>
35 *
36 * @see <a href="https://en.wikipedia.org/wiki/Weasel_program">Weasel program</a>
37 * @see WeaselMutator
38 *
39 * @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
40 * @since 3.5
41 * @version 3.5
42 */
43 public class WeaselSelector<
44 G extends Gene<?, G>,
45 C extends Comparable<? super C>
46 >
47 implements Selector<G, C>
48 {
49 @Override
50 public Population<G, C> select(
51 final Population<G, C> population,
52 final int count,
53 final Optimize opt
54 ) {
55 requireNonNull(population, "Population");
56 requireNonNull(opt, "Optimization");
57 if (count < 0) {
58 throw new IllegalArgumentException(format(
59 "Selection count must be greater or equal then zero, but was %s",
60 count
61 ));
62 }
63
64 final MinMax<Phenotype<G, C>> minMax = population.stream()
65 .collect(MinMax.toMinMax(opt.ascending()));
66
67 return new Population<G, C>(count).fill(minMax::getMax, count);
68 }
69 }
|