EnumGene.java
001 /*
002  * Java Genetic Algorithm Library (jenetics-5.2.0).
003  * Copyright (c) 2007-2020 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 io.jenetics.internal.util.Hashes.hash;
024 
025 import java.io.Serializable;
026 import java.util.Objects;
027 
028 import io.jenetics.util.ISeq;
029 import io.jenetics.util.RandomRegistry;
030 
031 /**
032  <p>
033  * Gene which holds enumerable (countable) genes. Will be used for combinatorial
034  * problems in combination with the {@link PermutationChromosome}.
035  </p>
036  * The following code shows how to create a combinatorial genotype factory which
037  * can be used when creating an {@link io.jenetics.engine.Engine} instance.
038  <pre>{@code
039  * final ISeq<Integer> alleles = ISeq.of(1, 2, 3, 4, 5, 6, 7, 8);
040  * final Factory<Genotype<EnumGene<Integer>>> gtf = Genotype.of(
041  *     PermutationChromosome.of(alleles)
042  * );
043  * }</pre>
044  *
045  * The following code shows the assurances of the {@code EnumGene}.
046  <pre>{@code
047  * final ISeq<Integer> alleles = ISeq.of(1, 2, 3, 4, 5, 6, 7, 8);
048  * final EnumGene<Integer> gene = new EnumGene<>(5, alleles);
049  *
050  * assert(gene.alleleIndex() == 5);
051  * assert(gene.allele() == gene.validAlleles().get(5));
052  * assert(gene.validAlleles() == alleles);
053  * }</pre>
054  *
055  @see PermutationChromosome
056  @see PartiallyMatchedCrossover
057  *
058  * @implNote
059  * This class is immutable and thread-safe.
060  *
061  @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
062  @since 1.0
063  @version 5.2
064  */
065 public final class EnumGene<A>
066     implements
067         Gene<A, EnumGene<A>>,
068         Comparable<EnumGene<A>>,
069         Serializable
070 {
071 
072     private static final long serialVersionUID = 2L;
073 
074     private final ISeq<A> _validAlleles;
075     private final int _alleleIndex;
076 
077     /**
078      * Create a new enum gene from the given valid genes and the chosen allele
079      * index.
080      *
081      @param alleleIndex the index of the allele for this gene.
082      @param validAlleles the sequence of valid alleles.
083      @throws IllegalArgumentException if the give valid alleles sequence is
084      *         empty
085      @throws NullPointerException if the valid alleles seq is {@code null}.
086      */
087     EnumGene(final int alleleIndex, final ISeq<? extends A> validAlleles) {
088         if (validAlleles.isEmpty()) {
089             throw new IllegalArgumentException(
090                 "Array of valid alleles must be greater than zero."
091             );
092         }
093 
094         if (alleleIndex < || alleleIndex >= validAlleles.length()) {
095             throw new IndexOutOfBoundsException(format(
096                 "Allele index is not in range [0, %d): %d.",
097                 validAlleles.length(),
098                 alleleIndex
099             ));
100         }
101 
102         _validAlleles = ISeq.upcast(validAlleles);
103         _alleleIndex = alleleIndex;
104     }
105 
106     /**
107      * Return sequence of the valid alleles where this gene is a part of.
108      *
109      @return the sequence of the valid alleles.
110      */
111     public ISeq<A> validAlleles() {
112         return _validAlleles;
113     }
114 
115     /**
116      * Return sequence of the valid alleles where this gene is a part of.
117      *
118      @return the sequence of the valid alleles.
119      @deprecated Use {@link #validAlleles()} instead
120      */
121     @Deprecated
122     public ISeq<A> getValidAlleles() {
123         return _validAlleles;
124     }
125 
126     /**
127      * Return the index of the allele this gene is representing.
128      *
129      @return the index of the allele this gene is representing.
130      */
131     public int alleleIndex() {
132         return _alleleIndex;
133     }
134 
135     /**
136      * Return the index of the allele this gene is representing.
137      *
138      @return the index of the allele this gene is representing.
139      @deprecated Use {@link #alleleIndex()} instead
140      */
141     @Deprecated
142     public int getAlleleIndex() {
143         return _alleleIndex;
144     }
145 
146     @Deprecated
147     @Override
148     public A getAllele() {
149         return _validAlleles.get(_alleleIndex);
150     }
151 
152     @Override
153     public boolean isValid() {
154         return _alleleIndex >= && _alleleIndex < _validAlleles.length();
155     }
156 
157     @Override
158     public EnumGene<A> newInstance() {
159         return new EnumGene<>(
160             RandomRegistry.random().nextInt(_validAlleles.length()),
161             _validAlleles
162         );
163     }
164 
165     /**
166      * Create a new gene from the given {@code value} and the gene context.
167      *
168      @since 1.6
169      *
170      @param value the value of the new gene.
171      @return a new gene with the given value.
172      */
173     public EnumGene<A> newInstance(final A value) {
174         return new EnumGene<>(
175             _validAlleles.indexOf(value),
176             _validAlleles
177         );
178     }
179 
180     @Override
181     public int compareTo(final EnumGene<A> gene) {
182         int result = 0;
183         if (_alleleIndex > gene._alleleIndex) {
184             result = 1;
185         else if (_alleleIndex < gene._alleleIndex) {
186             result = -1;
187         }
188 
189         return result;
190     }
191 
192     @Override
193     public int hashCode() {
194         return hash(_alleleIndex, hash(_validAlleles));
195     }
196 
197     @Override
198     public boolean equals(final Object obj) {
199         return obj == this ||
200             obj instanceof EnumGene &&
201             Objects.equals(((EnumGene)obj)._alleleIndex, _alleleIndex&&
202             Objects.equals(((EnumGene)obj)._validAlleles, _validAlleles);
203     }
204 
205     @Override
206     public String toString() {
207         return Objects.toString(allele());
208     }
209 
210 
211     /* *************************************************************************
212      *  Static object creation methods
213      * ************************************************************************/
214 
215     /**
216      * Create a new enum gene from the given valid genes and the chosen allele
217      * index.
218      *
219      @since 3.4
220      *
221      @param <A> the allele type
222      @param alleleIndex the index of the allele for this gene.
223      @param validAlleles the sequence of valid alleles.
224      @return a new {@code EnumGene} with the given with the allele
225      *        {@code validAlleles.get(alleleIndex)}
226      @throws IllegalArgumentException if the give valid alleles sequence is
227      *         empty
228      @throws NullPointerException if the valid alleles seq is {@code null}.
229      */
230     public static <A> EnumGene<A> of(
231         final int alleleIndex,
232         final ISeq<? extends A> validAlleles
233     ) {
234         return new EnumGene<>(alleleIndex, validAlleles);
235     }
236 
237     /**
238      * Return a new enum gene with an allele randomly chosen from the given
239      * valid alleles.
240      *
241      @param <A> the allele type
242      @param validAlleles the sequence of valid alleles.
243      @return a new {@code EnumGene} with an randomly chosen allele from the
244      *         sequence of valid alleles
245      @throws java.lang.IllegalArgumentException if the give valid alleles
246      *         sequence is empty
247      @throws NullPointerException if the valid alleles seq is {@code null}.
248      */
249     public static <A> EnumGene<A> of(final ISeq<? extends A> validAlleles) {
250         return new EnumGene<>(
251             RandomRegistry.random().nextInt(validAlleles.length()),
252             validAlleles
253         );
254     }
255 
256     /**
257      * Create a new enum gene from the given valid genes and the chosen allele
258      * index.
259      *
260      @param <A> the allele type
261      @param alleleIndex the index of the allele for this gene.
262      @param validAlleles the array of valid alleles.
263      @return a new {@code EnumGene} with the given with the allele
264      *        {@code validAlleles[alleleIndex]}
265      @throws java.lang.IllegalArgumentException if the give valid alleles
266      *         array is empty of the allele index is out of range.
267      */
268     @SafeVarargs
269     public static <A> EnumGene<A> of(
270         final int alleleIndex,
271         final A... validAlleles
272     ) {
273         return new EnumGene<>(alleleIndex, ISeq.of(validAlleles));
274     }
275 
276     /**
277      * Return a new enum gene with an allele randomly chosen from the given
278      * valid alleles.
279      *
280      @param <A> the allele type
281      @param validAlleles the array of valid alleles.
282      @return a new {@code EnumGene} with an randomly chosen allele from the
283      *         sequence of valid alleles
284      @throws IllegalArgumentException if the give valid alleles array is empty
285      */
286     @SafeVarargs
287     public static <A> EnumGene<A> of(final A... validAlleles) {
288         return EnumGene.of(ISeq.of(validAlleles));
289     }
290 
291 }