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