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