EvolutionStreamable.java
001 /*
002  * Java Genetic Algorithm Library (jenetics-6.3.0).
003  * Copyright (c) 2007-2021 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.util.Objects.requireNonNull;
023 
024 import java.util.function.Predicate;
025 import java.util.function.Supplier;
026 
027 import io.jenetics.Gene;
028 import io.jenetics.Genotype;
029 import io.jenetics.Phenotype;
030 import io.jenetics.util.ISeq;
031 
032 /**
033  * This interface defines the capability of creating {@link EvolutionStream}s
034  * from a given {@link EvolutionStart} object. It also decouples the engine's
035  * capability from the capability to create evolution streams. The purpose of
036  * this interface is similar to the {@link Iterable} interface.
037  *
038  @see EvolutionStream
039  *
040  @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
041  @version 4.1
042  @since 4.1
043  */
044 public interface EvolutionStreamable<
045     extends Gene<?, G>,
046     extends Comparable<? super C>
047 {
048 
049     /**
050      * Create a new, possibly <em>infinite</em>, evolution stream with the given
051      * evolution start. If an empty {@code Population} is given, the engines
052      * genotype factory is used for creating the population. The given
053      * population might be the result of an other engine and this method allows
054      * to start the evolution with the outcome of an different engine.
055      * The fitness function and the fitness scaler are replaced by the one
056      * defined for this engine.
057      *
058      @param start the data the evolution stream starts with
059      @return a new <b>infinite</b> evolution stream
060      @throws java.lang.NullPointerException if the given evolution
061      *         {@code start} is {@code null}.
062      */
063     EvolutionStream<G, C>
064     stream(final Supplier<EvolutionStart<G, C>> start);
065 
066     /**
067      * Create a new, possibly <em>infinite</em>, evolution stream with the given
068      * initial value. If an empty {@code Population} is given, the engines genotype
069      * factory is used for creating the population. The given population might
070      * be the result of an other engine and this method allows to start the
071      * evolution with the outcome of an different engine. The fitness function
072      * and the fitness scaler are replaced by the one defined for this engine.
073      *
074      @param init the data the evolution stream is initialized with
075      @return a new <b>infinite</b> evolution stream
076      @throws java.lang.NullPointerException if the given evolution
077      *         {@code start} is {@code null}.
078      */
079     EvolutionStream<G, C> stream(final EvolutionInit<G> init);
080 
081 
082     /* *************************************************************************
083      * Default interface methods.
084      * ************************************************************************/
085 
086     /**
087      * Create a new, possibly <em>infinite</em>, evolution stream with a newly
088      * created population. This method is a shortcut for
089      <pre>{@code
090      * final EvolutionStream<G, C> stream = streamable
091      *     .stream(() -> EvolutionStart.of(ISeq.empty(), 1));
092      * }</pre>
093      *
094      @return a new evolution stream.
095      */
096     default EvolutionStream<G, C> stream() {
097         return stream((Supplier<EvolutionStart<G, C>>)EvolutionStart::empty);
098     }
099 
100     /**
101      * Create a new, possibly <em>infinite</em>, evolution stream with the given
102      * evolution start. If an empty {@code Population} is given, the engines genotype
103      * factory is used for creating the population. The given population might
104      * be the result of an other engine and this method allows to start the
105      * evolution with the outcome of an different engine. The fitness function
106      * and the fitness scaler are replaced by the one defined for this engine.
107      *
108      @param start the data the evolution stream starts with
109      @return a new <b>infinite</b> evolution iterator
110      @throws java.lang.NullPointerException if the given evolution
111      *         {@code start} is {@code null}.
112      */
113     default EvolutionStream<G, C>
114     stream(final EvolutionStart<G, C> start) {
115         return stream(() -> start);
116     }
117 
118     /**
119      * Create a new {@code EvolutionStream} starting with a previously evolved
120      {@link EvolutionResult}. The stream is initialized with the population
121      * of the given {@code result} and its total generation
122      {@link EvolutionResult#totalGenerations()}.
123      *
124      <pre>{@code
125      * private static final Problem<Double, DoubleGene, Double>
126      * PROBLEM = Problem.of(
127      *     x -> cos(0.5 + sin(x))*cos(x),
128      *     Codecs.ofScalar(DoubleRange.of(0.0, 2.0*PI))
129      * );
130      *
131      * private static final Engine<DoubleGene, Double>
132      * ENGINE = Engine.builder(PROBLEM)
133      *     .optimize(Optimize.MINIMUM)
134      *     .offspringSelector(new RouletteWheelSelector<>())
135      *     .build();
136      *
137      * public static void main(final String[] args) throws IOException {
138      *     // Result of the first evolution run.
139      *     final EvolutionResult<DoubleGene, Double> rescue = ENGINE.stream()
140      *         .limit(Limits.bySteadyFitness(10))
141      *         .collect(EvolutionResult.toBestEvolutionResult());
142      *
143      *     // Save the result of the first run into a file.
144      *     final Path path = Paths.get("result.bin");
145      *     IO.object.write(rescue, path);
146      *
147      *     // Load the previous result and continue evolution.
148      *     \@SuppressWarnings("unchecked")
149      *     final EvolutionResult<DoubleGene, Double> result = ENGINE
150      *         .stream((EvolutionResult<DoubleGene, Double>)IO.object.read(path))
151      *         .limit(Limits.bySteadyFitness(20))
152      *         .collect(EvolutionResult.toBestEvolutionResult());
153      *
154      *     System.out.println(result.bestPhenotype());
155      * }
156      * }</pre>
157      *
158      * The example above shows how to save an {@link EvolutionResult} from a
159      * first run, save it to disk and continue the evolution.
160      *
161      @param result the previously evolved {@code EvolutionResult}
162      @return a new evolution stream, which continues a previous one
163      @throws NullPointerException if the given evolution {@code result} is
164      *         {@code null}
165      */
166     default EvolutionStream<G, C>
167     stream(final EvolutionResult<G, C> result) {
168         return stream(EvolutionStart.of(
169             result.population(),
170             result.generation()
171         ));
172     }
173 
174     /**
175      * Create a new, possibly <em>infinite</em>, evolution stream with the given
176      * initial population. If an empty {@code Population} is given, the engines
177      * genotype factory is used for creating the population. The given population
178      * might be the result of an other engine and this method allows to start the
179      * evolution with the outcome of an different engine. The fitness function
180      * and the fitness scaler are replaced by the one defined for this engine.
181      *
182      @param population the initial individuals used for the evolution stream.
183      *        Missing individuals are created and individuals not needed are
184      *        skipped.
185      @param generation the generation the stream starts from; must be greater
186      *        than zero.
187      @return a new evolution stream.
188      @throws java.lang.NullPointerException if the given {@code population} is
189      *         {@code null}.
190      @throws IllegalArgumentException if the given {@code generation} is
191      *         smaller then one
192      */
193     default EvolutionStream<G, C> stream(
194         final ISeq<Phenotype<G, C>> population,
195         final long generation
196     ) {
197         return stream(EvolutionStart.of(population, generation));
198     }
199 
200     /**
201      * Create a new, possibly <em>infinite</em>, evolution stream with the given
202      * initial population. If an empty {@code Population} is given, the engines
203      * genotype factory is used for creating the population. The given population
204      * might be the result of an other engine and this method allows to start the
205      * evolution with the outcome of an different engine. The fitness function
206      * and the fitness scaler are replaced by the one defined for this engine.
207      *
208      @param population the initial individuals used for the evolution stream.
209      *        Missing individuals are created and individuals not needed are
210      *        skipped.
211      @return a new evolution stream.
212      @throws java.lang.NullPointerException if the given {@code population} is
213      *         {@code null}.
214      */
215     default EvolutionStream<G, C> stream(final ISeq<Phenotype<G, C>> population) {
216         return stream(EvolutionStart.of(population, 1));
217     }
218 
219     /**
220      * Create a new, possibly <em>infinite</em>, evolution stream with the given
221      * initial individuals. If an empty {@code Iterable} is given, the engines
222      * genotype factory is used for creating the population.
223      *
224      @param genotypes the initial individuals used for the evolution stream.
225      *        Missing individuals are created and individuals not needed are
226      *        skipped.
227      @param generation the generation the stream starts from; must be greater
228      *        than zero.
229      @return a new evolution stream.
230      @throws java.lang.NullPointerException if the given {@code genotypes} is
231      *         {@code null}.
232      @throws IllegalArgumentException if the given {@code generation} is
233      *         smaller then one
234      */
235     default EvolutionStream<G, C> stream(
236         final Iterable<Genotype<G>> genotypes,
237         final long generation
238     ) {
239         return stream(EvolutionInit.of(ISeq.of(genotypes), generation));
240     }
241 
242     /**
243      * Create a new, possibly <em>infinite</em>, evolution stream with the given
244      * initial individuals. If an empty {@code Iterable} is given, the engines
245      * genotype factory is used for creating the population.
246      *
247      @param genotypes the initial individuals used for the evolution stream.
248      *        Missing individuals are created and individuals not needed are
249      *        skipped.
250      @return a new evolution stream.
251      @throws java.lang.NullPointerException if the given {@code genotypes} is
252      *         {@code null}.
253      */
254     default EvolutionStream<G, C>
255     stream(final Iterable<Genotype<G>> genotypes) {
256         return stream(genotypes, 1);
257     }
258 
259     /**
260      * Return a new {@code EvolutionStreamable} instance where all created
261      * {@code EvolutionStream}s are limited by the given predicate. Since some
262      * predicates has to maintain internal state, a predicate {@code Supplier}
263      * must be given instead a plain limiting predicate.
264      *
265      @param proceed the limiting predicate supplier.
266      @return a new evolution streamable object
267      @throws NullPointerException if the give {@code predicate} is {@code null}
268      */
269     default EvolutionStreamable<G, C>
270     limit(final Supplier<? extends Predicate<? super EvolutionResult<G, C>>> proceed) {
271         requireNonNull(proceed);
272 
273         return new EvolutionStreamable<>() {
274             @Override
275             public EvolutionStream<G, C>
276             stream(final Supplier<EvolutionStart<G, C>> start) {
277                 return EvolutionStreamable.this.stream(start).limit(proceed.get());
278             }
279 
280             @Override
281             public EvolutionStream<G, C> stream(final EvolutionInit<G> init) {
282                 return EvolutionStreamable.this.stream(init).limit(proceed.get());
283             }
284         };
285     }
286 
287     /**
288      * Return a new {@code EvolutionStreamable} instance where all created
289      * {@code EvolutionStream}s are limited to the given number of generations.
290      *
291      @param generations the number of generations after the created evolution
292      *        streams are truncated
293      @return a new evolution streamable object
294      @throws IllegalArgumentException if the given {@code generations} is
295      *         smaller than zero.
296      */
297     default EvolutionStreamable<G, C> limit(final long generations) {
298         return limit(() -> Limits.byFixedGeneration(generations));
299     }
300 
301 }