GaussianMutator.java
01 /*
02  * Java Genetic Algorithm Library (jenetics-4.0.0).
03  * Copyright (c) 2007-2017 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 import io.jenetics.internal.util.Hash;
28 
29 /**
30  * The GaussianMutator class performs the mutation of a {@link NumericGene}.
31  * This mutator picks a new value based on a Gaussian distribution around the
32  * current value of the gene. The variance of the new value (before clipping to
33  * the allowed gene range) will be
34  <p>
35  <img
36  *     src="doc-files/gaussian-mutator-var.gif"
37  *     alt="\hat{\sigma }^2 = \left ( \frac{ g_{max} - g_{min} }{4}\right )^2"
38  * >
39  </p>
40  * The new value will be cropped to the gene's boundaries.
41  *
42  *
43  @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
44  @since 1.0
45  @version 4.0
46  */
47 public final class GaussianMutator<
48     extends NumericGene<?, G>,
49     extends Comparable<? super C>
50 >
51     extends Mutator<G, C>
52 {
53 
54     public GaussianMutator(final double probability) {
55         super(probability);
56     }
57 
58     public GaussianMutator() {
59         this(DEFAULT_ALTER_PROBABILITY);
60     }
61 
62     @Override
63     protected G mutate(final G gene, final Random random) {
64         final double min = gene.getMin().doubleValue();
65         final double max = gene.getMax().doubleValue();
66         final double std = (max - min)*0.25;
67 
68         final double value = gene.doubleValue();
69         final double gaussian = random.nextGaussian();
70         return gene.newInstance(clamp(gaussian*std + value, min, max));
71     }
72 
73     @Override
74     public int hashCode() {
75         return Hash.of(getClass()).and(super.hashCode()).value();
76     }
77 
78     @Override
79     public boolean equals(final Object obj) {
80         return obj instanceof GaussianMutator && super.equals(obj);
81     }
82 
83     @Override
84     public String toString() {
85         return format(
86             "%s[p=%f]",
87             getClass().getSimpleName(),
88             _probability
89         );
90     }
91 
92 }