Codec.java
001 /*
002  * Java Genetic Algorithm Library (jenetics-4.1.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.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 gt the genotype to be converted
126      @return the converted genotype
127      */
128     public default T decode(final Genotype<G> gt) {
129         return decoder().apply(gt);
130     }
131 
132     /**
133      * Create a new {@code Codec} with the mapped result type. The following
134      * example creates a double codec who's values are not uniformly distributed
135      * between {@code [0..1)}. Instead the values now follow an exponential
136      * function.
137      *
138      <pre>{@code
139      *  final Codec<Double, DoubleGene> c = Codecs.ofScalar(DoubleRange.of(0, 1))
140      *      .map(Math::exp);
141      * }</pre>
142      *
143      @since 4.0
144      *
145      @param mapper the mapper function
146      @param <B> the new argument type of the given problem
147      @return a new {@code Codec} with the mapped result type
148      @throws NullPointerException if the mapper is {@code null}.
149      */
150     public default <B>
151     Codec<B, G> map(final Function<? super T, ? extends B> mapper) {
152         requireNonNull(mapper);
153 
154         return Codec.of(
155             encoding(),
156             gt -> mapper.apply(decode(gt))
157         );
158     }
159 
160     /**
161      * Create a new {@code Codec} object with the given {@code encoding} and
162      * {@code decoder} function.
163      *
164      @param encoding the genotype factory used for creating new
165      *        {@code Genotypes}.
166      @param decoder decoder function, which converts a {@code Genotype} to a
167      *        value in the problem domain.
168      @param <G> the {@code Gene} type
169      @param <T> the fitness function argument type in the problem domain
170      @return a new {@code Codec} object with the given parameters.
171      @throws NullPointerException if one of the arguments is {@code null}.
172      */
173     public static <G extends Gene<?, G>, T> Codec<T, G> of(
174         final Factory<Genotype<G>> encoding,
175         final Function<Genotype<G>, T> decoder
176     ) {
177         requireNonNull(encoding);
178         requireNonNull(decoder);
179 
180         return new Codec<T, G>() {
181             @Override
182             public Factory<Genotype<G>> encoding() {
183                 return encoding;
184             }
185 
186             @Override
187             public Function<Genotype<G>, T> decoder() {
188                 return decoder;
189             }
190         };
191     }
192 
193 
194     /**
195      * Converts two given {@code Codec} instances into one. This lets you divide
196      * a problem into sub problems and combine them again.
197      <p>
198      * The following example shows how to combine two codecs, which converts a
199      * {@code LongGene} to a {@code LocalDate}, to a codec which combines the
200      * two {@code LocalDate} object (this are the argument types of the
201      * component codecs) to a {@code Duration}.
202      *
203      <pre>{@code
204      * final Codec<LocalDate, LongGene> dateCodec1 = Codec.of(
205      *     Genotype.of(LongChromosome.of(0, 10_000)),
206      *     gt -> LocalDate.ofEpochDay(gt.getGene().longValue())
207      * );
208      *
209      * final Codec<LocalDate, LongGene> dateCodec2 = Codec.of(
210      *     Genotype.of(LongChromosome.of(1_000_000, 10_000_000)),
211      *     gt -> LocalDate.ofEpochDay(gt.getGene().longValue())
212      * );
213      *
214      * final Codec<Duration, LongGene> durationCodec = Codec.of(
215      *     dateCodec1,
216      *     dateCodec2,
217      *     (d1, d2) -> Duration.ofDays(d2.toEpochDay() - d1.toEpochDay())
218      * );
219      *
220      * final Engine<LongGene, Long> engine = Engine
221      *     .builder(Duration::toMillis, durationCodec)
222      *     .build();
223      *
224      * final Phenotype<LongGene, Long> pt = engine.stream()
225      *     .limit(100)
226      *     .collect(EvolutionResult.toBestPhenotype());
227      * System.out.println(pt);
228      *
229      * final Duration duration = durationCodec.decoder()
230      *     .apply(pt.getGenotype());
231      * System.out.println(duration);
232      * }</pre>
233      *
234      @since 3.3
235      *
236      @param <G> the gene type
237      @param <A> the argument type of the first codec
238      @param <B> the argument type of the second codec
239      @param <T> the argument type of the compound codec
240      @param codec1 the first codec
241      @param codec2 the second codec
242      @param decoder the decoder which combines the two argument types from the
243      *        given given codecs, to the argument type of the resulting codec.
244      @return a new codec which combines the given {@code codec1} and
245      *        {@code codec2}
246      @throws NullPointerException if one of the arguments is {@code null}
247      */
248     public static <G extends Gene<?, G>, A, B, T> Codec<T, G> of(
249         final Codec<A, G> codec1,
250         final Codec<B, G> codec2,
251         final BiFunction<A, B, T> decoder
252     ) {
253         @SuppressWarnings("unchecked")
254         final Function<Object[], T> decoderAdapter =
255             v -> decoder.apply((A)v[0](B)v[1]);
256 
257         return of(
258             ISeq.of(codec1, codec2),
259             decoderAdapter
260         );
261     }
262 
263     /**
264      * Combines the given {@code codecs} into one codec. This lets you divide
265      * a problem into sub problems and combine them again.
266      <p>
267      * The following example combines more than two sub-codecs into one.
268      <pre>{@code
269      * final Codec<LocalDate, LongGene> dateCodec = Codec.of(
270      *     Genotype.of(LongChromosome.of(0, 10_000)),
271      *     gt -> LocalDate.ofEpochDay(gt.getGene().longValue())
272      * );
273      *
274      * final Codec<Duration, LongGene> durationCodec = Codec.of(
275      *     ISeq.of(dateCodec, dateCodec, dateCodec),
276      *     dates -> {
277      *         final LocalDate ld1 = (LocalDate)dates[0];
278      *         final LocalDate ld2 = (LocalDate)dates[1];
279      *         final LocalDate ld3 = (LocalDate)dates[2];
280      *
281      *         return Duration.ofDays(
282      *             ld1.toEpochDay() + ld2.toEpochDay() - ld3.toEpochDay()
283      *         );
284      *     }
285      * );
286      *
287      * final Engine<LongGene, Long> engine = Engine
288      *     .builder(Duration::toMillis, durationCodec)
289      *     .build();
290      *
291      * final Phenotype<LongGene, Long> pt = engine.stream()
292      *     .limit(100)
293      *     .collect(EvolutionResult.toBestPhenotype());
294      * System.out.println(pt);
295      *
296      * final Duration duration = durationCodec.decoder()
297      *     .apply(pt.getGenotype());
298      * System.out.println(duration);
299      * }</pre>
300      *
301      @since 3.3
302      *
303      @param <G> the gene type
304      @param <T> the argument type of the compound codec
305      @param codecs the {@code Codec} sequence of the sub-problems
306      @param decoder the decoder which combines the argument types from the
307      *        given given codecs, to the argument type of the resulting codec.
308      @return a new codec which combines the given {@code codecs}
309      @throws NullPointerException if one of the arguments is {@code null}
310      */
311     public static <G extends Gene<?, G>, T> Codec<T, G> of(
312         final ISeq<? extends Codec<?, G>> codecs,
313         final Function<? super Object[], ? extends T> decoder
314     ) {
315         return new CompositeCodec<>(codecs, decoder);
316     }
317 
318 }