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