001 /*
002 * Java Genetic Algorithm Library (jenetics-6.1.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 java.lang.String.format;
023 import static io.jenetics.internal.util.Hashes.hash;
024 import static io.jenetics.internal.util.SerialIO.readInt;
025 import static io.jenetics.internal.util.SerialIO.writeInt;
026 import static io.jenetics.util.RandomRegistry.random;
027
028 import java.io.DataInput;
029 import java.io.DataOutput;
030 import java.io.IOException;
031 import java.io.InvalidObjectException;
032 import java.io.ObjectInputStream;
033 import java.io.Serializable;
034 import java.util.Random;
035
036 import io.jenetics.internal.math.Randoms;
037 import io.jenetics.util.ISeq;
038 import io.jenetics.util.IntRange;
039 import io.jenetics.util.MSeq;
040 import io.jenetics.util.Mean;
041
042 /**
043 * NumericGene implementation which holds a 32 bit integer number.
044 *
045 * <p>This is a <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/doc-files/ValueBased.html">
046 * value-based</a> class; use of identity-sensitive operations (including
047 * reference equality ({@code ==}), identity hash code, or synchronization) on
048 * instances of {@code IntegerGene} may have unpredictable results and should
049 * be avoided.
050 *
051 * @see IntegerChromosome
052 *
053 * @implNote
054 * This class is immutable and thread-safe.
055 *
056 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
057 * @since 2.0
058 * @version 6.1
059 */
060 public final class IntegerGene
061 implements
062 NumericGene<Integer, IntegerGene>,
063 Mean<IntegerGene>,
064 Comparable<IntegerGene>,
065 Serializable
066 {
067
068 private static final long serialVersionUID = 2L;
069
070 private final int _allele;
071 private final int _min;
072 private final int _max;
073
074 /**
075 * Create a new random {@code IntegerGene} with the given value and the
076 * given range. If the {@code value} isn't within the interval [min, max],
077 * no exception is thrown. In this case the method
078 * {@link IntegerGene#isValid()} returns {@code false}.
079 *
080 * @param allele the value of the gene.
081 * @param min the minimal valid value of this gene (inclusively).
082 * @param max the maximal valid value of this gene (inclusively).
083 */
084 private IntegerGene(final int allele, final int min, final int max) {
085 _allele = allele;
086 _min = min;
087 _max = max;
088 }
089
090 @Override
091 public Integer allele() {
092 return _allele;
093 }
094
095 @Override
096 public Integer min() {
097 return _min;
098 }
099
100 @Override
101 public Integer max() {
102 return _max;
103 }
104
105 /**
106 * Return the range of {@code this} gene.
107 *
108 * @since 4.4
109 *
110 * @return the range of {@code this} gene
111 */
112 public IntRange range() {
113 return IntRange.of(_min, _max);
114 }
115
116 @Override
117 public byte byteValue() {
118 return (byte) _allele;
119 }
120
121 @Override
122 public short shortValue() {
123 return (short) _allele;
124 }
125
126 @Override
127 public int intValue() {
128 return _allele;
129 }
130
131 @Override
132 public long longValue() {
133 return _allele;
134 }
135
136 @Override
137 public float floatValue() {
138 return (float) _allele;
139 }
140
141 @Override
142 public double doubleValue() {
143 return _allele;
144 }
145
146 @Override
147 public boolean isValid() {
148 return _allele >= _min && _allele <= _max;
149 }
150
151 @Override
152 public int compareTo(final IntegerGene other) {
153 return Integer.compare(_allele, other._allele);
154 }
155
156 @Override
157 public IntegerGene mean(final IntegerGene that) {
158 return IntegerGene.of(_allele + (that._allele - _allele)/2, _min, _max);
159 }
160
161 /**
162 * Create a new gene from the given {@code value} and the gene context.
163 *
164 * @since 5.0
165 * @param allele the value of the new gene.
166 * @return a new gene with the given value.
167 */
168 public IntegerGene newInstance(final int allele) {
169 return IntegerGene.of(allele, _min, _max);
170 }
171
172 @Override
173 public IntegerGene newInstance(final Integer allele) {
174 return IntegerGene.of(allele, _min, _max);
175 }
176
177 @Override
178 public IntegerGene newInstance(final Number allele) {
179 final int value = allele instanceof Double || allele instanceof Float
180 ? (int)Math.round(allele.doubleValue())
181 : allele.intValue();
182
183 return IntegerGene.of(value, _min, _max);
184 }
185
186 @Override
187 public IntegerGene newInstance() {
188 return IntegerGene.of(nextInt(random(), _min, _max), _min, _max);
189 }
190
191 @Override
192 public int hashCode() {
193 return hash(_allele, hash(_min, hash(_max)));
194 }
195
196 @Override
197 public boolean equals(final Object obj) {
198 return obj == this ||
199 obj instanceof IntegerGene &&
200 ((IntegerGene)obj)._allele == _allele &&
201 ((IntegerGene)obj)._min == _min &&
202 ((IntegerGene)obj)._max == _max;
203 }
204
205 @Override
206 public String toString() {
207 return String.format("[%s]", _allele);
208 }
209
210 /* *************************************************************************
211 * Static factory methods.
212 * ************************************************************************/
213
214 /**
215 * Create a new random {@code IntegerGene} with the given value and the
216 * given range. If the {@code value} isn't within the interval [min, max],
217 * no exception is thrown. In this case the method
218 * {@link IntegerGene#isValid()} returns {@code false}.
219 *
220 * @param allele the value of the gene.
221 * @param min the minimal valid value of this gene (inclusively).
222 * @param max the maximal valid value of this gene (inclusively).
223 * @return a new {@code IntegerGene} with the given {@code value}
224 */
225 public static IntegerGene of(final int allele, final int min, final int max) {
226 return new IntegerGene(allele, min, max);
227 }
228
229 /**
230 * Create a new random {@code IntegerGene} with the given value and the
231 * given range. If the {@code value} isn't within the interval [min, max],
232 * no exception is thrown. In this case the method
233 * {@link IntegerGene#isValid()} returns {@code false}.
234 *
235 * @since 3.2
236 *
237 * @param allele the value of the gene.
238 * @param range the integer range to use
239 * @return a new {@code IntegerGene} with the give {@code value}
240 * @throws NullPointerException if the given {@code range} is {@code null}.
241 */
242 public static IntegerGene of(final int allele, final IntRange range) {
243 return IntegerGene.of(allele, range.min(), range.max());
244 }
245
246 /**
247 * Create a new random {@code IntegerGene}. It is guaranteed that the value of
248 * the {@code IntegerGene} lies in the interval [min, max].
249 *
250 * @param min the minimal valid value of this gene (inclusively).
251 * @param max the maximal valid value of this gene (inclusively).
252 * @return a new random {@code IntegerGene}
253 */
254 public static IntegerGene of(final int min, final int max) {
255 return of(nextInt(random(), min, max), min, max);
256 }
257
258 /**
259 * Create a new random {@code IntegerGene}. It is guaranteed that the value of
260 * the {@code IntegerGene} lies in the interval [min, max].
261 *
262 * @since 3.2
263 *
264 * @param range the integer range to use
265 * @return a new random {@code IntegerGene}
266 * @throws NullPointerException if the given {@code range} is {@code null}.
267 */
268 public static IntegerGene of(final IntRange range) {
269 return of(nextInt(random(), range.min(), range.max()), range);
270 }
271
272 static ISeq<IntegerGene> seq(
273 final int min,
274 final int max,
275 final IntRange lengthRange
276 ) {
277 final Random r = random();
278 return MSeq.<IntegerGene>ofLength(Randoms.nextInt(lengthRange, r))
279 .fill(() -> new IntegerGene(nextInt(r, min, max), min, max))
280 .toISeq();
281 }
282
283 /**
284 * Returns a pseudo-random, uniformly distributed int value between min and
285 * max (min and max included).
286 *
287 * @param random the random engine to use for calculating the random int
288 * value
289 * @param min lower bound for generated integer
290 * @param max upper bound for generated integer
291 * @return a random integer greater than or equal to {@code min} and
292 * less than or equal to {@code max}
293 * @throws IllegalArgumentException if {@code min > max}
294 * @throws NullPointerException if the given {@code random}
295 * engine is {@code null}.
296 */
297 static int nextInt(
298 final Random random,
299 final int min, final int max
300 ) {
301 if (min > max) {
302 throw new IllegalArgumentException(format(
303 "Min >= max: %d >= %d", min, max
304 ));
305 }
306
307 final int diff = max - min + 1;
308 int result = 0;
309
310 if (diff <= 0) {
311 do {
312 result = random.nextInt();
313 } while (result < min || result > max);
314 } else {
315 result = random.nextInt(diff) + min;
316 }
317
318 return result;
319 }
320
321
322 /* *************************************************************************
323 * Java object serialization
324 * ************************************************************************/
325
326 private Object writeReplace() {
327 return new Serial(Serial.INTEGER_GENE, this);
328 }
329
330 private void readObject(final ObjectInputStream stream)
331 throws InvalidObjectException
332 {
333 throw new InvalidObjectException("Serialization proxy required.");
334 }
335
336 void write(final DataOutput out) throws IOException {
337 writeInt(_allele, out);
338 writeInt(_min, out);
339 writeInt(_max, out);
340 }
341
342 static IntegerGene read(final DataInput in) throws IOException {
343 return of(readInt(in), readInt(in), readInt(in));
344 }
345
346 }
|