IntegerChromosome.java
001 /*
002  * Java Genetic Algorithm Library (jenetics-6.3.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 java.util.Objects.requireNonNull;
023 import static io.jenetics.internal.util.SerialIO.readInt;
024 import static io.jenetics.internal.util.SerialIO.writeInt;
025 
026 import java.io.DataInput;
027 import java.io.DataOutput;
028 import java.io.IOException;
029 import java.io.InvalidObjectException;
030 import java.io.ObjectInputStream;
031 import java.io.Serializable;
032 import java.util.function.Function;
033 import java.util.stream.DoubleStream;
034 import java.util.stream.IntStream;
035 import java.util.stream.Stream;
036 
037 import io.jenetics.util.DoubleRange;
038 import io.jenetics.util.ISeq;
039 import io.jenetics.util.IntRange;
040 import io.jenetics.util.MSeq;
041 
042 /**
043  * Numeric chromosome implementation which holds 32 bit integer numbers.
044  *
045  @see IntegerGene
046  *
047  * @implNote
048  * This class is immutable and thread-safe.
049  *
050  @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz  Wilhelmstötter</a>
051  @since 2.0
052  @version 6.1
053  */
054 public class IntegerChromosome
055     extends AbstractBoundedChromosome<Integer, IntegerGene>
056     implements
057             NumericChromosome<Integer, IntegerGene>,
058             Serializable
059 {
060     private static final long serialVersionUID = 3L;
061 
062     /**
063      * Create a new chromosome from the given {@code genes} and the allowed
064      * length range of the chromosome.
065      *
066      @since 4.0
067      *
068      @param genes the genes that form the chromosome.
069      @param lengthRange the allowed length range of the chromosome
070      @throws NullPointerException if one of the arguments is {@code null}.
071      @throws IllegalArgumentException if the length of the gene sequence is
072      *         empty, doesn't match with the allowed length range, the minimum
073      *         or maximum of the range is smaller or equal zero or the given
074      *         range size is zero.
075      */
076     protected IntegerChromosome(
077         final ISeq<IntegerGene> genes,
078         final IntRange lengthRange
079     ) {
080         super(genes, lengthRange);
081     }
082 
083     @Override
084     public IntegerChromosome newInstance(final ISeq<IntegerGene> genes) {
085         return new IntegerChromosome(genes, lengthRange());
086     }
087 
088     @Override
089     public IntegerChromosome newInstance() {
090         return of(_min, _max, lengthRange());
091     }
092 
093     /**
094      * Maps the gene alleles of this chromosome, given as {@code int[]} array,
095      * by applying the given mapper function {@code f}. The mapped gene values
096      * are then wrapped into a newly created chromosome.
097      *
098      <pre>{@code
099      * final IntegerChromosome chromosome = ...;
100      * final IntegerChromosome halved = chromosome.map(Main::half);
101      *
102      * static int[] half(final int[] values) {
103      *     for (int i = 0; i < values.length; ++i) {
104      *         values[i] /= 2;
105      *     }
106      *     return values;
107      * }
108      * }</pre>
109      *
110      @since 6.1
111      *
112      @param f the mapper function
113      @return a newly created chromosome with the mapped gene values
114      @throws NullPointerException if the mapper function is {@code null}.
115      @throws IllegalArgumentException if the length of the mapped
116      *         {@code int[]} array is empty or doesn't match with the allowed
117      *         length range
118      */
119     public IntegerChromosome map(final Function<? super int[]int[]> f) {
120         requireNonNull(f);
121 
122         final var range = IntRange.of(_min, _max);
123         final var genes = IntStream.of(f.apply(toArray()))
124             .mapToObj(v -> IntegerGene.of(v, range))
125             .collect(ISeq.toISeq());
126 
127         return newInstance(genes);
128     }
129 
130     /**
131      * Returns a sequential stream of the alleles with this chromosome as its
132      * source.
133      *
134      @since 4.3
135      *
136      @return a sequential stream of alleles
137      */
138     public IntStream intStream() {
139         return IntStream.range(0, length()).map(this::intValue);
140     }
141 
142     /**
143      * Returns an int array containing all of the elements in this chromosome
144      * in proper sequence.  If the chromosome fits in the specified array, it is
145      * returned therein. Otherwise, a new array is allocated with the length of
146      * this chromosome.
147      *
148      @since 3.0
149      *
150      @param array the array into which the elements of this chromosomes are to
151      *        be stored, if it is big enough; otherwise, a new array is
152      *        allocated for this purpose.
153      @return an array containing the elements of this chromosome
154      @throws NullPointerException if the given {@code array} is {@code null}
155      */
156     public int[] toArray(final int[] array) {
157         final int[] a = array.length >= length() ? array : new int[length()];
158         for (int i = length(); --i >= 0;) {
159             a[i= intValue(i);
160         }
161 
162         return a;
163     }
164 
165     /**
166      * Returns an int array containing all of the elements in this chromosome
167      * in proper sequence.
168      *
169      @since 3.0
170      *
171      @return an array containing the elements of this chromosome
172      */
173     public int[] toArray() {
174         return toArray(new int[length()]);
175     }
176 
177 
178     /* *************************************************************************
179      * Static factory methods.
180      * ************************************************************************/
181 
182     /**
183      * Create a new {@code IntegerChromosome} with the given genes.
184      *
185      @param genes the genes of the chromosome.
186      @return a new chromosome with the given genes.
187      @throws IllegalArgumentException if the length of the genes array is
188      *         empty or the given {@code genes} doesn't have the same range.
189      */
190     public static IntegerChromosome of(final IntegerGene... genes) {
191         checkGeneRange(Stream.of(genes).map(IntegerGene::range));
192         return new IntegerChromosome(ISeq.of(genes), IntRange.of(genes.length));
193     }
194 
195     /**
196      * Create a new {@code IntegerChromosome} with the given genes.
197      *
198      @since 4.3
199      *
200      @param genes the genes of the chromosome.
201      @return a new chromosome with the given genes.
202      @throws NullPointerException if the given {@code genes} are {@code null}
203      @throws IllegalArgumentException if the of the genes iterable is empty or
204      *         the given {@code genes} doesn't have the same range.
205      */
206     public static IntegerChromosome of(final Iterable<IntegerGene> genes) {
207         final ISeq<IntegerGene> values = ISeq.of(genes);
208         checkGeneRange(values.stream().map(IntegerGene::range));
209         return new IntegerChromosome(values, IntRange.of(values.length()));
210     }
211 
212     /**
213      * Create a new random chromosome.
214      *
215      @since 4.0
216      *
217      @param min the min value of the {@link IntegerGene}s (inclusively).
218      @param max the max value of the {@link IntegerGene}s (inclusively).
219      @param lengthRange the allowed length range of the chromosome.
220      @return a new {@code IntegerChromosome} with the given parameter
221      @throws IllegalArgumentException if the length of the gene sequence is
222      *         empty, doesn't match with the allowed length range, the minimum
223      *         or maximum of the range is smaller or equal zero or the given
224      *         range size is zero.
225      @throws NullPointerException if the given {@code lengthRange} is
226      *         {@code null}
227      */
228     public static IntegerChromosome of(
229         final int min,
230         final int max,
231         final IntRange lengthRange
232     ) {
233         final ISeq<IntegerGene> values = IntegerGene.seq(min, max, lengthRange);
234         return new IntegerChromosome(values, lengthRange);
235     }
236 
237     /**
238      * Create a new random {@code IntegerChromosome}.
239      *
240      @param min the min value of the {@link IntegerGene}s (inclusively).
241      @param max the max value of the {@link IntegerGene}s (inclusively).
242      @param length the length of the chromosome.
243      @return a new random {@code IntegerChromosome}
244      @throws IllegalArgumentException if the length is smaller than one
245      */
246     public static IntegerChromosome of(
247         final int min,
248         final int max,
249         final int length
250     ) {
251         return of(min, max, IntRange.of(length));
252     }
253 
254     /**
255      * Create a new random chromosome.
256      *
257      @since 4.0
258      *
259      @param range the integer range of the chromosome.
260      @param lengthRange the allowed length range of the chromosome.
261      @return a new {@code IntegerChromosome} with the given parameter
262      @throws IllegalArgumentException if the length of the gene sequence is
263      *         empty, doesn't match with the allowed length range, the minimum
264      *         or maximum of the range is smaller or equal zero or the given
265      *         range size is zero.
266      @throws NullPointerException if the given {@code lengthRange} is
267      *         {@code null}
268      */
269     public static IntegerChromosome of(
270         final IntRange range,
271         final IntRange lengthRange
272     ) {
273         return of(range.min(), range.max(), lengthRange);
274     }
275 
276     /**
277      * Create a new random {@code IntegerChromosome}.
278      *
279      @since 3.2
280      *
281      @param range the integer range of the chromosome.
282      @param length the length of the chromosome.
283      @return a new random {@code IntegerChromosome}
284      @throws NullPointerException if the given {@code range} is {@code null}
285      @throws IllegalArgumentException if the length is smaller than one
286      */
287     public static IntegerChromosome of(final IntRange range, final int length) {
288         return of(range.min(), range.max(), length);
289     }
290 
291     /**
292      * Create a new random {@code IntegerChromosome} of length one.
293      *
294      @param min the minimal value of this chromosome (inclusively).
295      @param max the maximal value of this chromosome (inclusively).
296      @return a new random {@code IntegerChromosome} of length one
297      */
298     public static IntegerChromosome of(final int min, final int max) {
299         return of(min, max, 1);
300     }
301 
302     /**
303      * Create a new random {@code IntegerChromosome} of length one.
304      *
305      @since 3.2
306      *
307      @param range the integer range of the chromosome.
308      @return a new random {@code IntegerChromosome} of length one
309      @throws NullPointerException if the given {@code range} is {@code null}
310      */
311     public static IntegerChromosome of(final IntRange range) {
312         return of(range.min(), range.max()1);
313     }
314 
315 
316 
317     /* *************************************************************************
318      *  Java object serialization
319      * ************************************************************************/
320 
321     private Object writeReplace() {
322         return new Serial(Serial.INTEGER_CHROMOSOME, this);
323     }
324 
325     private void readObject(final ObjectInputStream stream)
326         throws InvalidObjectException
327     {
328         throw new InvalidObjectException("Serialization proxy required.");
329     }
330 
331     void write(final DataOutput outthrows IOException {
332         writeInt(length(), out);
333         writeInt(lengthRange().min(), out);
334         writeInt(lengthRange().max(), out);
335         writeInt(_min, out);
336         writeInt(_max, out);
337 
338         for (int i = 0, n = length(); i < n; ++i) {
339             writeInt(intValue(i), out);
340         }
341     }
342 
343     static IntegerChromosome read(final DataInput inthrows IOException {
344         final var length = readInt(in);
345         final var lengthRange = IntRange.of(readInt(in), readInt(in));
346         final var min = readInt(in);
347         final var max = readInt(in);
348 
349         final MSeq<IntegerGene> values = MSeq.ofLength(length);
350         for (int i = 0; i < length; ++i) {
351             values.set(i, IntegerGene.of(readInt(in), min, max));
352         }
353 
354         return new IntegerChromosome(values.toISeq(), lengthRange);
355     }
356 
357 }