LongGene.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 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 6.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 _allele;
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 allele 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 allele, final long min, final long max) {
086         _allele = allele;
087         _min = min;
088         _max = max;
089     }
090 
091     @Override
092     public Long allele() {
093         return _allele;
094     }
095 
096     @Override
097     public Long min() {
098         return _min;
099     }
100 
101     @Override
102     public Long max() {
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_allele;
120     }
121 
122     @Override
123     public short shortValue() {
124         return (short_allele;
125     }
126 
127     @Override
128     public int intValue() {
129         return (int_allele;
130     }
131 
132     @Override
133     public long longValue() {
134         return _allele;
135     }
136 
137     @Override
138     public float floatValue() {
139         return (float_allele;
140     }
141 
142     @Override
143     public double doubleValue() {
144         return _allele;
145     }
146 
147     @Override
148     public boolean isValid() {
149         return _allele >= _min && _allele <= _max;
150     }
151 
152     @Override
153     public int compareTo(final LongGene other) {
154         return Long.compare(_allele, other._allele);
155     }
156 
157     @Override
158     public LongGene mean(final LongGene that) {
159         return LongGene.of(_allele + (that._allele - _allele)/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 allele the value of the new gene.
167      @return a new gene with the given value.
168      */
169     public LongGene newInstance(final long allele) {
170         return LongGene.of(allele, _min, _max);
171     }
172 
173     @Override
174     public LongGene newInstance(final Long allele) {
175         return LongGene.of(allele, _min, _max);
176     }
177 
178     @Override
179     public LongGene newInstance(final Number allele) {
180         return LongGene.of(allele.longValue(), _min, _max);
181     }
182 
183     @Override
184     public LongGene newInstance() {
185         return LongGene.of(nextLong(random(), _min, _max), _min, _max);
186     }
187 
188     @Override
189     public int hashCode() {
190         return hash(_allele, 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)._allele == _allele &&
198             ((LongGene)obj)._min == _min &&
199             ((LongGene)obj)._max == _max;
200     }
201 
202     @Override
203     public String toString() {
204         return String.format("[%s]", _allele);
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 allele 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 allele, final long min, final long max) {
223         return new LongGene(allele, 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 allele 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 allele, final LongRange range) {
240         return LongGene.of(allele, range.min(), range.max());
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(random(), 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(random(), range.min(), range.max()), 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 = random();
275         return MSeq.<LongGene>ofLength(Randoms.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 - min1;
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 - 10);
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 outthrows IOException {
368         writeLong(_allele, out);
369         writeLong(_min, out);
370         writeLong(_max, out);
371     }
372 
373     static LongGene read(final DataInput inthrows IOException {
374         return of(readLong(in), readLong(in), readLong(in));
375     }
376 
377 }