001 /*
002 * Java Genetic Algorithm Library (jenetics-7.0.0).
003 * Copyright (c) 2007-2022 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 doesn'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 number genes.
052 *
053 * <pre>{@code
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 * }</pre>
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 * 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 6.0
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 * element.
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 * <pre>{@code
136 * final Genotype<DoubleGene>; gt = ...
137 * final Chromosome<DoubleGene> chromosome = gt.get(0);
138 * }</pre>
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 * <pre>{@code
152 * final Genotype<DoubleGene> gt = ...
153 * final DoubleGene gene = gt.get(0).get(0);
154 * }</pre>
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 * Return a new, random genotype by creating new, random chromosomes (calling
198 * the {@link Chromosome#newInstance()} method) from the chromosomes of this
199 * genotype.
200 */
201 @Override
202 public Genotype<G> newInstance() {
203 return new Genotype<>(_chromosomes.map(Factory::newInstance));
204 }
205
206 @Override
207 public int hashCode() {
208 return hash(_chromosomes);
209 }
210
211 @Override
212 public boolean equals(final Object obj) {
213 return obj instanceof Genotype<?> other &&
214 Objects.equals(_chromosomes, other._chromosomes);
215 }
216
217 @Override
218 public String toString() {
219 return _chromosomes.toString();
220 }
221
222 /**
223 * Create a new {@code Genotype} from a given array of {@code Chromosomes}.
224 *
225 * @since 3.0
226 *
227 * @param <G> the gene type
228 * @param first the first {@code Chromosome} of the {@code Genotype}
229 * @param rest the rest of the genotypes chromosomes.
230 * @return a new {@code Genotype} from the given chromosomes
231 * @throws NullPointerException if {@code chromosomes} is {@code null} or
232 * one of its element.
233 */
234 @SafeVarargs
235 public static <G extends Gene<?, G>> Genotype<G> of(
236 final Chromosome<G> first,
237 final Chromosome<G>... rest
238 ) {
239 final MSeq<Chromosome<G>> seq = MSeq.ofLength(1 + rest.length);
240 seq.set(0, first);
241 for (int i = 0; i < rest.length; ++i) {
242 seq.set(i + 1, rest[i]);
243 }
244 return new Genotype<>(seq.toISeq());
245 }
246
247 /**
248 * Create a new {@code Genotype} which consists of {@code n} chromosomes,
249 * which are created by the given {@code factory}. This method can be used
250 * for easily creating a <i>gene matrix</i>. The following example will
251 * create a 10x5 {@code DoubleGene} <i>matrix</i>.
252 *
253 * <pre>{@code
254 * final Genotype<DoubleGene> gt = Genotype
255 * .of(DoubleChromosome.of(0.0, 1.0, 10), 5);
256 * }</pre>
257 *
258 * @since 3.0
259 *
260 * @param <G> the gene type
261 * @param factory the factory which creates the chromosomes this genotype
262 * consists of
263 * @param n the number of chromosomes this genotype consists of
264 * @return new {@code Genotype} containing {@code n} chromosomes
265 * @throws IllegalArgumentException if {@code n < 1}.
266 * @throws NullPointerException if the {@code factory} is {@code null}.
267 */
268 public static <G extends Gene<?, G>> Genotype<G>
269 of(final Factory<? extends Chromosome<G>> factory, final int n) {
270 final ISeq<Chromosome<G>> ch = ISeq.of(factory::newInstance, n);
271 return new Genotype<>(ch);
272 }
273
274 /**
275 * Create a new {@code Genotype} from a given array of {@code chromosomes}.
276 *
277 * @since 3.0
278 *
279 * @param <G> the gene type
280 * @param chromosomes the {@code Chromosome}s the returned genotype consists
281 * of
282 * @return a new {@code Genotype} from the given chromosomes
283 * @throws NullPointerException if {@code chromosomes} is {@code null} or
284 * one of its element.
285 * @throws IllegalArgumentException if {@code chromosome.length() < 1}.
286 */
287 public static <G extends Gene<?, G>> Genotype<G>
288 of(final Iterable<? extends Chromosome<G>> chromosomes) {
289 return new Genotype<>(ISeq.of(chromosomes));
290 }
291
292
293 /* *************************************************************************
294 * Java object serialization
295 * ************************************************************************/
296
297 @Serial
298 private Object writeReplace() {
299 return new SerialProxy(SerialProxy.GENOTYPE, this);
300 }
301
302 @Serial
303 private void readObject(final ObjectInputStream stream)
304 throws InvalidObjectException
305 {
306 throw new InvalidObjectException("Serialization proxy required.");
307 }
308
309 void write(final ObjectOutput out) throws IOException {
310 writeInt(_chromosomes.length(), out);
311 for (var ch : _chromosomes) {
312 out.writeObject(ch);
313 }
314 }
315
316 @SuppressWarnings({"unchecked", "rawtypes"})
317 static Object read(final ObjectInput in)
318 throws IOException, ClassNotFoundException
319 {
320 final int length = readInt(in);
321 final MSeq chromosomes = MSeq.ofLength(length);
322 for (int i = 0; i < length; ++i) {
323 chromosomes.set(i, in.readObject());
324 }
325
326 return new Genotype(chromosomes.asISeq());
327 }
328
329 }
|