01 /*
02 * Java Genetic Algorithm Library (jenetics-5.0.0).
03 * Copyright (c) 2007-2019 Franz Wilhelmstötter
04 *
05 * Licensed under the Apache License, Version 2.0 (the "License");
06 * you may not use this file except in compliance with the License.
07 * You may obtain a copy of the License at
08 *
09 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 * Author:
18 * Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com)
19 */
20 package io.jenetics;
21
22 import static io.jenetics.stat.DoubleSummary.min;
23
24 import java.util.Arrays;
25
26 import io.jenetics.internal.math.DoubleAdder;
27 import io.jenetics.util.Seq;
28
29 /**
30 * The roulette-wheel selector is also known as fitness proportional selector,
31 * but in the <em>Jenetics</em> library it is implemented as probability selector.
32 * The fitness value <i>f<sub>i</sub></i> is used to calculate the selection
33 * probability of individual <i>i</i>.
34 *
35 * @see <a href="http://en.wikipedia.org/wiki/Roulette_wheel_selection">
36 * Wikipedia: Roulette wheel selection
37 * </a>
38 *
39 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
40 * @since 1.0
41 * @version 5.0
42 */
43 public class RouletteWheelSelector<
44 G extends Gene<?, G>,
45 N extends Number & Comparable<? super N>
46 >
47 extends ProbabilitySelector<G, N>
48 {
49
50 public RouletteWheelSelector() {
51 this(false);
52 }
53
54 protected RouletteWheelSelector(final boolean sorted) {
55 super(sorted);
56 }
57
58 @Override
59 protected double[] probabilities(
60 final Seq<Phenotype<G, N>> population,
61 final int count
62 ) {
63 assert population != null : "Population must not be null. ";
64 assert population.nonEmpty() : "Population is empty.";
65 assert count > 0 : "Population to select must be greater than zero. ";
66
67 // Copy the fitness values to probabilities arrays.
68 final double[] fitness = new double[population.size()];
69 for (int i = population.size(); --i >= 0;) {
70 fitness[i] = population.get(i).getFitness().doubleValue();
71 }
72
73 final double worst = Math.min(min(fitness), 0.0);
74 final double sum = DoubleAdder.sum(fitness) - worst*population.size();
75
76 if (eq(sum, 0.0)) {
77 Arrays.fill(fitness, 1.0/population.size());
78 } else {
79 for (int i = population.size(); --i >= 0;) {
80 fitness[i] = (fitness[i] - worst)/sum;
81 }
82 }
83
84 return fitness;
85 }
86
87 @Override
88 public String toString() {
89 return getClass().getSimpleName();
90 }
91
92 }
|