001 /*
002 * Java Genetic Algorithm Library (jenetics-2.0.2).
003 * Copyright (c) 2007-2014 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.object.eq;
024
025 import java.util.List;
026 import java.util.Objects;
027
028 import javax.xml.bind.annotation.XmlAccessType;
029 import javax.xml.bind.annotation.XmlAccessorType;
030 import javax.xml.bind.annotation.XmlAttribute;
031 import javax.xml.bind.annotation.XmlElement;
032 import javax.xml.bind.annotation.XmlElementWrapper;
033 import javax.xml.bind.annotation.XmlRootElement;
034 import javax.xml.bind.annotation.XmlType;
035 import javax.xml.bind.annotation.adapters.XmlAdapter;
036 import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
037
038 import org.jenetics.internal.util.HashBuilder;
039 import org.jenetics.internal.util.cast;
040 import org.jenetics.internal.util.jaxb;
041 import org.jenetics.internal.util.model.IndexedObject;
042
043 import org.jenetics.util.Array;
044 import org.jenetics.util.Factory;
045 import org.jenetics.util.Function;
046 import org.jenetics.util.ISeq;
047 import org.jenetics.util.RandomRegistry;
048
049 /**
050 * <p>
051 * Gene which holds enumerable (countable) genes. Will be used for combinatorial
052 * problems in combination with the {@link PermutationChromosome}.
053 * </p>
054 * The following code shows how to create a combinatorial genotype factory which
055 * can be used when creating an {@link GeneticAlgorithm} instance.
056 * [code]
057 * final ISeq<Integer> alleles = Array.box(1, 2, 3, 4, 5, 6, 7, 8).toISeq();
058 * final Factory<Genotype<EnumGene<Integer>>> gtf = Genotype.of(
059 * PermutationChromosome.of(alleles)
060 * );
061 * [/code]
062 *
063 * The following code shows the assurances of the {@code EnumGene}.
064 * [code]
065 * final ISeq<Integer> alleles = Array.box(1, 2, 3, 4, 5, 6, 7, 8).toISeq();
066 * final EnumGene<Integer> gene = new EnumGene<>(5, alleles);
067 *
068 * assert(gene.getAlleleIndex() == 5);
069 * assert(gene.getAllele() == gene.getValidAlleles().get(5));
070 * assert(gene.getValidAlleles() == alleles);
071 * [/code]
072 *
073 * @see PermutationChromosome
074 *
075 * @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
076 * @since 1.0
077 * @version 2.0 — <em>$Date: 2014-04-12 $</em>
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 {
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 * @param alleleIndex the index of the allele for this gene.
095 * @param validAlleles the sequence of valid alleles.
096 * @throws java.lang.IllegalArgumentException if the give valid alleles
097 * sequence is empty
098 * @throws NullPointerException if the valid alleles seq is {@code null}.
099 */
100 public EnumGene(final int alleleIndex, final ISeq<? extends A> validAlleles) {
101 if (validAlleles.length() == 0) {
102 throw new IllegalArgumentException(
103 "Array of valid alleles must be greater than zero."
104 );
105 }
106
107 if (alleleIndex < 0 || alleleIndex >= validAlleles.length()) {
108 throw new IndexOutOfBoundsException(format(
109 "Allele index is not in range [0, %d).", alleleIndex
110 ));
111 }
112
113 _validAlleles = cast.apply(validAlleles);
114 _alleleIndex = alleleIndex;
115 }
116
117 /**
118 * Return sequence of the valid alleles where this gene is a part of.
119 *
120 * @return the sequence of the valid alleles.
121 */
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 getAlleleIndex() {
132 return _alleleIndex;
133 }
134
135 @Override
136 public A getAllele() {
137 return _validAlleles.get(_alleleIndex);
138 }
139
140 @Override
141 public boolean isValid() {
142 return _alleleIndex >= 0 && _alleleIndex < _validAlleles.length();
143 }
144
145 @Override
146 public EnumGene<A> newInstance() {
147 return new EnumGene<>(
148 RandomRegistry.getRandom().nextInt(_validAlleles.length()),
149 _validAlleles
150 );
151 }
152
153 /**
154 * Create a new gene from the given {@code value} and the gene context.
155 *
156 * @since 1.6
157 * @param value the value of the new gene.
158 * @return a new gene with the given value.
159 */
160 public EnumGene<A> newInstance(final A value) {
161 return new EnumGene<>(
162 _validAlleles.indexOf(value),
163 _validAlleles
164 );
165 }
166
167 @Override
168 public int compareTo(final EnumGene<A> gene) {
169 int result = 0;
170 if (_alleleIndex > gene._alleleIndex) {
171 result = 1;
172 } else if (_alleleIndex < gene._alleleIndex) {
173 result = -1;
174 }
175
176 return result;
177 }
178
179 @Override
180 public int hashCode() {
181 return HashBuilder.of(EnumGene.class)
182 .and(_alleleIndex)
183 .and(_validAlleles).value();
184 }
185
186 @Override
187 public boolean equals(final Object obj) {
188 if (obj == this) {
189 return true;
190 }
191 if (obj == null || getClass() != obj.getClass()) {
192 return false;
193 }
194
195 final EnumGene<?> pg = (EnumGene<?>)obj;
196 return eq(_alleleIndex, pg._alleleIndex) &&
197 eq(_validAlleles, pg._validAlleles);
198 }
199
200 @Override
201 public String toString() {
202 return Objects.toString(getAllele());
203 }
204
205 /* *************************************************************************
206 * Static object creation methods
207 * ************************************************************************/
208
209 static <T> Function<Integer, EnumGene<T>> ToGene(
210 final ISeq<T> validAlleles
211 ) {
212 return new Function<Integer, EnumGene<T>>() {
213 @Override
214 public EnumGene<T> apply(final Integer index) {
215 return new EnumGene<>(index, validAlleles);
216 }
217 };
218 }
219
220 static <T> Factory<EnumGene<T>> Gene(final ISeq<? extends T> validAlleles) {
221 return new Factory<EnumGene<T>>() {
222 private int _index = 0;
223 @Override
224 public EnumGene<T> newInstance() {
225 return new EnumGene<>(_index++, validAlleles);
226 }
227 };
228 }
229
230 /**
231 * Return a new enum gene with an allele randomly chosen from the given
232 * valid alleles.
233 *
234 * @param <A> the allele type
235 * @param validAlleles the sequence of valid alleles.
236 * @return a new {@code EnumGene} with the given parameter
237 * @throws java.lang.IllegalArgumentException if the give valid alleles
238 * sequence is empty
239 * @throws NullPointerException if the valid alleles seq is {@code null}.
240 */
241 public static <A> EnumGene<A> of(final ISeq<? extends A> validAlleles) {
242 return new EnumGene<>(
243 RandomRegistry.getRandom().nextInt(validAlleles.length()),
244 validAlleles
245 );
246 }
247
248 /**
249 * Create a new enum gene from the given valid genes and the chosen allele
250 * index.
251 *
252 * @param <A> the allele type
253 * @param alleleIndex the index of the allele for this gene.
254 * @param validAlleles the array of valid alleles.
255 * @return a new {@code EnumGene} with the given parameter
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, Array.of(validAlleles).toISeq());
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 the given parameter
274 * @throws java.lang.IllegalArgumentException if the give valid alleles
275 * array is empty
276 */
277 @SafeVarargs
278 public static <A> EnumGene<A> of(final A... validAlleles) {
279 return EnumGene.of(Array.of(validAlleles).toISeq());
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 Array.of(m.alleles)
324 .map(jaxb.Unmarshaller(m.allele.value))
325 .toISeq()
326 );
327 }
328
329 }
330 }
331
332 }
|