001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  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
018package org.apache.commons.rng.core.source64;
019
020import java.util.stream.Stream;
021import org.apache.commons.rng.SplittableUniformRandomProvider;
022import org.apache.commons.rng.UniformRandomProvider;
023import org.apache.commons.rng.core.util.RandomStreams;
024
025/**
026 * A 64-bit all purpose generator.
027 *
028 * <p>This is a member of the LXM family of generators: L=Linear congruential generator;
029 * X=Xor based generator; and M=Mix. This member uses a 64-bit LCG and 128-bit Xor-based
030 * generator. It is named as {@code "L64X128MixRandom"} in the {@code java.util.random}
031 * package introduced in JDK 17; the LXM family is described in further detail in:
032 *
033 * <blockquote>Steele and Vigna (2021) LXM: better splittable pseudorandom number generators
034 * (and almost as fast). Proceedings of the ACM on Programming Languages, Volume 5,
035 * Article 148, pp 1–31.</blockquote>
036 *
037 * <p>Memory footprint is 256 bits and the period is 2<sup>64</sup> (2<sup>128</sup> - 1).
038 *
039 * <p>This generator implements
040 * {@link org.apache.commons.rng.LongJumpableUniformRandomProvider LongJumpableUniformRandomProvider}.
041 * In addition instances created with a different additive parameter for the LCG are robust
042 * against accidental correlation in a multi-threaded setting. The additive parameters must be
043 * different in the most significant 63-bits.
044 *
045 * <p>This generator implements
046 * {@link org.apache.commons.rng.SplittableUniformRandomProvider SplittableUniformRandomProvider}.
047 * The stream of generators created using the {@code splits} methods support parallelisation
048 * and are robust against accidental correlation by using unique values for the additive parameter
049 * for each instance in the same stream. The primitive streaming methods support parallelisation
050 * but with no assurances of accidental correlation; each thread uses a new instance with a
051 * randomly initialised state.
052 *
053 * @see <a href="https://doi.org/10.1145/3485525">Steele &amp; Vigna (2021) Proc. ACM Programming
054 *      Languages 5, 1-31</a>
055 * @see <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/random/package-summary.html">
056 *      JDK 17 java.util.random javadoc</a>
057 * @since 1.5
058 */
059public class L64X128Mix extends AbstractL64X128 implements SplittableUniformRandomProvider {
060    /**
061     * Creates a new instance.
062     *
063     * @param seed Initial seed.
064     * If the length is larger than 4, only the first 4 elements will
065     * be used; if smaller, the remaining elements will be automatically
066     * set. A seed containing all zeros in the last two elements
067     * will create a non-functional XBG sub-generator and a low
068     * quality output with a period of 2<sup>64</sup>.
069     *
070     * <p>The 1st element is used to set the LCG increment; the least significant bit
071     * is set to odd to ensure a full period LCG. The 2nd element is used
072     * to set the LCG state.</p>
073     */
074    public L64X128Mix(long[] seed) {
075        super(seed);
076    }
077
078    /**
079     * Creates a new instance using a 4 element seed.
080     * A seed containing all zeros in the last two elements
081     * will create a non-functional XBG sub-generator and a low
082     * quality output with a period of 2<sup>64</sup>.
083     *
084     * <p>The 1st element is used to set the LCG increment; the least significant bit
085     * is set to odd to ensure a full period LCG. The 2nd element is used
086     * to set the LCG state.</p>
087     *
088     * @param seed0 Initial seed element 0.
089     * @param seed1 Initial seed element 1.
090     * @param seed2 Initial seed element 2.
091     * @param seed3 Initial seed element 3.
092     */
093    public L64X128Mix(long seed0, long seed1, long seed2, long seed3) {
094        super(seed0, seed1, seed2, seed3);
095    }
096
097    /**
098     * Creates a copy instance.
099     *
100     * @param source Source to copy.
101     */
102    protected L64X128Mix(L64X128Mix source) {
103        super(source);
104    }
105
106    /** {@inheritDoc} */
107    @Override
108    public long next() {
109        // LXM generate.
110        // Old state is used for the output allowing parallel pipelining
111        // on processors that support multiple concurrent instructions.
112
113        final long s0 = x0;
114        final long s = ls;
115
116        // Mix
117        final long z = LXMSupport.lea64(s + s0);
118
119        // LCG update
120        ls = M * s + la;
121
122        // XBG update
123        long s1 = x1;
124
125        s1 ^= s0;
126        x0 = Long.rotateLeft(s0, 24) ^ s1 ^ (s1 << 16); // a, b
127        x1 = Long.rotateLeft(s1, 37); // c
128
129        return z;
130    }
131
132    /** {@inheritDoc} */
133    @Override
134    protected L64X128Mix copy() {
135        // This exists to ensure the jump function performed in the super class returns
136        // the correct class type. It should not be public.
137        return new L64X128Mix(this);
138    }
139
140    /** {@inheritDoc} */
141    @Override
142    public SplittableUniformRandomProvider split(UniformRandomProvider source) {
143        return create(source.nextLong(), source);
144    }
145
146    /** {@inheritDoc} */
147    @Override
148    public Stream<SplittableUniformRandomProvider> splits(long streamSize, SplittableUniformRandomProvider source) {
149        return RandomStreams.generateWithSeed(streamSize, source, L64X128Mix::create);
150    }
151
152    /**
153     * Create a new instance using the given {@code seed} and {@code source} of randomness
154     * to initialise the instance.
155     *
156     * @param seed Seed used to initialise the instance.
157     * @param source Source of randomness used to initialise the instance.
158     * @return A new instance.
159     */
160    private static SplittableUniformRandomProvider create(long seed, UniformRandomProvider source) {
161        // LCG state. The addition uses the input seed.
162        // The LCG addition parameter is set to odd so left-shift the seed.
163        final long s0 = seed << 1;
164        final long s1 = source.nextLong();
165        // XBG state must not be all zero
166        long x0 = source.nextLong();
167        long x1 = source.nextLong();
168        if ((x0 | x1) == 0) {
169            // SplitMix style seed ensures at least one non-zero value
170            x0 = LXMSupport.lea64(s1);
171            x1 = LXMSupport.lea64(s1 + LXMSupport.GOLDEN_RATIO_64);
172        }
173        return new L64X128Mix(s0, s1, x0, x1);
174    }
175}