GaussianMutator.java
01 /*
02  * Java Genetic Algorithm Library (jenetics-4.3.0).
03  * Copyright (c) 2007-2018 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.String.format;
23 import static io.jenetics.internal.math.base.clamp;
24 
25 import java.util.Random;
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.gif"
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 4.0
44  */
45 public final 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 Random random) {
62         final double min = gene.getMin().doubleValue();
63         final double max = gene.getMax().doubleValue();
64         final double std = (max - min)*0.25;
65 
66         final double value = gene.doubleValue();
67         final double gaussian = random.nextGaussian();
68         return gene.newInstance(clamp(gaussian*std + value, min, max));
69     }
70 
71     @Override
72     public String toString() {
73         return format("%s[p=%f]", getClass().getSimpleName(), _probability);
74     }
75 
76 }