Mutator.java
001 /*
002  * Java Genetic Algorithm Library (jenetics-1.6.0).
003  * Copyright (c) 2007-2014 Franz Wilhelmstötter
004  *
005  * Licensed under the Apache License, Version 2.0 (the "License");
006  * you may not use this file except in compliance with the License.
007  * You may obtain a copy of the License at
008  *
009  *      http://www.apache.org/licenses/LICENSE-2.0
010  *
011  * Unless required by applicable law or agreed to in writing, software
012  * distributed under the License is distributed on an "AS IS" BASIS,
013  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014  * See the License for the specific language governing permissions and
015  * limitations under the License.
016  *
017  * Author:
018  *    Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)
019  */
020 package org.jenetics;
021 
022 import static java.lang.Math.pow;
023 import static java.lang.String.format;
024 
025 import java.util.concurrent.atomic.AtomicInteger;
026 
027 import org.jenetics.internal.util.HashBuilder;
028 
029 import org.jenetics.util.IndexStream;
030 import org.jenetics.util.MSeq;
031 
032 
033 /**
034  * This class is for mutating a chromosomes of an given population. There are
035  * two distinct roles mutation plays
036  <ul>
037  *    <li>Exploring the search space. By making small moves mutation allows a
038  *    population to explore the search space. This exploration is often slow
039  *    compared to crossover, but in problems where crossover is disruptive this
040  *    can be an important way to explore the landscape.
041  *    </li>
042  *    <li>Maintaining diversity. Mutation prevents a population from
043  *    correlating. Even if most of the search is being performed by crossover,
044  *    mutation can be vital to provide the diversity which crossover needs.
045  *    </li>
046  </ul>
047  *
048  <p>
049  * The mutation probability is the parameter that must be optimized. The optimal
050  * value of the mutation rate depends on the role mutation plays. If mutation is
051  * the only source of exploration (if there is no crossover) then the mutation
052  * rate should be set so that a reasonable neighborhood of solutions is explored.
053  </p>
054  * The mutation probability <i>P(m)</i> is the probability that a specific gene
055  * over the whole population is mutated. The number of available genes of an
056  * population is
057  <p>
058  <img src="doc-files/mutator-N_G.gif" alt="N_P N_{g}=N_P \sum_{i=0}^{N_{G}-1}N_{C[i]}" />
059  </p>
060  * where <i>N<sub>P</sub></i>  is the population size, <i>N<sub>g</sub></i> the
061  * number of genes of a genotype. So the (average) number of genes
062  * mutated by the mutation is
063  <p>
064  <img src="doc-files/mutator-mean_m.gif" alt="\hat{\mu}=N_{P}N_{g}\cdot P(m)" />
065  </p>
066  *
067  @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
068  @since 1.0
069  @version 1.0 &mdash; <em>$Date: 2014-02-27 $</em>
070  */
071 public class Mutator<G extends Gene<?, G>> extends AbstractAlterer<G> {
072 
073     /**
074      * Construct a Mutation object which a given mutation probability.
075      *
076      @param probability Mutation probability. The given probability is
077      *         divided by the number of chromosomes of the genotype to form
078      *         the concrete mutation probability.
079      @throws IllegalArgumentException if the {@code probability} is not in the
080      *          valid range of {@code [0, 1]}..
081      */
082     public Mutator(final double probability) {
083         super(probability);
084     }
085 
086     /**
087      * Default constructor, with probability = 0.01.
088      */
089     public Mutator() {
090         this(0.01);
091     }
092 
093     /**
094      * Concrete implementation of the alter method.
095      */
096     @Override
097     public <C extends Comparable<? super C>> int alter(
098         final Population<G, C> population,
099         final int generation
100     ) {
101         assert(population != null"Not null is guaranteed from base class.";
102 
103         final double p = pow(_probability, 1.0/3.0);
104         final AtomicInteger alterations = new AtomicInteger(0);
105 
106         final IndexStream stream = IndexStream.Random(population.size(), p);
107         for (int i = stream.next(); i != -1; i = stream.next()) {
108             final Phenotype<G, C> pt = population.get(i);
109 
110             final Genotype<G> gt = pt.getGenotype();
111             final Genotype<G> mgt = mutate(gt, p, alterations);
112 
113             final Phenotype<G, C> mpt = pt.newInstance(mgt, generation);
114             population.set(i, mpt);
115         }
116 
117         return alterations.get();
118     }
119 
120     private Genotype<G> mutate(
121         final Genotype<G> genotype,
122         final double p,
123         final AtomicInteger alterations
124     ) {
125         Genotype<G> gt = genotype;
126 
127         final IndexStream stream = IndexStream.Random(genotype.length(), p);
128         final int start = stream.next();
129 
130         if (start != -1) {
131             final MSeq<Chromosome<G>> chromosomes = genotype.toSeq().copy();
132 
133             for (int i = start; i != -1; i = stream.next()) {
134                 final Chromosome<G> chromosome = chromosomes.get(i);
135                 final MSeq<G> genes = chromosome.toSeq().copy();
136 
137                 final int mutations = mutate(genes, p);
138                 if (mutations > 0) {
139                     alterations.addAndGet(mutations);
140                     chromosomes.set(i, chromosome.newInstance(genes.toISeq()));
141                 }
142             }
143 
144             gt = genotype.newInstance(chromosomes.toISeq());
145         }
146 
147         return gt;
148     }
149 
150     /**
151      <p>
152      * Template method which gives an (re)implementation of the mutation class
153      * the possibility to perform its own mutation operation, based on a
154      * writable gene array and the gene mutation probability <i>p</i>.
155      </p>
156      * This implementation, for example, does it in this way:
157      * [code]
158      * protected int mutate(final MSeq〈G〉 genes, final double p) {
159      *     final IndexStream stream = IndexStream.Random(genes.length(), p);
160      *
161      *     int alterations = 0;
162      *     for (int i = stream.next(); i != -1; i = stream.next()) {
163      *         genes.set(i, genes.get(i).newInstance());
164      *         ++alterations;
165      *     }
166      *     return alterations;
167      * }
168      * [/code]
169      *
170      @param genes the genes to mutate.
171      @param p the gene mutation probability.
172      */
173     protected int mutate(final MSeq<G> genes, final double p) {
174         final IndexStream stream = IndexStream.Random(genes.length(), p);
175 
176         int alterations = 0;
177         for (int i = stream.next(); i != -1; i = stream.next()) {
178             genes.set(i, genes.get(i).newInstance());
179             ++alterations;
180         }
181 
182         return alterations;
183     }
184 
185     @Override
186     public int hashCode() {
187         return HashBuilder.of(getClass()).and(super.hashCode()).value();
188     }
189 
190     @Override
191     public boolean equals(final Object obj) {
192         return obj == this || obj instanceof Mutator<?>;
193     }
194 
195     @Override
196     public String toString() {
197         return format("%s[p=%f]", getClass().getSimpleName(), _probability);
198     }
199 
200 }