01 /*
02 * Java Genetic Algorithm Library (jenetics-6.2.0).
03 * Copyright (c) 2007-2021 Franz Wilhelmstötter
04 *
05 * Licensed under the Apache License, Version 2.0 (the "License");
06 * you may not use this file except in compliance with the License.
07 * You may obtain a copy of the License at
08 *
09 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 * Author:
18 * Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com)
19 */
20 package io.jenetics.ext;
21
22 import java.util.Random;
23
24 import io.jenetics.Chromosome;
25 import io.jenetics.Mutator;
26 import io.jenetics.MutatorResult;
27 import io.jenetics.internal.math.Probabilities;
28
29 import io.jenetics.ext.util.FlatTreeNode;
30 import io.jenetics.ext.util.TreeNode;
31
32 /**
33 * Abstract class for mutating tree chromosomes.
34 *
35 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
36 * @version 4.1
37 * @since 4.1
38 */
39 public abstract class TreeMutator<
40 A,
41 G extends TreeGene<A, G>,
42 C extends Comparable<? super C>
43 >
44 extends Mutator<G, C>
45 {
46
47 public TreeMutator() {
48 this(DEFAULT_ALTER_PROBABILITY);
49 }
50
51 public TreeMutator(final double probability) {
52 super(probability);
53 }
54
55
56 /**
57 * Mutates the given chromosome.
58 *
59 * @param chromosome the chromosome to mutate
60 * @param p the mutation probability for the underlying genetic objects
61 * @param random the random engine used for the genotype mutation
62 * @return the mutation result
63 */
64 @Override
65 protected MutatorResult<Chromosome<G>> mutate(
66 final Chromosome<G> chromosome,
67 final double p,
68 final Random random
69 ) {
70 final int P = Probabilities.toInt(p);
71 return random.nextInt() < P
72 ? mutate(chromosome)
73 : MutatorResult.of(chromosome);
74 }
75
76 private MutatorResult<Chromosome<G>> mutate(final Chromosome<G> chromosome) {
77 final TreeNode<A> tree = TreeNode.ofTree(chromosome.gene());
78 mutate(tree);
79
80 final var flat = FlatTreeNode.ofTree(tree);
81 final var genes = flat.map(t -> chromosome.gene().newInstance(t));
82 return MutatorResult.of(chromosome.newInstance(genes), 1);
83 }
84
85 /**
86 * This method does the actual mutating, in place.
87 *
88 * @param tree the mutable tree to mutate
89 */
90 protected abstract void mutate(final TreeNode<A> tree);
91
92 }
|