001 /*
002 * Java Genetic Algorithm Library (jenetics-4.2.0).
003 * Copyright (c) 2007-2018 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.Equality.eq;
024
025 import java.io.IOException;
026 import java.io.ObjectInputStream;
027 import java.io.ObjectOutputStream;
028 import java.io.Serializable;
029 import java.util.function.Supplier;
030 import java.util.stream.Collectors;
031
032 import io.jenetics.internal.util.Equality;
033 import io.jenetics.internal.util.Hash;
034 import io.jenetics.internal.util.IntRef;
035 import io.jenetics.internal.util.reflect;
036 import io.jenetics.util.CharSeq;
037 import io.jenetics.util.ISeq;
038 import io.jenetics.util.IntRange;
039 import io.jenetics.util.MSeq;
040
041 /**
042 * CharacterChromosome which represents character sequences.
043 *
044 * @see CharacterGene
045 *
046 * @implNote
047 * This class is immutable and thread-safe.
048 *
049 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
050 * @since 1.0
051 * @version 4.0
052 */
053 public class CharacterChromosome
054 extends
055 VariableChromosome<CharacterGene>
056 implements
057 CharSequence,
058 Serializable
059 {
060 private static final long serialVersionUID = 3L;
061
062 private transient 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).getValidCharacters();
083 }
084
085 /**
086 * Create a new chromosome with the {@code validCharacters} char set as
087 * valid characters.
088 *
089 * @since 4.0
090 *
091 * @param validCharacters the valid characters for this chromosome.
092 * @param lengthRange the allowed length range of the chromosome.
093 * @throws NullPointerException if the {@code validCharacters} is
094 * {@code null}.
095 * @throws IllegalArgumentException if the length of the gene sequence is
096 * empty, doesn't match with the allowed length range, the minimum
097 * or maximum of the range is smaller or equal zero or the given
098 * range size is zero.
099 */
100 public CharacterChromosome(
101 final CharSeq validCharacters,
102 final IntRange lengthRange
103 ) {
104 this(CharacterGene.seq(validCharacters, lengthRange), lengthRange);
105 _valid = true;
106 }
107
108 /**
109 * Create a new chromosome with the {@code validCharacters} char set as
110 * valid characters.
111 *
112 * @param validCharacters the valid characters for this chromosome.
113 * @param length the length of the chromosome.
114 * @throws NullPointerException if the {@code validCharacters} is
115 * {@code null}.
116 * @throws IllegalArgumentException if the length of the gene sequence is
117 * empty, doesn't match with the allowed length range, the minimum
118 * or maximum of the range is smaller or equal zero or the given
119 * range size is zero.
120 */
121 public CharacterChromosome(
122 final CharSeq validCharacters,
123 final int length
124 ) {
125 this(validCharacters, IntRange.of(length));
126 }
127
128 @Override
129 public char charAt(final int index) {
130 return getGene(index).charValue();
131 }
132
133 @Override
134 public CharacterChromosome subSequence(final int start, final int end) {
135 return new CharacterChromosome(_genes.subSeq(start, end), lengthRange());
136 }
137
138 /**
139 * @throws NullPointerException if the given gene array is {@code null}.
140 */
141 @Override
142 public CharacterChromosome newInstance(final ISeq<CharacterGene> genes) {
143 return new CharacterChromosome(genes, lengthRange());
144 }
145
146 /**
147 * Create a new, <em>random</em> chromosome.
148 */
149 @Override
150 public CharacterChromosome newInstance() {
151 return new CharacterChromosome(_validCharacters, lengthRange());
152 }
153
154 @Override
155 public int hashCode() {
156 return Hash.of(getClass())
157 .and(super.hashCode())
158 .and(_validCharacters).value();
159 }
160
161 @Override
162 public boolean equals(final Object obj) {
163 return Equality.of(this, obj).test(cc ->
164 super.equals(obj) &&
165 eq(_validCharacters, cc._validCharacters)
166 );
167 }
168
169 @Override
170 public String toString() {
171 return toSeq().stream()
172 .map(Object::toString)
173 .collect(Collectors.joining());
174 }
175
176 /**
177 * Returns an char array containing all of the elements in this chromosome
178 * in proper sequence. If the chromosome fits in the specified array, it is
179 * returned therein. Otherwise, a new array is allocated with the length of
180 * this chromosome.
181 *
182 * @since 3.0
183 *
184 * @param array the array into which the elements of this chromosomes are to
185 * be stored, if it is big enough; otherwise, a new array is
186 * allocated for this purpose.
187 * @return an array containing the elements of this chromosome
188 * @throws NullPointerException if the given {@code array} is {@code null}
189 */
190 public char[] toArray(final char[] array) {
191 final char[] a = array.length >= length() ?
192 array : 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 * Create a new chromosome with the {@link CharacterGene#DEFAULT_CHARACTERS}
215 * char set as valid characters.
216 *
217 * @param lengthRange the allowed length range of the chromosome.
218 * @return a new {@code CharacterChromosome} with the given parameter
219 * @throws IllegalArgumentException if the {@code length} is smaller than
220 * one.
221 */
222 public static CharacterChromosome of(final IntRange lengthRange) {
223 return new CharacterChromosome(
224 CharacterGene.seq(DEFAULT_CHARACTERS, lengthRange),
225 lengthRange
226 );
227 }
228
229 /**
230 * Create a new chromosome with the {@link CharacterGene#DEFAULT_CHARACTERS}
231 * char set as valid characters.
232 *
233 * @param length the {@code length} of the new chromosome.
234 * @return a new {@code CharacterChromosome} with the given parameter
235 * @throws IllegalArgumentException if the {@code length} is smaller than
236 * one.
237 */
238 public static CharacterChromosome of(final int length) {
239 return new CharacterChromosome(
240 CharacterGene.seq(DEFAULT_CHARACTERS, IntRange.of(length)),
241 IntRange.of(length)
242 );
243 }
244
245 /**
246 * Create a new chromosome from the given genes (given as string).
247 *
248 * @param alleles the character genes.
249 * @param validChars the valid characters.
250 * @return a new {@code CharacterChromosome} with the given parameter
251 * @throws IllegalArgumentException if the genes string is empty.
252 */
253 public static CharacterChromosome of(
254 final String alleles,
255 final CharSeq validChars
256 ) {
257 final IntRef index = new IntRef();
258 final Supplier<CharacterGene> geneFactory = () -> CharacterGene.of(
259 alleles.charAt(index.value++), validChars
260 );
261
262 final ISeq<CharacterGene> genes =
263 MSeq.<CharacterGene>ofLength(alleles.length())
264 .fill(geneFactory)
265 .toISeq();
266
267 return new CharacterChromosome(genes, IntRange.of(alleles.length()));
268 }
269
270 /**
271 * Create a new chromosome from the given genes (given as string).
272 *
273 * @param alleles the character genes.
274 * @return a new {@code CharacterChromosome} with the given parameter
275 * @throws IllegalArgumentException if the genes string is empty.
276 */
277 public static CharacterChromosome of(final String alleles) {
278 return of(alleles, DEFAULT_CHARACTERS);
279 }
280
281
282 /* *************************************************************************
283 * Java object serialization
284 * ************************************************************************/
285
286 private void writeObject(final ObjectOutputStream out)
287 throws IOException
288 {
289 out.defaultWriteObject();
290
291 out.writeInt(length());
292 out.writeObject(_validCharacters);
293
294 for (CharacterGene gene : _genes) {
295 out.writeChar(gene.getAllele());
296 }
297 }
298
299 private void readObject(final ObjectInputStream in)
300 throws IOException, ClassNotFoundException
301 {
302 in.defaultReadObject();
303
304 final int length = in.readInt();
305 _validCharacters = (CharSeq)in.readObject();
306
307 final MSeq<CharacterGene> genes = MSeq.ofLength(length);
308 for (int i = 0; i < length; ++i) {
309 final CharacterGene gene = CharacterGene.of(
310 in.readChar(),
311 _validCharacters
312 );
313 genes.set(i, gene);
314 }
315 reflect.setField(this, "_genes", genes.toISeq());
316 }
317
318 }
|