TreeCrossover.java
001 /*
002  * Java Genetic Algorithm Library (jenetics-4.4.0).
003  * Copyright (c) 2007-2019 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.ext;
021 
022 import static java.lang.Math.min;
023 
024 import java.util.Random;
025 
026 import io.jenetics.Chromosome;
027 import io.jenetics.Genotype;
028 import io.jenetics.Phenotype;
029 import io.jenetics.Recombinator;
030 import io.jenetics.util.ISeq;
031 import io.jenetics.util.MSeq;
032 import io.jenetics.util.RandomRegistry;
033 
034 import io.jenetics.ext.util.FlatTree;
035 import io.jenetics.ext.util.FlatTreeNode;
036 import io.jenetics.ext.util.TreeNode;
037 
038 /**
039  * Abstract implementation of tree base crossover recombinator. This class
040  * simplifies the implementation of tree base crossover implementation, by doing
041  * the transformation of the flattened tree genes to actual trees and vice versa.
042  * Only the {@link #crossover(TreeNode, TreeNode)} method must be implemented.
043  *
044  @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
045  @version 3.9
046  @since 3.9
047  */
048 public abstract class TreeCrossover<
049     extends TreeGene<?, G>,
050     extends Comparable<? super C>
051 >
052     extends Recombinator<G, C>
053 {
054 
055     /**
056      * Constructs an tree crossover with a given recombination probability.
057      *
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      */
062     protected TreeCrossover(final double probability) {
063         super(probability, 2);
064     }
065 
066     @Override
067     @SuppressWarnings("deprecation")
068     protected int recombine(
069         final MSeq<Phenotype<G, C>> population,
070         final int[] individuals,
071         final long generation
072     ) {
073         assert individuals.length == "Required order of 2";
074         final Random random = RandomRegistry.getRandom();
075 
076         final Phenotype<G, C> pt1 = population.get(individuals[0]);
077         final Phenotype<G, C> pt2 = population.get(individuals[1]);
078         final Genotype<G> gt1 = pt1.getGenotype();
079         final Genotype<G> gt2 = pt2.getGenotype();
080 
081         //Choosing the Chromosome index for crossover.
082         final int chIndex = random.nextInt(min(gt1.length(), gt2.length()));
083 
084         final MSeq<Chromosome<G>> c1 = gt1.toSeq().copy();
085         final MSeq<Chromosome<G>> c2 = gt2.toSeq().copy();
086 
087         crossover(c1, c2, chIndex);
088 
089         //Creating two new Phenotypes and exchanging it with the old.
090         population.set(
091             individuals[0],
092             pt1.newInstance(Genotype.of(c1.toISeq()), generation)
093         );
094         population.set(
095             individuals[1],
096             pt2.newInstance(Genotype.of(c2.toISeq()), generation)
097         );
098 
099         return getOrder();
100     }
101 
102     // Since the allele type "A" is not part of the type signature, we have to
103     // do some unchecked casts to make it "visible" again. The implementor of
104     // the abstract "crossover" method usually don't have to do additional casts.
105     private <A> void crossover(
106         final MSeq<Chromosome<G>> c1,
107         final MSeq<Chromosome<G>> c2,
108         final int index
109     ) {
110         @SuppressWarnings("unchecked")
111         final TreeNode<A> tree1 = (TreeNode<A>)TreeNode.ofTree(c1.get(index).getGene());
112         @SuppressWarnings("unchecked")
113         final TreeNode<A> tree2 = (TreeNode<A>)TreeNode.ofTree(c2.get(index).getGene());
114 
115         crossover(tree1, tree2);
116 
117         final FlatTreeNode<A> flat1 = FlatTreeNode.of(tree1);
118         final FlatTreeNode<A> flat2 = FlatTreeNode.of(tree2);
119 
120         @SuppressWarnings("unchecked")
121         final TreeGene<A, ?> template = (TreeGene<A, ?>)c1.get(0).getGene();
122 
123         final ISeq<G> genes1 = flat1.map(tree -> gene(template, tree));
124         final ISeq<G> genes2 = flat2.map(tree -> gene(template, tree));
125 
126         c1.set(index, c1.get(index).newInstance(genes1));
127         c2.set(index, c2.get(index).newInstance(genes2));
128     }
129 
130     @SuppressWarnings("unchecked")
131     private <A> G gene(
132         final TreeGene<A, ?> template,
133         final FlatTree<? extends A, ?> tree
134     ) {
135         return (G)template.newInstance(
136             tree.getValue(),
137             tree.childOffset(),
138             tree.childCount()
139         );
140     }
141 
142     /**
143      * Template method which performs the crossover. The arguments given are
144      * mutable non null trees.
145      *
146      @param <A> the <em>existential</em> allele type
147      @param that the first (chromosome) tree
148      @param other he second (chromosome) tree
149      @return the number of altered genes
150      */
151     protected abstract <A> int crossover(
152         final TreeNode<A> that,
153         final TreeNode<A> other
154     );
155 
156 }