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