AnyGene.java
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;
021 
022 import static java.util.Objects.requireNonNull;
023 import static io.jenetics.util.RandomRegistry.getRandom;
024 
025 import java.util.Objects;
026 import java.util.function.Predicate;
027 import java.util.function.Supplier;
028 
029 import io.jenetics.internal.math.random;
030 import io.jenetics.util.ISeq;
031 import io.jenetics.util.IntRange;
032 import io.jenetics.util.MSeq;
033 
034 /**
035  * {@code Gene} implementation, which allows to create genes without explicit
036  * implementing the {@code Gene} interface.
037  *
038  <pre>{@code
039  * class Main {
040  *     // First monday of 2015.
041  *     private static final LocalDate MIN_MONDAY = LocalDate.of(2015, 1, 5);
042  *
043  *     // Supplier of random 'LocalDate' objects. The implementation is responsible
044  *     // for guaranteeing the desired allele restriction. In this case we will
045  *     // generate only mondays.
046  *     static LocalDate nextRandomMonday() {
047  *         return MIN_MONDAY.plusWeeks(RandomRegistry.getRandom().nextInt(1000));
048  *     }
049  *
050  *     // Create a new 'LocalDate' gene. All other genes, created with
051  *     // gene.newInstance(), are calling the 'newRandomMonday' method.
052  *     final AnyGene<LocalDate> gene = AnyGene.of(Main::nextRandomMonday);
053  * }
054  * }</pre>
055  * The example above shows how to create {@code LocalDate} genes from a random
056  * {@code LocalDate} supplier. It also shows how to implement a restriction on
057  * the created dates. The usage of the {@code AnyGene} class is useful for
058  * supporting custom allele types without explicit implementation of the
059  * {@code Gene} interface. But the {@code AnyGene} can only be used for a subset
060  * of the existing alterers.
061  *
062  @see AnyChromosome
063  *
064  @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
065  @version 3.3
066  @since 3.3
067  */
068 public final class AnyGene<A> implements Gene<A, AnyGene<A>> {
069 
070     private final A _allele;
071     private final Supplier<? extends A> _supplier;
072     private final Predicate<? super A> _validator;
073 
074     private AnyGene(
075         final A allele,
076         final Supplier<? extends A> supplier,
077         final Predicate<? super A> validator
078     ) {
079         _allele = allele;
080         _supplier = requireNonNull(supplier);
081         _validator = requireNonNull(validator);
082     }
083 
084     @Override
085     public A getAllele() {
086         return _allele;
087     }
088 
089     @Override
090     public AnyGene<A> newInstance() {
091         return new AnyGene<>(_supplier.get(), _supplier, _validator);
092     }
093 
094     @Override
095     public AnyGene<A> newInstance(final A value) {
096         return new AnyGene<>(value, _supplier, _validator);
097     }
098 
099     @Override
100     public boolean isValid() {
101         return _validator.test(_allele);
102     }
103 
104     @Override
105     public int hashCode() {
106         return Objects.hashCode(_allele);
107     }
108 
109     @Override
110     public boolean equals(final Object obj) {
111         return obj instanceof AnyGene<?> &&
112             Objects.equals(((AnyGene<?>)obj)._allele, _allele);
113     }
114 
115     @Override
116     public String toString() {
117         return Objects.toString(_allele);
118     }
119 
120 
121     /* *************************************************************************
122      *  Static factory methods.
123      * ************************************************************************/
124 
125     /**
126      * Create a new {@code AnyGene} instance with the given parameters. New
127      * (random) genes are created with the given allele {@code supplier}.
128      *
129      @param <A> the allele type
130      @param allele the actual allele instance the created gene represents.
131      *        {@code null} values are allowed.
132      @param supplier the allele-supplier which is used for creating new,
133      *        random alleles
134      @param validator the validator used for validating the created gene. This
135      *        predicate is used in the {@link #isValid()} method.
136      @return a new {@code AnyGene} with the given parameters
137      @throws NullPointerException if the {@code supplier} or {@code validator}
138      *         is {@code null}
139      */
140     public static <A> AnyGene<A> of(
141         final A allele,
142         final Supplier<? extends A> supplier,
143         final Predicate<? super A> validator
144     ) {
145         return new AnyGene<>(allele, supplier, validator);
146     }
147 
148     /**
149      * Create a new {@code AnyGene} instance with the given parameters. New
150      * (random) genes are created with the given allele {@code supplier}. The
151      * {@code validator} predicate of the generated gene will always return
152      * {@code true}.
153      *
154      @param <A> the allele type
155      @param allele the actual allele instance the created gene represents.
156      *        {@code null} values are allowed.
157      @param supplier the allele-supplier which is used for creating new,
158      *        random alleles
159      @return a new {@code AnyGene} with the given parameters
160      @throws NullPointerException if the {@code suppler} is {@code null}
161      */
162     public static <A> AnyGene<A> of(
163         final A allele,
164         final Supplier<? extends A> supplier
165     ) {
166         return new AnyGene<>(allele, supplier, a -> true);
167     }
168 
169     /**
170      * Create a new {@code AnyGene} instance with the given allele
171      * {@code supplier}. The {@code validator} predicate of the generated gene
172      * will always return {@code true}.
173      *
174      @param <A> the allele type
175      @param supplier the allele-supplier which is used for creating new,
176      *        random alleles
177      @return a new {@code AnyGene} with the given parameters
178      @throws NullPointerException if one of the parameters is {@code null}
179      */
180     public static <A> AnyGene<A> of(final Supplier<? extends A> supplier) {
181         return new AnyGene<>(supplier.get(), supplier, a -> true);
182     }
183 
184     /**
185      * Create a new {@code AnyGene} instance with the given parameters. New
186      * (random) genes are created with the given allele {@code supplier}.
187      *
188      @param <A> the allele type
189      @param supplier the allele-supplier which is used for creating new,
190      *        random alleles
191      @param validator the validator used for validating the created gene. This
192      *        predicate is used in the {@link #isValid()} method.
193      @return a new {@code AnyGene} with the given parameters
194      @throws NullPointerException if one of the parameters is {@code null}
195      */
196     public static <A> AnyGene<A> of(
197         final Supplier<? extends A> supplier,
198         final Predicate<? super A> validator
199     ) {
200         return new AnyGene<>(supplier.get(), supplier, validator);
201     }
202 
203     // Create gene sequence.
204     static <A> ISeq<AnyGene<A>> seq(
205         final IntRange lengthRange,
206         final Supplier<? extends A> supplier,
207         final Predicate<? super A> validator
208     ) {
209         return MSeq.<AnyGene<A>>ofLength(random.nextInt(lengthRange, getRandom()))
210             .fill(() -> of(supplier.get(), supplier, validator))
211             .toISeq();
212     }
213 
214 }