Recombinator.java
001 /*
002  * Java Genetic Algorithm Library (jenetics-5.2.0).
003  * Copyright (c) 2007-2020 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 io.jenetics.internal.math.Combinatorics.subset;
024 import static io.jenetics.internal.math.Randoms.indexes;
025 
026 import java.util.Random;
027 
028 import io.jenetics.util.MSeq;
029 import io.jenetics.util.RandomRegistry;
030 import io.jenetics.util.Seq;
031 
032 /**
033  <p>
034  * An enhanced genetic algorithm (EGA) combine elements of existing solutions in
035  * order to create a new solution, with some of the properties of each parent.
036  * Recombination creates a new chromosome by combining parts of two (or more)
037  * parent chromosomes. This combination of chromosomes can be made by selecting
038  * one or more crossover points, splitting these chromosomes on the selected
039  * points, and merge those portions of different chromosomes to form new ones.
040  </p>
041  <p>
042  * The recombination probability <i>P(r)</i> determines the probability that a
043  * given individual (genotype, not gene) of a population is selected for
044  * recombination. The (<i>mean</i>) number of changed individuals depend on the
045  * concrete implementation and can be vary from
046  <i>P(r)</i>&middot;<i>N<sub>G</sub></i> to
047  <i>P(r)</i>&middot;<i>N<sub>G</sub></i>&middot;<i>O<sub>R</sub></i>, where
048  <i>O<sub>R</sub></i> is the order of the recombination, which is the number
049  * of individuals involved int the {@link #recombine} method.
050  </p>
051  *
052  @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
053  @since 1.0
054  @version 5.2
055  */
056 public abstract class Recombinator<
057     extends Gene<?, G>,
058     extends Comparable<? super C>
059 >
060     extends AbstractAlterer<G, C>
061 {
062 
063     private final int _order;
064 
065     /**
066      * Constructs an alterer with a given recombination probability.
067      *
068      @param probability The recombination probability.
069      @param order the number of individuals involved in the
070      *        {@link #recombine(MSeq, int[], long)} step
071      @throws IllegalArgumentException if the {@code probability} is not in the
072      *         valid range of {@code [0, 1]} or the given {@code order} is
073      *         smaller than two.
074      */
075     protected Recombinator(final double probability, final int order) {
076         super(probability);
077         if (order < 2) {
078             throw new IllegalArgumentException(format(
079                 "Order must be greater than one, but was %d.", order
080             ));
081         }
082         _order = order;
083     }
084 
085     /**
086      * Return the number of individuals involved in the
087      {@link #recombine(MSeq, int[], long)} step.
088      *
089      @return the number of individuals involved in the recombination step.
090      */
091     public int order() {
092         return _order;
093     }
094 
095     /**
096      * Return the number of individuals involved in the
097      {@link #recombine(MSeq, int[], long)} step.
098      *
099      @return the number of individuals involved in the recombination step.
100      @deprecated Use {@link #order()} instead
101      */
102     @Deprecated
103     public int getOrder() {
104         return _order;
105     }
106 
107     @Override
108     public final AltererResult<G, C> alter(
109         final Seq<Phenotype<G, C>> population,
110         final long generation
111     ) {
112         final AltererResult<G, C> result;
113         if (population.size() >= 2) {
114             final Random random = RandomRegistry.random();
115             final int order = Math.min(_order, population.size());
116 
117             final MSeq<Phenotype<G, C>> pop = MSeq.of(population);
118             final int count = indexes(random, population.size(), _probability)
119                 .mapToObj(i -> individuals(i, population.size(), order, random))
120                 .mapToInt(ind -> recombine(pop, ind, generation))
121                 .sum();
122 
123             result = AltererResult.of(pop.toISeq(), count);
124         else {
125             result = AltererResult.of(population.asISeq());
126         }
127 
128         return result;
129     }
130 
131     static int[] individuals(
132         final int index,
133         final int size,
134         final int order,
135         final Random random
136     ) {
137         final int[] ind = subset(size, order, random);
138 
139         // Find the correct slot for the "master" individual.
140         // This prevents duplicate index entries.
141         int i = 0;
142         while (ind[i< index && i < ind.length - 1) {
143             ++i;
144         }
145         ind[i= index;
146 
147         return ind;
148     }
149 
150     /**
151      * Recombination template method. This method is called 0 to n times. It is
152      * guaranteed that this method is only called by one thread.
153      *
154      @param population the population to recombine
155      @param individuals the array with the indexes of the individuals which
156      *        are involved in the <i>recombination</i> step. The length of the
157      *        array is {@link #order()}. The first individual is the
158      *        <i>primary</i> individual.
159      @param generation the current generation.
160      @return the number of genes that has been altered.
161      */
162     protected abstract int recombine(
163         final MSeq<Phenotype<G, C>> population,
164         final int[] individuals,
165         final long generation
166     );
167 
168 }