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