LongGene.java
001 /*
002  * Java Genetic Algorithm Library (jenetics-6.3.0).
003  * Copyright (c) 2007-2021 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.1
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         final long value = allele instanceof Double || allele instanceof Float
181             ? Math.round(allele.doubleValue())
182             : allele.longValue();
183 
184         return LongGene.of(value, _min, _max);
185     }
186 
187     @Override
188     public LongGene newInstance() {
189         return LongGene.of(nextLong(random(), _min, _max), _min, _max);
190     }
191 
192     @Override
193     public int hashCode() {
194         return hash(_allele, hash(_min, hash(_max, hash(getClass()))));
195     }
196 
197     @Override
198     public boolean equals(final Object obj) {
199         return obj == this ||
200             obj instanceof LongGene &&
201             ((LongGene)obj)._allele == _allele &&
202             ((LongGene)obj)._min == _min &&
203             ((LongGene)obj)._max == _max;
204     }
205 
206     @Override
207     public String toString() {
208         return String.format("[%s]", _allele);
209     }
210 
211     /* *************************************************************************
212      * Static factory methods.
213      * ************************************************************************/
214 
215     /**
216      * Create a new random {@code LongGene} with the given value and the
217      * given range. If the {@code value} isn't within the interval [min, max],
218      * no exception is thrown. In this case the method
219      {@link LongGene#isValid()} returns {@code false}.
220      *
221      @param allele the value of the gene.
222      @param min the minimal valid value of this gene (inclusively).
223      @param max the maximal valid value of this gene (inclusively).
224      @return a new {@code LongGene} with the given parameters.
225      */
226     public static LongGene of(final long allele, final long min, final long max) {
227         return new LongGene(allele, min, max);
228     }
229 
230     /**
231      * Create a new random {@code LongGene} with the given value and the
232      * given range. If the {@code value} isn't within the interval [min, max],
233      * no exception is thrown. In this case the method
234      {@link LongGene#isValid()} returns {@code false}.
235      *
236      @since 3.2
237      *
238      @param allele the value of the gene.
239      @param range the long range to use
240      @return a new random {@code LongGene}
241      @throws NullPointerException if the given {@code range} is {@code null}.
242      */
243     public static LongGene of(final long allele, final LongRange range) {
244         return LongGene.of(allele, range.min(), range.max());
245     }
246 
247     /**
248      * Create a new random {@code LongGene}. It is guaranteed that the value of
249      * the {@code LongGene} lies in the interval [min, max].
250      *
251      @param min the minimal valid value of this gene (inclusively).
252      @param max the maximal valid value of this gene (inclusively).
253      @return a new {@code LongGene} with the given parameters.
254      */
255     public static LongGene of(final long min, final long max) {
256         return of(nextLong(random(), min, max), min, max);
257     }
258 
259     /**
260      * Create a new random {@code LongGene}. It is guaranteed that the value of
261      * the {@code LongGene} lies in the interval [min, max].
262      *
263      @since 3.2
264      *
265      @param range the long range to use
266      @return a new random {@code LongGene}
267      @throws NullPointerException if the given {@code range} is {@code null}.
268      */
269     public static LongGene of(final LongRange range) {
270         return of(nextLong(random(), range.min(), range.max()), range);
271     }
272 
273     static ISeq<LongGene> seq(
274         final long min,
275         final long max,
276         final IntRange lengthRange
277     ) {
278         final Random r = random();
279         return MSeq.<LongGene>ofLength(Randoms.nextInt(lengthRange, r))
280             .fill(() -> LongGene.of(nextLong(r, min, max), min, max))
281             .toISeq();
282     }
283 
284     /**
285      * Returns a pseudo-random, uniformly distributed int value between min
286      * and max (min and max included).
287      *
288      @param random the random engine to use for calculating the random
289      *        long value
290      @param min lower bound for generated long integer
291      @param max upper bound for generated long integer
292      @return a random long integer greater than or equal to {@code min}
293      *         and less than or equal to {@code max}
294      @throws IllegalArgumentException if {@code min > max}
295      @throws NullPointerException if the given {@code random}
296      *         engine is {@code null}.
297      */
298     static long nextLong(
299         final Random random,
300         final long min, final long max
301     ) {
302         if (min > max) {
303             throw new IllegalArgumentException(format(
304                 "min >= max: %d >= %d.", min, max
305             ));
306         }
307 
308         final long diff = (max - min1;
309         long result = 0;
310 
311         if (diff <= 0) {
312             do {
313                 result = random.nextLong();
314             while (result < min || result > max);
315         else if (diff < Integer.MAX_VALUE) {
316             result = random.nextInt((int)diff+ min;
317         else {
318             result = nextLong(random, diff+ min;
319         }
320 
321         return result;
322     }
323 
324     /**
325      * Returns a pseudo-random, uniformly distributed int value between 0
326      * (inclusive) and the specified value (exclusive), drawn from the given
327      * random number generator's sequence.
328      *
329      @param random the random engine used for creating the random number.
330      @param n the bound on the random number to be returned. Must be
331      *        positive.
332      @return the next pseudo-random, uniformly distributed int value
333      *         between 0 (inclusive) and n (exclusive) from the given random
334      *         number generator's sequence
335      @throws IllegalArgumentException if n is smaller than 1.
336      @throws NullPointerException if the given {@code random}
337      *         engine is {@code null}.
338      */
339     static long nextLong(final Random random, final long n) {
340         if (n <= 0) {
341             throw new IllegalArgumentException(format(
342                 "n is smaller than one: %d", n
343             ));
344         }
345 
346         long bits;
347         long result;
348         do {
349             bits = random.nextLong() 0x7fffffffffffffffL;
350             result = bits%n;
351         while (bits - result + (n - 10);
352 
353         return result;
354     }
355 
356 
357     /* *************************************************************************
358      *  Java object serialization
359      * ************************************************************************/
360 
361     private Object writeReplace() {
362         return new Serial(Serial.LONG_GENE, this);
363     }
364 
365     private void readObject(final ObjectInputStream stream)
366         throws InvalidObjectException
367     {
368         throw new InvalidObjectException("Serialization proxy required.");
369     }
370 
371     void write(final DataOutput outthrows IOException {
372         writeLong(_allele, out);
373         writeLong(_min, out);
374         writeLong(_max, out);
375     }
376 
377     static LongGene read(final DataInput inthrows IOException {
378         return of(readLong(in), readLong(in), readLong(in));
379     }
380 
381 }