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 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.0
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 return IntegerGene.of(allele.intValue(), _min, _max);
180 }
181
182 @Override
183 public IntegerGene newInstance() {
184 return IntegerGene.of(nextInt(random(), _min, _max), _min, _max);
185 }
186
187 @Override
188 public int hashCode() {
189 return hash(_allele, hash(_min, hash(_max)));
190 }
191
192 @Override
193 public boolean equals(final Object obj) {
194 return obj == this ||
195 obj instanceof IntegerGene &&
196 ((IntegerGene)obj)._allele == _allele &&
197 ((IntegerGene)obj)._min == _min &&
198 ((IntegerGene)obj)._max == _max;
199 }
200
201 @Override
202 public String toString() {
203 return String.format("[%s]", _allele);
204 }
205
206 /* *************************************************************************
207 * Static factory methods.
208 * ************************************************************************/
209
210 /**
211 * Create a new random {@code IntegerGene} with the given value and the
212 * given range. If the {@code value} isn't within the interval [min, max],
213 * no exception is thrown. In this case the method
214 * {@link IntegerGene#isValid()} returns {@code false}.
215 *
216 * @param allele the value of the gene.
217 * @param min the minimal valid value of this gene (inclusively).
218 * @param max the maximal valid value of this gene (inclusively).
219 * @return a new {@code IntegerGene} with the given {@code value}
220 */
221 public static IntegerGene of(final int allele, final int min, final int max) {
222 return new IntegerGene(allele, min, max);
223 }
224
225 /**
226 * Create a new random {@code IntegerGene} with the given value and the
227 * given range. If the {@code value} isn't within the interval [min, max],
228 * no exception is thrown. In this case the method
229 * {@link IntegerGene#isValid()} returns {@code false}.
230 *
231 * @since 3.2
232 *
233 * @param allele the value of the gene.
234 * @param range the integer range to use
235 * @return a new {@code IntegerGene} with the give {@code value}
236 * @throws NullPointerException if the given {@code range} is {@code null}.
237 */
238 public static IntegerGene of(final int allele, final IntRange range) {
239 return IntegerGene.of(allele, range.min(), range.max());
240 }
241
242 /**
243 * Create a new random {@code IntegerGene}. It is guaranteed that the value of
244 * the {@code IntegerGene} lies in the interval [min, max].
245 *
246 * @param min the minimal valid value of this gene (inclusively).
247 * @param max the maximal valid value of this gene (inclusively).
248 * @return a new random {@code IntegerGene}
249 */
250 public static IntegerGene of(final int min, final int max) {
251 return of(nextInt(random(), min, max), min, max);
252 }
253
254 /**
255 * Create a new random {@code IntegerGene}. It is guaranteed that the value of
256 * the {@code IntegerGene} lies in the interval [min, max].
257 *
258 * @since 3.2
259 *
260 * @param range the integer range to use
261 * @return a new random {@code IntegerGene}
262 * @throws NullPointerException if the given {@code range} is {@code null}.
263 */
264 public static IntegerGene of(final IntRange range) {
265 return of(nextInt(random(), range.min(), range.max()), range);
266 }
267
268 static ISeq<IntegerGene> seq(
269 final int min,
270 final int max,
271 final IntRange lengthRange
272 ) {
273 final Random r = random();
274 return MSeq.<IntegerGene>ofLength(Randoms.nextInt(lengthRange, r))
275 .fill(() -> new IntegerGene(nextInt(r, min, max), min, max))
276 .toISeq();
277 }
278
279 /**
280 * Returns a pseudo-random, uniformly distributed int value between min and
281 * max (min and max included).
282 *
283 * @param random the random engine to use for calculating the random int
284 * value
285 * @param min lower bound for generated integer
286 * @param max upper bound for generated integer
287 * @return a random integer greater than or equal to {@code min} and
288 * less than or equal to {@code max}
289 * @throws IllegalArgumentException if {@code min > max}
290 * @throws NullPointerException if the given {@code random}
291 * engine is {@code null}.
292 */
293 static int nextInt(
294 final Random random,
295 final int min, final int max
296 ) {
297 if (min > max) {
298 throw new IllegalArgumentException(format(
299 "Min >= max: %d >= %d", min, max
300 ));
301 }
302
303 final int diff = max - min + 1;
304 int result = 0;
305
306 if (diff <= 0) {
307 do {
308 result = random.nextInt();
309 } while (result < min || result > max);
310 } else {
311 result = random.nextInt(diff) + min;
312 }
313
314 return result;
315 }
316
317
318 /* *************************************************************************
319 * Java object serialization
320 * ************************************************************************/
321
322 private Object writeReplace() {
323 return new Serial(Serial.INTEGER_GENE, this);
324 }
325
326 private void readObject(final ObjectInputStream stream)
327 throws InvalidObjectException
328 {
329 throw new InvalidObjectException("Serialization proxy required.");
330 }
331
332 void write(final DataOutput out) throws IOException {
333 writeInt(_allele, out);
334 writeInt(_min, out);
335 writeInt(_max, out);
336 }
337
338 static IntegerGene read(final DataInput in) throws IOException {
339 return of(readInt(in), readInt(in), readInt(in));
340 }
341
342 }
|