001 /*
002 * Java Genetic Algorithm Library (jenetics-8.0.0).
003 * Copyright (c) 2007-2024 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.internal.util.Hashes.hash;
023 import static io.jenetics.internal.util.SerialIO.readInt;
024 import static io.jenetics.internal.util.SerialIO.writeInt;
025
026 import java.io.IOException;
027 import java.io.InvalidObjectException;
028 import java.io.ObjectInput;
029 import java.io.ObjectInputStream;
030 import java.io.ObjectOutput;
031 import java.io.Serial;
032 import java.io.Serializable;
033 import java.util.Objects;
034
035 import io.jenetics.util.BaseSeq;
036 import io.jenetics.util.Factory;
037 import io.jenetics.util.ISeq;
038 import io.jenetics.util.MSeq;
039 import io.jenetics.util.Verifiable;
040
041 /**
042 * The central class the GA is working with, is the {@code Genotype}. It is the
043 * structural representative of an individual. This class is the encoded problem
044 * solution with one to many {@link Chromosome}.
045 * <p>
046 * <img alt="Genotype" src="doc-files/Genotype.svg" width="400" height="252" >
047 * </p>
048 * The chromosomes of a genotype don't have to have necessarily the same size.
049 * It is only required that all genes are from the same type and the genes within
050 * a chromosome have the same constraints; e.g., the same min- and max values
051 * for the genes value.
052 *
053 * {@snippet lang="java":
054 * final Genotype<DoubleGene> genotype = Genotype.of(
055 * DoubleChromosome.of(0.0, 1.0, 8),
056 * DoubleChromosome.of(1.0, 2.0, 10),
057 * DoubleChromosome.of(0.0, 10.0, 9),
058 * DoubleChromosome.of(0.1, 0.9, 5)
059 * );
060 * }
061 * The code snippet above creates a genotype with the same structure as shown in
062 * the figure above. In this example the {@link DoubleGene} has been chosen as
063 * a gene type.
064 *
065 * @see Chromosome
066 * @see Phenotype
067 *
068 * @implNote
069 * This class is immutable and thread-safe.
070 *
071 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
072 * @since 1.0
073 * @version 7.2
074 */
075 public final class Genotype<G extends Gene<?, G>>
076 implements
077 BaseSeq<Chromosome<G>>,
078 Factory<Genotype<G>>,
079 Verifiable,
080 Serializable
081 {
082 @Serial
083 private static final long serialVersionUID = 3L;
084
085 private final ISeq<Chromosome<G>> _chromosomes;
086
087 //Caching isValid value.
088 private byte _valid = -1;
089
090 /**
091 * Create a new Genotype from a given sequence of {@code Chromosomes}.
092 *
093 * @param chromosomes The {@code Chromosome} array the {@code Genotype}
094 * consists of.
095 * @throws NullPointerException if {@code chromosomes} is null or one of its
096 * elements.
097 * @throws IllegalArgumentException if {@code chromosome.length == 0}.
098 */
099 Genotype(final ISeq<? extends Chromosome<G>> chromosomes) {
100 if (chromosomes.isEmpty()) {
101 throw new IllegalArgumentException("No chromosomes given.");
102 }
103
104 _chromosomes = ISeq.upcast(chromosomes);
105 }
106
107 /**
108 * Return the chromosome at the given index. It is guaranteed that the
109 * returned chromosome is not null.
110 *
111 * @since 4.0
112 *
113 * @param index the chromosome index
114 * @return the chromosome with the given index
115 * @throws IndexOutOfBoundsException if
116 * {@code (index < 0 || index >= _length)}.
117 */
118 @Override
119 public Chromosome<G> get(final int index) {
120 return _chromosomes.get(index);
121 }
122
123 /**
124 * Getting the number of chromosomes of this genotype.
125 *
126 * @return number of chromosomes.
127 */
128 @Override
129 public int length() {
130 return _chromosomes.length();
131 }
132
133 /**
134 * Return the first chromosome. This is an alias for
135 * {@snippet lang="java":
136 * final Genotype<DoubleGene> gt = null; // @replace substring='null' replacement="..."
137 * final Chromosome<DoubleGene> chromosome = gt.get(0);
138 * }
139 *
140 * @since 5.2
141 *
142 * @return The first chromosome.
143 */
144 public Chromosome<G> chromosome() {
145 return get(0);
146 }
147
148 /**
149 * Return the first {@link Gene} of the first {@link Chromosome} of this
150 * {@code Genotype}. This is an alias for
151 * {@snippet lang="java":
152 * final Genotype<DoubleGene> gt = null; // @replace substring='null' replacement="..."
153 * final DoubleGene gene = gt.get(0).get(0);
154 * }
155 *
156 * @since 5.2
157 *
158 * @return the first {@link Gene} of the first {@link Chromosome} of this
159 * {@code Genotype}.
160 */
161 public G gene() {
162 return get(0).get(0);
163 }
164
165 /**
166 * Return the number of genes this genotype consists of. This is the sum of
167 * the number of genes of the genotype chromosomes.
168 *
169 * @return Return the number of genes this genotype consists of.
170 */
171 public int geneCount() {
172 int count = 0;
173 for (var chromosome : this) {
174 count += chromosome.length();
175 }
176 return count;
177 }
178
179 /**
180 * Test if this genotype is valid. A genotype is valid if all its
181 * {@link Chromosome}s are valid.
182 *
183 * @return true if this genotype is valid, false otherwise.
184 */
185 @Override
186 public boolean isValid() {
187 byte valid = _valid;
188 if (valid == -1) {
189 valid = (byte)(_chromosomes.forAll(Verifiable::isValid) ? 1 : 0);
190 _valid = valid;
191 }
192
193 return _valid == 1;
194 }
195
196 /**
197 * Create a new Genotype which consists of the chromosomes from the given
198 * {@code fromIndex} (inclusively) to the given {@code toIndex} (exclusively).
199 * This method creates a <em>view</em> of the underlying chromosomes.
200 *
201 * @since 7.2
202 *
203 * @param fromIndex the start chromosome index, inclusively
204 * @param toIndex the end chromosome index, exclusively
205 * @return a new genotype consisting of the chromosomes within the given
206 * indexes
207 * @throws IndexOutOfBoundsException for an illegal end point index value
208 * ({@code fromIndex < 0 || toIndex > length() || fromIndex > toIndex}).
209 */
210 public Genotype<G> slice(int fromIndex, int toIndex) {
211 return new Genotype<>(_chromosomes.subSeq(fromIndex, toIndex));
212 }
213
214 /**
215 * Return a new, random genotype by creating new, random chromosomes (calling
216 * the {@link Chromosome#newInstance()} method) from the chromosomes of this
217 * genotype.
218 */
219 @Override
220 public Genotype<G> newInstance() {
221 return new Genotype<>(_chromosomes.map(Factory::newInstance));
222 }
223
224 @Override
225 public int hashCode() {
226 return hash(_chromosomes);
227 }
228
229 @Override
230 public boolean equals(final Object obj) {
231 return obj instanceof Genotype<?> other &&
232 Objects.equals(_chromosomes, other._chromosomes);
233 }
234
235 @Override
236 public String toString() {
237 return _chromosomes.toString();
238 }
239
240 /**
241 * Create a new {@code Genotype} from a given array of {@code Chromosomes}.
242 *
243 * @since 3.0
244 *
245 * @param <G> the gene type
246 * @param first the first {@code Chromosome} of the {@code Genotype}
247 * @param rest the rest of the genotype chromosomes.
248 * @return a new {@code Genotype} from the given chromosomes
249 * @throws NullPointerException if {@code chromosomes} is {@code null} or
250 * one of its elements.
251 */
252 @SafeVarargs
253 public static <G extends Gene<?, G>> Genotype<G> of(
254 final Chromosome<G> first,
255 final Chromosome<G>... rest
256 ) {
257 final MSeq<Chromosome<G>> seq = MSeq.ofLength(1 + rest.length);
258 seq.set(0, first);
259 for (int i = 0; i < rest.length; ++i) {
260 seq.set(i + 1, rest[i]);
261 }
262 return new Genotype<>(seq.toISeq());
263 }
264
265 /**
266 * Create a new {@code Genotype} which consists of {@code n} chromosomes,
267 * which are created by the given {@code factory}. This method can be used
268 * for easily creating a <i>gene matrix</i>. The following example will
269 * create a 10x5 {@code DoubleGene} <i>matrix</i>.
270 *
271 * {@snippet lang="java":
272 * final Genotype<DoubleGene> gt = Genotype
273 * .of(DoubleChromosome.of(0.0, 1.0, 10), 5);
274 * }
275 *
276 * @since 3.0
277 *
278 * @param <G> the gene type
279 * @param factory the factory which creates the chromosomes this genotype
280 * consists of
281 * @param n the number of chromosomes this genotype consists of
282 * @return new {@code Genotype} containing {@code n} chromosomes
283 * @throws IllegalArgumentException if {@code n < 1}.
284 * @throws NullPointerException if the {@code factory} is {@code null}.
285 */
286 public static <G extends Gene<?, G>> Genotype<G>
287 of(final Factory<? extends Chromosome<G>> factory, final int n) {
288 final ISeq<Chromosome<G>> ch = ISeq.of(factory::newInstance, n);
289 return new Genotype<>(ch);
290 }
291
292 /**
293 * Create a new {@code Genotype} from a given array of {@code chromosomes}.
294 *
295 * @since 3.0
296 *
297 * @param <G> the gene type
298 * @param chromosomes the {@code Chromosome}s the returned genotype consists
299 * of
300 * @return a new {@code Genotype} from the given chromosomes
301 * @throws NullPointerException if {@code chromosomes} is {@code null} or
302 * one of its elements.
303 * @throws IllegalArgumentException if {@code chromosome.length() < 1}.
304 */
305 public static <G extends Gene<?, G>> Genotype<G>
306 of(final Iterable<? extends Chromosome<G>> chromosomes) {
307 return new Genotype<>(ISeq.of(chromosomes));
308 }
309
310
311 /* *************************************************************************
312 * Java object serialization
313 * ************************************************************************/
314
315 @Serial
316 private Object writeReplace() {
317 return new SerialProxy(SerialProxy.GENOTYPE, this);
318 }
319
320 @Serial
321 private void readObject(final ObjectInputStream stream)
322 throws InvalidObjectException
323 {
324 throw new InvalidObjectException("Serialization proxy required.");
325 }
326
327 void write(final ObjectOutput out) throws IOException {
328 writeInt(_chromosomes.length(), out);
329 for (var ch : _chromosomes) {
330 out.writeObject(ch);
331 }
332 }
333
334 @SuppressWarnings({"unchecked", "rawtypes"})
335 static Object read(final ObjectInput in)
336 throws IOException, ClassNotFoundException
337 {
338 final int length = readInt(in);
339 final MSeq chromosomes = MSeq.ofLength(length);
340 for (int i = 0; i < length; ++i) {
341 chromosomes.set(i, in.readObject());
342 }
343
344 return new Genotype(chromosomes.asISeq());
345 }
346
347 }
|