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