001 /*
002 * Java Genetic Algorithm Library (jenetics-6.0.0).
003 * Copyright (c) 2007-2020 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.ext.engine;
021
022 import java.util.ArrayList;
023 import java.util.Collection;
024 import java.util.Collections;
025 import java.util.List;
026 import java.util.Spliterator;
027 import java.util.concurrent.atomic.AtomicReference;
028 import java.util.function.Supplier;
029 import java.util.stream.BaseStream;
030 import java.util.stream.Collectors;
031
032 import io.jenetics.Gene;
033 import io.jenetics.engine.EvolutionInit;
034 import io.jenetics.engine.EvolutionResult;
035 import io.jenetics.engine.EvolutionStart;
036 import io.jenetics.engine.EvolutionStream;
037 import io.jenetics.engine.EvolutionStreamable;
038 import io.jenetics.internal.engine.EvolutionStreamImpl;
039
040 import io.jenetics.ext.internal.ConcatSpliterator;
041
042 /**
043 * The {@code ConcatEngine} lets you concatenate two (or more) evolution
044 * {@link io.jenetics.engine.Engine}, with different configurations, and let it
045 * use as <em>one</em> engine {@link EvolutionStreamable}.
046 *
047 * <pre> {@code
048 * +----------+ +----------+
049 * | ES | | ES |
050 * +-------+----+ | +-------+----+ |
051 * (Start) | +-----+ Start | +-----+
052 * ------>| Engine 1 |------------>| Engine 2 |----------->
053 * | | Result | | Result
054 * +------------+ +------------+
055 * }</pre>
056 *
057 * The sketch above shows how the engine concatenation works. In this example,
058 * the evolution stream of the first engine is evaluated until it terminates.
059 * The result of the first stream is then used as start input of the second
060 * evolution stream, which then delivers the final result.
061 * <p>
062 * Concatenating evolution engines might be useful, if you want to explore your
063 * search space with random search first and then start the <em>real</em> GA
064 * search.
065 * <pre>{@code
066 * final Problem<double[], DoubleGene, Double> problem = Problem.of(
067 * v -> Math.sin(v[0])*Math.cos(v[1]),
068 * Codecs.ofVector(DoubleRange.of(0, 2*Math.PI), 2)
069 * );
070 *
071 * final Engine<DoubleGene, Double> engine1 = Engine.builder(problem)
072 * .minimizing()
073 * .alterers(new Mutator<>(0.2))
074 * .selector(new MonteCarloSelector<>())
075 * .build();
076 *
077 * final Engine<DoubleGene, Double> engine2 = Engine.builder(problem)
078 * .minimizing()
079 * .alterers(
080 * new Mutator<>(0.1),
081 * new MeanAlterer<>())
082 * .selector(new RouletteWheelSelector<>())
083 * .build();
084 *
085 * final Genotype<DoubleGene> result =
086 * ConcatEngine.of(
087 * engine1.limit(50),
088 * engine2.limit(() -> Limits.bySteadyFitness(30)))
089 * .stream()
090 * .collect(EvolutionResult.toBestGenotype());
091 *
092 * System.out.println(result + ": " +
093 * problem.fitness().apply(problem.codec().decode(result)));
094 * }</pre>
095 *
096 * An essential part, when concatenating evolution engines, is to make sure your
097 * your engines are creating <em>limited</em> evolution streams. This is what
098 * the {@link EvolutionStreamable#limit(Supplier)} and
099 * {@link EvolutionStreamable#limit(long)} methods are for. Limiting an engine
100 * means, that this engine will surely create only streams, which are limited
101 * with the predicate/generation given to the engine. If you have limited your
102 * engines, it is no longer necessary to limit your final evolution stream, but
103 * your are still able to do so.
104 *
105 * @see CyclicEngine
106 *
107 * @param <G> the gene type
108 * @param <C> the fitness type
109 *
110 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
111 * @version 4.1
112 * @since 4.1
113 */
114 public final class ConcatEngine<
115 G extends Gene<?, G>,
116 C extends Comparable<? super C>
117 >
118 extends EnginePool<G, C>
119 {
120
121 /**
122 * Create a new concatenating evolution engine with the given list of engines.
123 *
124 * @param engines the engines which are concatenated to <em>one</em> engine
125 * @throws NullPointerException if the {@code engines} or one of it's
126 * elements is {@code null}
127 */
128 public ConcatEngine(final List<? extends EvolutionStreamable<G, C>> engines) {
129 super(engines);
130 }
131
132 @Override
133 public EvolutionStream<G, C>
134 stream(final Supplier<EvolutionStart<G, C>> start) {
135 final AtomicReference<EvolutionStart<G, C>> other =
136 new AtomicReference<>(null);
137
138 return new EvolutionStreamImpl<>(
139 new ConcatSpliterator<>(
140 _engines.stream()
141 .map(engine -> engine
142 .stream(() -> start(start, other))
143 .peek(result -> other.set(result.toEvolutionStart())))
144 .map(BaseStream::spliterator)
145 .collect(Collectors.toList())
146 ),
147 false
148 );
149 }
150
151 private EvolutionStart<G, C> start(
152 final Supplier<EvolutionStart<G, C>> first,
153 final AtomicReference<EvolutionStart<G, C>> other
154 ) {
155 return other.get() != null ? other.get() : first.get();
156 }
157
158 @Override
159 public EvolutionStream<G, C> stream(final EvolutionInit<G> init) {
160 final AtomicReference<EvolutionStart<G, C>> other =
161 new AtomicReference<>(null);
162
163 return new EvolutionStreamImpl<>(
164 new ConcatSpliterator<>(spliterators(init, other)),
165 false
166 );
167 }
168
169 private Collection<Spliterator<EvolutionResult<G, C>>> spliterators(
170 final EvolutionInit<G> init,
171 final AtomicReference<EvolutionStart<G, C>> other
172 ) {
173 final Collection<Spliterator<EvolutionResult<G, C>>> result;
174 if (_engines.isEmpty()) {
175 result = Collections.emptyList();
176 } else if (_engines.size() == 1) {
177 result = List.of(
178 _engines.get(0)
179 .stream(init)
180 .peek(er -> other.set(er.toEvolutionStart()))
181 .spliterator()
182 );
183 } else {
184 final List<Spliterator<EvolutionResult<G, C>>> concat =
185 new ArrayList<>();
186
187 concat.add(
188 _engines.get(0)
189 .stream(init)
190 .peek(er -> other.set(er.toEvolutionStart()))
191 .spliterator()
192 );
193 concat.addAll(
194 _engines.subList(1, _engines.size()).stream()
195 .map(engine -> engine
196 .stream(other::get)
197 .peek(er -> other.set(er.toEvolutionStart())))
198 .map(BaseStream::spliterator)
199 .collect(Collectors.toList())
200 );
201
202 result = concat;
203 }
204
205 return result;
206 }
207
208 /**
209 * Create a new concatenating evolution engine with the given array of
210 * engines.
211 *
212 * @param engines the engines which are concatenated to <em>one</em> engine
213 * @param <G> the gene type
214 * @param <C> the fitness type
215 * @return a new concatenating evolution engine
216 * @throws NullPointerException if the {@code engines} or one of it's
217 * elements is {@code null}
218 */
219 @SafeVarargs
220 public static <G extends Gene<?, G>, C extends Comparable<? super C>>
221 ConcatEngine<G, C> of(final EvolutionStreamable<G, C>... engines) {
222 return new ConcatEngine<>(List.of(engines));
223 }
224
225
226 }
|