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