CombineAlterer.java
001 /*
002  * Java Genetic Algorithm Library (jenetics-6.3.0).
003  * Copyright (c) 2007-2021 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.Math.min;
023 import static java.lang.String.format;
024 import static java.util.Objects.requireNonNull;
025 
026 import java.util.Random;
027 import java.util.function.BinaryOperator;
028 
029 import io.jenetics.util.BaseSeq;
030 import io.jenetics.util.MSeq;
031 import io.jenetics.util.RandomRegistry;
032 
033 /**
034  * Alters a chromosome by replacing two genes by the result of a given
035  <em>combiner</em> function.
036  *
037  <p>
038  * The order ({@link #order()}) of this recombination implementation is two.
039  </p>
040  *
041  @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
042  @since 6.0
043  @version 6.0
044  */
045 public class CombineAlterer<
046     extends Gene<?, G>,
047     extends Comparable<? super C>
048 >
049     extends Recombinator<G, C>
050 {
051 
052     private final BinaryOperator<G> _combiner;
053 
054     /**
055      * Create a new combiner alterer with the given arguments.
056      *
057      @param combiner the function used for combining two genes
058      @param probability The recombination probability.
059      @throws IllegalArgumentException if the {@code probability} is not in the
060      *         valid range of {@code [0, 1]}
061      @throws NullPointerException if the given {@code combiner} is {@code null}
062      */
063     public CombineAlterer(
064         final BinaryOperator<G> combiner,
065         final double probability
066     ) {
067         super(probability, 2);
068         _combiner = requireNonNull(combiner);
069     }
070 
071     /**
072      * Create a new combiner alterer with the given arguments.
073      *
074      @param combiner the function used for combining two genes
075      @throws IllegalArgumentException if the {@code probability} is not in the
076      *         valid range of {@code [0, 1]}
077      @throws NullPointerException if the given {@code combiner} is {@code null}
078      */
079     public CombineAlterer(final BinaryOperator<G> combiner) {
080         this(combiner, DEFAULT_ALTER_PROBABILITY);
081     }
082 
083     /**
084      * Return the combiner function, used by {@code this} alterer.
085      *
086      @return the combiner function, used by {@code this} alterer
087      */
088     public BinaryOperator<G> combiner() {
089         return _combiner;
090     }
091 
092     @Override
093     protected int recombine(
094         final MSeq<Phenotype<G, C>> population,
095         final int[] individuals,
096         final long generation
097     ) {
098         final Random random = RandomRegistry.random();
099 
100         final Phenotype<G, C> pt1 = population.get(individuals[0]);
101         final Phenotype<G, C> pt2 = population.get(individuals[1]);
102         final Genotype<G> gt1 = pt1.genotype();
103         final Genotype<G> gt2 = pt2.genotype();
104 
105         //Choosing the Chromosome index for crossover.
106         final int ci = random.nextInt(min(gt1.length(), gt2.length()));
107 
108         final MSeq<Chromosome<G>> c1 = MSeq.of(gt1);
109 
110         // Calculate the mean value of the gene array.
111         final MSeq<G> mean = combine(c1.get(ci), gt2.get(ci), _combiner);
112 
113         c1.set(ci, c1.get(ci).newInstance(mean.toISeq()));
114         population.set(individuals[0], Phenotype.of(Genotype.of(c1), generation));
115 
116         return 1;
117     }
118 
119     private static <G extends Gene<?, G>>
120     MSeq<G> combine(
121         final BaseSeq<G> a,
122         final BaseSeq<G> b,
123         final BinaryOperator<G> combiner
124     ) {
125         final MSeq<G> result = MSeq.ofLength(a.length());
126         for (int i = a.length(); --i >= 0;) {
127             result.set(i, combiner.apply(a.get(i), b.get(i)));
128         }
129         return result;
130     }
131 
132     @Override
133     public String toString() {
134         return format("%s[p=%f]", getClass().getSimpleName(), _probability);
135     }
136 }