<commit_before>/*
 * Java Genetic Algorithm Library (@__identifier__@).
 * Copyright (c) @__year__@ <NAME>
 *
 * 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:
 *    <NAME> (<EMAIL>)
 */
package org.jenetics.engine;

import static java.lang.Math.round;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static org.jenetics.Population.toPopulation;
import static org.jenetics.internal.util.require.probability;

import java.time.Clock;
import java.util.Iterator;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.ForkJoinPool;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

import org.jenetics.internal.util.Concurrency;
import org.jenetics.internal.util.require;

import org.jenetics.Alterer;
import org.jenetics.Chromosome;
import org.jenetics.Gene;
import org.jenetics.Genotype;
import org.jenetics.Mutator;
import org.jenetics.Optimize;
import org.jenetics.Phenotype;
import org.jenetics.Population;
import org.jenetics.Selector;
import org.jenetics.SinglePointCrossover;
import org.jenetics.TournamentSelector;
import org.jenetics.util.Copyable;
import org.jenetics.util.Factory;
import org.jenetics.util.NanoClock;

/**
 * Genetic algorithm <em>engine</em> which is the main class. The following
 * example shows the main steps in initializing and executing the GA.
 *
 * <pre>{@code
 * public class RealFunction {
 *    // Definition of the fitness function.
 *    private static Double eval(final Genotype<DoubleGene> gt) {
 *        final double x = gt.getGene().doubleValue();
 *        return cos(0.5 + sin(x))*cos(x);
 *    }
 *
 *    public static void main(String[] args) {
 *        // Create/configuring the engine via its builder.
 *        final Engine<DoubleGene, Double> engine = Engine
 *            .builder(
 *                RealFunction::eval,
 *                DoubleChromosome.of(0.0, 2.0*PI))
 *            .populationSize(500)
 *            .optimize(Optimize.MINIMUM)
 *            .alterers(
 *                new Mutator<>(0.03),
 *                new MeanAlterer<>(0.6))
 *            .build();
 *
 *        // Execute the GA (engine).
 *        final Phenotype<DoubleGene, Double> result = engine.stream()
 *             // Truncate the evolution stream if no better individual could
 *             // be found after 5 consecutive generations.
 *            .limit(bySteadyFitness(5))
 *             // Terminate the evolution after maximal 100 generations.
 *            .limit(100)
 *            .collect(toBestPhenotype());
 *     }
 * }
 * }</pre>
 *
 * The architecture allows to decouple the configuration of the engine from the
 * execution. The {@code Engine} is configured via the {@code Engine.Builder}
 * class and can't be changed after creation. The actual <i>evolution</i> is
 * performed by the {@link EvolutionStream}, which is created by the
 * {@code Engine}.
 * <p>
 * <em>
 *     <b>This class is thread safe:</b>
 *     No mutable state is maintained by the engine. Therefore it is save to
 *     create multiple evolution streams with one engine, which may be actually
 *     used in different threads.
 * </em>
 *
 * @see Engine.Builder
 * @see EvolutionStart
 * @see EvolutionResult
 * @see EvolutionStream
 * @see EvolutionStatistics
 * @see Codec
 *
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @since 3.0
 * @version 3.7
 */
public final class Engine<
	G extends Gene<?, G>,
	C extends Comparable<? super C>
