001 /*
002 * Java Genetic Algorithm Library (jenetics-5.0.0).
003 * Copyright (c) 2007-2019 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.BiFunction;
025 import java.util.function.Function;
026
027 import io.jenetics.Gene;
028 import io.jenetics.Genotype;
029 import io.jenetics.util.Factory;
030 import io.jenetics.util.ISeq;
031
032 /**
033 * A problem {@code Codec} contains the information about how to encode a given
034 * argument type into a {@code Genotype}. It also lets convert the encoded
035 * {@code Genotype} back to the argument type. The engine creation and the
036 * implementation of the fitness function can be heavily simplified by using
037 * a {@code Codec} class. The example given in the {@link Engine} documentation
038 * can be simplified as follows:
039 *
040 * <pre>{@code
041 * public class RealFunction {
042 * // The conversion from the 'Genotype' to the argument type of the fitness
043 * // function is performed by the given 'Codec'. You can concentrate on the
044 * // implementation, because you are not bothered with the conversion code.
045 * private static double eval(final double x) {
046 * return cos(0.5 + sin(x)) * cos(x);
047 * }
048 *
049 * public static void main(final String[] args) {
050 * final Engine<DoubleGene, Double> engine = Engine
051 * // Create an Engine.Builder with the "pure" fitness function
052 * // and the appropriate Codec.
053 * .build(RealFunction::eval, Codecs.ofScalar(DoubleRange.of(0, 2*PI)))
054 * .build();
055 * ...
056 * }
057 * }
058 * }</pre>
059 *
060 * The {@code Codec} needed for the above usage example, will look like this:
061 * <pre>{@code
062 * final DoubleRange domain = DoubleRange.of(0, 2*PI);
063 * final Codec<Double, DoubleGene> codec = Codec.of(
064 * Genotype.of(DoubleChromosome.of(domain)),
065 * gt -> gt.getChromosome().getGene().getAllele()
066 * );
067 * }</pre>
068 *
069 * Calling the {@link Codec#of(Factory, Function)} method is the usual way for
070 * creating new {@code Codec} instances.
071 *
072 * @see Codecs
073 * @see Engine
074 * @see Engine.Builder
075 *
076 * @param <T> the argument type of a given problem
077 * @param <G> the {@code Gene} type used for encoding the argument type {@code T}
078 *
079 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
080 * @version 3.6
081 * @since 3.2
082 */
083 public interface Codec<T, G extends Gene<?, G>> {
084
085 /**
086 * Return the genotype factory for creating genotypes with the right
087 * encoding for the given problem. The genotype created with this factory
088 * must work together with the {@link #decoder()} function, which transforms
089 * the genotype into an object of the problem domain.
090 *
091 * <pre>{@code
092 * final Codec<SomeObject, DoubleGene> codec = ...
093 * final Genotype<DoubleGene> gt = codec.encoding().newInstance();
094 * final SomeObject arg = codec.decoder().apply(gt);
095 * }</pre>
096 *
097 * @see #decoder()
098 *
099 * @return the genotype (factory) representation of the problem domain
100 */
101 public Factory<Genotype<G>> encoding();
102
103 /**
104 * Return the <em>decoder</em> function which transforms the genotype back
105 * to the original problem domain representation.
106 *
107 * @see #encoding()
108 *
109 * @return genotype decoder
110 */
111 public Function<Genotype<G>, T> decoder();
112
113 /**
114 * Converts the given {@link Genotype} to the target type {@link T}. This is
115 * a shortcut for
116 * <pre>{@code
117 * final Codec<SomeObject, DoubleGene> codec = ...
118 * final Genotype<DoubleGene> gt = codec.encoding().newInstance();
119 *
120 * final SomeObject arg = codec.decoder().apply(gt);
121 * }</pre>
122 *
123 * @since 3.6
124 *
125 * @param genotype the genotype to be converted
126 * @return the converted genotype
127 * @throws NullPointerException if the given {@code genotype} is {@code null}
128 */
129 public default T decode(final Genotype<G> genotype) {
130 requireNonNull(genotype);
131 return decoder().apply(genotype);
132 }
133
134 /**
135 * Create a new {@code Codec} with the mapped result type. The following
136 * example creates a double codec who's values are not uniformly distributed
137 * between {@code [0..1)}. Instead the values now follow an exponential
138 * function.
139 *
140 * <pre>{@code
141 * final Codec<Double, DoubleGene> c = Codecs.ofScalar(DoubleRange.of(0, 1))
142 * .map(Math::exp);
143 * }</pre>
144 *
145 * @since 4.0
146 *
147 * @param mapper the mapper function
148 * @param <B> the new argument type of the given problem
149 * @return a new {@code Codec} with the mapped result type
150 * @throws NullPointerException if the mapper is {@code null}.
151 */
152 public default <B>
153 Codec<B, G> map(final Function<? super T, ? extends B> mapper) {
154 requireNonNull(mapper);
155
156 return Codec.of(
157 encoding(),
158 gt -> mapper.apply(decode(gt))
159 );
160 }
161
162 /**
163 * Create a new {@code Codec} object with the given {@code encoding} and
164 * {@code decoder} function.
165 *
166 * @param encoding the genotype factory used for creating new
167 * {@code Genotypes}.
168 * @param decoder decoder function, which converts a {@code Genotype} to a
169 * value in the problem domain.
170 * @param <G> the {@code Gene} type
171 * @param <T> the fitness function argument type in the problem domain
172 * @return a new {@code Codec} object with the given parameters.
173 * @throws NullPointerException if one of the arguments is {@code null}.
174 */
175 public static <T, G extends Gene<?, G>> Codec<T, G> of(
176 final Factory<Genotype<G>> encoding,
177 final Function<Genotype<G>, T> decoder
178 ) {
179 requireNonNull(encoding);
180 requireNonNull(decoder);
181
182 return new Codec<T, G>() {
183 @Override
184 public Factory<Genotype<G>> encoding() {
185 return encoding;
186 }
187
188 @Override
189 public Function<Genotype<G>, T> decoder() {
190 return decoder;
191 }
192 };
193 }
194
195
196 /**
197 * Converts two given {@code Codec} instances into one. This lets you divide
198 * a problem into sub problems and combine them again.
199 * <p>
200 * The following example shows how to combine two codecs, which converts a
201 * {@code LongGene} to a {@code LocalDate}, to a codec which combines the
202 * two {@code LocalDate} object (this are the argument types of the
203 * component codecs) to a {@code Duration}.
204 *
205 * <pre>{@code
206 * final Codec<LocalDate, LongGene> dateCodec1 = Codec.of(
207 * Genotype.of(LongChromosome.of(0, 10_000)),
208 * gt -> LocalDate.ofEpochDay(gt.getGene().longValue())
209 * );
210 *
211 * final Codec<LocalDate, LongGene> dateCodec2 = Codec.of(
212 * Genotype.of(LongChromosome.of(1_000_000, 10_000_000)),
213 * gt -> LocalDate.ofEpochDay(gt.getGene().longValue())
214 * );
215 *
216 * final Codec<Duration, LongGene> durationCodec = Codec.of(
217 * dateCodec1,
218 * dateCodec2,
219 * (d1, d2) -> Duration.ofDays(d2.toEpochDay() - d1.toEpochDay())
220 * );
221 *
222 * final Engine<LongGene, Long> engine = Engine
223 * .builder(Duration::toMillis, durationCodec)
224 * .build();
225 *
226 * final Phenotype<LongGene, Long> pt = engine.stream()
227 * .limit(100)
228 * .collect(EvolutionResult.toBestPhenotype());
229 * System.out.println(pt);
230 *
231 * final Duration duration = durationCodec.decoder()
232 * .apply(pt.getGenotype());
233 * System.out.println(duration);
234 * }</pre>
235 *
236 * @since 3.3
237 *
238 * @param <G> the gene type
239 * @param <A> the argument type of the first codec
240 * @param <B> the argument type of the second codec
241 * @param <T> the argument type of the compound codec
242 * @param codec1 the first codec
243 * @param codec2 the second codec
244 * @param decoder the decoder which combines the two argument types from the
245 * given given codecs, to the argument type of the resulting codec.
246 * @return a new codec which combines the given {@code codec1} and
247 * {@code codec2}
248 * @throws NullPointerException if one of the arguments is {@code null}
249 */
250 public static <A, B, T, G extends Gene<?, G>> Codec<T, G> of(
251 final Codec<A, G> codec1,
252 final Codec<B, G> codec2,
253 final BiFunction<A, B, T> decoder
254 ) {
255 @SuppressWarnings("unchecked")
256 final Function<Object[], T> decoderAdapter =
257 v -> decoder.apply((A)v[0], (B)v[1]);
258
259 return of(
260 ISeq.of(codec1, codec2),
261 decoderAdapter
262 );
263 }
264
265 /**
266 * Combines the given {@code codecs} into one codec. This lets you divide
267 * a problem into sub problems and combine them again.
268 * <p>
269 * The following example combines more than two sub-codecs into one.
270 * <pre>{@code
271 * final Codec<LocalDate, LongGene> dateCodec = Codec.of(
272 * Genotype.of(LongChromosome.of(0, 10_000)),
273 * gt -> LocalDate.ofEpochDay(gt.getGene().longValue())
274 * );
275 *
276 * final Codec<Duration, LongGene> durationCodec = Codec.of(
277 * ISeq.of(dateCodec, dateCodec, dateCodec),
278 * dates -> {
279 * final LocalDate ld1 = (LocalDate)dates[0];
280 * final LocalDate ld2 = (LocalDate)dates[1];
281 * final LocalDate ld3 = (LocalDate)dates[2];
282 *
283 * return Duration.ofDays(
284 * ld1.toEpochDay() + ld2.toEpochDay() - ld3.toEpochDay()
285 * );
286 * }
287 * );
288 *
289 * final Engine<LongGene, Long> engine = Engine
290 * .builder(Duration::toMillis, durationCodec)
291 * .build();
292 *
293 * final Phenotype<LongGene, Long> pt = engine.stream()
294 * .limit(100)
295 * .collect(EvolutionResult.toBestPhenotype());
296 * System.out.println(pt);
297 *
298 * final Duration duration = durationCodec.decoder()
299 * .apply(pt.getGenotype());
300 * System.out.println(duration);
301 * }</pre>
302 *
303 * @since 3.3
304 *
305 * @param <G> the gene type
306 * @param <T> the argument type of the compound codec
307 * @param codecs the {@code Codec} sequence of the sub-problems
308 * @param decoder the decoder which combines the argument types from the
309 * given given codecs, to the argument type of the resulting codec.
310 * @return a new codec which combines the given {@code codecs}
311 * @throws NullPointerException if one of the arguments is {@code null}
312 * @throws IllegalArgumentException if the given {@code codecs} sequence is
313 * empty
314 */
315 public static <G extends Gene<?, G>, T> Codec<T, G> of(
316 final ISeq<? extends Codec<?, G>> codecs,
317 final Function<? super Object[], ? extends T> decoder
318 ) {
319 if (codecs.isEmpty()) {
320 throw new IllegalArgumentException(
321 "Codecs sequence must not be empty."
322 );
323 }
324 return codecs.size() == 1
325 ? of(codecs.get(0).encoding(), gt -> {
326 final Object value = codecs.get(0).decoder().apply(gt);
327 return decoder.apply(new Object[]{value});
328 })
329 : new CompositeCodec<>(codecs, decoder);
330 }
331
332 }
|