Phenotype.java
001 /*
002  * Java Genetic Algorithm Library (jenetics-5.1.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;
021 
022 import static java.lang.String.format;
023 import static java.util.Objects.requireNonNull;
024 import static io.jenetics.internal.util.Hashes.hash;
025 import static io.jenetics.internal.util.SerialIO.readLong;
026 import static io.jenetics.internal.util.SerialIO.writeLong;
027 
028 import java.io.IOException;
029 import java.io.InvalidObjectException;
030 import java.io.ObjectInput;
031 import java.io.ObjectInputStream;
032 import java.io.ObjectOutput;
033 import java.io.Serializable;
034 import java.util.NoSuchElementException;
035 import java.util.Objects;
036 import java.util.Optional;
037 import java.util.function.Function;
038 
039 import io.jenetics.util.Verifiable;
040 
041 /**
042  * The {@code Phenotype} consists of a {@link Genotype}, the current generation
043  * and an optional fitness value. Once the fitness has been evaluated, a new
044  * {@code Phenotype} instance, with the calculated fitness, can be created with
045  * the {@link #withFitness(Comparable)}.
046  *
047  @see Genotype
048  *
049  * @implNote
050  * This class is immutable and thread-safe.
051  *
052  @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
053  @since 1.0
054  @version 5.0
055  */
056 public final class Phenotype<
057     extends Gene<?, G>,
058     extends Comparable<? super C>
059 >
060     implements
061         Comparable<Phenotype<G, C>>,
062         Verifiable,
063         Serializable
064 {
065     private static final long serialVersionUID = 6L;
066 
067     private final Genotype<G> _genotype;
068     private final long _generation;
069     private final C _fitness;
070 
071     /**
072      * Create a new phenotype from the given arguments.
073      *
074      @param genotype the genotype of this phenotype.
075      @param generation the current generation of the generated phenotype.
076      @param fitness the known fitness of the phenotype, maybe {@code null}
077      @throws NullPointerException if the genotype is {@code null}.
078      @throws IllegalArgumentException if the given {@code generation} is
079      *         {@code < 0}.
080      */
081     private Phenotype(
082         final Genotype<G> genotype,
083         final long generation,
084         final C fitness
085     ) {
086         if (generation < 0) {
087             throw new IllegalArgumentException(format(
088                 "Generation must not < 0 and was %s.", generation
089             ));
090         }
091 
092         _genotype = requireNonNull(genotype, "Genotype");
093         _generation = generation;
094         _fitness = fitness;
095     }
096 
097     /**
098      * Applies the given fitness function to the underlying genotype and return
099      * a new phenotype with the (newly) evaluated fitness function, if not
100      * already evaluated. If the fitness value is already set {@code this}
101      * phenotype is returned.
102      *
103      @since 5.0
104      *
105      @param ff the fitness function
106      @return a evaluated phenotype or {@code this} if the fitness value is
107      *         already set
108      @throws NullPointerException if the given fitness function is {@code null}
109      */
110     public Phenotype<G, C>
111     eval(final Function<? super Genotype<G>, ? extends C> ff) {
112         requireNonNull(ff);
113         return _fitness == null ? withFitness(ff.apply(_genotype)) this;
114     }
115 
116     /**
117      * This method returns a copy of the {@code Genotype}, to guarantee a
118      * immutable class.
119      *
120      @return the cloned {@code Genotype} of this {@code Phenotype}.
121      @throws NullPointerException if one of the arguments is {@code null}.
122      */
123     public Genotype<G> getGenotype() {
124         return _genotype;
125     }
126 
127     /**
128      * A phenotype instance can be created with or without fitness value.
129      * Initially, the phenotype is created without fitness value. The
130      * fitness evaluation strategy is responsible for creating phenotypes with
131      * fitness value assigned.
132      *
133      @since 4.2
134      *
135      @see #nonEvaluated()
136      *
137      @return {@code true} is this phenotype has an fitness value assigned,
138      *         {@code false} otherwise
139      */
140     public boolean isEvaluated() {
141         return _fitness != null;
142     }
143 
144     /**
145      * A phenotype instance can be created with or without fitness value.
146      * Initially, the phenotype is created without fitness value. The
147      * fitness evaluation strategy is responsible for creating phenotypes with
148      * fitness value assigned.
149      *
150      @since 5.0
151      *
152      @see #isEvaluated()
153      *
154      @return {@code false} is this phenotype has an fitness value assigned,
155      *         {@code true} otherwise
156      */
157     public boolean nonEvaluated() {
158         return _fitness == null;
159     }
160 
161     /**
162      * Return the fitness value of this {@code Phenotype}.
163      *
164      @see #fitnessOptional()
165      *
166      @return The fitness value of this {@code Phenotype}.
167      @throws NoSuchElementException if {@link #isEvaluated()} returns
168      *         {@code false}
169      */
170     public C getFitness() {
171         if (_fitness == null) {
172             throw new NoSuchElementException(
173                 "Phenotype has no assigned fitness value."
174             );
175         }
176 
177         return _fitness;
178     }
179 
180     /**
181      * Return the fitness value of {@code this} phenotype, or
182      {@link Optional#empty()} if not evaluated yet.
183      *
184      @since 5.0
185      *
186      @see #getFitness()
187      *
188      @return the fitness value
189      */
190     public Optional<C> fitnessOptional() {
191         return Optional.ofNullable(_fitness);
192     }
193 
194     /**
195      * Return the generation this {@link Phenotype} was created.
196      *
197      @see #getAge(long)
198      *
199      @return The generation this {@link Phenotype} was created.
200      */
201     public long getGeneration() {
202         return _generation;
203     }
204 
205     /**
206      * Return the age of this phenotype depending on the given current generation.
207      *
208      @see #getGeneration()
209      *
210      @param currentGeneration the current generation evaluated by the GA.
211      @return the age of this phenotype:
212      *          {@code currentGeneration - this.getGeneration()}.
213      */
214     public long getAge(final long currentGeneration) {
215         return currentGeneration - _generation;
216     }
217 
218     /**
219      * Test whether this phenotype is valid. The phenotype is valid if its
220      {@link Genotype} is valid.
221      *
222      @return true if this phenotype is valid, false otherwise.
223      */
224     @Override
225     public boolean isValid() {
226         return _genotype.isValid();
227     }
228 
229     @Override
230     public int compareTo(final Phenotype<G, C> pt) {
231         if (isEvaluated()) {
232             return pt.isEvaluated() ? getFitness().compareTo(pt.getFitness()) 1;
233         else {
234             return pt.isEvaluated() ? -0;
235         }
236     }
237 
238     @Override
239     public int hashCode() {
240         return hash(_generation, hash(_fitness, hash(_genotype)));
241     }
242 
243     @Override
244     public boolean equals(final Object obj) {
245         return obj == this ||
246             obj instanceof Phenotype &&
247             _generation == ((Phenotype)obj)._generation &&
248             Objects.equals(_fitness, ((Phenotype)obj)._fitness&&
249             Objects.equals(_genotype, ((Phenotype)obj)._genotype);
250     }
251 
252     @Override
253     public String toString() {
254         return _genotype + " -> " + _fitness;
255     }
256 
257     /**
258      * Return a new {@code Phenotype} object with the given <em>raw</em> fitness
259      * value. The returned phenotype is automatically <em>evaluated</em>:
260      * {@code isEvaluated() == true}
261      *
262      @since 4.2
263      *
264      @param fitness the phenotypes fitness value
265      @throws NullPointerException if the given {@code fitness} value is
266      *         {@code null}
267      @return a new phenotype with the given fitness value
268      */
269     public Phenotype<G, C> withFitness(final C fitness) {
270         return Phenotype.of(
271             _genotype,
272             _generation,
273             requireNonNull(fitness)
274         );
275     }
276 
277     /**
278      * Return a new {@code Phenotype} object with the given generation.
279      *
280      @since 5.0
281      *
282      @param generation the generation of the newly created phenotype
283      @return a new phenotype with the given generation
284      */
285     public Phenotype<G, C> withGeneration(final long generation) {
286         return Phenotype.of(
287             _genotype,
288             generation,
289             _fitness
290         );
291     }
292 
293 
294     /* *************************************************************************
295      *  Static factory methods.
296      * ************************************************************************/
297 
298     /**
299      * Create a new phenotype from the given arguments. The phenotype is created
300      * with a non assigned fitness function and the call of {@link #isEvaluated()}
301      * will return {@code false}.
302      *
303      @param <G> the gene type of the chromosome
304      @param <C> the fitness value type
305      @param genotype the genotype of this phenotype.
306      @param generation the current generation of the generated phenotype.
307      @return a new phenotype object
308      @throws NullPointerException if one of the arguments is {@code null}.
309      @throws IllegalArgumentException if the given {@code generation} is
310      *         {@code < 0}.
311      */
312     public static <G extends Gene<?, G>, C extends Comparable<? super C>>
313     Phenotype<G, C> of(final Genotype<G> genotype, final long generation) {
314         return new Phenotype<>(
315             genotype,
316             generation,
317             null
318         );
319     }
320 
321     /**
322      * Create a new phenotype from the given arguments.
323      *
324      @param <G> the gene type of the chromosome
325      @param <C> the fitness value type
326      @param genotype the genotype of this phenotype.
327      @param generation the current generation of the generated phenotype.
328      @param fitness the known fitness of the phenotype.
329      @return a new phenotype object
330      @throws NullPointerException if one of the arguments is {@code null}.
331      @throws IllegalArgumentException if the given {@code generation} is
332      *         {@code < 0}.
333      */
334     public static <G extends Gene<?, G>, C extends Comparable<? super C>>
335     Phenotype<G, C> of(
336         final Genotype<G> genotype,
337         final long generation,
338         final C fitness
339     ) {
340         return new Phenotype<>(
341             genotype,
342             generation,
343             requireNonNull(fitness)
344         );
345     }
346 
347 
348     /* *************************************************************************
349      *  Java object serialization
350      * ************************************************************************/
351 
352     private Object writeReplace() {
353         return new Serial(Serial.PHENOTYPE, this);
354     }
355 
356     private void readObject(final ObjectInputStream stream)
357         throws InvalidObjectException
358     {
359         throw new InvalidObjectException("Serialization proxy required.");
360     }
361 
362     void write(final ObjectOutput outthrows IOException {
363         writeLong(_generation, out);
364         out.writeObject(_genotype);
365         out.writeObject(_fitness);
366     }
367 
368     @SuppressWarnings({"unchecked""rawtypes"})
369     static Phenotype read(final ObjectInput in)
370         throws IOException, ClassNotFoundException
371     {
372         final long generation = readLong(in);
373         final Genotype genotype = (Genotype)in.readObject();
374         final Comparable fitness = (Comparable)in.readObject();
375 
376         return new Phenotype(
377             genotype,
378             generation,
379             fitness
380         );
381     }
382 
383 }