EnumGene.java
001 /*
002  * Java Genetic Algorithm Library (jenetics-6.0.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 the index of the allele this gene is representing.
117      *
118      @return the index of the allele this gene is representing.
119      */
120     public int alleleIndex() {
121         return _alleleIndex;
122     }
123 
124     @Override
125     public A allele() {
126         return _validAlleles.get(_alleleIndex);
127     }
128 
129     @Override
130     public boolean isValid() {
131         return _alleleIndex >= && _alleleIndex < _validAlleles.length();
132     }
133 
134     @Override
135     public EnumGene<A> newInstance() {
136         return new EnumGene<>(
137             RandomRegistry.random().nextInt(_validAlleles.length()),
138             _validAlleles
139         );
140     }
141 
142     /**
143      * Create a new gene from the given {@code value} and the gene context.
144      *
145      @since 1.6
146      *
147      @param value the value of the new gene.
148      @return a new gene with the given value.
149      */
150     public EnumGene<A> newInstance(final A value) {
151         return new EnumGene<>(
152             _validAlleles.indexOf(value),
153             _validAlleles
154         );
155     }
156 
157     @Override
158     public int compareTo(final EnumGene<A> gene) {
159         int result = 0;
160         if (_alleleIndex > gene._alleleIndex) {
161             result = 1;
162         else if (_alleleIndex < gene._alleleIndex) {
163             result = -1;
164         }
165 
166         return result;
167     }
168 
169     @Override
170     public int hashCode() {
171         return hash(_alleleIndex, hash(_validAlleles));
172     }
173 
174     @Override
175     public boolean equals(final Object obj) {
176         return obj == this ||
177             obj instanceof EnumGene &&
178             Objects.equals(((EnumGene)obj)._alleleIndex, _alleleIndex&&
179             Objects.equals(((EnumGene)obj)._validAlleles, _validAlleles);
180     }
181 
182     @Override
183     public String toString() {
184         return Objects.toString(allele());
185     }
186 
187 
188     /* *************************************************************************
189      *  Static object creation methods
190      * ************************************************************************/
191 
192     /**
193      * Create a new enum gene from the given valid genes and the chosen allele
194      * index.
195      *
196      @since 3.4
197      *
198      @param <A> the allele type
199      @param alleleIndex the index of the allele for this gene.
200      @param validAlleles the sequence of valid alleles.
201      @return a new {@code EnumGene} with the given with the allele
202      *        {@code validAlleles.get(alleleIndex)}
203      @throws IllegalArgumentException if the give valid alleles sequence is
204      *         empty
205      @throws NullPointerException if the valid alleles seq is {@code null}.
206      */
207     public static <A> EnumGene<A> of(
208         final int alleleIndex,
209         final ISeq<? extends A> validAlleles
210     ) {
211         return new EnumGene<>(alleleIndex, validAlleles);
212     }
213 
214     /**
215      * Return a new enum gene with an allele randomly chosen from the given
216      * valid alleles.
217      *
218      @param <A> the allele type
219      @param validAlleles the sequence of valid alleles.
220      @return a new {@code EnumGene} with an randomly chosen allele from the
221      *         sequence of valid alleles
222      @throws java.lang.IllegalArgumentException if the give valid alleles
223      *         sequence is empty
224      @throws NullPointerException if the valid alleles seq is {@code null}.
225      */
226     public static <A> EnumGene<A> of(final ISeq<? extends A> validAlleles) {
227         return new EnumGene<>(
228             RandomRegistry.random().nextInt(validAlleles.length()),
229             validAlleles
230         );
231     }
232 
233     /**
234      * Create a new enum gene from the given valid genes and the chosen allele
235      * index.
236      *
237      @param <A> the allele type
238      @param alleleIndex the index of the allele for this gene.
239      @param validAlleles the array of valid alleles.
240      @return a new {@code EnumGene} with the given with the allele
241      *        {@code validAlleles[alleleIndex]}
242      @throws java.lang.IllegalArgumentException if the give valid alleles
243      *         array is empty of the allele index is out of range.
244      */
245     @SafeVarargs
246     public static <A> EnumGene<A> of(
247         final int alleleIndex,
248         final A... validAlleles
249     ) {
250         return new EnumGene<>(alleleIndex, ISeq.of(validAlleles));
251     }
252 
253     /**
254      * Return a new enum gene with an allele randomly chosen from the given
255      * valid alleles.
256      *
257      @param <A> the allele type
258      @param validAlleles the array of valid alleles.
259      @return a new {@code EnumGene} with an randomly chosen allele from the
260      *         sequence of valid alleles
261      @throws IllegalArgumentException if the give valid alleles array is empty
262      */
263     @SafeVarargs
264     public static <A> EnumGene<A> of(final A... validAlleles) {
265         return EnumGene.of(ISeq.of(validAlleles));
266     }
267 
268 }