001 /*
002 * Java Genetic Algorithm Library (jenetics-4.2.0).
003 * Copyright (c) 2007-2018 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 */
020 package io.jenetics.engine;
021
022 import static java.lang.Math.abs;
023 import static java.lang.Math.max;
024 import static java.lang.String.format;
025
026 import java.time.Clock;
027 import java.time.Duration;
028 import java.util.concurrent.atomic.AtomicLong;
029 import java.util.function.BiPredicate;
030 import java.util.function.Predicate;
031
032 import io.jenetics.NumericGene;
033 import io.jenetics.internal.util.require;
034 import io.jenetics.stat.DoubleMoments;
035 import io.jenetics.util.NanoClock;
036
037 /**
038 * This class contains factory methods for creating predicates, which can be
039 * used for limiting the evolution stream. Some of the <em>limit</em> predicates
040 * have to maintain internal state for working properly. It is therefor
041 * recommended to create new instances for every stream and don't reuse it.
042 *
043 * @see EvolutionStream#limit(Predicate)
044 *
045 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
046 * @since 3.0
047 * @version 3.7
048 */
049 public final class Limits {
050 private Limits() {require.noInstance();}
051
052 /**
053 * Return a predicate which always return {@code true}.
054 *
055 * @since 4.1
056 *
057 * @return a predicate which always return {@code true}
058 */
059 public static Predicate<Object> infinite() {
060 return result -> true;
061 }
062
063 /**
064 * Return a predicate, which will truncate the evolution stream after the
065 * given number of generations. The returned predicate behaves like a call
066 * of the {@link java.util.stream.Stream#limit(long)} and exists for
067 * <i>completeness</i> reasons.
068 *
069 * @since 3.1
070 *
071 * @param generation the number of generations after the evolution stream is
072 * truncated
073 * @return a predicate which truncates the evolution stream after the given
074 * number of generations
075 * @throws java.lang.IllegalArgumentException if the given {@code generation}
076 * is smaller than zero.
077 */
078 public static Predicate<Object> byFixedGeneration(final long generation) {
079 if (generation < 0) {
080 throw new IllegalArgumentException(format(
081 "The number of generations must greater than one, but was %d",
082 generation
083 ));
084 }
085
086 return new Predicate<Object>() {
087 private final AtomicLong _current = new AtomicLong();
088 @Override
089 public boolean test(final Object o) {
090 return _current.incrementAndGet() <= generation;
091 }
092 };
093 }
094
095 /**
096 * Return a predicate, which will truncate the evolution stream if no
097 * better phenotype could be found after the given number of
098 * {@code generations}.
099 *
100 * <pre>{@code
101 * final Phenotype<DoubleGene, Double> result = engine.stream()
102 * // Truncate the evolution stream after 5 "steady" generations.
103 * .limit(bySteadyFitness(5))
104 * // The evolution will stop after maximal 100 generations.
105 * .limit(100)
106 * .collect(toBestPhenotype());
107 * }</pre>
108 *
109 * @param generations the number of <i>steady</i> generations
110 * @param <C> the fitness type
111 * @return a predicate which truncate the evolution stream if no better
112 * phenotype could be found after a give number of
113 * {@code generations}
114 * @throws IllegalArgumentException if the generation is smaller than
115 * one.
116 */
117 public static <C extends Comparable<? super C>>
118 Predicate<EvolutionResult<?, C>> bySteadyFitness(final int generations) {
119 return new SteadyFitnessLimit<>(generations);
120 }
121
122 /**
123 * Return a predicate, which will truncate the evolution stream if the GA
124 * execution exceeds a given time duration. This predicate is (normally)
125 * used as safety net, for guaranteed stream truncation.
126 *
127 * <pre>{@code
128 * final Phenotype<DoubleGene, Double> result = engine.stream()
129 * // Truncate the evolution stream after 5 "steady" generations.
130 * .limit(bySteadyFitness(5))
131 * // The evolution will stop after maximal 500 ms.
132 * .limit(byExecutionTime(Duration.ofMillis(500), Clock.systemUTC())
133 * .collect(toBestPhenotype());
134 * }</pre>
135 *
136 * @since 3.1
137 *
138 * @param duration the duration after the evolution stream will be truncated
139 * @param clock the clock used for measure the execution time
140 * @return a predicate, which will truncate the evolution stream, based on
141 * the exceeded execution time
142 * @throws NullPointerException if one of the arguments is {@code null}
143 */
144 public static Predicate<Object>
145 byExecutionTime(final Duration duration, final Clock clock) {
146 return new ExecutionTimeLimit(duration, clock);
147 }
148
149 /**
150 * Return a predicate, which will truncate the evolution stream if the GA
151 * execution exceeds a given time duration. This predicate is (normally)
152 * used as safety net, for guaranteed stream truncation.
153 *
154 * <pre>{@code
155 * final Phenotype<DoubleGene, Double> result = engine.stream()
156 * // Truncate the evolution stream after 5 "steady" generations.
157 * .limit(bySteadyFitness(5))
158 * // The evolution will stop after maximal 500 ms.
159 * .limit(byExecutionTime(Duration.ofMillis(500))
160 * .collect(toBestPhenotype());
161 * }</pre>
162 *
163 * @since 3.1
164 *
165 * @param duration the duration after the evolution stream will be truncated
166 * @return a predicate, which will truncate the evolution stream, based on
167 * the exceeded execution time
168 * @throws NullPointerException if the evolution {@code duration} is
169 * {@code null}
170 */
171 public static Predicate<Object>
172 byExecutionTime(final Duration duration) {
173 return byExecutionTime(duration, NanoClock.systemUTC());
174 }
175
176 /**
177 * Return a predicate, which will truncated the evolution stream if the
178 * best fitness of the current population becomes less than the specified
179 * threshold and the objective is set to minimize the fitness. This
180 * predicate also stops the evolution if the best fitness in the current
181 * population becomes greater than the user-specified fitness threshold when
182 * the objective is to maximize the fitness.
183 *
184 * <pre>{@code
185 * final Phenotype<DoubleGene, Double> result = engine.stream()
186 * // Truncate the evolution stream if the best fitness is higher than
187 * // the given threshold of '2.3'.
188 * .limit(byFitnessThreshold(2.3))
189 * // The evolution will stop after maximal 250 generations; guarantees
190 * // the termination (truncation) of the evolution stream.
191 * .limit(250)
192 * .collect(toBestPhenotype());
193 * }</pre>
194 *
195 * @since 3.1
196 *
197 * @param threshold the desired threshold
198 * @param <C> the fitness type
199 * @return the predicate which truncates the evolution stream based on the
200 * given {@code threshold}.
201 * @throws NullPointerException if the given {@code threshold} is
202 * {@code null}.
203 */
204 public static <C extends Comparable<? super C>>
205 Predicate<EvolutionResult<?, C>> byFitnessThreshold(final C threshold) {
206 return new FitnessThresholdLimit<>(threshold);
207 }
208
209 /**
210 * Return a predicate, which will truncate the evolution stream if the
211 * fitness is converging. Two filters of different lengths are used to
212 * smooth the best fitness across the generations.
213 *
214 * <pre>{@code
215 * final Phenotype<DoubleGene, Double> result = engine.stream()
216 * .limit(byFitnessConvergence(5, 15, (s, l) -> {
217 * final double div = max(abs(s.getMean()), abs(l.getMean()));
218 * final eps = abs(s.getMean() - l.getMean())/(div <= 10E-20 ? 1.0 : div);
219 * return esp >= 10E-5
220 * }))
221 * .collect(toBestPhenotype());
222 * }</pre>
223 *
224 * In the example above, the moving average of the short- and long filter
225 * is used for determining the fitness convergence.
226 *
227 * @apiNote The returned predicate maintains mutable state.
228 * Using it in a parallel evolution streams needs external synchronization
229 * of the {@code test} method.
230 *
231 * @since 3.7
232 *
233 * @param shortFilterSize the size of the short filter
234 * @param longFilterSize the size of the long filter. The long filter size
235 * also determines the minimum number of generations of the evolution
236 * stream.
237 * @param proceed the predicate which determines when the evolution stream
238 * is truncated. The first parameter of the predicate contains the
239 * double statistics of the short filter and the second parameter
240 * contains the statistics of the long filter
241 * @param <N> the fitness type
242 * @return a new fitness convergence strategy
243 * @throws NullPointerException if the {@code proceed} predicate is
244 * {@code null}
245 */
246 public static <N extends Number & Comparable<? super N>>
247 Predicate<EvolutionResult<?, N>> byFitnessConvergence(
248 final int shortFilterSize,
249 final int longFilterSize,
250 final BiPredicate<DoubleMoments, DoubleMoments> proceed
251 ) {
252 return new FitnessConvergenceLimit<>(
253 shortFilterSize,
254 longFilterSize,
255 proceed
256 );
257 }
258
259 /**
260 * Return a predicate, which will truncate the evolution stream if the
261 * fitness is converging. Two filters of different lengths are used to
262 * smooth the best fitness across the generations. When the smoothed best
263 * fitness from the long filter is less than a user-specified percentage
264 * away from the smoothed best fitness from the short filter, the fitness is
265 * deemed as converged and the evolution terminates.
266 *
267 * <pre>{@code
268 * final Phenotype<DoubleGene, Double> result = engine.stream()
269 * .limit(byFitnessConvergence(5, 15, 10E-4))
270 * .collect(toBestPhenotype());
271 * }</pre>
272 *
273 * In the given example, the evolution stream stops, if the difference of the
274 * mean values of the long and short filter is less than 1%. The short
275 * filter calculates the mean of the best fitness values of the last 5
276 * generations. The long filter uses the best fitness values of the last 15
277 * generations.
278 *
279 * @apiNote The returned predicate maintains mutable state.
280 * Using it in a parallel evolution streams needs external synchronization
281 * of the {@code test} method.
282 *
283 * @since 3.7
284 *
285 * @param shortFilterSize the size of the short filter
286 * @param longFilterSize the size of the long filter. The long filter size
287 * also determines the minimum number of generations of the evolution
288 * stream.
289 * @param epsilon the maximal relative distance of the mean value between
290 * the short and the long filter. The {@code epsilon} must within the
291 * range of {@code [0..1]}.
292 * @param <N> the fitness type
293 * @return a new fitness convergence strategy
294 * @throws IllegalArgumentException if {@code shortFilterSize < 1} ||
295 * {@code longFilterSize < 2} ||
296 * {@code shortFilterSize >= longFilterSize}
297 * @throws IllegalArgumentException if {@code epsilon} is not in the range
298 * of {@code [0..1]}
299 */
300 public static <N extends Number & Comparable<? super N>>
301 Predicate<EvolutionResult<?, N>> byFitnessConvergence(
302 final int shortFilterSize,
303 final int longFilterSize,
304 final double epsilon
305 ) {
306 if (epsilon < 0.0 || epsilon > 1.0) {
307 throw new IllegalArgumentException(format(
308 "The given epsilon is not in the range [0, 1]: %f", epsilon
309 ));
310 }
311
312 return new FitnessConvergenceLimit<>(
313 shortFilterSize,
314 longFilterSize,
315 (s, l) -> eps(s.getMean(), l.getMean()) >= epsilon
316 );
317 }
318
319 // Calculate the relative mean difference between short and long filter.
320 private static double eps(final double s, final double l) {
321 final double div = max(abs(s), abs(l));
322 return abs(s - l)/(div <= 10E-20 ? 1.0 : div);
323 }
324
325 /**
326 * A termination method that stops the evolution when the population is
327 * deemed as converged. The population is deemed as converged when the
328 * average fitness across the current population is less than a
329 * user-specified percentage away from the best fitness of the current
330 * population. This method takes a predicate with the <em>best</em> fitness
331 * and the population fitness moments and determine whether to proceed or
332 * not.
333 *
334 * @since 3.9
335 *
336 * @param proceed the predicate which determines when the evolution stream
337 * is truncated. The first parameter of the predicate contains the
338 * best fitness of the population and the second parameter contains
339 * the statistics of population fitness values
340 * @param <N> the fitness type
341 * @return a new fitness convergence strategy
342 * @throws NullPointerException if the {@code proceed} predicate is
343 * {@code null}
344 */
345 public static <N extends Number & Comparable<? super N>>
346 Predicate<EvolutionResult<?, N>> byPopulationConvergence(
347 final BiPredicate<Double, DoubleMoments> proceed
348 ) {
349 return new PopulationConvergenceLimit<>(proceed);
350 }
351
352 /**
353 * A termination method that stops the evolution when the population is
354 * deemed as converged. The population is deemed as converged when the
355 * average fitness across the current population is less than a
356 * user-specified percentage away from the best fitness of the current
357 * population.
358 *
359 * @since 3.9
360 *
361 * @param epsilon the maximal relative distance of the best fitness value of
362 * the population and the mean value of the population fitness values.
363 * @param <N> the fitness type
364 * @return a new fitness convergence strategy
365 * @throws IllegalArgumentException if {@code epsilon} is not in the range
366 * of {@code [0..1]}
367 */
368 public static <N extends Number & Comparable<? super N>>
369 Predicate<EvolutionResult<?, N>>
370 byPopulationConvergence(final double epsilon) {
371 if (epsilon < 0.0 || epsilon > 1.0) {
372 throw new IllegalArgumentException(format(
373 "The given epsilon is not in the range [0, 1]: %f", epsilon
374 ));
375 }
376
377 return new PopulationConvergenceLimit<>((best, moments) ->
378 eps(best, moments.getMean()) >= epsilon
379 );
380 }
381
382 /**
383 * A termination method that stops the evolution when a user-specified
384 * percentage of the genes ({@code convergedGeneRage}) that make up a
385 * {@code Genotype} are deemed as converged. A gene is deemed as converged,
386 * if the {@code geneConvergence} {@code Predicate<DoubleMoments>} for this
387 * gene returns {@code true}.
388 *
389 * @since 4.0
390 * @see #byGeneConvergence(double, double)
391 *
392 * @param geneConvergence predicate which defines when a gene is deemed as
393 * converged, by using the statistics of this gene over all genotypes
394 * of the population
395 * @param convergedGeneRate the percentage of genes which must be converged
396 * for truncating the evolution stream
397 * @param <G> the gene type
398 * @return a new gene convergence predicate
399 * @throws NullPointerException if the given gene convergence predicate is
400 * {@code null}
401 * @throws IllegalArgumentException if the {@code convergedGeneRate} is not
402 * within the range {@code [0, 1]}
403 */
404 public static <G extends NumericGene<?, G>> Predicate<EvolutionResult<G, ?>>
405 byGeneConvergence(
406 final Predicate<DoubleMoments> geneConvergence,
407 final double convergedGeneRate
408 ) {
409 return new GeneConvergenceLimit<>(geneConvergence, convergedGeneRate);
410 }
411
412 /**
413 * A termination method that stops the evolution when a user-specified
414 * percentage of the genes ({@code convergedGeneRage}) that make up a
415 * {@code Genotype} are deemed as converged. A gene is deemed as converged
416 * when the average value of that gene across all of the genotypes in the
417 * current population is less than a user-specified percentage
418 * ({@code convergenceRate}) away from the maximum gene value across the
419 * genotypes.
420 * <p>
421 * This method is equivalent the following code snippet:
422 * <pre>{@code
423 * final Predicate<EvolutionResult<DoubleGene, ?>> limit =
424 * byGeneConvergence(
425 * stat -> stat.getMax()*convergenceRate <= stat.getMean(),
426 * convergedGeneRate
427 * );
428 * }</pre>
429 *
430 * @since 4.0
431 * @see #byGeneConvergence(Predicate, double)
432 *
433 * @param convergenceRate the relative distance of the average gene value
434 * to its maximum value
435 * @param convergedGeneRate the percentage of genes which must be converged
436 * for truncating the evolution stream
437 * @param <G> the gene type
438 * @return a new gene convergence predicate
439 * @throws IllegalArgumentException if the {@code convergedGeneRate} or
440 * {@code convergenceRate} are not within the range {@code [0, 1]}
441 */
442 public static <G extends NumericGene<?, G>> Predicate<EvolutionResult<G, ?>>
443 byGeneConvergence(
444 final double convergenceRate,
445 final double convergedGeneRate
446 ) {
447 return byGeneConvergence(
448 stat -> stat.getMax()*convergenceRate <= stat.getMean(),
449 convergedGeneRate
450 );
451 }
452
453 }
|