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