LongGene.java
001 /*
002  * Java Genetic Algorithm Library (jenetics-5.2.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.readLong;
025 import static io.jenetics.internal.util.SerialIO.writeLong;
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.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.2
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     @Deprecated
092     @Override
093     public Long getAllele() {
094         return _value;
095     }
096 
097     @Deprecated
098     @Override
099     public Long getMin() {
100         return _min;
101     }
102 
103     @Deprecated
104     @Override
105     public Long getMax() {
106         return _max;
107     }
108 
109     /**
110      * Return the range of {@code this} gene.
111      *
112      @since 4.4
113      *
114      @return the range of {@code this} gene
115      */
116     public LongRange range() {
117         return LongRange.of(_min, _max);
118     }
119 
120     @Override
121     public byte byteValue() {
122         return (byte)_value;
123     }
124 
125     @Override
126     public short shortValue() {
127         return (short)_value;
128     }
129 
130     @Override
131     public int intValue() {
132         return (int)_value;
133     }
134 
135     @Override
136     public long longValue() {
137         return _value;
138     }
139 
140     @Override
141     public float floatValue() {
142         return (float)_value;
143     }
144 
145     @Override
146     public double doubleValue() {
147         return _value;
148     }
149 
150     @Override
151     public boolean isValid() {
152         return _value >= _min && _value <= _max;
153     }
154 
155     @Override
156     public int compareTo(final LongGene other) {
157         return Long.compare(_value, other._value);
158     }
159 
160     @Override
161     public LongGene mean(final LongGene that) {
162         return LongGene.of(_value + (that._value - _value)/2, _min, _max);
163     }
164 
165     /**
166      * Create a new gene from the given {@code value} and the gene context.
167      *
168      @since 5.0
169      @param value the value of the new gene.
170      @return a new gene with the given value.
171      */
172     public LongGene newInstance(final long value) {
173         return LongGene.of(value, _min, _max);
174     }
175 
176     @Override
177     public LongGene newInstance(final Long number) {
178         return LongGene.of(number, _min, _max);
179     }
180 
181     @Override
182     public LongGene newInstance(final Number number) {
183         return LongGene.of(number.longValue(), _min, _max);
184     }
185 
186     @Override
187     public LongGene newInstance() {
188         return LongGene.of(nextLong(random(), _min, _max), _min, _max);
189     }
190 
191     @Override
192     public int hashCode() {
193         return hash(_value, hash(_min, hash(_max, hash(getClass()))));
194     }
195 
196     @Override
197     public boolean equals(final Object obj) {
198         return obj == this ||
199             obj instanceof LongGene &&
200             ((LongGene)obj)._value == _value &&
201             ((LongGene)obj)._min == _min &&
202             ((LongGene)obj)._max == _max;
203     }
204 
205     @Override
206     public String toString() {
207         return String.format("[%s]", _value);
208     }
209 
210     /* *************************************************************************
211      * Static factory methods.
212      * ************************************************************************/
213 
214     /**
215      * Create a new random {@code LongGene} 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 LongGene#isValid()} returns {@code false}.
219      *
220      @param value 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 LongGene} with the given parameters.
224      */
225     public static LongGene of(final long value, final long min, final long max) {
226         return new LongGene(value, min, max);
227     }
228 
229     /**
230      * Create a new random {@code LongGene} 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 LongGene#isValid()} returns {@code false}.
234      *
235      @since 3.2
236      *
237      @param value the value of the gene.
238      @param range the long range to use
239      @return a new random {@code LongGene}
240      @throws NullPointerException if the given {@code range} is {@code null}.
241      */
242     public static LongGene of(final long value, final LongRange range) {
243         return LongGene.of(value, range.min(), range.max());
244     }
245 
246     /**
247      * Create a new random {@code LongGene}. It is guaranteed that the value of
248      * the {@code LongGene} 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 {@code LongGene} with the given parameters.
253      */
254     public static LongGene of(final long min, final long max) {
255         return of(nextLong(random(), min, max), min, max);
256     }
257 
258     /**
259      * Create a new random {@code LongGene}. It is guaranteed that the value of
260      * the {@code LongGene} lies in the interval [min, max].
261      *
262      @since 3.2
263      *
264      @param range the long range to use
265      @return a new random {@code LongGene}
266      @throws NullPointerException if the given {@code range} is {@code null}.
267      */
268     public static LongGene of(final LongRange range) {
269         return of(nextLong(random(), range.min(), range.max()), range);
270     }
271 
272     static ISeq<LongGene> seq(
273         final long min,
274         final long max,
275         final IntRange lengthRange
276     ) {
277         final Random r = random();
278         return MSeq.<LongGene>ofLength(Randoms.nextInt(lengthRange, r))
279             .fill(() -> LongGene.of(nextLong(r, min, max), min, max))
280             .toISeq();
281     }
282 
283     /**
284      * Returns a pseudo-random, uniformly distributed int value between min
285      * and max (min and max included).
286      *
287      @param random the random engine to use for calculating the random
288      *        long value
289      @param min lower bound for generated long integer
290      @param max upper bound for generated long integer
291      @return a random long integer greater than or equal to {@code min}
292      *         and 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 long nextLong(
298         final Random random,
299         final long min, final long max
300     ) {
301         if (min > max) {
302             throw new IllegalArgumentException(format(
303                 "min >= max: %d >= %d.", min, max
304             ));
305         }
306 
307         final long diff = (max - min1;
308         long result = 0;
309 
310         if (diff <= 0) {
311             do {
312                 result = random.nextLong();
313             while (result < min || result > max);
314         else if (diff < Integer.MAX_VALUE) {
315             result = random.nextInt((int)diff+ min;
316         else {
317             result = nextLong(random, diff+ min;
318         }
319 
320         return result;
321     }
322 
323     /**
324      * Returns a pseudo-random, uniformly distributed int value between 0
325      * (inclusive) and the specified value (exclusive), drawn from the given
326      * random number generator's sequence.
327      *
328      @param random the random engine used for creating the random number.
329      @param n the bound on the random number to be returned. Must be
330      *        positive.
331      @return the next pseudo-random, uniformly distributed int value
332      *         between 0 (inclusive) and n (exclusive) from the given random
333      *         number generator's sequence
334      @throws IllegalArgumentException if n is smaller than 1.
335      @throws NullPointerException if the given {@code random}
336      *         engine is {@code null}.
337      */
338     static long nextLong(final Random random, final long n) {
339         if (n <= 0) {
340             throw new IllegalArgumentException(format(
341                 "n is smaller than one: %d", n
342             ));
343         }
344 
345         long bits;
346         long result;
347         do {
348             bits = random.nextLong() 0x7fffffffffffffffL;
349             result = bits%n;
350         while (bits - result + (n - 10);
351 
352         return result;
353     }
354 
355 
356     /* *************************************************************************
357      *  Java object serialization
358      * ************************************************************************/
359 
360     private Object writeReplace() {
361         return new Serial(Serial.LONG_GENE, this);
362     }
363 
364     private void readObject(final ObjectInputStream stream)
365         throws InvalidObjectException
366     {
367         throw new InvalidObjectException("Serialization proxy required.");
368     }
369 
370     void write(final DataOutput outthrows IOException {
371         writeLong(_value, out);
372         writeLong(_min, out);
373         writeLong(_max, out);
374     }
375 
376     static LongGene read(final DataInput inthrows IOException {
377         return of(readLong(in), readLong(in), readLong(in));
378     }
379 
380 }