L128X1024Mix.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.rng.core.source64;

  18. import java.util.stream.Stream;
  19. import org.apache.commons.rng.JumpableUniformRandomProvider;
  20. import org.apache.commons.rng.SplittableUniformRandomProvider;
  21. import org.apache.commons.rng.UniformRandomProvider;
  22. import org.apache.commons.rng.core.util.NumberFactory;
  23. import org.apache.commons.rng.core.util.RandomStreams;

  24. /**
  25.  * A 64-bit all purpose generator.
  26.  *
  27.  * <p>This is a member of the LXM family of generators: L=Linear congruential generator;
  28.  * X=Xor based generator; and M=Mix. This member uses a 128-bit LCG and 1024-bit Xor-based
  29.  * generator. It is named as {@code "L128X1024MixRandom"} in the {@code java.util.random}
  30.  * package introduced in JDK 17; the LXM family is described in further detail in:
  31.  *
  32.  * <blockquote>Steele and Vigna (2021) LXM: better splittable pseudorandom number generators
  33.  * (and almost as fast). Proceedings of the ACM on Programming Languages, Volume 5,
  34.  * Article 148, pp 1–31.</blockquote>
  35.  *
  36.  * <p>Memory footprint is 1312 bits and the period is 2<sup>128</sup> (2<sup>1024</sup> - 1).
  37.  *
  38.  * <p>This generator implements
  39.  * {@link org.apache.commons.rng.LongJumpableUniformRandomProvider LongJumpableUniformRandomProvider}.
  40.  * In addition instances created with a different additive parameter for the LCG are robust
  41.  * against accidental correlation in a multi-threaded setting. The additive parameters must be
  42.  * different in the most significant 127-bits.
  43.  *
  44.  * <p>This generator implements
  45.  * {@link org.apache.commons.rng.SplittableUniformRandomProvider SplittableUniformRandomProvider}.
  46.  * The stream of generators created using the {@code splits} methods support parallelisation
  47.  * and are robust against accidental correlation by using unique values for the additive parameter
  48.  * for each instance in the same stream. The primitive streaming methods support parallelisation
  49.  * but with no assurances of accidental correlation; each thread uses a new instance with a
  50.  * randomly initialised state.
  51.  *
  52.  * @see <a href="https://doi.org/10.1145/3485525">Steele &amp; Vigna (2021) Proc. ACM Programming
  53.  *      Languages 5, 1-31</a>
  54.  * @see <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/random/package-summary.html">
  55.  *      JDK 17 java.util.random javadoc</a>
  56.  * @since 1.5
  57.  */
  58. public class L128X1024Mix extends AbstractL128 implements SplittableUniformRandomProvider {
  59.     /** Size of the seed vector. */
  60.     private static final int SEED_SIZE = 20;
  61.     /** Size of the XBG state vector. */
  62.     private static final int XBG_STATE_SIZE = 16;
  63.     /** Size of the LCG state vector. */
  64.     private static final int LCG_STATE_SIZE = SEED_SIZE - XBG_STATE_SIZE;
  65.     /** Low half of 128-bit LCG multiplier. */
  66.     private static final long ML = LXMSupport.M128L;

  67.     /** State of the XBG. */
  68.     private final long[] x = new long[XBG_STATE_SIZE];
  69.     /** Index in "state" array. */
  70.     private int index;

  71.     /**
  72.      * Creates a new instance.
  73.      *
  74.      * @param seed Initial seed.
  75.      * If the length is larger than 20, only the first 20 elements will
  76.      * be used; if smaller, the remaining elements will be automatically
  77.      * set. A seed containing all zeros in the last 16 elements
  78.      * will create a non-functional XBG sub-generator and a low
  79.      * quality output with a period of 2<sup>128</sup>.
  80.      *
  81.      * <p>The 1st and 2nd elements are used to set the LCG increment; the least significant bit
  82.      * is set to odd to ensure a full period LCG. The 3rd and 4th elements are used
  83.      * to set the LCG state.</p>
  84.      */
  85.     public L128X1024Mix(long[] seed) {
  86.         super(seed = extendSeed(seed, SEED_SIZE));
  87.         System.arraycopy(seed, SEED_SIZE - XBG_STATE_SIZE, x, 0, XBG_STATE_SIZE);
  88.         // Initialising to 15 ensures that (index + 1) % 16 == 0 and the
  89.         // first state picked from the XBG generator is state[0].
  90.         index = XBG_STATE_SIZE - 1;
  91.     }

  92.     /**
  93.      * Creates a copy instance.
  94.      *
  95.      * @param source Source to copy.
  96.      */
  97.     protected L128X1024Mix(L128X1024Mix source) {
  98.         super(source);
  99.         System.arraycopy(source.x, 0, x, 0, XBG_STATE_SIZE);
  100.         index = source.index;
  101.     }

  102.     /** {@inheritDoc} */
  103.     @Override
  104.     protected byte[] getStateInternal() {
  105.         final long[] s = new long[XBG_STATE_SIZE + 1];
  106.         System.arraycopy(x, 0, s, 0, XBG_STATE_SIZE);
  107.         s[XBG_STATE_SIZE] = index;
  108.         return composeStateInternal(NumberFactory.makeByteArray(s),
  109.                                     super.getStateInternal());
  110.     }

  111.     /** {@inheritDoc} */
  112.     @Override
  113.     protected void setStateInternal(byte[] s) {
  114.         final byte[][] c = splitStateInternal(s, (XBG_STATE_SIZE + 1) * Long.BYTES);

  115.         final long[] tmp = NumberFactory.makeLongArray(c[0]);
  116.         System.arraycopy(tmp, 0, x, 0, XBG_STATE_SIZE);
  117.         index = (int) tmp[XBG_STATE_SIZE];

  118.         super.setStateInternal(c[1]);
  119.     }

  120.     /** {@inheritDoc} */
  121.     @Override
  122.     public long next() {
  123.         // LXM generate.
  124.         // Old state is used for the output allowing parallel pipelining
  125.         // on processors that support multiple concurrent instructions.

  126.         final int q = index;
  127.         index = (q + 1) & 15;
  128.         final long s0 = x[index];
  129.         long s15 = x[q];
  130.         final long sh = lsh;

  131.         // Mix
  132.         final long z = LXMSupport.lea64(sh + s0);

  133.         // LCG update
  134.         // The LCG is, in effect, "s = m * s + a" where m = ((1LL << 64) + ML)
  135.         final long sl = lsl;
  136.         final long al = lal;
  137.         final long u = ML * sl;
  138.         // High half
  139.         lsh = ML * sh + LXMSupport.unsignedMultiplyHigh(ML, sl) + sl + lah +
  140.               // Carry propagation
  141.               LXMSupport.unsignedAddHigh(u, al);
  142.         // Low half
  143.         lsl = u + al;

  144.         // XBG update
  145.         s15 ^= s0;
  146.         x[q] = Long.rotateLeft(s0, 25) ^ s15 ^ (s15 << 27);
  147.         x[index] = Long.rotateLeft(s15, 36);

  148.         return z;
  149.     }

  150.     /**
  151.      * {@inheritDoc}
  152.      *
  153.      * <p>The jump size is the equivalent of moving the state <em>backwards</em> by
  154.      * (2<sup>1024</sup> - 1) positions. It can provide up to 2<sup>128</sup>
  155.      * non-overlapping subsequences.
  156.      */
  157.     @Override
  158.     public UniformRandomProvider jump() {
  159.         return super.jump();
  160.     }

  161.     /**
  162.      * {@inheritDoc}
  163.      *
  164.      * <p>The jump size is the equivalent of moving the state <em>backwards</em> by
  165.      * 2<sup>64</sup> (2<sup>1024</sup> - 1) positions. It can provide up to
  166.      * 2<sup>64</sup> non-overlapping subsequences of length 2<sup>64</sup>
  167.      * (2<sup>1024</sup> - 1); each subsequence can provide up to 2<sup>64</sup>
  168.      * non-overlapping subsequences of length (2<sup>1024</sup> - 1) using the
  169.      * {@link #jump()} method.
  170.      */
  171.     @Override
  172.     public JumpableUniformRandomProvider longJump() {
  173.         return super.longJump();
  174.     }

  175.     /** {@inheritDoc} */
  176.     @Override
  177.     AbstractL128 copy() {
  178.         // This exists to ensure the jump function performed in the super class returns
  179.         // the correct class type. It should not be public.
  180.         return new L128X1024Mix(this);
  181.     }

  182.     /** {@inheritDoc} */
  183.     @Override
  184.     public SplittableUniformRandomProvider split(UniformRandomProvider source) {
  185.         return create(source.nextLong(), source);
  186.     }

  187.     /** {@inheritDoc} */
  188.     @Override
  189.     public Stream<SplittableUniformRandomProvider> splits(long streamSize, SplittableUniformRandomProvider source) {
  190.         return RandomStreams.generateWithSeed(streamSize, source, L128X1024Mix::create);
  191.     }

  192.     /**
  193.      * Create a new instance using the given {@code seed} and {@code source} of randomness
  194.      * to initialise the instance.
  195.      *
  196.      * @param seed Seed used to initialise the instance.
  197.      * @param source Source of randomness used to initialise the instance.
  198.      * @return A new instance.
  199.      */
  200.     private static SplittableUniformRandomProvider create(long seed, UniformRandomProvider source) {
  201.         final long[] s = new long[SEED_SIZE];
  202.         // LCG state. The addition lower-half uses the input seed.
  203.         // The LCG addition parameter is set to odd so left-shift the seed.
  204.         s[0] = source.nextLong();
  205.         s[1] = seed << 1;
  206.         s[2] = source.nextLong();
  207.         s[3] = source.nextLong();
  208.         // XBG state must not be all zero
  209.         long x = 0;
  210.         for (int i = LCG_STATE_SIZE; i < s.length; i++) {
  211.             s[i] = source.nextLong();
  212.             x |= s[i];
  213.         }
  214.         if (x == 0) {
  215.             // SplitMix style seed ensures at least one non-zero value
  216.             x = s[LCG_STATE_SIZE - 1];
  217.             for (int i = LCG_STATE_SIZE; i < s.length; i++) {
  218.                 s[i] = LXMSupport.lea64(x);
  219.                 x += LXMSupport.GOLDEN_RATIO_64;
  220.             }
  221.         }
  222.         return new L128X1024Mix(s);
  223.     }
  224. }