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