CharacterChromosome.java
001 /*
002  * Java Genetic Algorithm Library (jenetics-6.1.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 io.jenetics.CharacterGene.DEFAULT_CHARACTERS;
023 import static io.jenetics.internal.util.Hashes.hash;
024 import static io.jenetics.internal.util.SerialIO.readInt;
025 import static io.jenetics.internal.util.SerialIO.readString;
026 import static io.jenetics.internal.util.SerialIO.writeInt;
027 import static io.jenetics.internal.util.SerialIO.writeString;
028 import static java.util.Objects.requireNonNull;
029 
030 import java.io.DataInput;
031 import java.io.DataOutput;
032 import java.io.IOException;
033 import java.io.InvalidObjectException;
034 import java.io.ObjectInputStream;
035 import java.io.Serializable;
036 import java.util.Objects;
037 import java.util.function.Function;
038 import java.util.stream.IntStream;
039 
040 import io.jenetics.util.CharSeq;
041 import io.jenetics.util.ISeq;
042 import io.jenetics.util.IntRange;
043 import io.jenetics.util.MSeq;
044 
045 /**
046  * CharacterChromosome which represents character sequences.
047  *
048  @see CharacterGene
049  *
050  * @implNote
051  * This class is immutable and thread-safe.
052  *
053  @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
054  @since 1.0
055  @version 6.1
056  */
057 public class CharacterChromosome
058     extends VariableChromosome<CharacterGene>
059     implements
060         CharSequence,
061         Serializable
062 {
063     private static final long serialVersionUID = 3L;
064 
065     private transient final CharSeq _validCharacters;
066 
067     /**
068      * Create a new chromosome from the given {@code genes} array. The genes
069      * array is copied, so changes to the given genes array doesn't effect the
070      * genes of this chromosome.
071      *
072      @since 4.0
073      *
074      @param genes the genes that form the chromosome.
075      @param lengthRange the allowed length range of the chromosome.
076      @throws NullPointerException if the given gene array is {@code null}.
077      @throws IllegalArgumentException if the length of the gene array is
078      *         smaller than one.
079      */
080     protected CharacterChromosome(
081         final ISeq<CharacterGene> genes,
082         final IntRange lengthRange
083     ) {
084         super(genes, lengthRange);
085         _validCharacters = genes.get(0).validChars();
086     }
087 
088     @Override
089     public char charAt(final int index) {
090         return get(index).charValue();
091     }
092 
093     @Override
094     public CharacterChromosome subSequence(final int start, final int end) {
095         return new CharacterChromosome(_genes.subSeq(start, end), lengthRange());
096     }
097 
098     /**
099      @throws NullPointerException if the given gene array is {@code null}.
100      */
101     @Override
102     public CharacterChromosome newInstance(final ISeq<CharacterGene> genes) {
103         return new CharacterChromosome(genes, lengthRange());
104     }
105 
106     /**
107      * Create a new, <em>random</em> chromosome.
108      */
109     @Override
110     public CharacterChromosome newInstance() {
111         return of(_validCharacters, lengthRange());
112     }
113 
114     /**
115      * Maps the gene alleles of this chromosome, given as {@code char[]} array,
116      * by applying the given mapper function {@code f}. The mapped gene values
117      * are then wrapped into a newly created chromosome.
118      *
119      <pre>{@code
120      * final CharacterChromosome chromosome = ...;
121      * final CharacterChromosome uppercase = chromosome.map(Main::uppercase);
122      *
123      * static int[] uppercase(final int[] values) {
124      *     for (int i = 0; i < values.length; ++i) {
125      *         values[i] = Character.toUpperCase(values[i]);
126      *     }
127      *     return values;
128      * }
129      * }</pre>
130      *
131      @since 6.1
132      *
133      @param f the mapper function
134      @return a newly created chromosome with the mapped gene values
135      @throws NullPointerException if the mapper function is {@code null}.
136      @throws IllegalArgumentException if the length of the mapped
137      *         {@code char[]} array is empty or doesn't match with the allowed
138      *         length range
139      */
140     public CharacterChromosome map(final Function<? super char[]char[]> f) {
141         requireNonNull(f);
142 
143         final char[] chars = f.apply(toArray());
144         final var genes = IntStream.range(0, chars.length)
145             .mapToObj(i -> CharacterGene.of(chars[i], _validCharacters))
146             .collect(ISeq.toISeq());
147 
148         return newInstance(genes);
149     }
150 
151     @Override
152     public int hashCode() {
153         return hash(super.hashCode(), hash(_validCharacters));
154     }
155 
156     @Override
157     public boolean equals(final Object obj) {
158         return obj == this ||
159             obj != null &&
160             getClass() == obj.getClass() &&
161             Objects.equals(_validCharacters, ((CharacterChromosome)obj)._validCharacters&&
162             super.equals(obj);
163     }
164 
165     @Override
166     public String toString() {
167         return new String(toArray());
168     }
169 
170     /**
171      * Returns an char array containing all of the elements in this chromosome
172      * in proper sequence.  If the chromosome fits in the specified array, it is
173      * returned therein. Otherwise, a new array is allocated with the length of
174      * this chromosome.
175      *
176      @since 3.0
177      *
178      @param array the array into which the elements of this chromosomes are to
179      *        be stored, if it is big enough; otherwise, a new array is
180      *        allocated for this purpose.
181      @return an array containing the elements of this chromosome
182      @throws NullPointerException if the given {@code array} is {@code null}
183      */
184     public char[] toArray(final char[] array) {
185         final char[] a = array.length >= length()
186             ? array
187             new char[length()];
188 
189         for (int i = length(); --i >= 0;) {
190             a[i= charAt(i);
191         }
192 
193         return a;
194     }
195 
196     /**
197      * Returns an char array containing all of the elements in this chromosome
198      * in proper sequence.
199      *
200      @since 3.0
201      *
202      @return an array containing the elements of this chromosome
203      */
204     public char[] toArray() {
205         return toArray(new char[length()]);
206     }
207 
208 
209     /* *************************************************************************
210      * Static factory methods.
211      * ************************************************************************/
212 
213     /**
214      * Create a new chromosome with the {@code validCharacters} char set as
215      * valid characters.
216      *
217      @since 4.3
218      *
219      @param validCharacters the valid characters for this chromosome.
220      @param lengthRange the allowed length range of the chromosome.
221      @return a new {@code CharacterChromosome} with the given parameter
222      @throws NullPointerException if the {@code validCharacters} is
223      *         {@code null}.
224      @throws IllegalArgumentException if the length of the gene sequence is
225      *         empty, doesn't match with the allowed length range, the minimum
226      *         or maximum of the range is smaller or equal zero or the given
227      *         range size is zero.
228      */
229     public static CharacterChromosome of(
230         final CharSeq validCharacters,
231         final IntRange lengthRange
232     ) {
233         return new CharacterChromosome(
234             CharacterGene.seq(validCharacters, lengthRange),
235             lengthRange
236         );
237     }
238 
239     /**
240      * Create a new chromosome with the {@link CharacterGene#DEFAULT_CHARACTERS}
241      * char set as valid characters.
242      *
243      @param lengthRange the allowed length range of the chromosome.
244      @return a new {@code CharacterChromosome} with the given parameter
245      @throws IllegalArgumentException if the {@code length} is smaller than
246      *         one.
247      */
248     public static CharacterChromosome of(final IntRange lengthRange) {
249         return of(DEFAULT_CHARACTERS, lengthRange);
250     }
251 
252     /**
253      * Create a new chromosome with the {@code validCharacters} char set as
254      * valid characters.
255      *
256      @since 4.3
257      *
258      @param validCharacters the valid characters for this chromosome.
259      @param length the {@code length} of the new chromosome.
260      @return a new {@code CharacterChromosome} with the given parameter
261      @throws NullPointerException if the {@code validCharacters} is
262      *         {@code null}.
263      @throws IllegalArgumentException if the length of the gene sequence is
264      *         empty, doesn't match with the allowed length range, the minimum
265      *         or maximum of the range is smaller or equal zero or the given
266      *         range size is zero.
267      */
268     public static CharacterChromosome of(
269         final CharSeq validCharacters,
270         final int length
271     ) {
272         return of(validCharacters, IntRange.of(length));
273     }
274 
275     /**
276      * Create a new chromosome with the {@link CharacterGene#DEFAULT_CHARACTERS}
277      * char set as valid characters.
278      *
279      @param length the {@code length} of the new chromosome.
280      @return a new {@code CharacterChromosome} with the given parameter
281      @throws IllegalArgumentException if the {@code length} is smaller than
282      *         one.
283      */
284     public static CharacterChromosome of(final int length) {
285         return of(DEFAULT_CHARACTERS, length);
286     }
287 
288     /**
289      * Create a new chromosome from the given genes (given as string).
290      *
291      @param alleles the character genes.
292      @param validChars the valid characters.
293      @return a new {@code CharacterChromosome} with the given parameter
294      @throws IllegalArgumentException if the genes string is empty.
295      */
296     public static CharacterChromosome of(
297         final String alleles,
298         final CharSeq validChars
299     ) {
300         final MSeq<CharacterGene> genes = MSeq.ofLength(alleles.length());
301         for (int i = 0; i < alleles.length(); ++i) {
302             genes.set(i, CharacterGene.of(alleles.charAt(i), validChars));
303         }
304 
305         return new CharacterChromosome(genes.toISeq(), IntRange.of(alleles.length()));
306     }
307 
308     /**
309      * Create a new chromosome from the given genes (given as string).
310      *
311      @param alleles the character genes.
312      @return a new {@code CharacterChromosome} with the given parameter
313      @throws IllegalArgumentException if the genes string is empty.
314      */
315     public static CharacterChromosome of(final String alleles) {
316         return of(alleles, DEFAULT_CHARACTERS);
317     }
318 
319 
320     /* *************************************************************************
321      *  Java object serialization
322      * ************************************************************************/
323 
324     private Object writeReplace() {
325         return new Serial(Serial.CHARACTER_CHROMOSOME, this);
326     }
327 
328     private void readObject(final ObjectInputStream stream)
329         throws InvalidObjectException
330     {
331         throw new InvalidObjectException("Serialization proxy required.");
332     }
333 
334     void write(final DataOutput outthrows IOException {
335         writeInt(lengthRange().min(), out);
336         writeInt(lengthRange().max(), out);
337         writeString(_validCharacters.toString(), out);
338         writeString(toString(), out);
339     }
340 
341     static CharacterChromosome read(final DataInput inthrows IOException {
342         final var lengthRange = IntRange.of(readInt(in), readInt(in));
343         final var validCharacters = new CharSeq(readString(in));
344         final var chars = readString(in);
345 
346         final MSeq<CharacterGene> values = MSeq.ofLength(chars.length());
347         for (int i = 0, n = chars.length(); i <  n; ++i) {
348             values.set(i, CharacterGene.of(chars.charAt(i), validCharacters));
349         }
350 
351         return new CharacterChromosome(values.toISeq(), lengthRange);
352     }
353 
354 }