All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.jenetics.ext.WeaselSelector Maven / Gradle / Ivy

The newest version!
/*
 * Java Genetic Algorithm Library (jenetics-8.1.0).
 * Copyright (c) 2007-2024 Franz Wilhelmstötter
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Author:
 *    Franz Wilhelmstötter ([email protected])
 */
package io.jenetics.ext;

import static java.lang.String.format;
import static java.util.Objects.requireNonNull;

import io.jenetics.Gene;
import io.jenetics.Optimize;
import io.jenetics.Phenotype;
import io.jenetics.Selector;
import io.jenetics.stat.MinMax;
import io.jenetics.util.ISeq;
import io.jenetics.util.MSeq;
import io.jenetics.util.Seq;

/**
 * Selector implementation which is part of the
 * Weasel program
 * algorithm. The Weasel program is a thought experiment by Richard
 * Dawkins to illustrate the functioning of the evolution: random mutation
 * combined with non-random cumulative selection.
 * 

* The selector always returns populations which only contains "{@code count}" * instances of the best {@link Phenotype}. *

* {@link io.jenetics.engine.Engine} setup for the Weasel program: * {@snippet lang="java": * final Engine engine = Engine.builder(problem) * // Set the 'WeaselSelector'. * .selector(new WeaselSelector<>()) * // Disable survivors selector. * .offspringFraction(1) * // Set the 'WeaselMutator'. * .alterers(new WeaselMutator<>(0.05)) * .build(); * } * * @see Weasel program * @see WeaselMutator * * @param the gene type * @param the fitness result type * * @author Franz Wilhelmstötter * @since 3.5 * @version 5.0 */ public class WeaselSelector< G extends Gene, C extends Comparable > implements Selector { @Override public ISeq> select( final Seq> population, final int count, final Optimize opt ) { requireNonNull(population, "Population"); requireNonNull(opt, "Optimization"); if (count < 0) { throw new IllegalArgumentException(format( "Selection count must be greater or equal then zero, but was %s", count )); } final MinMax> minMax = population.stream() .collect(MinMax.toMinMax(opt.ascending())); final MSeq> result = MSeq.ofLength(count); return result.fill(minMax::max).toISeq(); } @Override public String toString() { return "WeaselSelector"; } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy