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.source32;
019
020import java.util.stream.Stream;
021import org.apache.commons.rng.JumpableUniformRandomProvider;
022import org.apache.commons.rng.LongJumpableUniformRandomProvider;
023import org.apache.commons.rng.SplittableUniformRandomProvider;
024import org.apache.commons.rng.UniformRandomProvider;
025import org.apache.commons.rng.core.util.NumberFactory;
026import org.apache.commons.rng.core.util.RandomStreams;
027
028/**
029 * A 32-bit all purpose generator.
030 *
031 * <p>This is a member of the LXM family of generators: L=Linear congruential generator;
032 * X=Xor based generator; and M=Mix. This member uses a 32-bit LCG and 64-bit Xor-based
033 * generator. It is named as {@code "L32X64MixRandom"} in the {@code java.util.random}
034 * package introduced in JDK 17; the LXM family is described in further detail in:
035 *
036 * <blockquote>Steele and Vigna (2021) LXM: better splittable pseudorandom number generators
037 * (and almost as fast). Proceedings of the ACM on Programming Languages, Volume 5,
038 * Article 148, pp 1–31.</blockquote>
039 *
040 * <p>Memory footprint is 128 bits and the period is 2<sup>32</sup> (2<sup>64</sup> - 1).
041 *
042 * <p>This generator implements {@link LongJumpableUniformRandomProvider}.
043 * In addition instances created with a different additive parameter for the LCG are robust
044 * against accidental correlation in a multi-threaded setting. The additive parameters must be
045 * different in the most significant 31-bits.
046 *
047 * <p>This generator implements
048 * {@link org.apache.commons.rng.SplittableUniformRandomProvider SplittableUniformRandomProvider}.
049 * The stream of generators created using the {@code splits} methods support parallelisation
050 * and are robust against accidental correlation by using unique values for the additive parameter
051 * for each instance in the same stream. The primitive streaming methods support parallelisation
052 * but with no assurances of accidental correlation; each thread uses a new instance with a
053 * randomly initialised state.
054 *
055 * @see <a href="https://doi.org/10.1145/3485525">Steele &amp; Vigna (2021) Proc. ACM Programming
056 *      Languages 5, 1-31</a>
057 * @see <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/random/package-summary.html">
058 *      JDK 17 java.util.random javadoc</a>
059 * @since 1.5
060 */
061public final class L32X64Mix extends IntProvider implements LongJumpableUniformRandomProvider,
062    SplittableUniformRandomProvider {
063    // Implementation note:
064    // This does not extend AbstractXoRoShiRo64 as the XBG function is re-implemented
065    // inline to allow parallel pipelining. Inheritance would provide only the XBG state.
066
067    /** LCG multiplier. */
068    private static final int M = LXMSupport.M32;
069    /** Size of the state vector. */
070    private static final int SEED_SIZE = 4;
071
072    /** Per-instance LCG additive parameter (must be odd).
073     * Cannot be final to support RestorableUniformRandomProvider. */
074    private int la;
075    /** State of the LCG generator. */
076    private int ls;
077    /** State 0 of the XBG generator. */
078    private int x0;
079    /** State 1 of the XBG generator. */
080    private int x1;
081
082    /**
083     * Creates a new instance.
084     *
085     * @param seed Initial seed.
086     * If the length is larger than 4, only the first 4 elements will
087     * be used; if smaller, the remaining elements will be automatically
088     * set. A seed containing all zeros in the last two elements
089     * will create a non-functional XBG sub-generator and a low
090     * quality output with a period of 2<sup>32</sup>.
091     *
092     * <p>The 1st element is used to set the LCG increment; the least significant bit
093     * is set to odd to ensure a full period LCG. The 2nd element is used
094     * to set the LCG state.</p>
095     */
096    public L32X64Mix(int[] seed) {
097        setState(extendSeed(seed, SEED_SIZE));
098    }
099
100    /**
101     * Creates a new instance using a 4 element seed.
102     * A seed containing all zeros in the last two elements
103     * will create a non-functional XBG sub-generator and a low
104     * quality output with a period of 2<sup>32</sup>.
105     *
106     * <p>The 1st element is used to set the LCG increment; the least significant bit
107     * is set to odd to ensure a full period LCG. The 2nd element is used
108     * to set the LCG state.</p>
109     *
110     * @param seed0 Initial seed element 0.
111     * @param seed1 Initial seed element 1.
112     * @param seed2 Initial seed element 2.
113     * @param seed3 Initial seed element 3.
114     */
115    public L32X64Mix(int seed0, int seed1, int seed2, int seed3) {
116        // Additive parameter must be odd
117        la = seed0 | 1;
118        ls = seed1;
119        x0 = seed2;
120        x1 = seed3;
121    }
122
123    /**
124     * Creates a copy instance.
125     *
126     * @param source Source to copy.
127     */
128    private L32X64Mix(L32X64Mix source) {
129        super(source);
130        la = source.la;
131        ls = source.ls;
132        x0 = source.x0;
133        x1 = source.x1;
134    }
135
136    /**
137     * Copies the state into the generator state.
138     *
139     * @param state the new state
140     */
141    private void setState(int[] state) {
142        // Additive parameter must be odd
143        la = state[0] | 1;
144        ls = state[1];
145        x0 = state[2];
146        x1 = state[3];
147    }
148
149    /** {@inheritDoc} */
150    @Override
151    protected byte[] getStateInternal() {
152        return composeStateInternal(NumberFactory.makeByteArray(new int[] {la, ls, x0, x1}),
153                                    super.getStateInternal());
154    }
155
156    /** {@inheritDoc} */
157    @Override
158    protected void setStateInternal(byte[] s) {
159        final byte[][] c = splitStateInternal(s, SEED_SIZE * Integer.BYTES);
160        setState(NumberFactory.makeIntArray(c[0]));
161        super.setStateInternal(c[1]);
162    }
163
164    /** {@inheritDoc} */
165    @Override
166    public int next() {
167        // LXM generate.
168        // Old state is used for the output allowing parallel pipelining
169        // on processors that support multiple concurrent instructions.
170
171        final int s0 = x0;
172        final int s = ls;
173
174        // Mix
175        final int z = LXMSupport.lea32(s + s0);
176
177        // LCG update
178        ls = M * s + la;
179
180        // XBG update
181        int s1 = x1;
182
183        s1 ^= s0;
184        x0 = Integer.rotateLeft(s0, 26) ^ s1 ^ (s1 << 9); // a, b
185        x1 = Integer.rotateLeft(s1, 13); // c
186
187        return z;
188    }
189
190    /**
191     * Creates a copy of the UniformRandomProvider and then <em>retreats</em> the state of the
192     * current instance. The copy is returned.
193     *
194     * <p>The jump is performed by advancing the state of the LCG sub-generator by 1 cycle.
195     * The XBG state is unchanged. The jump size is the equivalent of moving the state
196     * <em>backwards</em> by (2<sup>64</sup> - 1) positions. It can provide up to 2<sup>32</sup>
197     * non-overlapping subsequences.</p>
198     */
199    @Override
200    public UniformRandomProvider jump() {
201        final UniformRandomProvider copy = new L32X64Mix(this);
202        // Advance the LCG 1 step
203        ls = M * ls + la;
204        resetCachedState();
205        return copy;
206    }
207
208    /**
209     * Creates a copy of the UniformRandomProvider and then <em>retreats</em> the state of the
210     * current instance. The copy is returned.
211     *
212     * <p>The jump is performed by advancing the state of the LCG sub-generator by
213     * 2<sup>16</sup> cycles. The XBG state is unchanged. The jump size is the equivalent
214     * of moving the state <em>backwards</em> by 2<sup>16</sup> (2<sup>64</sup> - 1)
215     * positions. It can provide up to 2<sup>16</sup> non-overlapping subsequences of
216     * length 2<sup>16</sup> (2<sup>64</sup> - 1); each subsequence can provide up to
217     * 2<sup>16</sup> non-overlapping subsequences of length (2<sup>64</sup> - 1) using
218     * the {@link #jump()} method.</p>
219     */
220    @Override
221    public JumpableUniformRandomProvider longJump() {
222        final JumpableUniformRandomProvider copy = new L32X64Mix(this);
223        // Advance the LCG 2^16 steps
224        ls = LXMSupport.M32P * ls + LXMSupport.C32P * la;
225        resetCachedState();
226        return copy;
227    }
228
229    /** {@inheritDoc} */
230    @Override
231    public SplittableUniformRandomProvider split(UniformRandomProvider source) {
232        // The upper half of the long seed is discarded so use nextInt
233        return create(source.nextInt(), source);
234    }
235
236    /** {@inheritDoc} */
237    @Override
238    public Stream<SplittableUniformRandomProvider> splits(long streamSize, SplittableUniformRandomProvider source) {
239        return RandomStreams.generateWithSeed(streamSize, source, L32X64Mix::create);
240    }
241
242    /**
243     * Create a new instance using the given {@code seed} and {@code source} of randomness
244     * to initialise the instance.
245     *
246     * @param seed Seed used to initialise the instance.
247     * @param source Source of randomness used to initialise the instance.
248     * @return A new instance.
249     */
250    private static SplittableUniformRandomProvider create(long seed, UniformRandomProvider source) {
251        // LCG state. The addition uses the input seed.
252        // The LCG addition parameter is set to odd so left-shift the seed.
253        final int s0 = (int) seed << 1;
254        final int s1 = source.nextInt();
255        // XBG state must not be all zero
256        int x0 = source.nextInt();
257        int x1 = source.nextInt();
258        if ((x0 | x1) == 0) {
259            // SplitMix style seed ensures at least one non-zero value
260            x0 = LXMSupport.lea32(s1);
261            x1 = LXMSupport.lea32(s1 + LXMSupport.GOLDEN_RATIO_32);
262        }
263        return new L32X64Mix(s0, s1, x0, x1);
264    }
265}