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