L32X64Mix.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.source32;

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

  25. /**
  26.  * A 32-bit all purpose generator.
  27.  *
  28.  * <p>This is a member of the LXM family of generators: L=Linear congruential generator;
  29.  * X=Xor based generator; and M=Mix. This member uses a 32-bit LCG and 64-bit Xor-based
  30.  * generator. It is named as {@code "L32X64MixRandom"} in the {@code java.util.random}
  31.  * package introduced in JDK 17; the LXM family is described in further detail in:
  32.  *
  33.  * <blockquote>Steele and Vigna (2021) LXM: better splittable pseudorandom number generators
  34.  * (and almost as fast). Proceedings of the ACM on Programming Languages, Volume 5,
  35.  * Article 148, pp 1–31.</blockquote>
  36.  *
  37.  * <p>Memory footprint is 128 bits and the period is 2<sup>32</sup> (2<sup>64</sup> - 1).
  38.  *
  39.  * <p>This generator implements {@link 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 31-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 final class L32X64Mix extends IntProvider implements LongJumpableUniformRandomProvider,
  59.     SplittableUniformRandomProvider {
  60.     // Implementation note:
  61.     // This does not extend AbstractXoRoShiRo64 as the XBG function is re-implemented
  62.     // inline to allow parallel pipelining. Inheritance would provide only the XBG state.

  63.     /** LCG multiplier. */
  64.     private static final int M = LXMSupport.M32;
  65.     /** Size of the state vector. */
  66.     private static final int SEED_SIZE = 4;

  67.     /** Per-instance LCG additive parameter (must be odd).
  68.      * Cannot be final to support RestorableUniformRandomProvider. */
  69.     private int la;
  70.     /** State of the LCG generator. */
  71.     private int ls;
  72.     /** State 0 of the XBG generator. */
  73.     private int x0;
  74.     /** State 1 of the XBG generator. */
  75.     private int x1;

  76.     /**
  77.      * Creates a new instance.
  78.      *
  79.      * @param seed Initial seed.
  80.      * If the length is larger than 4, only the first 4 elements will
  81.      * be used; if smaller, the remaining elements will be automatically
  82.      * set. A seed containing all zeros in the last two elements
  83.      * will create a non-functional XBG sub-generator and a low
  84.      * quality output with a period of 2<sup>32</sup>.
  85.      *
  86.      * <p>The 1st element is used to set the LCG increment; the least significant bit
  87.      * is set to odd to ensure a full period LCG. The 2nd element is used
  88.      * to set the LCG state.</p>
  89.      */
  90.     public L32X64Mix(int[] seed) {
  91.         setState(extendSeed(seed, SEED_SIZE));
  92.     }

  93.     /**
  94.      * Creates a new instance using a 4 element seed.
  95.      * A seed containing all zeros in the last two elements
  96.      * will create a non-functional XBG sub-generator and a low
  97.      * quality output with a period of 2<sup>32</sup>.
  98.      *
  99.      * <p>The 1st element is used to set the LCG increment; the least significant bit
  100.      * is set to odd to ensure a full period LCG. The 2nd element is used
  101.      * to set the LCG state.</p>
  102.      *
  103.      * @param seed0 Initial seed element 0.
  104.      * @param seed1 Initial seed element 1.
  105.      * @param seed2 Initial seed element 2.
  106.      * @param seed3 Initial seed element 3.
  107.      */
  108.     public L32X64Mix(int seed0, int seed1, int seed2, int seed3) {
  109.         // Additive parameter must be odd
  110.         la = seed0 | 1;
  111.         ls = seed1;
  112.         x0 = seed2;
  113.         x1 = seed3;
  114.     }

  115.     /**
  116.      * Creates a copy instance.
  117.      *
  118.      * @param source Source to copy.
  119.      */
  120.     private L32X64Mix(L32X64Mix source) {
  121.         super(source);
  122.         la = source.la;
  123.         ls = source.ls;
  124.         x0 = source.x0;
  125.         x1 = source.x1;
  126.     }

  127.     /**
  128.      * Copies the state into the generator state.
  129.      *
  130.      * @param state the new state
  131.      */
  132.     private void setState(int[] state) {
  133.         // Additive parameter must be odd
  134.         la = state[0] | 1;
  135.         ls = state[1];
  136.         x0 = state[2];
  137.         x1 = state[3];
  138.     }

  139.     /** {@inheritDoc} */
  140.     @Override
  141.     protected byte[] getStateInternal() {
  142.         return composeStateInternal(NumberFactory.makeByteArray(new int[] {la, ls, x0, x1}),
  143.                                     super.getStateInternal());
  144.     }

  145.     /** {@inheritDoc} */
  146.     @Override
  147.     protected void setStateInternal(byte[] s) {
  148.         final byte[][] c = splitStateInternal(s, SEED_SIZE * Integer.BYTES);
  149.         setState(NumberFactory.makeIntArray(c[0]));
  150.         super.setStateInternal(c[1]);
  151.     }

  152.     /** {@inheritDoc} */
  153.     @Override
  154.     public int next() {
  155.         // LXM generate.
  156.         // Old state is used for the output allowing parallel pipelining
  157.         // on processors that support multiple concurrent instructions.

  158.         final int s0 = x0;
  159.         final int s = ls;

  160.         // Mix
  161.         final int z = LXMSupport.lea32(s + s0);

  162.         // LCG update
  163.         ls = M * s + la;

  164.         // XBG update
  165.         int s1 = x1;

  166.         s1 ^= s0;
  167.         x0 = Integer.rotateLeft(s0, 26) ^ s1 ^ (s1 << 9); // a, b
  168.         x1 = Integer.rotateLeft(s1, 13); // c

  169.         return z;
  170.     }

  171.     /**
  172.      * Creates a copy of the UniformRandomProvider and then <em>retreats</em> the state of the
  173.      * current instance. The copy is returned.
  174.      *
  175.      * <p>The jump is performed by advancing the state of the LCG sub-generator by 1 cycle.
  176.      * The XBG state is unchanged. The jump size is the equivalent of moving the state
  177.      * <em>backwards</em> by (2<sup>64</sup> - 1) positions. It can provide up to 2<sup>32</sup>
  178.      * non-overlapping subsequences.</p>
  179.      */
  180.     @Override
  181.     public UniformRandomProvider jump() {
  182.         final UniformRandomProvider copy = new L32X64Mix(this);
  183.         // Advance the LCG 1 step
  184.         ls = M * ls + la;
  185.         resetCachedState();
  186.         return copy;
  187.     }

  188.     /**
  189.      * Creates a copy of the UniformRandomProvider and then <em>retreats</em> the state of the
  190.      * current instance. The copy is returned.
  191.      *
  192.      * <p>The jump is performed by advancing the state of the LCG sub-generator by
  193.      * 2<sup>16</sup> cycles. The XBG state is unchanged. The jump size is the equivalent
  194.      * of moving the state <em>backwards</em> by 2<sup>16</sup> (2<sup>64</sup> - 1)
  195.      * positions. It can provide up to 2<sup>16</sup> non-overlapping subsequences of
  196.      * length 2<sup>16</sup> (2<sup>64</sup> - 1); each subsequence can provide up to
  197.      * 2<sup>16</sup> non-overlapping subsequences of length (2<sup>64</sup> - 1) using
  198.      * the {@link #jump()} method.</p>
  199.      */
  200.     @Override
  201.     public JumpableUniformRandomProvider longJump() {
  202.         final JumpableUniformRandomProvider copy = new L32X64Mix(this);
  203.         // Advance the LCG 2^16 steps
  204.         ls = LXMSupport.M32P * ls + LXMSupport.C32P * la;
  205.         resetCachedState();
  206.         return copy;
  207.     }

  208.     /** {@inheritDoc} */
  209.     @Override
  210.     public SplittableUniformRandomProvider split(UniformRandomProvider source) {
  211.         // The upper half of the long seed is discarded so use nextInt
  212.         return create(source.nextInt(), source);
  213.     }

  214.     /** {@inheritDoc} */
  215.     @Override
  216.     public Stream<SplittableUniformRandomProvider> splits(long streamSize, SplittableUniformRandomProvider source) {
  217.         return RandomStreams.generateWithSeed(streamSize, source, L32X64Mix::create);
  218.     }

  219.     /**
  220.      * Create a new instance using the given {@code seed} and {@code source} of randomness
  221.      * to initialise the instance.
  222.      *
  223.      * @param seed Seed used to initialise the instance.
  224.      * @param source Source of randomness used to initialise the instance.
  225.      * @return A new instance.
  226.      */
  227.     private static SplittableUniformRandomProvider create(long seed, UniformRandomProvider source) {
  228.         // LCG state. The addition uses the input seed.
  229.         // The LCG addition parameter is set to odd so left-shift the seed.
  230.         final int s0 = (int) seed << 1;
  231.         final int s1 = source.nextInt();
  232.         // XBG state must not be all zero
  233.         int x0 = source.nextInt();
  234.         int x1 = source.nextInt();
  235.         if ((x0 | x1) == 0) {
  236.             // SplitMix style seed ensures at least one non-zero value
  237.             x0 = LXMSupport.lea32(s1);
  238.             x1 = LXMSupport.lea32(s1 + LXMSupport.GOLDEN_RATIO_32);
  239.         }
  240.         return new L32X64Mix(s0, s1, x0, x1);
  241.     }
  242. }