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