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