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