GaussianMutator.java
01 /*
02  * Java Genetic Algorithm Library (jenetics-6.3.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;
21 
22 import static java.lang.Math.nextDown;
23 import static java.lang.String.format;
24 import static io.jenetics.internal.math.Basics.clamp;
25 
26 import java.util.Random;
27 
28 /**
29  * The GaussianMutator class performs the mutation of a {@link NumericGene}.
30  * This mutator picks a new value based on a Gaussian distribution around the
31  * current value of the gene. The variance of the new value (before clipping to
32  * the allowed gene range) will be
33  <p>
34  <img
35  *     src="doc-files/gaussian-mutator-var.svg"
36  *     alt="\hat{\sigma }^2 = \left ( \frac{ g_{max} - g_{min} }{4}\right )^2"
37  * >
38  </p>
39  * The new value will be cropped to the gene's boundaries.
40  *
41  *
42  @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
43  @since 1.0
44  @version 6.1
45  */
46 public class GaussianMutator<
47     extends NumericGene<?, G>,
48     extends Comparable<? super C>
49 >
50     extends Mutator<G, C>
51 {
52 
53     public GaussianMutator(final double probability) {
54         super(probability);
55     }
56 
57     public GaussianMutator() {
58         this(DEFAULT_ALTER_PROBABILITY);
59     }
60 
61     @Override
62     protected G mutate(final G gene, final Random random) {
63         return gene.isValid() ? mutate0(gene, random: gene;
64     }
65 
66     private G mutate0(final G gene, final Random random) {
67         final double min = gene.min().doubleValue();
68         final double max = gene.max().doubleValue();
69         final double std = (max - min)*0.25;
70 
71         final double value = gene.doubleValue();
72         final double gaussian = random.nextGaussian();
73         return gene.newInstance(clamp(gaussian*std + value, min, nextDown(max)));
74     }
75 
76     @Override
77     public String toString() {
78         return format("%s[p=%f]", getClass().getSimpleName(), _probability);
79     }
80 
81 }