001/* 002 * Java Genetic Algorithm Library (jenetics-8.2.0). 003 * Copyright (c) 2007-2025 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 */ 020package io.jenetics; 021 022import static java.util.Objects.requireNonNull; 023import static io.jenetics.CharacterGene.DEFAULT_CHARACTERS; 024import static io.jenetics.internal.util.Hashes.hash; 025import static io.jenetics.internal.util.SerialIO.readInt; 026import static io.jenetics.internal.util.SerialIO.readString; 027import static io.jenetics.internal.util.SerialIO.writeInt; 028import static io.jenetics.internal.util.SerialIO.writeString; 029 030import java.io.DataInput; 031import java.io.DataOutput; 032import java.io.IOException; 033import java.io.InvalidObjectException; 034import java.io.ObjectInputStream; 035import java.io.Serial; 036import java.io.Serializable; 037import java.util.Objects; 038import java.util.function.Function; 039import java.util.stream.IntStream; 040 041import io.jenetics.util.CharSeq; 042import io.jenetics.util.ISeq; 043import io.jenetics.util.IntRange; 044import io.jenetics.util.MSeq; 045 046/** 047 * Character chromosome which represents character sequences. 048 * 049 * @see CharacterGene 050 * 051 * @implNote 052 * This class is immutable and thread-safe. 053 * 054 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a> 055 * @since 1.0 056 * @version 6.1 057 */ 058public class CharacterChromosome 059 extends VariableChromosome<CharacterGene> 060 implements 061 CharSequence, 062 Serializable 063{ 064 @Serial 065 private static final long serialVersionUID = 3L; 066 067 private transient final CharSeq _validCharacters; 068 069 /** 070 * Create a new chromosome from the given {@code genes} array. The genes 071 * array is copied, so changes to the given genes array don't affect the 072 * genes of this chromosome. 073 * 074 * @since 4.0 075 * 076 * @param genes the genes that form the chromosome. 077 * @param lengthRange the allowed length range of the chromosome. 078 * @throws NullPointerException if the given gene array is {@code null}. 079 * @throws IllegalArgumentException if the length of the gene array is 080 * smaller than one. 081 */ 082 protected CharacterChromosome( 083 final ISeq<CharacterGene> genes, 084 final IntRange lengthRange 085 ) { 086 super(genes, lengthRange); 087 _validCharacters = genes.get(0).validChars(); 088 } 089 090 @Override 091 public char charAt(final int index) { 092 return get(index).charValue(); 093 } 094 095 @Override 096 public boolean isEmpty() { 097 return super.isEmpty(); 098 } 099 100 @Override 101 public CharacterChromosome subSequence(final int start, final int end) { 102 return new CharacterChromosome(_genes.subSeq(start, end), lengthRange()); 103 } 104 105 /** 106 * @throws NullPointerException if the given gene array is {@code null}. 107 */ 108 @Override 109 public CharacterChromosome newInstance(final ISeq<CharacterGene> genes) { 110 return new CharacterChromosome(genes, lengthRange()); 111 } 112 113 /** 114 * Create a new, <em>random</em> chromosome. 115 */ 116 @Override 117 public CharacterChromosome newInstance() { 118 return of(_validCharacters, lengthRange()); 119 } 120 121 /** 122 * Maps the gene alleles of this chromosome, given as {@code char[]} array, 123 * by applying the given mapper function {@code f}. The mapped gene values 124 * are then wrapped into a newly created chromosome. 125 * {@snippet lang="java": 126 * final CharacterChromosome chromosome = null; // @replace substring='null' replacement="..." 127 * final CharacterChromosome uppercase = chromosome.map(Main::uppercase); 128 * 129 * static int[] uppercase(final int[] values) { 130 * for (int i = 0; i < values.length; ++i) { 131 * values[i] = Character.toUpperCase(values[i]); 132 * } 133 * return values; 134 * } 135 * } 136 * 137 * @since 6.1 138 * 139 * @param f the mapper function 140 * @return a newly created chromosome with the mapped gene values 141 * @throws NullPointerException if the mapper function is {@code null}. 142 * @throws IllegalArgumentException if the length of the mapped 143 * {@code char[]} array is empty or doesn't match with the allowed 144 * length range 145 */ 146 public CharacterChromosome map(final Function<? super char[], char[]> f) { 147 requireNonNull(f); 148 149 final char[] chars = f.apply(toArray()); 150 final var genes = IntStream.range(0, chars.length) 151 .mapToObj(i -> CharacterGene.of(chars[i], _validCharacters)) 152 .collect(ISeq.toISeq()); 153 154 return newInstance(genes); 155 } 156 157 @Override 158 public int hashCode() { 159 return hash(super.hashCode(), hash(_validCharacters)); 160 } 161 162 @Override 163 public boolean equals(final Object obj) { 164 return 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 a char array containing all the elements in this chromosome 177 * in a 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 chromosome 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 a char array containing all the elements in this chromosome 203 * in a 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 @Serial 330 private Object writeReplace() { 331 return new SerialProxy(SerialProxy.CHARACTER_CHROMOSOME, this); 332 } 333 334 @Serial 335 private void readObject(final ObjectInputStream stream) 336 throws InvalidObjectException 337 { 338 throw new InvalidObjectException("Serialization proxy required."); 339 } 340 341 void write(final DataOutput out) throws IOException { 342 writeInt(lengthRange().min(), out); 343 writeInt(lengthRange().max(), out); 344 writeString(_validCharacters.toString(), out); 345 writeString(toString(), out); 346 } 347 348 static CharacterChromosome read(final DataInput in) throws IOException { 349 final var lengthRange = IntRange.of(readInt(in), readInt(in)); 350 final var validCharacters = new CharSeq(readString(in)); 351 final var chars = readString(in); 352 353 final MSeq<CharacterGene> values = MSeq.ofLength(chars.length()); 354 for (int i = 0, n = chars.length(); i < n; ++i) { 355 values.set(i, CharacterGene.of(chars.charAt(i), validCharacters)); 356 } 357 358 return new CharacterChromosome(values.toISeq(), lengthRange); 359 } 360 361}