public static void main(final String[] args) { RandomRegistry.setRandom(new Random()); final Engine<EnumGene<Integer>, Integer> engine = Engine .builder( Sorting::length, PermutationChromosome.ofInteger(20)) .optimize(Optimize.MINIMUM) .populationSize(1000) //.survivorsSelector(new RouletteWheelSelector<>()) //.offspringSelector(new TruncationSelector<>()) .offspringFraction(0.9) .alterers( new SwapMutator<>(0.01), new PartiallyMatchedCrossover<>(0.3)) .build(); final EvolutionStatistics<Integer, DoubleMomentStatistics> statistics = EvolutionStatistics.ofNumber(); final EvolutionResult<EnumGene<Integer>, Integer> result = engine.stream() .limit(Limits.bySteadyFitness(100)) .limit(2500) .peek(statistics) .collect(EvolutionResult.toBestEvolutionResult()); System.out.println(statistics); System.out.println(result.getBestPhenotype()); }
@Test public void populationEvaluator() { final int populationSize = 100; final AtomicInteger count = new AtomicInteger(); final Engine<DoubleGene, Double> engine = Engine .builder(gt -> gt.getGene().doubleValue(), DoubleChromosome.of(0, 1)) .populationSize(populationSize) .evaluator((gt, ff) -> { count.compareAndSet(0, gt.length()); return gt.stream().map(ff).collect(ISeq.toISeq()); }) .build(); engine.stream() .limit(1) .collect(EvolutionResult.toBestGenotype()); Assert.assertEquals(count.get(), populationSize); }
@Test public void toUniquePopulation() { final int populationSize = 100; final Engine<IntegerGene, Integer> engine = Engine .builder(a -> a.getGene().getAllele(), IntegerChromosome.of(0, 10)) .populationSize(populationSize) .mapping(EvolutionResult.toUniquePopulation( Genotype.of(IntegerChromosome.of(0, Integer.MAX_VALUE)))) .build(); final EvolutionResult<IntegerGene, Integer> result = engine.stream() .limit(10) .peek(r -> { if (r.getGenotypes().stream().collect(Collectors.toSet()).size() != populationSize) { throw new AssertionError(format( "Expected unique population size %d, but got %d.", populationSize, r.getGenotypes().stream().collect(Collectors.toSet()).size() )); } }) .collect(EvolutionResult.toBestEvolutionResult()); Assert.assertEquals(result.getPopulation().size(), populationSize); }
public static void main(final String[] args) { final Knapsack knapsack = Knapsack.of(15, new Random(123)); // The base engine tries to approximate to good solution in current // environment. final Engine<BitGene, Double> baseEngine = Engine.builder(knapsack) .populationSize(500) .alterers( new Mutator<>(0.115), new SinglePointCrossover<>(0.16)) .build(); // The 'diversity' engine tries to broaden the search space again. final Engine<BitGene, Double> diversityEngine = baseEngine.builder() .alterers(new Mutator<>(0.5)) .build(); // Concatenates the two engines into one cyclic engine. final EvolutionStreamable<BitGene, Double> engine = CyclicEngine.of( // This engine stops the evolution after 10 non-improving // generations and hands over to the diversity engine. baseEngine.limit(() -> Limits.bySteadyFitness(10)), // The higher mutation rate of this engine broadens the search // space for 15 generations and hands over to the base engine. diversityEngine.limit(15) ); final EvolutionResult<BitGene, Double> best = engine.stream() // The evolution is stopped after 50 non-improving generations. .limit(bySteadyFitness(50)) .collect(toBestEvolutionResult()); System.out.println(best.getTotalGenerations()); System.out.println(best.getBestPhenotype()); }
/** * Create a new {@link Engine} for solving the {@link Knapsack} problem. The * engine is used for testing purpose. * * @see Knapsack#of(int, Random) * * @param populationSize the population size of the created engine * @param random the random engine used for creating the {@link Knapsack} * problem instance * @return a new {@link Knapsack} solving evolution {@link Engine} */ public static Engine<BitGene, Double> knapsack( final int populationSize, final Random random ) { // Search space fo 2^250 ~ 10^75. final Knapsack knapsack = Knapsack.of(250, random); // Configure and build the evolution engine. return Engine.builder(knapsack) .populationSize(populationSize) .survivorsSelector(new TournamentSelector<>(5)) .offspringSelector(new RouletteWheelSelector<>()) .alterers( new Mutator<>(0.03), new SinglePointCrossover<>(0.125)) .build(); }
/** * Create a new evolution {@code Engine.Builder} initialized with the values * of the current evolution {@code Engine}. With this method, the evolution * engine can serve as a template for a new one. * * @return a new engine builder */ public Builder<G, C> builder() { return new Builder<G, C>(_genotypeFactory, _fitnessFunction) .alterers(_alterer) .clock(_clock) .evaluator(_evaluator) .executor(_executor.get()) .fitnessScaler(_fitnessScaler) .maximalPhenotypeAge(_maximalPhenotypeAge) .offspringFraction((double)_offspringCount/(double)getPopulationSize()) .offspringSelector(_offspringSelector) .optimize(_optimize) .phenotypeValidator(_validator) .populationSize(getPopulationSize()) .survivorsSelector(_survivorsSelector) .individualCreationRetries(_individualCreationRetries) .mapping(_mapper); }
public static void main(final String[] args) { final int μ = 5; final int λ = 20; final double p = 0.2; final Codec<Double, DoubleGene> codec = Codecs .ofScalar(DoubleRange.of(0, 1)); final Engine<DoubleGene, Double> engine = Engine .builder(MpLStrategy::fitness, codec) .populationSize(λ) .survivorsSize(μ) .selector(new TruncationSelector<>(μ)) .alterers(new Mutator<>(p)) .build(); System.out.println( codec.decode( engine.stream() .limit(100) .collect(EvolutionResult.toBestGenotype()) ) ); }
public static void main(final String[] args) { final int μ = 5; final int λ = 20; final double p = 0.2; final Codec<Double, DoubleGene> codec = Codecs .ofScalar(DoubleRange.of(0, 1)); final Engine<DoubleGene, Double> engine = Engine .builder(MLStrategy::fitness, codec) .populationSize(λ) .survivorsSize(0) .offspringSelector(new TruncationSelector<>(μ)) .alterers(new Mutator<>(p)) .build(); System.out.println( codec.decode( engine.stream() .limit(100) .collect(EvolutionResult.toBestGenotype()) ) ); }
/** * Create a new builder, with the current configuration. * * @since 3.1 * * @return a new builder, with the current configuration */ @Override public Builder<G, C> copy() { return new Builder<G, C>(_genotypeFactory, _fitnessFunction) .alterers(_alterer) .clock(_clock) .executor(_executor) .evaluator(_evaluator) .fitnessScaler(_fitnessScaler) .maximalPhenotypeAge(_maximalPhenotypeAge) .offspringFraction(_offspringFraction) .offspringSelector(_offspringSelector) .phenotypeValidator(_validator) .optimize(_optimize) .populationSize(_populationSize) .survivorsSelector(_survivorsSelector) .individualCreationRetries(_individualCreationRetries) .mapping(_mapper); }
@Test(timeOut = 15_000L) public void deadLock() { final Function<Genotype<DoubleGene>, Double> ff = gt -> { try { Thread.sleep( 50 ); } catch (InterruptedException ignore) { Thread.currentThread().interrupt(); } return gt.getGene().getAllele(); }; final Engine<DoubleGene, Double> engine = Engine .builder(ff, DoubleChromosome.of(0, 1)) //.executor(Executors.newFixedThreadPool(10)) .populationSize(10) .build(); final EvolutionResult<DoubleGene, Double> result = engine.stream() .limit(3) .collect(EvolutionResult.toBestEvolutionResult()); //Assert.assertEquals(25L, result.getTotalGenerations()); }
@Test public void constantPopulationForZeroSurvivors() { final int populationSize = 20; final Engine<DoubleGene, Double> engine = Engine .builder(gt -> gt.getGene().doubleValue(), DoubleChromosome.of(0, 1)) .populationSize(populationSize) .survivorsSize(0) .build(); final EvolutionResult<DoubleGene, Double> result = engine.stream() .limit(100) .peek(r -> { if (r.getPopulation().size() != populationSize) { throw new AssertionError(format( "Expected population size %d, but got %d.", populationSize, r.getPopulation().size() )); } }) .collect(EvolutionResult.toBestEvolutionResult()); }
public static void main(final String[] args) { final Engine<DoubleGene, Double> engine = Engine .builder( RastriginFunction::fitness, // Codec for 'x' vector. Codecs.ofVector(DoubleRange.of(-R, R), N)) .populationSize(500) .optimize(Optimize.MINIMUM) .alterers( new Mutator<>(0.03), new MeanAlterer<>(0.6)) .build(); final EvolutionStatistics<Double, ?> statistics = EvolutionStatistics.ofNumber(); final Phenotype<DoubleGene, Double> best = engine.stream() .limit(bySteadyFitness(7)) .peek(statistics) .collect(toBestPhenotype()); System.out.println(statistics); System.out.println(best); } }
public static void main(String[] args) throws Exception { final CharSeq chars = CharSeq.of("A-Z "); final Factory<Genotype<CharacterGene>> gtf = Genotype.of( CharacterChromosome.of(chars, TARGET.length()) ); final Engine<CharacterGene, Integer> engine = Engine .builder(WeaselProgram::score, gtf) .populationSize(150) .selector(new WeaselSelector<>()) .offspringFraction(1) .alterers(new WeaselMutator<>(0.05)) .build(); final Phenotype<CharacterGene, Integer> result = engine.stream() .limit(byFitnessThreshold(TARGET.length() - 1)) .peek(r -> System.out.println( r.getTotalGenerations() + ": " + r.getBestPhenotype())) .collect(toBestPhenotype()); System.out.println(result); }
@Test public void constantPopulationForZeroOffspring() { final int populationSize = 20; final Engine<DoubleGene, Double> engine = Engine .builder(gt -> gt.getGene().doubleValue(), DoubleChromosome.of(0, 1)) .populationSize(populationSize) .offspringSize(0) .build(); final EvolutionResult<DoubleGene, Double> result = engine.stream() .limit(100) .peek(r -> { if (r.getPopulation().size() != populationSize) { throw new AssertionError(format( "Expected population size %d, but got %d.", populationSize, r.getPopulation().size() )); } }) .collect(EvolutionResult.toBestEvolutionResult()); }
public static void main(String[] args) throws IOException { final Knapsack knapsack = Knapsack.of(15, new Random(123)); final Engine<BitGene, Double> engine = Engine.builder(knapsack) .populationSize(500) .alterers( new Mutator<>(0.115), new SinglePointCrossover<>(0.16)) .evaluator(BatchEvalKnapsack::batchEval) .evaluator(pop -> { pop.forEach(Phenotype::evaluate); return pop.asISeq(); }) .build(); final Phenotype<BitGene, Double> best = engine.stream() .limit(bySteadyFitness(20)) .collect(toBestPhenotype()); System.out.println(best); }
@Test(dataProvider = "executors", timeOut = 2_000L) public void executorDeadLock(final Executor executor) { try { final Engine<DoubleGene, Double> engine = Engine .builder(gt -> gt.getGene().doubleValue(), DoubleChromosome.of(0, 1)) .executor(executor) .populationSize(10) .build(); engine.stream() .limit(100) .collect(EvolutionResult.toBestEvolutionResult()); } finally { if (executor instanceof ExecutorService) { ((ExecutorService)executor).shutdown(); } } }
@Test public void genotypeValidator() { final int populationSize = 100; final Engine<DoubleGene, Double> engine = Engine .builder(a -> a.getGene().getAllele(), DoubleChromosome.of(0, 1)) .genotypeValidator(pt -> false) .populationSize(populationSize) .build(); final EvolutionResult<DoubleGene, Double> result = engine.stream() .limit(10) .collect(EvolutionResult.toBestEvolutionResult()); Assert.assertEquals(result.getInvalidCount(), populationSize); }
@Test public void phenotypeValidator() { final int populationSize = 100; final Engine<DoubleGene, Double> engine = Engine .builder(a -> a.getGene().getAllele(), DoubleChromosome.of(0, 1)) .phenotypeValidator(pt -> false) .populationSize(populationSize) .build(); final EvolutionResult<DoubleGene, Double> result = engine.stream() .limit(10) .collect(EvolutionResult.toBestEvolutionResult()); Assert.assertEquals(result.getInvalidCount(), populationSize); }
public static void main(final String[] args) { final Engine<CharacterGene, Integer> engine = Engine.builder(PROBLEM) .populationSize(500) .survivorsSelector(new StochasticUniversalSelector<>()) .offspringSelector(new TournamentSelector<>(5)) .alterers( new Mutator<>(0.1), new SinglePointCrossover<>(0.5)) .build(); final Phenotype<CharacterGene, Integer> result = engine.stream() .limit(100) .collect(toBestPhenotype()); System.out.println(result); }
static Engine<EnumGene<Integer>, Integer> buildEngine(Codec<ISeq<Integer>, EnumGene<Integer>> codec) { return Engine.builder(E305::fitness, codec) .offspringSelector(new RouletteWheelSelector<>()) .alterers( new SwapMutator<>(), new PartiallyMatchedCrossover<>(0.9) ) .populationSize(20) .optimize(Optimize.MINIMUM) .build(); }