L128X128Mix.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 128-bit Xor-based
  29.  * generator. It is named as {@code "L128X128MixRandom"} 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 384 bits and the period is 2<sup>128</sup> (2<sup>128</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 L128X128Mix extends AbstractL128 implements SplittableUniformRandomProvider {
  59.     /** Size of the seed vector. */
  60.     private static final int SEED_SIZE = 6;
  61.     /** Size of the XBG state vector. */
  62.     private static final int XBG_STATE_SIZE = 2;
  63.     /** Low half of 128-bit LCG multiplier. */
  64.     private static final long ML = LXMSupport.M128L;

  65.     /** State 0 of the XBG. */
  66.     private long x0;
  67.     /** State 1 of the XBG. */
  68.     private long x1;

  69.     /**
  70.      * Creates a new instance.
  71.      *
  72.      * @param seed Initial seed.
  73.      * If the length is larger than 6, only the first 6 elements will
  74.      * be used; if smaller, the remaining elements will be automatically
  75.      * set. A seed containing all zeros in the last four elements
  76.      * will create a non-functional XBG sub-generator and a low
  77.      * quality output with a period of 2<sup>128</sup>.
  78.      *
  79.      * <p>The 1st and 2nd elements are used to set the LCG increment; the least significant bit
  80.      * is set to odd to ensure a full period LCG. The 3rd and 4th elements are used
  81.      * to set the LCG state.</p>
  82.      */
  83.     public L128X128Mix(long[] seed) {
  84.         super(seed = extendSeed(seed, SEED_SIZE));
  85.         x0 = seed[4];
  86.         x1 = seed[5];
  87.     }

  88.     /**
  89.      * Creates a new instance using a 6 element seed.
  90.      * A seed containing all zeros in the last four elements
  91.      * will create a non-functional XBG sub-generator and a low
  92.      * quality output with a period of 2<sup>128</sup>.
  93.      *
  94.      * <p>The 1st and 2nd elements are used to set the LCG increment; the least significant bit
  95.      * is set to odd to ensure a full period LCG. The 3rd and 4th elements are used
  96.      * to set the LCG state.</p>
  97.      *
  98.      * @param seed0 Initial seed element 0.
  99.      * @param seed1 Initial seed element 1.
  100.      * @param seed2 Initial seed element 2.
  101.      * @param seed3 Initial seed element 3.
  102.      * @param seed4 Initial seed element 4.
  103.      * @param seed5 Initial seed element 5.
  104.      */
  105.     public L128X128Mix(long seed0, long seed1, long seed2, long seed3,
  106.                        long seed4, long seed5) {
  107.         super(seed0, seed1, seed2, seed3);
  108.         x0 = seed4;
  109.         x1 = seed5;
  110.     }

  111.     /**
  112.      * Creates a copy instance.
  113.      *
  114.      * @param source Source to copy.
  115.      */
  116.     protected L128X128Mix(L128X128Mix source) {
  117.         super(source);
  118.         x0 = source.x0;
  119.         x1 = source.x1;
  120.     }

  121.     /** {@inheritDoc} */
  122.     @Override
  123.     protected byte[] getStateInternal() {
  124.         return composeStateInternal(NumberFactory.makeByteArray(
  125.                                         new long[] {x0, x1}),
  126.                                     super.getStateInternal());
  127.     }

  128.     /** {@inheritDoc} */
  129.     @Override
  130.     protected void setStateInternal(byte[] s) {
  131.         final byte[][] c = splitStateInternal(s, XBG_STATE_SIZE * Long.BYTES);
  132.         final long[] tmp = NumberFactory.makeLongArray(c[0]);
  133.         x0 = tmp[0];
  134.         x1 = tmp[1];
  135.         super.setStateInternal(c[1]);
  136.     }

  137.     /** {@inheritDoc} */
  138.     @Override
  139.     public long next() {
  140.         // LXM generate.
  141.         // Old state is used for the output allowing parallel pipelining
  142.         // on processors that support multiple concurrent instructions.

  143.         final long s0 = x0;
  144.         final long sh = lsh;

  145.         // Mix
  146.         final long z = LXMSupport.lea64(sh + s0);

  147.         // LCG update
  148.         // The LCG is, in effect, "s = m * s + a" where m = ((1LL << 64) + ML)
  149.         final long sl = lsl;
  150.         final long al = lal;
  151.         final long u = ML * sl;
  152.         // High half
  153.         lsh = ML * sh + LXMSupport.unsignedMultiplyHigh(ML, sl) + sl + lah +
  154.               // Carry propagation
  155.               LXMSupport.unsignedAddHigh(u, al);
  156.         // Low half
  157.         lsl = u + al;

  158.         // XBG update
  159.         long s1 = x1;

  160.         s1 ^= s0;
  161.         x0 = Long.rotateLeft(s0, 24) ^ s1 ^ (s1 << 16); // a, b
  162.         x1 = Long.rotateLeft(s1, 37); // c

  163.         return z;
  164.     }

  165.     /**
  166.      * {@inheritDoc}
  167.      *
  168.      * <p>The jump size is the equivalent of moving the state <em>backwards</em> by
  169.      * (2<sup>128</sup> - 1) positions. It can provide up to 2<sup>128</sup>
  170.      * non-overlapping subsequences.
  171.      */
  172.     @Override
  173.     public UniformRandomProvider jump() {
  174.         return super.jump();
  175.     }

  176.     /**
  177.      * {@inheritDoc}
  178.      *
  179.      * <p>The jump size is the equivalent of moving the state <em>backwards</em> by
  180.      * 2<sup>64</sup> (2<sup>128</sup> - 1) positions. It can provide up to
  181.      * 2<sup>64</sup> non-overlapping subsequences of length 2<sup>64</sup>
  182.      * (2<sup>128</sup> - 1); each subsequence can provide up to 2<sup>64</sup>
  183.      * non-overlapping subsequences of length (2<sup>128</sup> - 1) using the
  184.      * {@link #jump()} method.
  185.      */
  186.     @Override
  187.     public JumpableUniformRandomProvider longJump() {
  188.         return super.longJump();
  189.     }

  190.     /** {@inheritDoc} */
  191.     @Override
  192.     AbstractL128 copy() {
  193.         // This exists to ensure the jump function performed in the super class returns
  194.         // the correct class type. It should not be public.
  195.         return new L128X128Mix(this);
  196.     }

  197.     /** {@inheritDoc} */
  198.     @Override
  199.     public SplittableUniformRandomProvider split(UniformRandomProvider source) {
  200.         return create(source.nextLong(), source);
  201.     }

  202.     /** {@inheritDoc} */
  203.     @Override
  204.     public Stream<SplittableUniformRandomProvider> splits(long streamSize, SplittableUniformRandomProvider source) {
  205.         return RandomStreams.generateWithSeed(streamSize, source, L128X128Mix::create);
  206.     }

  207.     /**
  208.      * Create a new instance using the given {@code seed} and {@code source} of randomness
  209.      * to initialise the instance.
  210.      *
  211.      * @param seed Seed used to initialise the instance.
  212.      * @param source Source of randomness used to initialise the instance.
  213.      * @return A new instance.
  214.      */
  215.     private static SplittableUniformRandomProvider create(long seed, UniformRandomProvider source) {
  216.         // LCG state. The addition lower-half uses the input seed.
  217.         // The LCG addition parameter is set to odd so left-shift the seed.
  218.         final long s0 = source.nextLong();
  219.         final long s1 = seed << 1;
  220.         final long s2 = source.nextLong();
  221.         final long s3 = source.nextLong();
  222.         // XBG state must not be all zero
  223.         long x0 = source.nextLong();
  224.         long x1 = source.nextLong();
  225.         if ((x0 | x1) == 0) {
  226.             // SplitMix style seed ensures at least one non-zero value
  227.             final long z = s3;
  228.             x0 = LXMSupport.lea64(z);
  229.             x1 = LXMSupport.lea64(z + LXMSupport.GOLDEN_RATIO_64);
  230.         }
  231.         return new L128X128Mix(s0, s1, s2, s3, x0, x1);
  232.     }
  233. }