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