001/*
002 * Java Genetic Algorithm Library (jenetics-7.2.0).
003 * Copyright (c) 2007-2023 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@gmail.com)
019 */
020package io.jenetics.ext;
021
022import static java.lang.String.format;
023
024import java.util.random.RandomGenerator;
025
026import io.jenetics.AltererResult;
027import io.jenetics.Gene;
028import io.jenetics.Genotype;
029import io.jenetics.Mutator;
030import io.jenetics.MutatorResult;
031import io.jenetics.Phenotype;
032import io.jenetics.util.ISeq;
033import io.jenetics.util.RandomRegistry;
034import io.jenetics.util.Seq;
035
036/**
037 * Mutator implementation which is part of the
038 * <a href="https://en.wikipedia.org/wiki/Weasel_program">Weasel program</a>
039 * algorithm. The <i>Weasel program</i> is a thought experiment by Richard
040 * Dawkins to illustrate the functioning of the evolution: random <i>mutation</i>
041 * combined with non-random cumulative <i>selection</i>.
042 * <p>
043 * The mutator mutates the genes of <i>every</i> chromosome of <i>every</i>
044 * genotype in the population with the given mutation probability.
045 * </p>
046 * {@link io.jenetics.engine.Engine} setup for the <i>Weasel program:</i>
047 * <pre>{@code
048 * final Engine<CharacterGene, Integer> engine = Engine.builder(problem)
049 *      // Set the 'WeaselSelector'.
050 *     .selector(new WeaselSelector<>())
051 *      // Disable survivors selector.
052 *     .offspringFraction(1)
053 *      // Set the 'WeaselMutator'.
054 *     .alterers(new WeaselMutator<>(0.05))
055 *     .build();
056 * }</pre>
057 *
058 * @see <a href="https://en.wikipedia.org/wiki/Weasel_program">Weasel program</a>
059 * @see WeaselSelector
060 *
061 * @param <G> the gene type
062 * @param <C> the fitness result type
063 *
064 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
065 * @since 3.5
066 * @version 5.0
067 */
068public class WeaselMutator<
069        G extends Gene<?, G>,
070        C extends Comparable<? super C>
071>
072        extends Mutator<G, C>
073{
074
075        /**
076         * Create a new weasel mutator with the given mutation probability.
077         *
078         * @param probability the mutation probability
079         * @throws IllegalArgumentException if the {@code probability} is not in the
080         *          valid range of {@code [0, 1]}.
081         */
082        public WeaselMutator(final double probability) {
083                super(probability);
084        }
085
086        /**
087         * Create a new weasel mutator with the <em>default</em> mutation probability
088         * of {@code 0.05}.
089         */
090        public WeaselMutator() {
091                this(0.05);
092        }
093
094        @Override
095        public AltererResult<G, C>
096        alter(final Seq<Phenotype<G, C>> population, final long generation) {
097                final var random = RandomRegistry.random();
098                final var result = population
099                        .map(pt -> mutate(pt, generation, _probability, random));
100
101                return new AltererResult<>(
102                        result
103                                .map(MutatorResult::result)
104                                .asISeq(),
105                        result.stream()
106                                .mapToInt(MutatorResult::mutations)
107                                .sum()
108                );
109        }
110
111        @Override
112        protected MutatorResult<Genotype<G>> mutate(
113                final Genotype<G> genotype,
114                final double p,
115                final RandomGenerator random
116        ) {
117                final var result = genotype.stream()
118                        .map(gt -> mutate(gt, p, random))
119                        .collect(ISeq.toISeq());
120
121                return new MutatorResult<>(
122                        Genotype.of(result.map(MutatorResult::result)),
123                        result.stream().mapToInt(MutatorResult::mutations).sum()
124                );
125        }
126
127        @Override
128        public String toString() {
129                return format("WeaselMutator[%f]", _probability);
130        }
131
132}