001/*
002 * Java Genetic Algorithm Library (jenetics-8.1.0).
003 * Copyright (c) 2007-2024 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 io.jenetics.Gene;
023import io.jenetics.engine.Engine.Builder;
024import io.jenetics.engine.Engine.Setup;
025import io.jenetics.internal.util.Requires;
026
027/**
028 * Configures the evolution engine to execute the
029 * <a href="https://en.wikipedia.org/wiki/Weasel_program">Weasel program</a>
030 * algorithm.
031 *
032 * {@snippet lang="java":
033 * final Engine<CharacterGene, Integer> engine = Engine.builder(problem)
034 *     .setup(new WeaselProgram<>())
035 *     .build();
036 * }
037 *
038 * @see WeaselSelector
039 * @see WeaselMutator
040 * @see io.jenetics.engine.Engine.Builder#setup(Setup)
041 *
042 * @param <G> the gene type
043 * @param <C> the fitness result type
044 *
045 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
046 * @version 6.0
047 * @since 6.0
048 */
049public final class WeaselProgram<
050        G extends Gene<?, G>,
051        C extends Comparable<? super C>
052>
053        implements Setup<G, C>
054{
055
056        private final double _mutationProbability;
057
058        /**
059         * Create a new weasel program setup with the give mutation probability.
060         *
061         * @param mutationProbability the mutation probability
062         * @throws IllegalArgumentException if the {@code mutationProbability} is
063         *         not in the valid range of {@code [0, 1]}.
064         */
065        public WeaselProgram(final double mutationProbability) {
066                _mutationProbability = Requires.probability(mutationProbability);
067        }
068
069        /**
070         * Create a new weasel program setup with the <em>default</em> mutation
071         * probability of {@code 0.05}.
072         */
073        public WeaselProgram() {
074                this(0.05);
075        }
076
077        @Override
078        public void apply(final Builder<G, C> builder) {
079                builder
080                        .selector(new WeaselSelector<>())
081                        .offspringFraction(1)
082                        .alterers(new WeaselMutator<>(_mutationProbability));
083        }
084
085}