/** * Return a new {@code EvolutionStreamable} instance where all created * {@code EvolutionStream}s are limited to the given number of generations. * * @param generations the number of generations after the created evolution * streams are truncated * @return a new evolution streamable object * @throws IllegalArgumentException if the given {@code generations} is * smaller than zero. */ public default EvolutionStreamable<G, C> limit(final long generations) { return limit(() -> Limits.byFixedGeneration(generations)); }
public static void main(final String[] args) throws IOException { final EvolutionResult<DoubleGene, Double> rescue = ENGINE.stream() .limit(Limits.bySteadyFitness(10)) .collect(EvolutionResult.toBestEvolutionResult()); final Path path = Paths.get("result.bin"); IO.object.write(rescue, path); @SuppressWarnings("unchecked") final EvolutionResult<DoubleGene, Double> result = ENGINE .stream((EvolutionResult<DoubleGene, Double>)IO.object.read(path)) .limit(Limits.bySteadyFitness(20)) .collect(EvolutionResult.toBestEvolutionResult()); System.out.println(result); }
/** * Return a predicate, which will truncate the evolution stream if the GA * execution exceeds a given time duration. This predicate is (normally) * used as safety net, for guaranteed stream truncation. * * <pre>{@code * final Phenotype<DoubleGene, Double> result = engine.stream() * // Truncate the evolution stream after 5 "steady" generations. * .limit(bySteadyFitness(5)) * // The evolution will stop after maximal 500 ms. * .limit(byExecutionTime(Duration.ofMillis(500)) * .collect(toBestPhenotype()); * }</pre> * * @since 3.1 * * @param duration the duration after the evolution stream will be truncated * @return a predicate, which will truncate the evolution stream, based on * the exceeded execution time * @throws NullPointerException if the evolution {@code duration} is * {@code null} */ public static Predicate<Object> byExecutionTime(final Duration duration) { return byExecutionTime(duration, NanoClock.systemUTC()); }
@Test public void limit() { final Predicate<EvolutionResult<?, Double>> l = Limits.byFitnessConvergence(5, 10, 0.015); int g = 0; while (l.test(result(10 + g, 100 + g, Optimize.MAXIMUM))) { ++g; } Assert.assertEquals(g, 69); }
@Test(dataProvider = "limits") public void limit( final ISeq<Phenotype<DoubleGene, Double>> pop, final double geneConvergence, final double convergenceRage, final boolean proceed ) { //final ISeq<DoubleMoments> stat = GeneConvergenceLimit.statistics(pop); //stat.forEach(System.out::println); final Predicate<EvolutionResult<DoubleGene, ?>> l = Limits.byGeneConvergence(geneConvergence, convergenceRage); //System.out.println(l.test(result(pop))); Assert.assertEquals(l.test(result(pop)), proceed); }
@Test // https://github.com/jenetics/jenetics/issues/318 public void initialFitnessConvergence() { final Problem<Double, DoubleGene, Double> problem = Problem.of( d -> 1.0, Codecs.ofScalar(DoubleRange.of(0, 1)) ); final Engine<DoubleGene, Double> engine = Engine.builder(problem).build(); final AtomicInteger count = new AtomicInteger(); final EvolutionResult<DoubleGene, Double> result = engine.stream() .limit(Limits.byFitnessThreshold(0.3)) .peek(er -> count.incrementAndGet()) .collect(EvolutionResult.toBestEvolutionResult()); Assert.assertNotNull(result); Assert.assertEquals(count.get(), 1); Assert.assertEquals(result.getTotalGenerations(), 1); Assert.assertEquals(result.getGeneration(), 1); }
@Test // https://github.com/jenetics/jenetics/issues/318 public void initialFitnessConvergence() { final Problem<Double, DoubleGene, Double> problem = Problem.of( d -> 1.0, Codecs.ofScalar(DoubleRange.of(0, 1)) ); final Engine<DoubleGene, Double> engine = Engine.builder(problem).build(); final AtomicInteger count = new AtomicInteger(); final EvolutionResult<DoubleGene, Double> result = engine.stream() .limit(Limits.byFitnessConvergence(1, 2, 0.03)) .peek(er -> count.incrementAndGet()) .collect(EvolutionResult.toBestEvolutionResult()); Assert.assertNotNull(result); Assert.assertEquals(count.get(), 1); Assert.assertEquals(result.getTotalGenerations(), 1); Assert.assertEquals(result.getGeneration(), 1); }
final double convergedGeneRate ) { return byGeneConvergence( stat -> stat.getMax()*convergenceRate <= stat.getMean(), convergedGeneRate
@Test // https://github.com/jenetics/jenetics/issues/420 public void bestFitnessResult() { final Genotype<IntegerGene> genotype = Genotype.of(IntegerChromosome.of(0, 10)); final AtomicInteger ai = new AtomicInteger(); final Function<Genotype<IntegerGene>, Integer> ff = x -> ai.incrementAndGet(); final int threshold = 100; final Integer result = Engine.builder(ff, genotype) .build() .stream() .limit(Limits.byFitnessThreshold(threshold)) .collect(EvolutionResult.toBestEvolutionResult()) .getBestFitness(); Assert.assertNotNull(result); Assert.assertTrue( result >= 100, format("Expected value >= %s, but got %s", threshold, result) ); }
public static void main(final String[] args) throws IOException { final String base = "/home/fwilhelm/Workspace/Development/Projects/" + "Jenetics/jenetics.tool/src/main/resources/io/jenetics/tool/moea"; final Path data = Paths.get(base, "circle_max_front.dat"); final Path output = Paths.get(base, "circle_max_front.svg"); final Engine<DoubleGene, Vec<double[]>> engine = Engine.builder(PROBLEM) .alterers( new Mutator<>(0.1), new MeanAlterer<>()) .offspringSelector(new TournamentSelector<>(3)) .survivorsSelector(UFTournamentSelector.ofVec()) .build(); final ISeq<Phenotype<DoubleGene, Vec<double[]>>> front = engine.stream() .limit(Limits.byFixedGeneration(100)) .collect(MOEA.toParetoSet(IntRange.of(100, 150))); final StringBuilder out = new StringBuilder(); out.append("#x y\n"); front.forEach(p -> { out.append(p.getFitness().data()[0]); out.append(" "); out.append(p.getFitness().data()[1]); out.append("\n"); }); Files.write(data, out.toString().getBytes()); final Gnuplot gnuplot = new Gnuplot(Paths.get(base, "circle_points.gp")); gnuplot.create(data, output); }
public static void main(final String[] args) { final Genotype<DoubleGene> best = EvolutionStream .of(() -> start(50, 0), SpecialEngine::evolve) .limit(Limits.bySteadyFitness(10)) .limit(1000) .collect(EvolutionResult.toBestGenotype()); System.out.println(String.format("Best Genotype: %s", best)); } }
@Test(dataProvider = "durations") public void test(final Integer millis) { final CountClock clock = new CountClock(); final Duration duration = Duration.ofMillis(millis); final AtomicInteger count = new AtomicInteger(); stream() .limit(Limits.byExecutionTime(duration, clock)) .forEach(s -> count.incrementAndGet()); Assert.assertEquals(count.get(), millis.intValue()); Assert.assertEquals(clock.count, count.get() + 1); }
public static void main(final String[] args) throws InterruptedException { final Args arguments = Args.of(args); final ISeq<Integer> sizes = arguments.intArgs("params"); final Runner<Double, BitGene, Double> runner = Runner.of( fitness -> KNAPSACK, epsilon -> Limits.byFitnessConvergence(sizes.get(0), sizes.get(1), epsilon), TRIAL_METER, Writer.text().map(Object::toString), Reader.text().map(Double::parseDouble), args ); runner.start(); runner.join(); }
@Test // https://github.com/jenetics/jenetics/issues/318 public void initialGeneConvergence() { RandomRegistry.using(Random32.of(() -> 234), random -> { final Problem<Double, DoubleGene, Double> problem = Problem.of( d -> 1.0, Codecs.ofScalar(DoubleRange.of(0, 1)) ); final Engine<DoubleGene, Double> engine = Engine .builder(problem) .executor(Runnable::run) .build(); final AtomicInteger count = new AtomicInteger(); final EvolutionResult<DoubleGene, Double> result = engine.stream() .limit(Limits.byGeneConvergence(0.03, 0.03)) .peek(er -> count.incrementAndGet()) .collect(EvolutionResult.toBestEvolutionResult()); Assert.assertNotNull(result); Assert.assertEquals(count.get(), 1); Assert.assertEquals(result.getTotalGenerations(), 1); Assert.assertEquals(result.getGeneration(), 1); }); }
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); }
public static void main(final String[] args) throws IOException { final String base = "/home/fwilhelm/Workspace/Development/Projects/" + "Jenetics/jenetics.tool/src/main/resources/io/jenetics/tool/moea"; final Path data = Paths.get(base, "circle_min_front.dat"); final Path output = Paths.get(base, "circle_min_front.svg"); final Engine<DoubleGene, Vec<double[]>> engine = Engine.builder(PROBLEM) .alterers( new Mutator<>(0.1), new MeanAlterer<>()) .offspringSelector(new TournamentSelector<>(3)) .survivorsSelector(UFTournamentSelector.ofVec()) .minimizing() .build(); final ISeq<Phenotype<DoubleGene, Vec<double[]>>> front = engine.stream() .limit(Limits.byFixedGeneration(100)) .collect(MOEA.toParetoSet(IntRange.of(100, 150))); final StringBuilder out = new StringBuilder(); out.append("#x y\n"); front.forEach(p -> { out.append(p.getFitness().data()[0]); out.append(" "); out.append(p.getFitness().data()[1]); out.append("\n"); }); Files.write(data, out.toString().getBytes()); final Gnuplot gnuplot = new Gnuplot(Paths.get(base, "circle_points.gp")); gnuplot.create(data, output); }
public static void main(String[] args) { // Set the PRNG used by the evolution Engine. final LCG64ShiftRandom random = new LCG64ShiftRandom(123); RandomRegistry.setRandom(random); // Configure and build the evolution Engine. final Engine<BitGene, Integer> engine = Engine .builder( RngExample::count, BitChromosome.of(20, 0.15)) .build(); // The 'Random(123)' object is used for creating a *reproducible* // initial population. The original PRNG is restored after the 'with' // block. assert RandomRegistry.getRandom() == random; final List<Genotype<BitGene>> genotypes = RandomRegistry.with(new Random(123), r -> { assert RandomRegistry.getRandom() == r; return Genotype.of(BitChromosome.of(20, 0.15)) .instances() .limit(50) .collect(Collectors.toList()); }); assert RandomRegistry.getRandom() == random; // The evolution process uses the global 'random' instance. final Phenotype<BitGene, Integer> best = engine.stream(genotypes) .limit(bySteadyFitness(20)) .limit(100) .collect(toBestPhenotype()); System.out.println(best); }
public static void main(final String[] args) throws InterruptedException { final Runner<Long, BitGene, Double> runner = Runner.of( duration -> KNAPSACK, duration -> Limits.byExecutionTime(Duration.ofMillis(duration)), TRIAL_METER, Writer.text().map(Object::toString), Reader.text().map(Long::parseLong), args ); runner.start(); runner.join(); }
@Test(invocationCount = 5) public void onesCountLimit() { final Problem<ISeq<BitGene>, BitGene, Integer> problem = Problem.of( genes -> (int)genes.stream().filter(BitGene::getBit).count(), Codec.of( Genotype.of(BitChromosome.of(20, 0.125)), gt -> gt.getChromosome().toSeq() ) ); final Engine<BitGene, Integer> engine = Engine.builder(problem) .build(); final EvolutionResult<BitGene, Integer> result = engine.stream() .limit(Limits.byFitnessConvergence(5, 10, 0.01)) .collect(EvolutionResult.toBestEvolutionResult()); Assert.assertTrue( result.getTotalGenerations() < 50, "Gen: " + result.getTotalGenerations() ); }
@Test(dataProvider = "generations") public void engineGenerationLimit2(final Long generations) { final Engine<DoubleGene, Double> engine = Engine .builder(a -> a.getGene().getAllele(), DoubleChromosome.of(0, 1)) .build(); final EvolutionResult<DoubleGene, Double> result = engine .limit(() -> Limits.byFixedGeneration(generations)) .limit(() -> Limits.byFixedGeneration(Math.min(generations, 5))) .stream() .collect(EvolutionResult.toBestEvolutionResult()); Assert.assertEquals(Math.min(generations, 5), result.getTotalGenerations()); }