>
	implements Function<EvolutionStart<G, C>, EvolutionResult<G, C>>
{

	// Problem definition.
	private final Function<? super Genotype<G>, ? extends C> _fitnessFunction;
	private final Factory<Genotype<G>> _genotypeFactory;

	// Evolution parameters.
	private final Function<? super C, ? extends C> _fitnessScaler;
	private final Selector<G, C> _survivorsSelector;
	private final Selector<G, C> _offspringSelector;
	private final Alterer<G, C> _alterer;
	private final Predicate<? super Phenotype<G, C>> _validator;
	private final Optimize _optimize;
	private final int _offspringCount;
	private final int _survivorsCount;
	private final long _maximalPhenotypeAge;

	// Execution context for concurrent execution of evolving steps.
	private final TimedExecutor _executor;
	private final Clock _clock;

	// Additional parameters.
	private final int _individualCreationRetries;


	/**
	 * Create a new GA engine with the given parameters.
	 *
	 * @param fitnessFunction the fitness function this GA is using.
	 * @param genotypeFactory the genotype factory this GA is working with.
	 * @param fitnessScaler the fitness scaler this GA is using.
	 * @param survivorsSelector the selector used for selecting the survivors
	 * @param offspringSelector the selector used for selecting the offspring
	 * @param alterer the alterer used for altering the offspring
	 * @param validator phenotype validator which can override the default
	 *        implementation the {@link Phenotype#isValid()} method.
	 * @param optimize the kind of optimization (minimize or maximize)
	 * @param offspringCount the number of the offspring individuals
	 * @param survivorsCount the number of the survivor individuals
	 * @param maximalPhenotypeAge the maximal age of an individual
	 * @param executor the executor used for executing the single evolve steps
	 * @param clock the clock used for calculating the timing results
	 * @param individualCreationRetries the maximal number of attempts for
	 *        creating a valid individual.
	 * @throws NullPointerException if one of the arguments is {@code null}
	 * @throws IllegalArgumentException if the given integer values are smaller
	 *         than one.
	 */
	Engine(
		final Function<? super Genotype<G>, ? extends C> fitnessFunction,
		final Factory<Genotype<G>> genotypeFactory,
		final Function<? super C, ? extends C> fitnessScaler,
		final Selector<G, C> survivorsSelector,
		final Selector<G, C> offspringSelector,
		final Alterer<G, C> alterer,
		final Predicate<? super Phenotype<G, C>> validator,
		final Optimize optimize,
		final int offspringCount,
		final int survivorsCount,
		final long maximalPhenotypeAge,
		final Executor executor,
		final Clock clock,
		final int individualCreationRetries
	) {
		_fitnessFunction = requireNonNull(fitnessFunction);
		_fitnessScaler = requireNonNull(fitnessScaler);
		_genotypeFactory = requireNonNull(genotypeFactory);
		_survivorsSelector = requireNonNull(survivorsSelector);
		_offspringSelector = requireNonNull(offspringSelector);
		_alterer = requireNonNull(alterer);
		_validator = requireNonNull(validator);
		_optimize = requireNonNull(optimize);

		_offspringCount = require.nonNegative(offspringCount);
		_survivorsCount = require.nonNegative(survivorsCount);
		_maximalPhenotypeAge = require.positive(maximalPhenotypeAge);

		_executor = new TimedExecutor(requireNonNull(executor));
		_clock = requireNonNull(clock);

		if (individualCreationRetries < 0) {
			throw new IllegalArgumentException(format(
				"Retry count must not be negative: %d",
				individualCreationRetries
			));
		}
		_individualCreationRetries = individualCreationRetries;
	}

	/**
	 * Perform one evolution step with the given {@code population} and
	 * {@code generation}. New phenotypes are created with the fitness function
	 * and fitness scaler defined by this <em>engine</em>
	 * <p>
	 * <em>This method is thread-safe.</em>
	 *
	 * @see #evolve(EvolutionStart)
	 *
	 * @param population the population to evolve
	 * @param generation the current generation; used for calculating the
	 *        phenotype age.
	 * @return the evolution result
	 * @throws java.lang.NullPointerException if the given {@code population} is
	 *         {@code null}
	 * @throws IllegalArgumentException if the given {@code generation} is
	 *         smaller then one
	 */
	public EvolutionResult<G, C> evolve(
		final Population<G, C> population,
		final long generation
	) {
		return evolve(EvolutionStart.of(population, generation));
	}

	/**
	 * Perform one evolution step with the given evolution {@code start} object
	 * New phenotypes are created with the fitness function and fitness scaler
	 * defined by this <em>engine</em>
	 * <p>
	 * <em>This method is thread-safe.</em>
	 *
	 * @since 3.1
	 * @see #evolve(org.jenetics.Population, long)
	 *
	 * @param start the evolution start object
	 * @return the evolution result
	 * @throws java.lang.NullPointerException if the given evolution
	 *         {@code start} is {@code null}
	 */
	public EvolutionResult<G, C> evolve(final EvolutionStart<G, C> start) {
		final Timer timer = Timer.of().start();

		final Population<G, C> startPopulation = start.getPopulation();

		// Initial evaluation of the population.
		final Timer evaluateTimer = Timer.of(_clock).start();
		evaluate(startPopulation);
		evaluateTimer.stop();

		// Select the offspring population.
		final CompletableFuture<TimedResult<Population<G, C>>> offspring =<commit_msg>Add missing clock to timer.<commit_after>/*
 * Java Genetic Algorithm Library (@__identifier__@).
 * Copyright (c) @__year__@ <NAME>
 *
 * 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:
 *    <NAME> (<EMAIL>)
 */
package org.jenetics.engine;

import static java.lang.Math.round;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static org.jenetics.Population.toPopulation;
import static org.jenetics.internal.util.require.probability;

import java.time.Clock;
import java.util.Iterator;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.ForkJoinPool;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

import org.jenetics.internal.util.Concurrency;
import org.jenetics.internal.util.require;

import org.jenetics.Alterer;
import org.jenetics.Chromosome;
import org.jenetics.Gene;
import org.jenetics.Genotype;
import org.jenetics.Mutator;
import org.jenetics.Optimize;
import org.jenetics.Phenotype;
import org.jenetics.Population;
import org.jenetics.Selector;
import org.jenetics.SinglePointCrossover;
import org.jenetics.TournamentSelector;
import org.jenetics.util.Copyable;
import org.jenetics.util.Factory;
import org.jenetics.util.NanoClock;

/**
 * Genetic algorithm <em>engine</em> which is the main class. The following
 * example shows the main steps in initializing and executing the GA.
 *
 * <pre>{@code
 * public class RealFunction {
 *    // Definition of the fitness function.
 *    private static Double eval(final Genotype<DoubleGene> gt) {
 *        final double x = gt.getGene().doubleValue();
 *        return cos(0.5 + sin(x))*cos(x);
 *    }
 *
 *    public static void main(String[] args) {
 *        // Create/configuring the engine via its builder.
 *        final Engine<DoubleGene, Double> engine = Engine
 *            .builder(
 *                RealFunction::eval,
 *                DoubleChromosome.of(0.0, 2.0*PI))
 *            .populationSize(500)
 *            .optimize(Optimize.MINIMUM)
 *            .alterers(
 *                new Mutator<>(0.03),
 *                new MeanAlterer<>(0.6))
 *            .build();
 *
 *        // Execute the GA (engine).
 *        final Phenotype<DoubleGene, Double> result = engine.stream()
 *             // Truncate the evolution stream if no better individual could
 *             // be found after 5 consecutive generations.
 *            .limit(bySteadyFitness(5))
 *             // Terminate the evolution after maximal 100 generations.
 *            .limit(100)
 *            .collect(toBestPhenotype());
 *     }
 * }
 * }</pre>
 *
 * The architecture allows to decouple the configuration of the engine from the
 * execution. The {@code Engine} is configured via the {@code Engine.Builder}
 * class and can't be changed after creation. The actual <i>evolution</i> is
 * performed by the {@link EvolutionStream}, which is created by the
 * {@code Engine}.
 * <p>
 * <em>
 *     <b>This class is thread safe:</b>
 *     No mutable state is maintained by the engine. Therefore it is save to
 *     create multiple evolution streams with one engine, which may be actually
 *     used in different threads.
 * </em>
 *
 * @see Engine.Builder
 * @see EvolutionStart
 * @see EvolutionResult
 * @see EvolutionStream
 * @see EvolutionStatistics
 * @see Codec
 *
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @since 3.0
 * @version 3.7
 */
public final class Engine<
	G extends Gene<?, G>,
	C extends Comparable<? super C>
>
	implements Function<EvolutionStart<G, C>, EvolutionResult<G, C>>
{

	// Problem definition.
	private final Function<? super Genotype<G>, ? extends C> _fitnessFunction;
	private final Factory<Genotype<G>> _genotypeFactory;

	// Evolution parameters.
	private final Function<? super C, ? extends C> _fitnessScaler;
	private final Selector<G, C> _survivorsSelector;
	private final Selector<G, C> _offspringSelector;
	private final Alterer<G, C> _alterer;
	private final Predicate<? super Phenotype<G, C>> _validator;
	private final Optimize _optimize;
	private final int _offspringCount;
	private final int _survivorsCount;
	private final long _maximalPhenotypeAge;

	// Execution context for concurrent execution of evolving steps.
	private final TimedExecutor _executor;
	private final Clock _clock;

	// Additional parameters.
	private final int _individualCreationRetries;


	/**
	 * Create a new GA engine with the given parameters.
	 *
	 * @param fitnessFunction the fitness function this GA is using.
	 * @param genotypeFactory the genotype factory this GA is working with.
	 * @param fitnessScaler the fitness scaler this GA is using.
	 * @param survivorsSelector the selector used for selecting the survivors
	 * @param offspringSelector the selector used for selecting the offspring
	 * @param alterer the alterer used for altering the offspring
	 * @param validator phenotype validator which can override the default
	 *        implementation the {@link Phenotype#isValid()} method.
	 * @param optimize the kind of optimization (minimize or maximize)
	 * @param offspringCount the number of the offspring individuals
	 * @param survivorsCount the number of the survivor individuals
	 * @param maximalPhenotypeAge the maximal age of an individual
	 * @param executor the executor used for executing the single evolve steps
	 * @param clock the clock used for calculating the timing results
	 * @param individualCreationRetries the maximal number of attempts for
	 *        creating a valid individual.
	 * @throws NullPointerException if one of the arguments is {@code null}
	 * @throws IllegalArgumentException if the given integer values are smaller
	 *         than one.
	 */
	Engine(
		final Function<? super Genotype<G>, ? extends C> fitnessFunction,
		final Factory<Genotype<G>> genotypeFactory,
		final Function<? super C, ? extends C> fitnessScaler,
		final Selector<G, C> survivorsSelector,
		final Selector<G, C> offspringSelector,
		final Alterer<G, C> alterer,
		final Predicate<? super Phenotype<G, C>> validator,
		final Optimize optimize,
		final int offspringCount,
		final int survivorsCount,
		final long maximalPhenotypeAge,
		final Executor executor,
		final Clock clock,
		final int individualCreationRetries
	) {
		_fitnessFunction = requireNonNull(fitnessFunction);
		_fitnessScaler = requireNonNull(fitnessScaler);
		_genotypeFactory = requireNonNull(genotypeFactory);
		_survivorsSelector = requireNonNull(survivorsSelector);
		_offspringSelector = requireNonNull(offspringSelector);
		_alterer = requireNonNull(alterer);
		_validator = requireNonNull(validator);
		_optimize = requireNonNull(optimize);

		_offspringCount = require.nonNegative(offspringCount);
		_survivorsCount = require.nonNegative(survivorsCount);
		_maximalPhenotypeAge = require.positive(maximalPhenotypeAge);

		_executor = new TimedExecutor(requireNonNull(executor));
		_clock = requireNonNull(clock);

		if (individualCreationRetries < 0) {
			throw new IllegalArgumentException(format(
				"Retry count must not be negative: %d",
				individualCreationRetries
			));
		}
		_individualCreationRetries = individualCreationRetries;
	}

	/**
	 * Perform one evolution step with the given {@code population} and
	 * {@code generation}. New phenotypes are created with the fitness function
	 * and fitness scaler defined by this <em>engine</em>
	 * <p>
	 * <em>This method is thread-safe.</em>
	 *
	 * @see #evolve(EvolutionStart)
	 *
	 * @param population the population to evolve
	 * @param generation the current generation; used for calculating the
	 *        phenotype age.
	 * @return the evolution result
	 * @throws java.lang.NullPointerException if the given {@code population} is
	 *         {@code null}
	 * @throws IllegalArgumentException if the given {@code generation} is
	 *         smaller then one
	 */
	public EvolutionResult<G, C> evolve(
		final Population<G, C> population,
		final long generation
	) {
		return evolve(EvolutionStart.of(population, generation));
	}

	/**
	 * Perform one evolution step with the given evolution {@code start} object
	 * New phenotypes are created with the fitness function and fitness scaler
	 * defined by this <em>engine</em>
	 * <p>
	 * <em>This method is thread-safe.</em>
	 *
	 * @since 3.1
	 * @see #evolve(org.jenetics.Population, long)
	 *
	 * @param start the evolution start object
	 * @return the evolution result
	 * @throws java.lang.NullPointerException if the given evolution
	 *         {@code start} is {@code null}
	 */
	public EvolutionResult<G, C> evolve(final EvolutionStart<G, C> start) {
		final Timer timer = Timer.of(_clock).start();

		final Population<G, C> startPopulation = start.getPopulation();

		// Initial evaluation of the population.
		final Timer evaluateTimer = Timer.of(_clock).start();
		evaluate(startPopulation);
		evaluateTimer.stop();

		// Select the offspring population.
		final CompletableFuture<TimedResult<Population<G, C>>> offspring =
{'fraction_non_alphanumeric': 0.09299050797955564, 'fraction_numerical': 0.003442161260039637, 'mean_word_length': 3.8642820903094877, 'pattern_counts': {'":': 0, '<': 139, '<?xml version=': 0, '>': 137, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5932159', 'n_tokens_mistral': 5643, 'n_tokens_neox': 5224, 'n_words': 1834}