TruncationSelector.java
001 /*
002  * Java Genetic Algorithm Library (jenetics-3.9.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@gmx.at)
019  */
020 package org.jenetics;
021 
022 import static java.lang.Math.min;
023 import static java.lang.String.format;
024 import static java.util.Objects.requireNonNull;
025 
026 import org.jenetics.internal.util.Equality;
027 import org.jenetics.internal.util.Hash;
028 
029 /**
030  * In truncation selection individuals are sorted according to their fitness.
031  * Only the n  best individuals are selected. The truncation selection is a very
032  * basic selection algorithm. It has it's strength in fast selecting individuals
033  * in large populations, but is not very often used in practice.
034  *
035  @see <a href="http://en.wikipedia.org/wiki/Truncation_selection">
036  *          Wikipedia: Truncation selection
037  *      </a>
038  *
039  @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
040  @since 1.0
041  @version 3.8
042  */
043 public final class TruncationSelector<
044     extends Gene<?, G>,
045     extends Comparable<? super C>
046 >
047     implements Selector<G, C>
048 {
049 
050     private final int _n;
051 
052     /**
053      * Create a new {@code TruncationSelector} object, where the worst selected
054      * individual has rank {@code n}. This means, if you want to select
055      * {@code count} individuals, the worst selected individual has rank
056      * {@code n}. If {@code count > n}, the selected population will contain
057      <em>duplicate</em> individuals.
058      *
059      @since 3.8
060      *
061      @param n the worst rank of the selected individuals
062      @throws IllegalArgumentException if {@code n < 1}
063      */
064     public TruncationSelector(final int n) {
065         if (n < 1) {
066             throw new IllegalArgumentException(format(
067                 "n must be greater or equal 1, but was %d.", n
068             ));
069         }
070 
071         _n = n;
072     }
073 
074     /**
075      * Create a new TruncationSelector object.
076      */
077     public TruncationSelector() {
078         this(Integer.MAX_VALUE);
079     }
080 
081     /**
082      * This method sorts the population in descending order while calculating
083      * the selection probabilities. (The method
084      {@link Population#sortWith(java.util.Comparator)} )} is called by this
085      * method.) If the selection size is greater the the population size, the
086      * whole population is duplicated until the desired sample size is reached.
087      *
088      @throws NullPointerException if the {@code population} or {@code opt} is
089      *         {@code null}.
090      */
091     @Override
092     public Population<G, C> select(
093         final Population<G, C> population,
094         final int count,
095         final Optimize opt
096     ) {
097         requireNonNull(population, "Population");
098         requireNonNull(opt, "Optimization");
099         if (count < 0) {
100             throw new IllegalArgumentException(format(
101                 "Selection count must be greater or equal then zero, but was %s",
102                 count
103             ));
104         }
105 
106         final Population<G, C> selection = new Population<>(count);
107         if (count > && !population.isEmpty()) {
108             final Population<G, C> copy = population.copy();
109             copy.sortWith(opt.<C>descending());
110 
111             int size = count;
112             do {
113                 final int length = min(min(copy.size(), size), _n);
114                 selection.addAll(copy.subList(0, length));
115                 size -= length;
116             while (size > 0);
117         }
118 
119         return selection;
120     }
121 
122     @Override
123     public int hashCode() {
124         return Hash.of(getClass()).value();
125     }
126 
127     @Override
128     public boolean equals(final Object obj) {
129         return Equality.ofType(this, obj);
130     }
131 
132     @Override
133     public String toString() {
134         return getClass().getName();
135     }
136 
137 }