index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/PcgMcgXshRr32.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
/**
* A Permuted Congruential Generator (PCG) that is composed of a 64-bit Multiplicative Congruential
* Generator (MCG) combined with the XSH-RR (xorshift; random rotate) output
* transformation to create 32-bit output.
*
* <p>State size is 64 bits and the period is 2<sup>62</sup>.</p>
*
* @see <a href="http://www.pcg-random.org/">
* PCG, A Family of Better Random Number Generators</a>
* @since 1.3
*/
public class PcgMcgXshRr32 extends AbstractPcgMcg6432 {
/**
* Creates a new instance.
*
* @param seed Initial seed.
*/
public PcgMcgXshRr32(Long seed) {
super(seed);
}
/** {@inheritDoc} */
@Override
protected int transform(long x) {
final int count = (int)(x >>> 59);
return Integer.rotateRight((int)((x ^ (x >>> 18)) >>> 27), count);
}
}
| 3,100 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/L32X64Mix.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
import java.util.stream.Stream;
import org.apache.commons.rng.JumpableUniformRandomProvider;
import org.apache.commons.rng.LongJumpableUniformRandomProvider;
import org.apache.commons.rng.SplittableUniformRandomProvider;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.core.util.NumberFactory;
import org.apache.commons.rng.core.util.RandomStreams;
/**
* A 32-bit all purpose generator.
*
* <p>This is a member of the LXM family of generators: L=Linear congruential generator;
* X=Xor based generator; and M=Mix. This member uses a 32-bit LCG and 64-bit Xor-based
* generator. It is named as {@code "L32X64MixRandom"} in the {@code java.util.random}
* package introduced in JDK 17; the LXM family is described in further detail in:
*
* <blockquote>Steele and Vigna (2021) LXM: better splittable pseudorandom number generators
* (and almost as fast). Proceedings of the ACM on Programming Languages, Volume 5,
* Article 148, pp 1–31.</blockquote>
*
* <p>Memory footprint is 128 bits and the period is 2<sup>32</sup> (2<sup>64</sup> - 1).
*
* <p>This generator implements {@link LongJumpableUniformRandomProvider}.
* In addition instances created with a different additive parameter for the LCG are robust
* against accidental correlation in a multi-threaded setting. The additive parameters must be
* different in the most significant 31-bits.
*
* <p>This generator implements
* {@link org.apache.commons.rng.SplittableUniformRandomProvider SplittableUniformRandomProvider}.
* The stream of generators created using the {@code splits} methods support parallelisation
* and are robust against accidental correlation by using unique values for the additive parameter
* for each instance in the same stream. The primitive streaming methods support parallelisation
* but with no assurances of accidental correlation; each thread uses a new instance with a
* randomly initialised state.
*
* @see <a href="https://doi.org/10.1145/3485525">Steele & Vigna (2021) Proc. ACM Programming
* Languages 5, 1-31</a>
* @see <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/random/package-summary.html">
* JDK 17 java.util.random javadoc</a>
* @since 1.5
*/
public final class L32X64Mix extends IntProvider implements LongJumpableUniformRandomProvider,
SplittableUniformRandomProvider {
// Implementation note:
// This does not extend AbstractXoRoShiRo64 as the XBG function is re-implemented
// inline to allow parallel pipelining. Inheritance would provide only the XBG state.
/** LCG multiplier. */
private static final int M = LXMSupport.M32;
/** Size of the state vector. */
private static final int SEED_SIZE = 4;
/** Per-instance LCG additive parameter (must be odd).
* Cannot be final to support RestorableUniformRandomProvider. */
private int la;
/** State of the LCG generator. */
private int ls;
/** State 0 of the XBG generator. */
private int x0;
/** State 1 of the XBG generator. */
private int x1;
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 4, only the first 4 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros in the last two elements
* will create a non-functional XBG sub-generator and a low
* quality output with a period of 2<sup>32</sup>.
*
* <p>The 1st element is used to set the LCG increment; the least significant bit
* is set to odd to ensure a full period LCG. The 2nd element is used
* to set the LCG state.</p>
*/
public L32X64Mix(int[] seed) {
setState(extendSeed(seed, SEED_SIZE));
}
/**
* Creates a new instance using a 4 element seed.
* A seed containing all zeros in the last two elements
* will create a non-functional XBG sub-generator and a low
* quality output with a period of 2<sup>32</sup>.
*
* <p>The 1st element is used to set the LCG increment; the least significant bit
* is set to odd to ensure a full period LCG. The 2nd element is used
* to set the LCG state.</p>
*
* @param seed0 Initial seed element 0.
* @param seed1 Initial seed element 1.
* @param seed2 Initial seed element 2.
* @param seed3 Initial seed element 3.
*/
public L32X64Mix(int seed0, int seed1, int seed2, int seed3) {
// Additive parameter must be odd
la = seed0 | 1;
ls = seed1;
x0 = seed2;
x1 = seed3;
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
private L32X64Mix(L32X64Mix source) {
super(source);
la = source.la;
ls = source.ls;
x0 = source.x0;
x1 = source.x1;
}
/**
* Copies the state into the generator state.
*
* @param state the new state
*/
private void setState(int[] state) {
// Additive parameter must be odd
la = state[0] | 1;
ls = state[1];
x0 = state[2];
x1 = state[3];
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
return composeStateInternal(NumberFactory.makeByteArray(new int[] {la, ls, x0, x1}),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] c = splitStateInternal(s, SEED_SIZE * Integer.BYTES);
setState(NumberFactory.makeIntArray(c[0]));
super.setStateInternal(c[1]);
}
/** {@inheritDoc} */
@Override
public int next() {
// LXM generate.
// Old state is used for the output allowing parallel pipelining
// on processors that support multiple concurrent instructions.
final int s0 = x0;
final int s = ls;
// Mix
final int z = LXMSupport.lea32(s + s0);
// LCG update
ls = M * s + la;
// XBG update
int s1 = x1;
s1 ^= s0;
x0 = Integer.rotateLeft(s0, 26) ^ s1 ^ (s1 << 9); // a, b
x1 = Integer.rotateLeft(s1, 13); // c
return z;
}
/**
* Creates a copy of the UniformRandomProvider and then <em>retreats</em> the state of the
* current instance. The copy is returned.
*
* <p>The jump is performed by advancing the state of the LCG sub-generator by 1 cycle.
* The XBG state is unchanged. The jump size is the equivalent of moving the state
* <em>backwards</em> by (2<sup>64</sup> - 1) positions. It can provide up to 2<sup>32</sup>
* non-overlapping subsequences.</p>
*/
@Override
public UniformRandomProvider jump() {
final UniformRandomProvider copy = new L32X64Mix(this);
// Advance the LCG 1 step
ls = M * ls + la;
resetCachedState();
return copy;
}
/**
* Creates a copy of the UniformRandomProvider and then <em>retreats</em> the state of the
* current instance. The copy is returned.
*
* <p>The jump is performed by advancing the state of the LCG sub-generator by
* 2<sup>16</sup> cycles. The XBG state is unchanged. The jump size is the equivalent
* of moving the state <em>backwards</em> by 2<sup>16</sup> (2<sup>64</sup> - 1)
* positions. It can provide up to 2<sup>16</sup> non-overlapping subsequences of
* length 2<sup>16</sup> (2<sup>64</sup> - 1); each subsequence can provide up to
* 2<sup>16</sup> non-overlapping subsequences of length (2<sup>64</sup> - 1) using
* the {@link #jump()} method.</p>
*/
@Override
public JumpableUniformRandomProvider longJump() {
final JumpableUniformRandomProvider copy = new L32X64Mix(this);
// Advance the LCG 2^16 steps
ls = LXMSupport.M32P * ls + LXMSupport.C32P * la;
resetCachedState();
return copy;
}
/** {@inheritDoc} */
@Override
public SplittableUniformRandomProvider split(UniformRandomProvider source) {
// The upper half of the long seed is discarded so use nextInt
return create(source.nextInt(), source);
}
/** {@inheritDoc} */
@Override
public Stream<SplittableUniformRandomProvider> splits(long streamSize, SplittableUniformRandomProvider source) {
return RandomStreams.generateWithSeed(streamSize, source, L32X64Mix::create);
}
/**
* Create a new instance using the given {@code seed} and {@code source} of randomness
* to initialise the instance.
*
* @param seed Seed used to initialise the instance.
* @param source Source of randomness used to initialise the instance.
* @return A new instance.
*/
private static SplittableUniformRandomProvider create(long seed, UniformRandomProvider source) {
// LCG state. The addition uses the input seed.
// The LCG addition parameter is set to odd so left-shift the seed.
final int s0 = (int) seed << 1;
final int s1 = source.nextInt();
// XBG state must not be all zero
int x0 = source.nextInt();
int x1 = source.nextInt();
if ((x0 | x1) == 0) {
// SplitMix style seed ensures at least one non-zero value
x0 = LXMSupport.lea32(s1);
x1 = LXMSupport.lea32(s1 + LXMSupport.GOLDEN_RATIO_32);
}
return new L32X64Mix(s0, s1, x0, x1);
}
}
| 3,101 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/AbstractXoRoShiRo64.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
import org.apache.commons.rng.core.util.NumberFactory;
/**
* This abstract class is a base for algorithms from the Xor-Shift-Rotate family of 32-bit
* generators with 64-bits of state.
*
* @see <a href="http://xoshiro.di.unimi.it/">xorshiro / xoroshiro generators</a>
* @since 1.3
*/
abstract class AbstractXoRoShiRo64 extends IntProvider {
/** Size of the state vector. */
private static final int SEED_SIZE = 2;
// State is maintained using variables rather than an array for performance
/** State 0 of the generator. */
protected int state0;
/** State 1 of the generator. */
protected int state1;
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 2, only the first 2 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros will create a non-functional generator.
*/
AbstractXoRoShiRo64(int[] seed) {
if (seed.length < SEED_SIZE) {
final int[] state = new int[SEED_SIZE];
fillState(state, seed);
setState(state);
} else {
setState(seed);
}
}
/**
* Creates a new instance using a 2 element seed.
* A seed containing all zeros will create a non-functional generator.
*
* @param seed0 Initial seed element 0.
* @param seed1 Initial seed element 1.
*/
AbstractXoRoShiRo64(int seed0, int seed1) {
state0 = seed0;
state1 = seed1;
}
/**
* Copies the state from the array into the generator state.
*
* @param state the new state
*/
private void setState(int[] state) {
state0 = state[0];
state1 = state[1];
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
return composeStateInternal(NumberFactory.makeByteArray(new int[] {state0, state1}),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] c = splitStateInternal(s, SEED_SIZE * 4);
setState(NumberFactory.makeIntArray(c[0]));
super.setStateInternal(c[1]);
}
/** {@inheritDoc} */
@Override
public int next() {
final int result = nextOutput();
final int s0 = state0;
int s1 = state1;
s1 ^= s0;
state0 = Integer.rotateLeft(s0, 26) ^ s1 ^ (s1 << 9); // a, b
state1 = Integer.rotateLeft(s1, 13); // c
return result;
}
/**
* Use the current state to compute the next output from the generator.
* The output function shall vary with respect to different generators.
* This method is called from {@link #next()} before the current state is updated.
*
* @return the next output
*/
protected abstract int nextOutput();
}
| 3,102 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/XoShiRo128Plus.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
/**
* A fast 32-bit generator suitable for {@code float} generation. This is slightly faster than the
* all-purpose generator {@link XoShiRo128StarStar}.
*
* <p>This is a member of the Xor-Shift-Rotate family of generators. Memory footprint is 128
* bits.</p>
*
* @see <a href="http://xoshiro.di.unimi.it/xoshiro128plus.c">Original source code</a>
* @see <a href="http://xoshiro.di.unimi.it/">xorshiro / xoroshiro generators</a>
* @since 1.3
*/
public class XoShiRo128Plus extends AbstractXoShiRo128 {
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 4, only the first 4 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros will create a non-functional generator.
*/
public XoShiRo128Plus(int[] seed) {
super(seed);
}
/**
* Creates a new instance using a 4 element seed.
* A seed containing all zeros will create a non-functional generator.
*
* @param seed0 Initial seed element 0.
* @param seed1 Initial seed element 1.
* @param seed2 Initial seed element 2.
* @param seed3 Initial seed element 3.
*/
public XoShiRo128Plus(int seed0, int seed1, int seed2, int seed3) {
super(seed0, seed1, seed2, seed3);
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
protected XoShiRo128Plus(XoShiRo128Plus source) {
super(source);
}
/** {@inheritDoc} */
@Override
protected int nextOutput() {
return state0 + state3;
}
/** {@inheritDoc} */
@Override
protected XoShiRo128Plus copy() {
// This exists to ensure the jump function performed in the super class returns
// the correct class type. It should not be public.
return new XoShiRo128Plus(this);
}
}
| 3,103 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/AbstractXoShiRo128.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
import org.apache.commons.rng.JumpableUniformRandomProvider;
import org.apache.commons.rng.LongJumpableUniformRandomProvider;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.core.util.NumberFactory;
/**
* This abstract class is a base for algorithms from the Xor-Shift-Rotate family of 32-bit
* generators with 128-bits of state.
*
* @see <a href="http://xoshiro.di.unimi.it/">xorshiro / xoroshiro generators</a>
* @since 1.3
*/
abstract class AbstractXoShiRo128 extends IntProvider implements LongJumpableUniformRandomProvider {
/** Size of the state vector. */
private static final int SEED_SIZE = 4;
/** The coefficients for the jump function. */
private static final int[] JUMP_COEFFICIENTS = {
0x8764000b, 0xf542d2d3, 0x6fa035c3, 0x77f2db5b
};
/** The coefficients for the long jump function. */
private static final int[] LONG_JUMP_COEFFICIENTS = {
0xb523952e, 0x0b6f099f, 0xccf5a0ef, 0x1c580662
};
// State is maintained using variables rather than an array for performance
/** State 0 of the generator. */
protected int state0;
/** State 1 of the generator. */
protected int state1;
/** State 2 of the generator. */
protected int state2;
/** State 3 of the generator. */
protected int state3;
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 4, only the first 4 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros will create a non-functional generator.
*/
AbstractXoShiRo128(int[] seed) {
if (seed.length < SEED_SIZE) {
final int[] state = new int[SEED_SIZE];
fillState(state, seed);
setState(state);
} else {
setState(seed);
}
}
/**
* Creates a new instance using a 4 element seed.
* A seed containing all zeros will create a non-functional generator.
*
* @param seed0 Initial seed element 0.
* @param seed1 Initial seed element 1.
* @param seed2 Initial seed element 2.
* @param seed3 Initial seed element 3.
*/
AbstractXoShiRo128(int seed0, int seed1, int seed2, int seed3) {
state0 = seed0;
state1 = seed1;
state2 = seed2;
state3 = seed3;
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
protected AbstractXoShiRo128(AbstractXoShiRo128 source) {
super(source);
state0 = source.state0;
state1 = source.state1;
state2 = source.state2;
state3 = source.state3;
}
/**
* Copies the state from the array into the generator state.
*
* @param state the new state
*/
private void setState(int[] state) {
state0 = state[0];
state1 = state[1];
state2 = state[2];
state3 = state[3];
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
return composeStateInternal(NumberFactory.makeByteArray(
new int[] {state0, state1, state2, state3}),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] c = splitStateInternal(s, SEED_SIZE * 4);
setState(NumberFactory.makeIntArray(c[0]));
super.setStateInternal(c[1]);
}
/** {@inheritDoc} */
@Override
public int next() {
final int result = nextOutput();
final int t = state1 << 9;
state2 ^= state0;
state3 ^= state1;
state1 ^= state2;
state0 ^= state3;
state2 ^= t;
state3 = Integer.rotateLeft(state3, 11);
return result;
}
/**
* Use the current state to compute the next output from the generator.
* The output function shall vary with respect to different generators.
* This method is called from {@link #next()} before the current state is updated.
*
* @return the next output
*/
protected abstract int nextOutput();
/**
* {@inheritDoc}
*
* <p>The jump size is the equivalent of 2<sup>64</sup>
* calls to {@link UniformRandomProvider#nextInt() nextInt()}. It can provide
* up to 2<sup>64</sup> non-overlapping subsequences.</p>
*/
@Override
public UniformRandomProvider jump() {
final UniformRandomProvider copy = copy();
performJump(JUMP_COEFFICIENTS);
return copy;
}
/**
* {@inheritDoc}
*
* <p>The jump size is the equivalent of 2<sup>96</sup> calls to
* {@link UniformRandomProvider#nextLong() nextLong()}. It can provide up to
* 2<sup>32</sup> non-overlapping subsequences of length 2<sup>96</sup>; each
* subsequence can provide up to 2<sup>32</sup> non-overlapping subsequences of
* length 2<sup>64</sup> using the {@link #jump()} method.</p>
*/
@Override
public JumpableUniformRandomProvider longJump() {
final JumpableUniformRandomProvider copy = copy();
performJump(LONG_JUMP_COEFFICIENTS);
return copy;
}
/**
* Create a copy.
*
* @return the copy
*/
protected abstract AbstractXoShiRo128 copy();
/**
* Perform the jump to advance the generator state. Resets the cached state of the generator.
*
* @param jumpCoefficients Jump coefficients.
*/
private void performJump(int[] jumpCoefficients) {
int s0 = 0;
int s1 = 0;
int s2 = 0;
int s3 = 0;
for (final int jc : jumpCoefficients) {
for (int b = 0; b < 32; b++) {
if ((jc & (1 << b)) != 0) {
s0 ^= state0;
s1 ^= state1;
s2 ^= state2;
s3 ^= state3;
}
next();
}
}
state0 = s0;
state1 = s1;
state2 = s2;
state3 = s3;
resetCachedState();
}
}
| 3,104 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/IntProvider.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
import org.apache.commons.rng.core.util.NumberFactory;
import org.apache.commons.rng.core.BaseProvider;
/**
* Base class for all implementations that provide an {@code int}-based
* source randomness.
*/
public abstract class IntProvider
extends BaseProvider
implements RandomIntSource {
/** Empty boolean source. This is the location of the sign-bit after 31 right shifts on
* the boolean source. */
private static final int EMPTY_BOOL_SOURCE = 1;
/**
* Provides a bit source for booleans.
*
* <p>A cached value from a call to {@link #next()}.
*
* <p>Only stores 31-bits when full as 1 bit has already been consumed.
* The sign bit is a flag that shifts down so the source eventually equals 1
* when all bits are consumed and will trigger a refill.
*/
private int booleanSource = EMPTY_BOOL_SOURCE;
/**
* Creates a new instance.
*/
public IntProvider() {
super();
}
/**
* Creates a new instance copying the state from the source.
*
* <p>This provides base functionality to allow a generator to create a copy, for example
* for use in the {@link org.apache.commons.rng.JumpableUniformRandomProvider
* JumpableUniformRandomProvider} interface.
*
* @param source Source to copy.
* @since 1.3
*/
protected IntProvider(IntProvider source) {
booleanSource = source.booleanSource;
}
/**
* Reset the cached state used in the default implementation of {@link #nextBoolean()}.
*
* <p>This should be used when the state is no longer valid, for example after a jump
* performed for the {@link org.apache.commons.rng.JumpableUniformRandomProvider
* JumpableUniformRandomProvider} interface.</p>
*
* @since 1.3
*/
protected void resetCachedState() {
booleanSource = EMPTY_BOOL_SOURCE;
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
return composeStateInternal(NumberFactory.makeByteArray(booleanSource),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] c = splitStateInternal(s, Integer.BYTES);
booleanSource = NumberFactory.makeInt(c[0]);
super.setStateInternal(c[1]);
}
/** {@inheritDoc} */
@Override
public int nextInt() {
return next();
}
/** {@inheritDoc} */
@Override
public boolean nextBoolean() {
int bits = booleanSource;
if (bits == 1) {
// Refill
bits = next();
// Store a refill flag in the sign bit and the unused 31 bits, return lowest bit
booleanSource = Integer.MIN_VALUE | (bits >>> 1);
return (bits & 0x1) == 1;
}
// Shift down eventually triggering refill, return current lowest bit
booleanSource = bits >>> 1;
return (bits & 0x1) == 1;
}
/** {@inheritDoc} */
@Override
public double nextDouble() {
return NumberFactory.makeDouble(next(), next());
}
/** {@inheritDoc} */
@Override
public long nextLong() {
return NumberFactory.makeLong(next(), next());
}
/** {@inheritDoc} */
@Override
public void nextBytes(byte[] bytes) {
nextBytesFill(this, bytes, 0, bytes.length);
}
/** {@inheritDoc} */
@Override
public void nextBytes(byte[] bytes,
int start,
int len) {
checkFromIndexSize(start, len, bytes.length);
nextBytesFill(this, bytes, start, len);
}
/**
* Generates random bytes and places them into a user-supplied array.
*
* <p>
* The array is filled with bytes extracted from random {@code int} values.
* This implies that the number of random bytes generated may be larger than
* the length of the byte array.
* </p>
*
* @param source Source of randomness.
* @param bytes Array in which to put the generated bytes. Cannot be null.
* @param start Index at which to start inserting the generated bytes.
* @param len Number of bytes to insert.
*/
static void nextBytesFill(RandomIntSource source,
byte[] bytes,
int start,
int len) {
int index = start; // Index of first insertion.
// Index of first insertion plus multiple of 4 part of length
// (i.e. length with 2 least significant bits unset).
final int indexLoopLimit = index + (len & 0x7ffffffc);
// Start filling in the byte array, 4 bytes at a time.
while (index < indexLoopLimit) {
final int random = source.next();
bytes[index++] = (byte) random;
bytes[index++] = (byte) (random >>> 8);
bytes[index++] = (byte) (random >>> 16);
bytes[index++] = (byte) (random >>> 24);
}
final int indexLimit = start + len; // Index of last insertion + 1.
// Fill in the remaining bytes.
if (index < indexLimit) {
int random = source.next();
while (true) {
bytes[index++] = (byte) random;
if (index < indexLimit) {
random >>>= 8;
} else {
break;
}
}
}
}
/**
* Checks if the sub-range from fromIndex (inclusive) to fromIndex + size (exclusive) is
* within the bounds of range from 0 (inclusive) to length (exclusive).
*
* <p>This function provides the functionality of
* {@code java.utils.Objects.checkFromIndexSize} introduced in JDK 9. The
* <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Objects.html#checkFromIndexSize(int,int,int)">Objects</a>
* javadoc has been reproduced for reference.
*
* <p>The sub-range is defined to be out of bounds if any of the following inequalities
* is true:
* <ul>
* <li>{@code fromIndex < 0}
* <li>{@code size < 0}
* <li>{@code fromIndex + size > length}, taking into account integer overflow
* <li>{@code length < 0}, which is implied from the former inequalities
* </ul>
*
* @param fromIndex the lower-bound (inclusive) of the sub-interval
* @param size the size of the sub-range
* @param length the upper-bound (exclusive) of the range
* @return the fromIndex
* @throws IndexOutOfBoundsException if the sub-range is out of bounds
*/
private static int checkFromIndexSize(int fromIndex, int size, int length) {
// check for any negatives,
// or overflow safe length check given the values are all positive
// remaining = length - fromIndex
if ((fromIndex | size | length) < 0 || size > length - fromIndex) {
throw new IndexOutOfBoundsException(
// Note: %<d is 'relative indexing' to re-use the last argument
String.format("Range [%d, %<d + %d) out of bounds for length %d",
fromIndex, size, length));
}
return fromIndex;
}
}
| 3,105 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/ISAACRandom.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
import java.util.Arrays;
import org.apache.commons.rng.core.util.NumberFactory;
/**
* A fast cryptographic pseudo-random number generator.
* <p>
* ISAAC (Indirection, Shift, Accumulate, Add, and Count) generates 32-bit
* random numbers.
* ISAAC has been designed to be cryptographically secure and is inspired
* by RC4.
* Cycles are guaranteed to be at least 2<sup>40</sup> values long, and they
* are 2<sup>8295</sup> values long on average.
* The results are uniformly distributed, unbiased, and unpredictable unless
* you know the seed.
* <p>
* This code is based (with minor changes and improvements) on the original
* implementation of the algorithm by Bob Jenkins.
*
* @see <a href="http://burtleburtle.net/bob/rand/isaacafa.html">
* ISAAC: a fast cryptographic pseudo-random number generator</a>
*
* @see <a href="https://en.wikipedia.org/wiki/ISAAC_(cipher)">ISAAC (Wikipedia)</a>
* @since 1.0
*/
public class ISAACRandom extends IntProvider {
/** Log of size of rsl[] and mem[]. */
private static final int SIZE_L = 8;
/** Size of rsl[] and mem[]. */
private static final int SIZE = 1 << SIZE_L;
/** Half-size of rsl[] and mem[]. */
private static final int H_SIZE = SIZE >> 1;
/** For pseudo-random lookup. */
private static final int MASK = SIZE - 1 << 2;
/** The golden ratio. */
private static final int GLD_RATIO = 0x9e3779b9;
/** The results given to the user. */
private final int[] rsl = new int[SIZE];
/** The internal state. */
private final int[] mem = new int[SIZE];
/** Count through the results in rsl[]. */
private int count;
/** Accumulator. */
private int isaacA;
/** The last result. */
private int isaacB;
/** Counter, guarantees cycle is at least 2^40. */
private int isaacC;
/** Service variable. */
private final int[] arr = new int[8];
/** Service variable. */
private int isaacX;
/** Service variable. */
private int isaacI;
/** Service variable. */
private int isaacJ;
/**
* Creates a new ISAAC random number generator.
*
* @param seed Initial seed
*/
public ISAACRandom(int[] seed) {
setSeedInternal(seed);
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
final int[] sRsl = Arrays.copyOf(rsl, SIZE);
final int[] sMem = Arrays.copyOf(mem, SIZE);
final int[] sRem = Arrays.copyOf(new int[] {count, isaacA, isaacB, isaacC}, 4);
final int[] s = new int[2 * SIZE + sRem.length];
System.arraycopy(sRsl, 0, s, 0, SIZE);
System.arraycopy(sMem, 0, s, SIZE, SIZE);
System.arraycopy(sRem, 0, s, 2 * SIZE, sRem.length);
return composeStateInternal(NumberFactory.makeByteArray(s),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] c = splitStateInternal(s, (2 * SIZE + 4) * 4);
final int[] tmp = NumberFactory.makeIntArray(c[0]);
System.arraycopy(tmp, 0, rsl, 0, SIZE);
System.arraycopy(tmp, SIZE, mem, 0, SIZE);
final int offset = 2 * SIZE;
count = tmp[offset];
isaacA = tmp[offset + 1];
isaacB = tmp[offset + 2];
isaacC = tmp[offset + 3];
super.setStateInternal(c[1]);
}
/**
* Reseeds the RNG.
*
* @param seed Seed. Cannot be null.
*/
private void setSeedInternal(int[] seed) {
final int seedLen = seed.length;
final int rslLen = rsl.length;
System.arraycopy(seed, 0, rsl, 0, Math.min(seedLen, rslLen));
if (seedLen < rslLen) {
for (int j = seedLen; j < rslLen; j++) {
final long k = rsl[j - seedLen];
rsl[j] = (int) (0x6c078965L * (k ^ k >> 30) + j & 0xffffffffL);
}
}
initState();
}
/** {@inheritDoc} */
@Override
public int next() {
if (count < 0) {
isaac();
count = SIZE - 1;
}
return rsl[count--];
}
/** Generate 256 results. */
private void isaac() {
isaacI = 0;
isaacJ = H_SIZE;
isaacB += ++isaacC;
while (isaacI < H_SIZE) {
isaac2();
}
isaacJ = 0;
while (isaacJ < H_SIZE) {
isaac2();
}
}
/** Intermediate internal loop. */
private void isaac2() {
isaacX = mem[isaacI];
isaacA ^= isaacA << 13;
isaacA += mem[isaacJ++];
isaac3();
isaacX = mem[isaacI];
isaacA ^= isaacA >>> 6;
isaacA += mem[isaacJ++];
isaac3();
isaacX = mem[isaacI];
isaacA ^= isaacA << 2;
isaacA += mem[isaacJ++];
isaac3();
isaacX = mem[isaacI];
isaacA ^= isaacA >>> 16;
isaacA += mem[isaacJ++];
isaac3();
}
/** Lowest level internal loop. */
private void isaac3() {
mem[isaacI] = mem[(isaacX & MASK) >> 2] + isaacA + isaacB;
isaacB = mem[(mem[isaacI] >> SIZE_L & MASK) >> 2] + isaacX;
rsl[isaacI++] = isaacB;
}
/** Initialize, or reinitialize, this instance of rand. */
private void initState() {
isaacA = 0;
isaacB = 0;
isaacC = 0;
Arrays.fill(arr, GLD_RATIO);
for (int j = 0; j < 4; j++) {
shuffle();
}
// fill in mem[] with messy stuff
for (int j = 0; j < SIZE; j += 8) {
arr[0] += rsl[j];
arr[1] += rsl[j + 1];
arr[2] += rsl[j + 2];
arr[3] += rsl[j + 3];
arr[4] += rsl[j + 4];
arr[5] += rsl[j + 5];
arr[6] += rsl[j + 6];
arr[7] += rsl[j + 7];
shuffle();
setState(j);
}
// second pass makes all of seed affect all of mem
for (int j = 0; j < SIZE; j += 8) {
arr[0] += mem[j];
arr[1] += mem[j + 1];
arr[2] += mem[j + 2];
arr[3] += mem[j + 3];
arr[4] += mem[j + 4];
arr[5] += mem[j + 5];
arr[6] += mem[j + 6];
arr[7] += mem[j + 7];
shuffle();
setState(j);
}
isaac();
count = SIZE - 1;
}
/** Shuffle array. */
private void shuffle() {
arr[0] ^= arr[1] << 11;
arr[3] += arr[0];
arr[1] += arr[2];
arr[1] ^= arr[2] >>> 2;
arr[4] += arr[1];
arr[2] += arr[3];
arr[2] ^= arr[3] << 8;
arr[5] += arr[2];
arr[3] += arr[4];
arr[3] ^= arr[4] >>> 16;
arr[6] += arr[3];
arr[4] += arr[5];
arr[4] ^= arr[5] << 10;
arr[7] += arr[4];
arr[5] += arr[6];
arr[5] ^= arr[6] >>> 4;
arr[0] += arr[5];
arr[6] += arr[7];
arr[6] ^= arr[7] << 8;
arr[1] += arr[6];
arr[7] += arr[0];
arr[7] ^= arr[0] >>> 9;
arr[2] += arr[7];
arr[0] += arr[1];
}
/** Set the state by copying the internal arrays.
*
* @param start First index into {@link #mem} array.
*/
private void setState(int start) {
mem[start] = arr[0];
mem[start + 1] = arr[1];
mem[start + 2] = arr[2];
mem[start + 3] = arr[3];
mem[start + 4] = arr[4];
mem[start + 5] = arr[5];
mem[start + 6] = arr[6];
mem[start + 7] = arr[7];
}
}
| 3,106 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/Well19937a.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
/**
* This class implements the WELL19937a pseudo-random number generator
* from François Panneton, Pierre L'Ecuyer and Makoto Matsumoto.
* <p>
* This generator is described in a paper by François Panneton,
* Pierre L'Ecuyer and Makoto Matsumoto
* <a href="http://www.iro.umontreal.ca/~lecuyer/myftp/papers/wellrng.pdf">
* Improved Long-Period Generators Based on Linear Recurrences Modulo 2</a>
* ACM Transactions on Mathematical Software, 32, 1 (2006).
* The errata for the paper are in
* <a href="http://www.iro.umontreal.ca/~lecuyer/myftp/papers/wellrng-errata.txt">wellrng-errata.txt</a>.
* </p>
*
* @see <a href="http://www.iro.umontreal.ca/~panneton/WELLRNG.html">WELL Random number generator</a>
* @since 1.0
*/
public class Well19937a extends AbstractWell {
/** Number of bits in the pool. */
private static final int K = 19937;
/** First parameter of the algorithm. */
private static final int M1 = 70;
/** Second parameter of the algorithm. */
private static final int M2 = 179;
/** Third parameter of the algorithm. */
private static final int M3 = 449;
/** The indirection index table. */
private static final IndexTable TABLE = new IndexTable(K, M1, M2, M3);
/**
* Creates a new random number generator.
*
* @param seed Initial seed.
*/
public Well19937a(int[] seed) {
super(K, seed);
}
/** {@inheritDoc} */
@Override
public int next() {
final int indexRm1 = TABLE.getIndexPred(index);
final int indexRm2 = TABLE.getIndexPred2(index);
final int v0 = v[index];
final int vM1 = v[TABLE.getIndexM1(index)];
final int vM2 = v[TABLE.getIndexM2(index)];
final int vM3 = v[TABLE.getIndexM3(index)];
final int z0 = (0x80000000 & v[indexRm1]) ^ (0x7FFFFFFF & v[indexRm2]);
final int z1 = (v0 ^ (v0 << 25)) ^ (vM1 ^ (vM1 >>> 27));
final int z2 = (vM2 >>> 9) ^ (vM3 ^ (vM3 >>> 1));
final int z3 = z1 ^ z2;
final int z4 = z0 ^ (z1 ^ (z1 << 9)) ^ (z2 ^ (z2 << 21)) ^ (z3 ^ (z3 >>> 21));
v[index] = z3;
v[indexRm1] = z4;
v[indexRm2] &= 0x80000000;
index = indexRm1;
return z4;
}
}
| 3,107 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/Well1024a.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
/**
* This class implements the WELL1024a pseudo-random number generator
* from François Panneton, Pierre L'Ecuyer and Makoto Matsumoto.
* <p>
* This generator is described in a paper by François Panneton,
* Pierre L'Ecuyer and Makoto Matsumoto
* <a href="http://www.iro.umontreal.ca/~lecuyer/myftp/papers/wellrng.pdf">
* Improved Long-Period Generators Based on Linear Recurrences Modulo 2</a>
* ACM Transactions on Mathematical Software, 32, 1 (2006).
* The errata for the paper are in
* <a href="http://www.iro.umontreal.ca/~lecuyer/myftp/papers/wellrng-errata.txt">wellrng-errata.txt</a>.
* </p>
*
* @see <a href="http://www.iro.umontreal.ca/~panneton/WELLRNG.html">WELL Random number generator</a>
* @since 1.0
*/
public class Well1024a extends AbstractWell {
/** Number of bits in the pool. */
private static final int K = 1024;
/** First parameter of the algorithm. */
private static final int M1 = 3;
/** Second parameter of the algorithm. */
private static final int M2 = 24;
/** Third parameter of the algorithm. */
private static final int M3 = 10;
/** The indirection index table. */
private static final IndexTable TABLE = new IndexTable(K, M1, M2, M3);
/**
* Creates a new random number generator.
*
* @param seed Initial seed.
*/
public Well1024a(int[] seed) {
super(K, seed);
}
/** {@inheritDoc} */
@Override
public int next() {
final int indexRm1 = TABLE.getIndexPred(index);
final int v0 = v[index];
final int vM1 = v[TABLE.getIndexM1(index)];
final int vM2 = v[TABLE.getIndexM2(index)];
final int vM3 = v[TABLE.getIndexM3(index)];
final int z0 = v[indexRm1];
final int z1 = v0 ^ (vM1 ^ (vM1 >>> 8));
final int z2 = (vM2 ^ (vM2 << 19)) ^ (vM3 ^ (vM3 << 14));
final int z3 = z1 ^ z2;
final int z4 = (z0 ^ (z0 << 11)) ^ (z1 ^ (z1 << 7)) ^ (z2 ^ (z2 << 13));
v[index] = z3;
v[indexRm1] = z4;
index = indexRm1;
return z4;
}
}
| 3,108 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/JDKRandom.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
import java.util.Random;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.ObjectInputStream;
import java.io.ByteArrayOutputStream;
import org.apache.commons.rng.core.util.NumberFactory;
import java.io.ByteArrayInputStream;
/**
* A provider that uses the {@link Random#nextInt()} method of the JDK's
* {@link Random} class as the source of randomness.
*
* <p>
* <b>Caveat:</b> All the other calls will be redirected to the methods
* implemented within this library.
* </p>
*
* <p>
* The state of this source of randomness is saved and restored through
* the serialization of the {@link Random} instance.
* </p>
*
* @since 1.0
*/
public class JDKRandom extends IntProvider {
/** Delegate. Cannot be "final" (to allow serialization). */
private Random delegate;
/**
* An <code>ObjectInputStream</code> that's restricted to deserialize
* only {@link java.util.Random} using look-ahead deserialization.
*
* <p>Adapted from o.a.c.io.serialization.ValidatingObjectInputStream.</p>
*
* @see <a href="http://www.ibm.com/developerworks/library/se-lookahead/">
* IBM DeveloperWorks Article: Look-ahead Java deserialization</a>
*/
private static class ValidatingObjectInputStream extends ObjectInputStream {
/**
* @param in Input stream
* @throws IOException Signals that an I/O exception has occurred.
*/
ValidatingObjectInputStream(final InputStream in) throws IOException {
super(in);
}
/** {@inheritDoc} */
@Override
protected Class<?> resolveClass(final ObjectStreamClass osc) throws IOException,
ClassNotFoundException {
// For legacy reasons the Random class is serialized using only primitives
// even though modern implementations use AtomicLong.
// The only expected class is java.util.Random.
if (!Random.class.getName().equals(osc.getName())) {
throw new IllegalStateException("Stream does not contain java.util.Random: " + osc.getName());
}
return super.resolveClass(osc);
}
}
/**
* Creates an instance with the given seed.
*
* @param seed Initial seed.
*/
public JDKRandom(Long seed) {
delegate = new Random(seed);
}
/**
* {@inheritDoc}
*
* @see Random#nextInt()
*/
@Override
public int next() {
return delegate.nextInt();
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos)) {
// Serialize the "delegate".
oos.writeObject(delegate);
final byte[] state = bos.toByteArray();
final int stateSize = state.length; // To allow state recovery.
// Compose the size with the state
final byte[] sizeAndState = composeStateInternal(NumberFactory.makeByteArray(stateSize),
state);
return composeStateInternal(sizeAndState,
super.getStateInternal());
} catch (IOException e) {
// Workaround checked exception.
throw new IllegalStateException(e);
}
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
// First obtain the state size
final byte[][] s2 = splitStateInternal(s, 4);
final int stateSize = NumberFactory.makeInt(s2[0]);
// Second obtain the state
final byte[][] c = splitStateInternal(s2[1], stateSize);
// Use look-ahead deserialization to validate the state byte[] contains java.util.Random.
try (ByteArrayInputStream bis = new ByteArrayInputStream(c[0]);
ObjectInputStream ois = new ValidatingObjectInputStream(bis)) {
delegate = (Random) ois.readObject();
} catch (ClassNotFoundException | IOException e) {
// Workaround checked exception.
throw new IllegalStateException(e);
}
super.setStateInternal(c[1]);
}
}
| 3,109 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/XoRoShiRo64Star.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
/**
* A fast 32-bit generator suitable for {@code float} generation. This is slightly faster than the
* all-purpose generator {@link XoRoShiRo64StarStar}.
*
* <p>This is a member of the Xor-Shift-Rotate family of generators. Memory footprint is 64
* bits.</p>
*
* @see <a href="http://xoshiro.di.unimi.it/xoroshiro64star.c">Original source code</a>
* @see <a href="http://xoshiro.di.unimi.it/">xorshiro / xoroshiro generators</a>
* @since 1.3
*/
public class XoRoShiRo64Star extends AbstractXoRoShiRo64 {
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 2, only the first 2 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros will create a non-functional generator.
*/
public XoRoShiRo64Star(int[] seed) {
super(seed);
}
/**
* Creates a new instance using a 2 element seed.
* A seed containing all zeros will create a non-functional generator.
*
* @param seed0 Initial seed element 0.
* @param seed1 Initial seed element 1.
*/
public XoRoShiRo64Star(int seed0, int seed1) {
super(seed0, seed1);
}
/** {@inheritDoc} */
@Override
protected int nextOutput() {
return state0 * 0x9e3779bb;
}
}
| 3,110 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/Well44497a.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
/**
* This class implements the WELL44497a pseudo-random number generator
* from François Panneton, Pierre L'Ecuyer and Makoto Matsumoto.
* <p>
* This generator is described in a paper by François Panneton,
* Pierre L'Ecuyer and Makoto Matsumoto
* <a href="http://www.iro.umontreal.ca/~lecuyer/myftp/papers/wellrng.pdf">
* Improved Long-Period Generators Based on Linear Recurrences Modulo 2</a>
* ACM Transactions on Mathematical Software, 32, 1 (2006).
* The errata for the paper are in
* <a href="http://www.iro.umontreal.ca/~lecuyer/myftp/papers/wellrng-errata.txt">wellrng-errata.txt</a>.
* </p>
*
* @see <a href="http://www.iro.umontreal.ca/~panneton/WELLRNG.html">WELL Random number generator</a>
* @since 1.0
*/
public class Well44497a extends AbstractWell {
/** Number of bits in the pool. */
private static final int K = 44497;
/** First parameter of the algorithm. */
private static final int M1 = 23;
/** Second parameter of the algorithm. */
private static final int M2 = 481;
/** Third parameter of the algorithm. */
private static final int M3 = 229;
/** The indirection index table. */
private static final IndexTable TABLE = new IndexTable(K, M1, M2, M3);
/**
* Creates a new random number generator.
*
* @param seed Initial seed.
*/
public Well44497a(int[] seed) {
super(K, seed);
}
/** {@inheritDoc} */
@Override
public int next() {
final int indexRm1 = TABLE.getIndexPred(index);
final int indexRm2 = TABLE.getIndexPred2(index);
final int v0 = v[index];
final int vM1 = v[TABLE.getIndexM1(index)];
final int vM2 = v[TABLE.getIndexM2(index)];
final int vM3 = v[TABLE.getIndexM3(index)];
// the values below include the errata of the original article
final int z0 = (0xFFFF8000 & v[indexRm1]) ^ (0x00007FFF & v[indexRm2]);
final int z1 = (v0 ^ (v0 << 24)) ^ (vM1 ^ (vM1 >>> 30));
final int z2 = (vM2 ^ (vM2 << 10)) ^ (vM3 << 26);
final int z3 = z1 ^ z2;
final int z2Prime = ((z2 << 9) ^ (z2 >>> 23)) & 0xfbffffff;
final int z2Second = ((z2 & 0x00020000) == 0) ? z2Prime : (z2Prime ^ 0xb729fcec);
final int z4 = z0 ^ (z1 ^ (z1 >>> 20)) ^ z2Second ^ z3;
v[index] = z3;
v[indexRm1] = z4;
v[indexRm2] &= 0xFFFF8000;
index = indexRm1;
return z4;
}
}
| 3,111 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/MultiplyWithCarry256.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
import java.util.Arrays;
import org.apache.commons.rng.core.util.NumberFactory;
/**
* Port from Marsaglia's <a href="https://en.wikipedia.org/wiki/Multiply-with-carry">
* "Multiply-With-Carry" algorithm</a>.
*
* <p>
* Implementation is based on the (non-portable!) C code reproduced on
* <a href="http://school.anhb.uwa.edu.au/personalpages/kwessen/shared/Marsaglia03.html">
* that page</a>.
* </p>
*
* @see <a href="https://en.wikipedia.org/wiki/Multiply-with-carry">Multiply with carry (Wikipedia)</a>
* @since 1.0
*/
public class MultiplyWithCarry256 extends IntProvider {
/** Length of the state array. */
private static final int Q_SIZE = 256;
/** Size of the seed. */
private static final int SEED_SIZE = Q_SIZE + 1;
/** Multiply. */
private static final long A = 809430660;
/** State. */
private final int[] state = new int[Q_SIZE];
/** Current index in "state" array. */
private int index;
/** Carry. */
private int carry;
/**
* Creates a new instance.
*
* @param seed Seed.
* If the length is larger than 257, only the first 257 elements will
* be used; if smaller, the remaining elements will be automatically
* set.
*/
public MultiplyWithCarry256(int[] seed) {
setSeedInternal(seed);
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
final int[] s = Arrays.copyOf(state, SEED_SIZE + 1);
s[SEED_SIZE - 1] = carry;
s[SEED_SIZE] = index;
return composeStateInternal(NumberFactory.makeByteArray(s),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] c = splitStateInternal(s, (SEED_SIZE + 1) * 4);
final int[] tmp = NumberFactory.makeIntArray(c[0]);
System.arraycopy(tmp, 0, state, 0, Q_SIZE);
carry = tmp[SEED_SIZE - 1];
index = tmp[SEED_SIZE];
super.setStateInternal(c[1]);
}
/**
* Seeds the RNG.
*
* @param seed Seed.
*/
private void setSeedInternal(int[] seed) {
// Reset the whole state of this RNG (i.e. "state" and "index").
// Filling procedure is not part of the reference code.
final int[] tmp = new int[SEED_SIZE];
fillState(tmp, seed);
// First element of the "seed" is the initial "carry".
final int c = tmp[0];
// Marsaglia's recommendation: 0 <= carry < A.
carry = (int) (Math.abs(c) % A);
// Initial state.
System.arraycopy(tmp, 1, state, 0, Q_SIZE);
// Initial index.
index = Q_SIZE;
}
/** {@inheritDoc} */
@Override
public int next() {
// Produce an index in the range 0-255
index &= 0xff;
final long t = A * (state[index] & 0xffffffffL) + carry;
carry = (int) (t >> 32);
return state[index++] = (int) t;
}
}
| 3,112 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/PcgXshRs32.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
/**
* A Permuted Congruential Generator (PCG) that is composed of a 64-bit Linear Congruential
* Generator (LCG) combined with the XSH-RS (xorshift; random shift) output
* transformation to create 32-bit output.
*
* <p>State size is 128 bits and the period is 2<sup>64</sup>.</p>
*
* <p><strong>Note:</strong> Although the seed size is 128 bits, only the first 64 are
* effective: in effect, two seeds that only differ by the last 64 bits may produce
* highly correlated sequences.
*
* @see <a href="http://www.pcg-random.org/">
* PCG, A Family of Better Random Number Generators</a>
* @since 1.3
*/
public class PcgXshRs32 extends AbstractPcg6432 {
/**
* Creates a new instance using a default increment.
*
* @param seed Initial state.
* @since 1.4
*/
public PcgXshRs32(Long seed) {
super(seed);
}
/**
* Creates a new instance.
*
* <p><strong>Note:</strong> Although the seed size is 128 bits, only the first 64 are
* effective: in effect, two seeds that only differ by the last 64 bits may produce
* highly correlated sequences.
*
* @param seed Initial seed.
* If the length is larger than 2, only the first 2 elements will
* be used; if smaller, the remaining elements will be automatically set.
*
* <p>The 1st element is used to set the LCG state. The 2nd element is used
* to set the LCG increment; the most significant bit
* is discarded by left shift and the increment is set to odd.</p>
*/
public PcgXshRs32(long[] seed) {
super(seed);
}
/** {@inheritDoc} */
@Override
protected int transform(long x) {
final int count = (int)(x >>> 61);
return (int)((x ^ (x >>> 22)) >>> (22 + count));
}
}
| 3,113 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/XoRoShiRo64StarStar.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
/**
* A fast all-purpose 32-bit generator. For faster generation of {@code float} values try the
* {@link XoRoShiRo64Star} generator.
*
* <p>This is a member of the Xor-Shift-Rotate family of generators. Memory footprint is 64
* bits.</p>
*
* @see <a href="http://xoshiro.di.unimi.it/xoroshiro64starstar.c">Original source code</a>
* @see <a href="http://xoshiro.di.unimi.it/">xorshiro / xoroshiro generators</a>
* @since 1.3
*/
public class XoRoShiRo64StarStar extends AbstractXoRoShiRo64 {
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 2, only the first 2 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros will create a non-functional generator.
*/
public XoRoShiRo64StarStar(int[] seed) {
super(seed);
}
/**
* Creates a new instance using a 2 element seed.
* A seed containing all zeros will create a non-functional generator.
*
* @param seed0 Initial seed element 0.
* @param seed1 Initial seed element 1.
*/
public XoRoShiRo64StarStar(int seed0, int seed1) {
super(seed0, seed1);
}
/** {@inheritDoc} */
@Override
protected int nextOutput() {
return Integer.rotateLeft(state0 * 0x9e3779bb, 5) * 5;
}
}
| 3,114 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/Well19937c.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
/**
* This class implements the WELL19937c pseudo-random number generator
* from François Panneton, Pierre L'Ecuyer and Makoto Matsumoto.
* <p>
* This generator is described in a paper by François Panneton,
* Pierre L'Ecuyer and Makoto Matsumoto
* <a href="http://www.iro.umontreal.ca/~lecuyer/myftp/papers/wellrng.pdf">
* Improved Long-Period Generators Based on Linear Recurrences Modulo 2</a>
* ACM Transactions on Mathematical Software, 32, 1 (2006).
* The errata for the paper are in
* <a href="http://www.iro.umontreal.ca/~lecuyer/myftp/papers/wellrng-errata.txt">wellrng-errata.txt</a>.
* </p>
*
* @see <a href="http://www.iro.umontreal.ca/~panneton/WELLRNG.html">WELL Random number generator</a>
* @since 1.0
*/
public class Well19937c extends Well19937a {
/**
* Creates a new random number generator.
*
* @param seed Initial seed.
*/
public Well19937c(int[] seed) {
super(seed);
}
/** {@inheritDoc} */
@Override
public int next() {
int z4 = super.next();
// Matsumoto-Kurita tempering to get a maximally equidistributed generator.
z4 ^= (z4 << 7) & 0xe46e1700;
z4 ^= (z4 << 15) & 0x9b868000;
return z4;
}
}
| 3,115 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/AbstractPcgMcg6432.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
import org.apache.commons.rng.core.util.NumberFactory;
/**
* This abstract class is a base for algorithms from the Permuted Congruential Generator (PCG)
* family that use an internal 64-bit Multiplicative Congruential Generator (MCG) and output
* 32-bits per cycle.
*
* @see <a href="http://www.pcg-random.org/">
* PCG, A Family of Better Random Number Generators</a>
* @since 1.3
*/
abstract class AbstractPcgMcg6432 extends IntProvider {
/** The state of the MCG. */
private long state;
/**
* Creates a new instance.
*
* @param seed Initial seed.
*/
AbstractPcgMcg6432(Long seed) {
// A seed of zero will result in a non-functional MCG; it must be odd for a maximal
// period MCG. The multiplication factor always sets the 2 least-significant bits to 1
// if they are already 1 so these are explicitly set. Bit k (zero-based) will have
// period 2^(k-1) starting from bit 2 with a period of 1. Bit 63 has period 2^62.
state = seed | 3;
}
/**
* Provides the next state of the MCG.
*
* @param input Current state.
* @return next state
*/
private static long bump(long input) {
return input * 6364136223846793005L;
}
/** {@inheritDoc} */
@Override
public int next() {
final long x = state;
state = bump(state);
return transform(x);
}
/**
* Transform the 64-bit state of the generator to a 32-bit output.
* The transformation function shall vary with respect to different generators.
*
* @param x State.
* @return the output
*/
protected abstract int transform(long x);
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
return composeStateInternal(NumberFactory.makeByteArray(state),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] d = splitStateInternal(s, 8);
// As per the constructor, ensure the lower 2 bits of state are set.
state = NumberFactory.makeLong(d[0]) | 3;
super.setStateInternal(d[1]);
}
}
| 3,116 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/JenkinsSmallFast32.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
import org.apache.commons.rng.core.util.NumberFactory;
/**
* Implement Bob Jenkins's small fast (JSF) 32-bit generator.
*
* <p>The state size is 128-bits; the shortest period is expected to be about 2<sup>94</sup>
* and it expected that about one seed will run into another seed within 2<sup>64</sup> values.</p>
*
* @see <a href="https://burtleburtle.net/bob/rand/smallprng.html">A small noncryptographic PRNG</a>
* @since 1.3
*/
public class JenkinsSmallFast32 extends IntProvider {
/** State a. */
private int a;
/** State b. */
private int b;
/** State c. */
private int c;
/** Statd d. */
private int d;
/**
* Creates an instance with the given seed.
*
* @param seed Initial seed.
*/
public JenkinsSmallFast32(Integer seed) {
setSeedInternal(seed);
}
/**
* Seeds the RNG.
*
* @param seed Seed.
*/
private void setSeedInternal(int seed) {
a = 0xf1ea5eed;
b = c = d = seed;
for (int i = 0; i < 20; i++) {
next();
}
}
/** {@inheritDoc} */
@Override
public final int next() {
final int e = a - Integer.rotateLeft(b, 27);
a = b ^ Integer.rotateLeft(c, 17);
b = c + d;
c = d + e;
d = e + a;
return d;
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
return composeStateInternal(NumberFactory.makeByteArray(new int[] {a, b, c, d}),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] parts = splitStateInternal(s, 4 * 4);
final int[] tmp = NumberFactory.makeIntArray(parts[0]);
a = tmp[0];
b = tmp[1];
c = tmp[2];
d = tmp[3];
super.setStateInternal(parts[1]);
}
}
| 3,117 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/AbstractPcg6432.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
import org.apache.commons.rng.core.util.NumberFactory;
/**
* This abstract class is a base for algorithms from the Permuted Congruential Generator (PCG)
* family that use an internal 64-bit Linear Congruential Generator (LCG) and output 32-bits
* per cycle.
*
* <h2>Note: PCG generators may exhibit massive stream correlation</h2>
*
* <p>Although the seed size is 128 bits, only the first 64 are effective: in effect,
* two seeds that only differ by the last 64 bits may produce highly correlated sequences.
*
* <p>Due to the use of an underlying linear congruential generator (LCG) alterations
* to the 128 bit seed have the following effect: the first 64-bits alter the
* generator state; the second 64 bits, with the exception of the most significant bit,
* which is discarded, choose between one of two alternative LCGs
* where the output of the chosen LCG is the same sequence except for an additive
* constant determined by the seed bits. The result is that seeds that differ
* only in the last 64-bits will have a 50% chance of producing highly correlated
* output sequences.
* <p>Consider using the fixed increment variant where the 64-bit seed sets the
* generator state.
*
* <p>For further information see:
* <ul>
* <li>
* <blockquote>
* Durst, M.J. (1989) <i>Using Linear Congruential Generators For Parallel Random Number Generation.
* Section 3.1: Different additive constants in a maximum potency congruential generator</i>.
* 1989 Winter Simulation Conference Proceedings, Washington, DC, USA, 1989, pp. 462-466.
* </blockquote>
* </li>
* </ul>
*
* @see <a href="http://www.pcg-random.org/">
* PCG, A Family of Better Random Number Generators</a>
* @see <a href="https://ieeexplore.ieee.org/document/718715">Durst, M.J. (1989)
* Using Linear Congruential Generators For Parallel Random Number Generation</a>
* @see <a href="https://issues.apache.org/jira/browse/RNG-123">
* PCG generators may exhibit massive stream correlation</a>
* @since 1.3
*/
abstract class AbstractPcg6432 extends IntProvider {
/** Size of the seed array. */
private static final int SEED_SIZE = 2;
/** The default increment. */
private static final long DEFAULT_INCREMENT = 1442695040888963407L;
/** The state of the LCG. */
private long state;
/** The increment of the LCG. */
private long increment;
/**
* Creates a new instance using a default increment.
*
* @param seed Initial state.
* @since 1.4
*/
AbstractPcg6432(Long seed) {
increment = DEFAULT_INCREMENT;
state = bump(seed + this.increment);
}
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 2, only the first 2 elements will
* be used; if smaller, the remaining elements will be automatically set.
*
* <p>The 1st element is used to set the LCG state. The 2nd element is used
* to set the LCG increment; the most significant bit
* is discarded by left shift and the increment is set to odd.</p>
*/
AbstractPcg6432(long[] seed) {
if (seed.length < SEED_SIZE) {
final long[] tmp = new long[SEED_SIZE];
fillState(tmp, seed);
setSeedInternal(tmp);
} else {
setSeedInternal(seed);
}
}
/**
* Seeds the RNG.
*
* @param seed Seed.
*/
private void setSeedInternal(long[] seed) {
// Ensure the increment is odd to provide a maximal period LCG.
this.increment = (seed[1] << 1) | 1;
this.state = bump(seed[0] + this.increment);
}
/**
* Provides the next state of the LCG.
*
* @param input Current state.
* @return next state
*/
private long bump(long input) {
return input * 6364136223846793005L + increment;
}
/** {@inheritDoc} */
@Override
public int next() {
final long x = state;
state = bump(state);
return transform(x);
}
/**
* Transform the 64-bit state of the generator to a 32-bit output.
* The transformation function shall vary with respect to different generators.
*
* @param x State.
* @return the output
*/
protected abstract int transform(long x);
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
// The increment is divided by 2 before saving.
// This transform is used in the reference PCG code; it prevents restoring from
// a byte state a non-odd increment that results in a sub-maximal period generator.
return composeStateInternal(NumberFactory.makeByteArray(
new long[] {state, increment >>> 1}),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] c = splitStateInternal(s, SEED_SIZE * 8);
final long[] tempseed = NumberFactory.makeLongArray(c[0]);
state = tempseed[0];
// Reverse the transform performed during getState to make the increment odd again.
increment = tempseed[1] << 1 | 1;
super.setStateInternal(c[1]);
}
}
| 3,118 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/PcgMcgXshRs32.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
/**
* A Permuted Congruential Generator (PCG) that is composed of a 64-bit Multiplicative Congruential
* Generator (MCG) combined with the XSH-RS (xorshift; random shift) output
* transformation to create 32-bit output.
*
* <p>State size is 64 bits and the period is 2<sup>62</sup>.</p>
*
* @see <a href="http://www.pcg-random.org/">
* PCG, A Family of Better Random Number Generators</a>
* @since 1.3
*/
public class PcgMcgXshRs32 extends AbstractPcgMcg6432 {
/**
* Creates a new instance.
*
* @param seed Initial seed.
*/
public PcgMcgXshRs32(Long seed) {
super(seed);
}
/** {@inheritDoc} */
@Override
protected int transform(long x) {
final int count = (int)(x >>> 61);
return (int)((x ^ (x >>> 22)) >>> (22 + count));
}
}
| 3,119 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/Well44497b.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
/**
* This class implements the WELL44497b pseudo-random number generator
* from François Panneton, Pierre L'Ecuyer and Makoto Matsumoto.
* <p>
* This generator is described in a paper by François Panneton,
* Pierre L'Ecuyer and Makoto Matsumoto
* <a href="http://www.iro.umontreal.ca/~lecuyer/myftp/papers/wellrng.pdf">
* Improved Long-Period Generators Based on Linear Recurrences Modulo 2</a>
* ACM Transactions on Mathematical Software, 32, 1 (2006).
* The errata for the paper are in
* <a href="http://www.iro.umontreal.ca/~lecuyer/myftp/papers/wellrng-errata.txt">wellrng-errata.txt</a>.
* </p>
*
* @see <a href="http://www.iro.umontreal.ca/~panneton/WELLRNG.html">WELL Random number generator</a>
* @since 1.0
*/
public class Well44497b extends Well44497a {
/**
* Creates a new random number generator.
*
* @param seed Initial seed.
*/
public Well44497b(int[] seed) {
super(seed);
}
/** {@inheritDoc} */
@Override
public int next() {
int z4 = super.next();
// Matsumoto-Kurita tempering to get a maximally equidistributed generator.
z4 ^= (z4 << 7) & 0x93dd1400;
z4 ^= (z4 << 15) & 0xfa118000;
return z4;
}
}
| 3,120 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/DotyHumphreySmallFastCounting32.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
import org.apache.commons.rng.core.util.NumberFactory;
/**
* Implement the Small, Fast, Counting (SFC) 32-bit generator of Chris Doty-Humphrey.
* The original source is the PractRand test suite by the same author.
*
* <p>The state size is 128-bits; the period is a minimum of 2<sup>32</sup> and an
* average of approximately 2<sup>127</sup>.</p>
*
* @see <a href="http://pracrand.sourceforge.net/">PractRand</a>
* @since 1.3
*/
public class DotyHumphreySmallFastCounting32 extends IntProvider {
/** Size of the seed. */
private static final int SEED_SIZE = 3;
/** State a. */
private int a;
/** State b. */
private int b;
/** State c. */
private int c;
/** Counter. */
private int counter;
/**
* Creates an instance with the given seed.
*
* @param seed Initial seed.
* If the length is larger than 3, only the first 3 elements will
* be used; if smaller, the remaining elements will be automatically set.
*/
public DotyHumphreySmallFastCounting32(int[] seed) {
if (seed.length < SEED_SIZE) {
final int[] state = new int[SEED_SIZE];
fillState(state, seed);
setSeedInternal(state);
} else {
setSeedInternal(seed);
}
}
/**
* Seeds the RNG.
*
* @param seed Seed.
*/
private void setSeedInternal(int[] seed) {
a = seed[0];
b = seed[1];
c = seed[2];
counter = 1;
for (int i = 0; i < 15; i++) {
next();
}
}
/** {@inheritDoc} */
@Override
public final int next() {
final int tmp = a + b + counter++;
a = b ^ (b >>> 9);
b = c + (c << 3);
c = Integer.rotateLeft(c, 21) + tmp;
return tmp;
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
return composeStateInternal(NumberFactory.makeByteArray(new int[] {a, b, c, counter}),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] parts = splitStateInternal(s, 4 * 4);
final int[] tmp = NumberFactory.makeIntArray(parts[0]);
a = tmp[0];
b = tmp[1];
c = tmp[2];
counter = tmp[3];
super.setStateInternal(parts[1]);
}
}
| 3,121 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/LXMSupport.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
/**
* Utility support for the LXM family of generators. The LXM family is described
* in further detail in:
*
* <blockquote>Steele and Vigna (2021) LXM: better splittable pseudorandom number generators
* (and almost as fast). Proceedings of the ACM on Programming Languages, Volume 5,
* Article 148, pp 1–31.</blockquote>
*
* <p>Constants are provided to advance the state of an LCG by a power of 2 in a single
* multiply operation to support jump operations.
*
* @see <a href="https://doi.org/10.1145/3485525">Steele & Vigna (2021) Proc. ACM Programming
* Languages 5, 1-31</a>
* @since 1.5
*/
final class LXMSupport {
/** 32-bit LCG multiplier. Note: (M % 8) = 5. */
static final int M32 = 0xadb4a92d;
/** Jump constant {@code m'} for an advance of the 32-bit LCG by 2^16.
* Computed as: {@code m' = m^(2^16) (mod 2^32)}. */
static final int M32P = 0x65640001;
/** Jump constant precursor for {@code c'} for an advance of the 32-bit LCG by 2^16.
* Computed as:
* <pre>
* product_{i=0}^{15} { M^(2^i) + 1 } (mod 2^32)
* </pre>
* <p>The jump is computed for the LCG with an update step of {@code s = m * s + c} as:
* <pre>
* s = m' * s + c' * c
* </pre>
*/
static final int C32P = 0x046b0000;
/**
* The fractional part of the golden ratio, phi, scaled to 32-bits and rounded to odd.
* <pre>
* phi = (sqrt(5) - 1) / 2) * 2^32
* </pre>
* @see <a href="https://en.wikipedia.org/wiki/Golden_ratio">Golden ratio</a>
*/
static final int GOLDEN_RATIO_32 = 0x9e3779b9;
/** No instances. */
private LXMSupport() {}
/**
* Perform a 32-bit mixing function using Doug Lea's 32-bit mix constants and shifts.
*
* <p>This is based on the original 32-bit mix function of Austin Appleby's
* MurmurHash3 modified to use a single mix constant and 16-bit shifts, which may have
* a performance advantage on some processors.
*
* <p>The code was kindly provided by Guy Steele as a printing constraint led to
* its omission from Steele and Vigna's paper.
*
* <p>Note from Guy Steele:
* <blockquote>
* The constant 0xd36d884b was chosen by Doug Lea by taking the (two’s-complement)
* negation of the decimal constant 747796405, which appears in Table 5 of L’Ecuyer’s
* classic paper “Tables of Linear Congruential Generators of Different Sizes and Good
* Lattice Structure” (January 1999); the constant in lea64 was chosen in a similar manner.
* These choices were based on his engineering intuition and then validated by testing.
* </blockquote>
*
* @param x the input value
* @return the output value
*/
static int lea32(int x) {
x = (x ^ (x >>> 16)) * 0xd36d884b;
x = (x ^ (x >>> 16)) * 0xd36d884b;
return x ^ (x >>> 16);
}
}
| 3,122 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/Well512a.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
/**
* This class implements the WELL512a pseudo-random number generator
* from François Panneton, Pierre L'Ecuyer and Makoto Matsumoto.
* <p>
* This generator is described in a paper by François Panneton,
* Pierre L'Ecuyer and Makoto Matsumoto
* <a href="http://www.iro.umontreal.ca/~lecuyer/myftp/papers/wellrng.pdf">
* Improved Long-Period Generators Based on Linear Recurrences Modulo 2</a>
* ACM Transactions on Mathematical Software, 32, 1 (2006).
* The errata for the paper are in
* <a href="http://www.iro.umontreal.ca/~lecuyer/myftp/papers/wellrng-errata.txt">wellrng-errata.txt</a>.
* </p>
*
* @see <a href="http://www.iro.umontreal.ca/~panneton/WELLRNG.html">WELL Random number generator</a>
* @since 1.0
*/
public class Well512a extends AbstractWell {
/** Number of bits in the pool. */
private static final int K = 512;
/** First parameter of the algorithm. */
private static final int M1 = 13;
/** Second parameter of the algorithm. */
private static final int M2 = 9;
/** Third parameter of the algorithm. */
private static final int M3 = 5;
/** The indirection index table. */
private static final IndexTable TABLE = new IndexTable(K, M1, M2, M3);
/**
* Creates a new random number generator.
*
* @param seed Initial seed.
*/
public Well512a(int[] seed) {
super(K, seed);
}
/** {@inheritDoc} */
@Override
public int next() {
final int indexRm1 = TABLE.getIndexPred(index);
final int vi = v[index];
final int vi1 = v[TABLE.getIndexM1(index)];
final int vi2 = v[TABLE.getIndexM2(index)];
final int z0 = v[indexRm1];
// the values below include the errata of the original article
final int z1 = (vi ^ (vi << 16)) ^ (vi1 ^ (vi1 << 15));
final int z2 = vi2 ^ (vi2 >>> 11);
final int z3 = z1 ^ z2;
final int z4 = (z0 ^ (z0 << 2)) ^ (z1 ^ (z1 << 18)) ^ (z2 << 28) ^ (z3 ^ ((z3 << 5) & 0xda442d24));
v[index] = z3;
v[indexRm1] = z4;
index = indexRm1;
return z4;
}
}
| 3,123 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/RandomIntSource.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
/**
* Source of randomness that generates values of type {@code int}.
*
* @since 1.0
*/
public interface RandomIntSource {
/**
* @return the next random value.
*/
int next();
}
| 3,124 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/XoShiRo128PlusPlus.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
/**
* A fast all-purpose 32-bit generator. For faster generation of {@code float} values try the
* {@link XoShiRo128Plus} generator.
*
* <p>This is a member of the Xor-Shift-Rotate family of generators. Memory footprint is 128
* bits.</p>
*
* @see <a href="http://xoshiro.di.unimi.it/xoshiro128plusplus.c">Original source code</a>
* @see <a href="http://xoshiro.di.unimi.it/">xorshiro / xoroshiro generators</a>
* @since 1.3
*/
public class XoShiRo128PlusPlus extends AbstractXoShiRo128 {
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 4, only the first 4 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros will create a non-functional generator.
*/
public XoShiRo128PlusPlus(int[] seed) {
super(seed);
}
/**
* Creates a new instance using a 4 element seed.
* A seed containing all zeros will create a non-functional generator.
*
* @param seed0 Initial seed element 0.
* @param seed1 Initial seed element 1.
* @param seed2 Initial seed element 2.
* @param seed3 Initial seed element 3.
*/
public XoShiRo128PlusPlus(int seed0, int seed1, int seed2, int seed3) {
super(seed0, seed1, seed2, seed3);
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
protected XoShiRo128PlusPlus(XoShiRo128PlusPlus source) {
super(source);
}
/** {@inheritDoc} */
@Override
protected int nextOutput() {
return Integer.rotateLeft(state0 + state3, 7) + state0;
}
/**
* Create a copy.
*
* @return the copy
*/
@Override
protected XoShiRo128PlusPlus copy() {
// This exists to ensure the jump function performed in the super class returns
// the correct class type. It should not be public.
return new XoShiRo128PlusPlus(this);
}
}
| 3,125 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/XoShiRo128StarStar.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
/**
* A fast all-purpose 32-bit generator. For faster generation of {@code float} values try the
* {@link XoShiRo128Plus} generator.
*
* <p>This is a member of the Xor-Shift-Rotate family of generators. Memory footprint is 128
* bits.</p>
*
* @see <a href="http://xoshiro.di.unimi.it/xoshiro128starstar.c">Original source code</a>
* @see <a href="http://xoshiro.di.unimi.it/">xorshiro / xoroshiro generators</a>
* @since 1.3
*/
public class XoShiRo128StarStar extends AbstractXoShiRo128 {
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 4, only the first 4 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros will create a non-functional generator.
*/
public XoShiRo128StarStar(int[] seed) {
super(seed);
}
/**
* Creates a new instance using a 4 element seed.
* A seed containing all zeros will create a non-functional generator.
*
* @param seed0 Initial seed element 0.
* @param seed1 Initial seed element 1.
* @param seed2 Initial seed element 2.
* @param seed3 Initial seed element 3.
*/
public XoShiRo128StarStar(int seed0, int seed1, int seed2, int seed3) {
super(seed0, seed1, seed2, seed3);
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
protected XoShiRo128StarStar(XoShiRo128StarStar source) {
super(source);
}
/** {@inheritDoc} */
@Override
protected int nextOutput() {
return Integer.rotateLeft(state0 * 5, 7) * 9;
}
/** {@inheritDoc} */
@Override
protected XoShiRo128StarStar copy() {
// This exists to ensure the jump function performed in the super class returns
// the correct class type. It should not be public.
return new XoShiRo128StarStar(this);
}
}
| 3,126 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/PcgXshRr32.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
/**
* A Permuted Congruential Generator (PCG) that is composed of a 64-bit Linear Congruential
* Generator (LCG) combined with the XSH-RR (xorshift; random rotate) output
* transformation to create 32-bit output.
*
* <p>State size is 128 bits and the period is 2<sup>64</sup>.</p>
*
* <p><strong>Note:</strong> Although the seed size is 128 bits, only the first 64 are
* effective: in effect, two seeds that only differ by the last 64 bits may produce
* highly correlated sequences.
*
* @see <a href="http://www.pcg-random.org/">
* PCG, A Family of Better Random Number Generators</a>
* @since 1.3
*/
public class PcgXshRr32 extends AbstractPcg6432 {
/**
* Creates a new instance using a default increment.
*
* @param seed Initial state.
* @since 1.4
*/
public PcgXshRr32(Long seed) {
super(seed);
}
/**
* Creates a new instance.
*
* <p><strong>Note:</strong> Although the seed size is 128 bits, only the first 64 are
* effective: in effect, two seeds that only differ by the last 64 bits may produce
* highly correlated sequences.
*
* @param seed Initial seed.
* If the length is larger than 2, only the first 2 elements will
* be used; if smaller, the remaining elements will be automatically set.
*
* <p>The 1st element is used to set the LCG state. The 2nd element is used
* to set the LCG increment; the most significant bit
* is discarded by left shift and the increment is set to odd.</p>
*/
public PcgXshRr32(long[] seed) {
super(seed);
}
/** {@inheritDoc} */
@Override
protected int transform(long x) {
final int count = (int)(x >>> 59);
return Integer.rotateRight((int)((x ^ (x >>> 18)) >>> 27), count);
}
}
| 3,127 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/MiddleSquareWeylSequence.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
import org.apache.commons.rng.core.util.NumberFactory;
import java.util.Arrays;
/**
* Middle Square Weyl Sequence Random Number Generator.
*
* <p>A fast all-purpose 32-bit generator. Memory footprint is 192 bits and the period is at least
* {@code 2^64}.</p>
*
* <p>Implementation is based on the paper
* <a href="https://arxiv.org/abs/1704.00358v3">Middle Square Weyl Sequence RNG</a>.</p>
*
* @see <a href="https://en.wikipedia.org/wiki/Middle-square_method">Middle Square Method</a>
* @since 1.3
*/
public class MiddleSquareWeylSequence extends IntProvider {
/** Size of the seed array. */
private static final int SEED_SIZE = 3;
/**
* The default seed.
* This has a high quality Weyl increment (containing many bit state transitions).
*/
private static final long[] DEFAULT_SEED =
{0x012de1babb3c4104L, 0xc8161b4202294965L, 0xb5ad4eceda1ce2a9L};
/** State of the generator. */
private long x;
/** State of the Weyl sequence. */
private long w;
/**
* Increment for the Weyl sequence. This must be odd to ensure a full period.
*
* <p>This is not final to support the restore functionality.</p>
*/
private long s;
/**
* Creates a new instance.
*
* <p>Note: The generator output quality is highly dependent on the initial seed.
* If the generator is seeded poorly (for example with all zeros) it is possible the
* generator may output zero for many cycles before the internal state recovers randomness.
* The seed elements are used to set:</p>
*
* <ol>
* <li>The state of the generator
* <li>The state of the Weyl sequence
* <li>The increment of the Weyl sequence
* </ol>
*
* <p>The third element is set to odd to ensure a period of at least 2<sup>64</sup>. If the
* increment is of low complexity then the Weyl sequence does not contribute high quality
* randomness. It is recommended to use a permutation of 8 hex characters for the upper
* and lower 32-bits of the increment.</p>
*
* <p>The state of the generator is squared during each cycle. There is a possibility that
* different seeds can produce the same output, for example 0 and 2<sup>32</sup> produce
* the same square. This can be avoided by using the high complexity Weyl increment for the
* state seed element.</p>
*
* @param seed Initial seed.
* If the length is larger than 3, only the first 3 elements will
* be used; if smaller, the remaining elements will be automatically set.
*/
public MiddleSquareWeylSequence(long[] seed) {
if (seed.length < SEED_SIZE) {
// Complete the seed with a default to avoid
// low complexity Weyl increments.
final long[] tmp = Arrays.copyOf(seed, SEED_SIZE);
System.arraycopy(DEFAULT_SEED, seed.length, tmp, seed.length, SEED_SIZE - seed.length);
setSeedInternal(tmp);
} else {
setSeedInternal(seed);
}
}
/**
* Seeds the RNG.
*
* @param seed Seed.
*/
private void setSeedInternal(long[] seed) {
x = seed[0];
w = seed[1];
// Ensure the increment is odd to provide a maximal period Weyl sequence.
this.s = seed[2] | 1L;
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
return composeStateInternal(NumberFactory.makeByteArray(new long[] {x, w, s}),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] state) {
final byte[][] c = splitStateInternal(state, SEED_SIZE * 8);
setSeedInternal(NumberFactory.makeLongArray(c[0]));
super.setStateInternal(c[1]);
}
/** {@inheritDoc} */
@Override
public int next() {
x *= x;
x += w += s;
x = (x >>> 32) | (x << 32);
return (int) x;
}
/** {@inheritDoc} */
@Override
public long nextLong() {
// Avoid round trip from long to int to long by performing two iterations inline
x *= x;
x += w += s;
final long i1 = x & 0xffffffff00000000L;
x = (x >>> 32) | (x << 32);
x *= x;
x += w += s;
final long i2 = x >>> 32;
x = i2 | x << 32;
return i1 | i2;
}
}
| 3,128 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/KISSRandom.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
import org.apache.commons.rng.core.util.NumberFactory;
/**
* Port from Marsaglia's <a href="http://www.cse.yorku.ca/~oz/marsaglia-rng.html">
* "KISS" algorithm</a>.
* This version contains the correction referred to
* <a href="https://programmingpraxis.com/2010/10/05/george-marsaglias-random-number-generators/">here</a>
* in a reply to the original post.
*
* @see <a href="https://en.wikipedia.org/wiki/KISS_(algorithm)">KISS (Wikipedia)</a>
* @since 1.0
*/
public class KISSRandom extends IntProvider {
/** Size of the seed. */
private static final int SEED_SIZE = 4;
/** State variable. */
private int z;
/** State variable. */
private int w;
/** State variable. */
private int jsr;
/** State variable. */
private int jcong;
/**
* Creates a new instance.
*
* @param seed Seed.
* If the length is larger than 4, only the first 4 elements will
* be used; if smaller, the remaining elements will be automatically
* set.
*/
public KISSRandom(int[] seed) {
setSeedInternal(seed);
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
return composeStateInternal(NumberFactory.makeByteArray(new int[] {z, w, jsr, jcong}),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] c = splitStateInternal(s, SEED_SIZE * 4);
final int[] tmp = NumberFactory.makeIntArray(c[0]);
z = tmp[0];
w = tmp[1];
jsr = tmp[2];
jcong = tmp[3];
super.setStateInternal(c[1]);
}
/**
* Seeds the RNG.
*
* @param seed Seed.
*/
private void setSeedInternal(int[] seed) {
// Reset the whole state of this RNG (i.e. the 4 state variables).
// Filling procedure is not part of the reference code.
final int[] tmp = new int[SEED_SIZE];
fillState(tmp, seed);
z = tmp[0];
w = tmp[1];
jsr = tmp[2];
jcong = tmp[3];
}
/** {@inheritDoc} */
@Override
public int next() {
z = computeNew(36969, z);
w = computeNew(18000, w);
final int mwc = (z << 16) + w;
// Cf. correction mentioned in the reply to the original post:
// https://programmingpraxis.com/2010/10/05/george-marsaglias-random-number-generators/
jsr ^= jsr << 13;
jsr ^= jsr >>> 17;
jsr ^= jsr << 5;
jcong = 69069 * jcong + 1234567;
return (mwc ^ jcong) + jsr;
}
/**
* Compute new value.
*
* @param mult Multiplier.
* @param previous Previous value.
* @return new value.
*/
private static int computeNew(int mult,
int previous) {
return mult * (previous & 65535) + (previous >>> 16);
}
}
| 3,129 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/AbstractWell.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
import java.util.Arrays;
import org.apache.commons.rng.core.util.NumberFactory;
/**
* This abstract class implements the WELL class of pseudo-random number
* generator from François Panneton, Pierre L'Ecuyer and Makoto
* Matsumoto.
* <p>
* This generator is described in a paper by François Panneton,
* Pierre L'Ecuyer and Makoto Matsumoto
* <a href="http://www.iro.umontreal.ca/~lecuyer/myftp/papers/wellrng.pdf">
* Improved Long-Period Generators Based on Linear Recurrences Modulo 2</a>
* ACM Transactions on Mathematical Software, 32, 1 (2006).
* The errata for the paper are in
* <a href="http://www.iro.umontreal.ca/~lecuyer/myftp/papers/wellrng-errata.txt">wellrng-errata.txt</a>.
* </p>
*
* @see <a href="http://www.iro.umontreal.ca/~panneton/WELLRNG.html">WELL Random number generator</a>
*
* @since 1.0
*/
public abstract class AbstractWell extends IntProvider {
/** Block size. */
private static final int BLOCK_SIZE = 32;
/** Current index in the bytes pool. */
protected int index;
/** Bytes pool. */
protected final int[] v;
/**
* Creates an instance with the given {@code seed}.
*
* @param k Number of bits in the pool (not necessarily a multiple of 32).
* @param seed Initial seed.
*/
protected AbstractWell(final int k,
final int[] seed) {
final int r = calculateBlockCount(k);
v = new int[r];
index = 0;
// Initialize the pool content.
setSeedInternal(seed);
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
final int[] s = Arrays.copyOf(v, v.length + 1);
s[v.length] = index;
return composeStateInternal(NumberFactory.makeByteArray(s),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] c = splitStateInternal(s, (v.length + 1) * 4);
final int[] tmp = NumberFactory.makeIntArray(c[0]);
System.arraycopy(tmp, 0, v, 0, v.length);
index = tmp[v.length];
super.setStateInternal(c[1]);
}
/**
* Initializes the generator with the given {@code seed}.
*
* @param seed Seed. Cannot be null.
*/
private void setSeedInternal(final int[] seed) {
System.arraycopy(seed, 0, v, 0, Math.min(seed.length, v.length));
if (seed.length < v.length) {
for (int i = seed.length; i < v.length; ++i) {
final long current = v[i - seed.length];
v[i] = (int) ((1812433253L * (current ^ (current >> 30)) + i) & 0xffffffffL);
}
}
index = 0;
}
/**
* Calculate the number of 32-bits blocks.
*
* @param k Number of bits in the pool (not necessarily a multiple of 32).
* @return the number of 32-bits blocks.
*/
private static int calculateBlockCount(final int k) {
// The bits pool contains k bits, k = r w - p where r is the number
// of w bits blocks, w is the block size (always 32 in the original paper)
// and p is the number of unused bits in the last block.
return (k + BLOCK_SIZE - 1) / BLOCK_SIZE;
}
/**
* Inner class used to store the indirection index table which is fixed for a given
* type of WELL class of pseudo-random number generator.
*/
protected static final class IndexTable {
/** Index indirection table giving for each index its predecessor taking table size into account. */
private final int[] iRm1;
/** Index indirection table giving for each index its second predecessor taking table size into account. */
private final int[] iRm2;
/** Index indirection table giving for each index the value index + m1 taking table size into account. */
private final int[] i1;
/** Index indirection table giving for each index the value index + m2 taking table size into account. */
private final int[] i2;
/** Index indirection table giving for each index the value index + m3 taking table size into account. */
private final int[] i3;
/** Creates a new pre-calculated indirection index table.
* @param k number of bits in the pool (not necessarily a multiple of 32)
* @param m1 first parameter of the algorithm
* @param m2 second parameter of the algorithm
* @param m3 third parameter of the algorithm
*/
public IndexTable(final int k, final int m1, final int m2, final int m3) {
final int r = calculateBlockCount(k);
// precompute indirection index tables. These tables are used for optimizing access
// they allow saving computations like "(j + r - 2) % r" with costly modulo operations
iRm1 = new int[r];
iRm2 = new int[r];
i1 = new int[r];
i2 = new int[r];
i3 = new int[r];
for (int j = 0; j < r; ++j) {
iRm1[j] = (j + r - 1) % r;
iRm2[j] = (j + r - 2) % r;
i1[j] = (j + m1) % r;
i2[j] = (j + m2) % r;
i3[j] = (j + m3) % r;
}
}
/**
* Returns the predecessor of the given index modulo the table size.
* @param index the index to look at
* @return (index - 1) % table size
*/
public int getIndexPred(final int index) {
return iRm1[index];
}
/**
* Returns the second predecessor of the given index modulo the table size.
* @param index the index to look at
* @return (index - 2) % table size
*/
public int getIndexPred2(final int index) {
return iRm2[index];
}
/**
* Returns index + M1 modulo the table size.
* @param index the index to look at
* @return (index + M1) % table size
*/
public int getIndexM1(final int index) {
return i1[index];
}
/**
* Returns index + M2 modulo the table size.
* @param index the index to look at
* @return (index + M2) % table size
*/
public int getIndexM2(final int index) {
return i2[index];
}
/**
* Returns index + M3 modulo the table size.
* @param index the index to look at
* @return (index + M3) % table size
*/
public int getIndexM3(final int index) {
return i3[index];
}
}
}
| 3,130 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/package-info.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Concrete algorithms for {@code int}-based sources of randomness.
*
* <p>
* <b>For internal use only:</b> Direct access to classes in this package
* is discouraged, as they could be modified without notice.
* </p>
*
* <p><b>Notes for developers</b></p>
*
* <ul>
* <li>
* A source of randomness must inherit from
* {@link org.apache.commons.rng.core.source32.IntProvider}
* </li>
* <li>
* The "provider" must specify <em>one</em> way for setting the seed.
* For a given seed, the generated sequence must always be the same.
* </li>
* <li>
* The "provider" must implement methods {@code getStateInternal} and
* {@code setStateInternal} in order to save and restore the state of an
* instance (cf. {@link org.apache.commons.rng.core.BaseProvider}).
* </li>
* <li>
* When a new class is implemented here, user-access to it must be
* provided through associated {@code RandomSource} factory methods
* defined in module "commons-rng-simple".
* </li>
* </ul>
*/
package org.apache.commons.rng.core.source32;
| 3,131 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source32/MersenneTwister.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source32;
import java.util.Arrays;
import org.apache.commons.rng.core.util.NumberFactory;
/**
* This class implements a powerful pseudo-random number generator
* developed by Makoto Matsumoto and Takuji Nishimura during
* 1996-1997.
*
* <p>
* This generator features an extremely long period
* (2<sup>19937</sup>-1) and 623-dimensional equidistribution up to
* 32 bits accuracy. The home page for this generator is located at
* <a href="http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html">
* http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html</a>.
* </p>
*
* <p>
* This generator is described in a paper by Makoto Matsumoto and
* Takuji Nishimura in 1998:
* <a href="http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/ARTICLES/mt.pdf">
* Mersenne Twister: A 623-Dimensionally Equidistributed Uniform Pseudo-Random
* Number Generator</a>,
* ACM Transactions on Modeling and Computer Simulation, Vol. 8, No. 1,
* January 1998, pp 3--30
* </p>
*
* <p>
* This class is mainly a Java port of the
* <a href="http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html">
* 2002-01-26 version of the generator</a> written in C by Makoto Matsumoto
* and Takuji Nishimura. Here is their original copyright:
* </p>
*
* <table style="background-color: #E0E0E0; width: 80%">
* <caption>Mersenne Twister licence</caption>
* <tr><td style="padding: 10px">Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
* All rights reserved.</td></tr>
*
* <tr><td style="padding: 10px">Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* <ol>
* <li>Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.</li>
* <li>Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.</li>
* <li>The names of its contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.</li>
* </ol></td></tr>
*
* <tr><td style="padding: 10px"><strong>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.</strong></td></tr>
* </table>
*
* @see <a href="https://en.wikipedia.org/wiki/Mersenne_Twister">Mersenne Twister (Wikipedia)</a>
* @since 1.0
*/
public class MersenneTwister extends IntProvider {
/** Mask 32 most significant bits. */
private static final long INT_MASK_LONG = 0xffffffffL;
/** Most significant w-r bits. */
private static final long UPPER_MASK_LONG = 0x80000000L;
/** Least significant r bits. */
private static final long LOWER_MASK_LONG = 0x7fffffffL;
/** Most significant w-r bits. */
private static final int UPPER_MASK = 0x80000000;
/** Least significant r bits. */
private static final int LOWER_MASK = 0x7fffffff;
/** Size of the bytes pool. */
private static final int N = 624;
/** Period second parameter. */
private static final int M = 397;
/** X * MATRIX_A for X = {0, 1}. */
private static final int[] MAG01 = {0x0, 0x9908b0df};
/** Bytes pool. */
private final int[] mt = new int[N];
/** Current index in the bytes pool. */
private int mti;
/**
* Creates a new random number generator.
*
* @param seed Initial seed.
*/
public MersenneTwister(int[] seed) {
setSeedInternal(seed);
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
final int[] s = Arrays.copyOf(mt, N + 1);
s[N] = mti;
return composeStateInternal(NumberFactory.makeByteArray(s),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] c = splitStateInternal(s, (N + 1) * 4);
final int[] tmp = NumberFactory.makeIntArray(c[0]);
System.arraycopy(tmp, 0, mt, 0, N);
mti = tmp[N];
super.setStateInternal(c[1]);
}
/**
* Initializes the generator with the given seed.
*
* @param seed Initial seed.
*/
private void setSeedInternal(int[] seed) {
fillStateMersenneTwister(mt, seed);
// Initial index.
mti = N;
}
/**
* Utility for wholly filling a {@code state} array with non-zero
* bytes, even if the {@code seed} has a smaller size.
* The procedure is the one defined by the standard implementation
* of the algorithm.
*
* @param state State to be filled (must be allocated).
* @param inputSeed Seed (cannot be {@code null}).
*/
private static void fillStateMersenneTwister(int[] state,
int[] inputSeed) {
// Accept empty seed.
final int[] seed = (inputSeed.length == 0) ? new int[1] : inputSeed;
initializeState(state);
final int nextIndex = mixSeedAndState(state, seed);
mixState(state, nextIndex);
state[0] = (int) UPPER_MASK_LONG; // MSB is 1, ensuring non-zero initial array.
}
/**
* Fill the state using a defined pseudo-random sequence.
*
* @param state State to be filled (must be allocated).
*/
private static void initializeState(int[] state) {
long mt = 19650218 & INT_MASK_LONG;
state[0] = (int) mt;
for (int i = 1; i < state.length; i++) {
mt = (1812433253L * (mt ^ (mt >> 30)) + i) & INT_MASK_LONG;
state[i] = (int) mt;
}
}
/**
* Mix the seed into the state using a non-linear combination. The procedure
* uses {@code k} steps where {@code k = max(state.length, seed.length)}. If
* the seed is smaller than the state it is wrapped to obtain enough values.
* If the seed is larger than the state then the procedure visits entries in
* the state multiple times.
*
* <p>Returns the index immediately after the most recently visited position
* in the state array.</p>
*
* @param state State to be filled (must be allocated).
* @param seed Seed (must be at least length 1).
* @return the next index
*/
private static int mixSeedAndState(int[] state, final int[] seed) {
final int stateSize = state.length;
int i = 1;
int j = 0;
for (int k = Math.max(stateSize, seed.length); k > 0; k--) {
final long a = (state[i] & LOWER_MASK_LONG) | ((state[i] < 0) ? UPPER_MASK_LONG : 0);
final long b = (state[i - 1] & LOWER_MASK_LONG) | ((state[i - 1] < 0) ? UPPER_MASK_LONG : 0);
final long c = (a ^ ((b ^ (b >> 30)) * 1664525L)) + seed[j] + j; // Non linear.
state[i] = (int) (c & INT_MASK_LONG);
i++;
j++;
if (i >= stateSize) {
state[0] = state[stateSize - 1];
i = 1;
}
if (j >= seed.length) {
j = 0;
}
}
return i;
}
/**
* Mix each position of the state using a non-linear combination. The
* procedure starts from the specified index in the state array and wraps
* iteration through the array if required.
*
* @param state State to be filled (must be allocated).
* @param startIndex The index to begin within the state array.
*/
private static void mixState(int[] state, int startIndex) {
final int stateSize = state.length;
int i = startIndex;
for (int k = stateSize - 1; k > 0; k--) {
final long a = (state[i] & LOWER_MASK_LONG) | ((state[i] < 0) ? UPPER_MASK_LONG : 0);
final long b = (state[i - 1] & LOWER_MASK_LONG) | ((state[i - 1] < 0) ? UPPER_MASK_LONG : 0);
final long c = (a ^ ((b ^ (b >> 30)) * 1566083941L)) - i; // Non linear.
state[i] = (int) (c & INT_MASK_LONG);
i++;
if (i >= stateSize) {
state[0] = state[stateSize - 1];
i = 1;
}
}
}
/** {@inheritDoc} */
@Override
public int next() {
int y;
if (mti >= N) { // Generate N words at one time.
int mtNext = mt[0];
for (int k = 0; k < N - M; ++k) {
final int mtCurr = mtNext;
mtNext = mt[k + 1];
y = (mtCurr & UPPER_MASK) | (mtNext & LOWER_MASK);
mt[k] = mt[k + M] ^ (y >>> 1) ^ MAG01[y & 1];
}
for (int k = N - M; k < N - 1; ++k) {
final int mtCurr = mtNext;
mtNext = mt[k + 1];
y = (mtCurr & UPPER_MASK) | (mtNext & LOWER_MASK);
mt[k] = mt[k + (M - N)] ^ (y >>> 1) ^ MAG01[y & 1];
}
y = (mtNext & UPPER_MASK) | (mt[0] & LOWER_MASK);
mt[N - 1] = mt[M - 1] ^ (y >>> 1) ^ MAG01[y & 1];
mti = 0;
}
y = mt[mti++];
// Tempering.
y ^= y >>> 11;
y ^= (y << 7) & 0x9d2c5680;
y ^= (y << 15) & 0xefc60000;
y ^= y >>> 18;
return y;
}
}
| 3,132 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/XoRoShiRo128PlusPlus.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
import org.apache.commons.rng.JumpableUniformRandomProvider;
import org.apache.commons.rng.UniformRandomProvider;
/**
* A fast all-purpose 64-bit generator.
*
* <p>This is a member of the Xor-Shift-Rotate family of generators. Memory footprint is 128 bits
* and the period is 2<sup>128</sup>-1. Speed is expected to be similar to
* {@link XoShiRo256StarStar}.</p>
*
* @see <a href="http://xoshiro.di.unimi.it/xoroshiro128plusplus.c">Original source code</a>
* @see <a href="http://xoshiro.di.unimi.it/">xorshiro / xoroshiro generators</a>
* @since 1.3
*/
public class XoRoShiRo128PlusPlus extends AbstractXoRoShiRo128 {
/** The coefficients for the jump function. */
private static final long[] JUMP_COEFFICIENTS = {
0x2bd7a6a6e99c2ddcL, 0x0992ccaf6a6fca05L
};
/** The coefficients for the long jump function. */
private static final long[] LONG_JUMP_COEFFICIENTS = {
0x360fd5f2cf8d5d99L, 0x9c6e6877736c46e3L
};
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 2, only the first 2 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros will create a non-functional generator.
*/
public XoRoShiRo128PlusPlus(long[] seed) {
super(seed);
}
/**
* Creates a new instance using a 2 element seed.
* A seed containing all zeros will create a non-functional generator.
*
* @param seed0 Initial seed element 0.
* @param seed1 Initial seed element 1.
*/
public XoRoShiRo128PlusPlus(long seed0, long seed1) {
super(seed0, seed1);
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
protected XoRoShiRo128PlusPlus(XoRoShiRo128PlusPlus source) {
super(source);
}
/** {@inheritDoc} */
@Override
public long next() {
// Override the abstract class to use a different state update step.
// Note: This requires different jump coefficients.
final long s0 = state0;
long s1 = state1;
final long result = Long.rotateLeft(s0 + s1, 17) + s0;
s1 ^= s0;
state0 = Long.rotateLeft(s0, 49) ^ s1 ^ (s1 << 21); // a, b
state1 = Long.rotateLeft(s1, 28); // c
return result;
}
/** {@inheritDoc} */
@Override
protected long nextOutput() {
throw new UnsupportedOperationException("The PlusPlus algorithm redefines the next() method");
}
/** {@inheritDoc} */
@Override
public UniformRandomProvider jump() {
// Duplicated from the abstract class to change the jump coefficients
final UniformRandomProvider copy = copy();
performJump(JUMP_COEFFICIENTS);
return copy;
}
/** {@inheritDoc} */
@Override
public JumpableUniformRandomProvider longJump() {
// Duplicated from the abstract class to change the jump coefficients
final JumpableUniformRandomProvider copy = copy();
performJump(LONG_JUMP_COEFFICIENTS);
return copy;
}
/** {@inheritDoc} */
@Override
protected XoRoShiRo128PlusPlus copy() {
// This exists to ensure the jump function performed in the super class returns
// the correct class type. It should not be public.
return new XoRoShiRo128PlusPlus(this);
}
}
| 3,133 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/XoShiRo256PlusPlus.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
/**
* A fast all-purpose 64-bit generator.
*
* <p>This is a member of the Xor-Shift-Rotate family of generators. Memory footprint is 256 bits
* and the period is 2<sup>256</sup>-1.</p>
*
* @see <a href="http://xoshiro.di.unimi.it/xoshiro256starstar.c">Original source code</a>
* @see <a href="http://xoshiro.di.unimi.it/">xorshiro / xoroshiro generators</a>
* @since 1.3
*/
public class XoShiRo256PlusPlus extends AbstractXoShiRo256 {
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 4, only the first 4 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros will create a non-functional generator.
*/
public XoShiRo256PlusPlus(long[] seed) {
super(seed);
}
/**
* Creates a new instance using a 4 element seed.
* A seed containing all zeros will create a non-functional generator.
*
* @param seed0 Initial seed element 0.
* @param seed1 Initial seed element 1.
* @param seed2 Initial seed element 2.
* @param seed3 Initial seed element 3.
*/
public XoShiRo256PlusPlus(long seed0, long seed1, long seed2, long seed3) {
super(seed0, seed1, seed2, seed3);
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
protected XoShiRo256PlusPlus(XoShiRo256PlusPlus source) {
super(source);
}
/** {@inheritDoc} */
@Override
protected long nextOutput() {
return Long.rotateLeft(state0 + state3, 23) + state0;
}
/** {@inheritDoc} */
@Override
protected XoShiRo256PlusPlus copy() {
// This exists to ensure the jump function performed in the super class returns
// the correct class type. It should not be public.
return new XoShiRo256PlusPlus(this);
}
}
| 3,134 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/L128X1024Mix.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
import java.util.stream.Stream;
import org.apache.commons.rng.JumpableUniformRandomProvider;
import org.apache.commons.rng.SplittableUniformRandomProvider;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.core.util.NumberFactory;
import org.apache.commons.rng.core.util.RandomStreams;
/**
* A 64-bit all purpose generator.
*
* <p>This is a member of the LXM family of generators: L=Linear congruential generator;
* X=Xor based generator; and M=Mix. This member uses a 128-bit LCG and 1024-bit Xor-based
* generator. It is named as {@code "L128X1024MixRandom"} in the {@code java.util.random}
* package introduced in JDK 17; the LXM family is described in further detail in:
*
* <blockquote>Steele and Vigna (2021) LXM: better splittable pseudorandom number generators
* (and almost as fast). Proceedings of the ACM on Programming Languages, Volume 5,
* Article 148, pp 1–31.</blockquote>
*
* <p>Memory footprint is 1312 bits and the period is 2<sup>128</sup> (2<sup>1024</sup> - 1).
*
* <p>This generator implements
* {@link org.apache.commons.rng.LongJumpableUniformRandomProvider LongJumpableUniformRandomProvider}.
* In addition instances created with a different additive parameter for the LCG are robust
* against accidental correlation in a multi-threaded setting. The additive parameters must be
* different in the most significant 127-bits.
*
* <p>This generator implements
* {@link org.apache.commons.rng.SplittableUniformRandomProvider SplittableUniformRandomProvider}.
* The stream of generators created using the {@code splits} methods support parallelisation
* and are robust against accidental correlation by using unique values for the additive parameter
* for each instance in the same stream. The primitive streaming methods support parallelisation
* but with no assurances of accidental correlation; each thread uses a new instance with a
* randomly initialised state.
*
* @see <a href="https://doi.org/10.1145/3485525">Steele & Vigna (2021) Proc. ACM Programming
* Languages 5, 1-31</a>
* @see <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/random/package-summary.html">
* JDK 17 java.util.random javadoc</a>
* @since 1.5
*/
public class L128X1024Mix extends AbstractL128 implements SplittableUniformRandomProvider {
/** Size of the seed vector. */
private static final int SEED_SIZE = 20;
/** Size of the XBG state vector. */
private static final int XBG_STATE_SIZE = 16;
/** Size of the LCG state vector. */
private static final int LCG_STATE_SIZE = SEED_SIZE - XBG_STATE_SIZE;
/** Low half of 128-bit LCG multiplier. */
private static final long ML = LXMSupport.M128L;
/** State of the XBG. */
private final long[] x = new long[XBG_STATE_SIZE];
/** Index in "state" array. */
private int index;
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 20, only the first 20 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros in the last 16 elements
* will create a non-functional XBG sub-generator and a low
* quality output with a period of 2<sup>128</sup>.
*
* <p>The 1st and 2nd elements are used to set the LCG increment; the least significant bit
* is set to odd to ensure a full period LCG. The 3rd and 4th elements are used
* to set the LCG state.</p>
*/
public L128X1024Mix(long[] seed) {
super(seed = extendSeed(seed, SEED_SIZE));
System.arraycopy(seed, SEED_SIZE - XBG_STATE_SIZE, x, 0, XBG_STATE_SIZE);
// Initialising to 15 ensures that (index + 1) % 16 == 0 and the
// first state picked from the XBG generator is state[0].
index = XBG_STATE_SIZE - 1;
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
protected L128X1024Mix(L128X1024Mix source) {
super(source);
System.arraycopy(source.x, 0, x, 0, XBG_STATE_SIZE);
index = source.index;
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
final long[] s = new long[XBG_STATE_SIZE + 1];
System.arraycopy(x, 0, s, 0, XBG_STATE_SIZE);
s[XBG_STATE_SIZE] = index;
return composeStateInternal(NumberFactory.makeByteArray(s),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] c = splitStateInternal(s, (XBG_STATE_SIZE + 1) * Long.BYTES);
final long[] tmp = NumberFactory.makeLongArray(c[0]);
System.arraycopy(tmp, 0, x, 0, XBG_STATE_SIZE);
index = (int) tmp[XBG_STATE_SIZE];
super.setStateInternal(c[1]);
}
/** {@inheritDoc} */
@Override
public long next() {
// LXM generate.
// Old state is used for the output allowing parallel pipelining
// on processors that support multiple concurrent instructions.
final int q = index;
index = (q + 1) & 15;
final long s0 = x[index];
long s15 = x[q];
final long sh = lsh;
// Mix
final long z = LXMSupport.lea64(sh + s0);
// LCG update
// The LCG is, in effect, "s = m * s + a" where m = ((1LL << 64) + ML)
final long sl = lsl;
final long al = lal;
final long u = ML * sl;
// High half
lsh = ML * sh + LXMSupport.unsignedMultiplyHigh(ML, sl) + sl + lah +
// Carry propagation
LXMSupport.unsignedAddHigh(u, al);
// Low half
lsl = u + al;
// XBG update
s15 ^= s0;
x[q] = Long.rotateLeft(s0, 25) ^ s15 ^ (s15 << 27);
x[index] = Long.rotateLeft(s15, 36);
return z;
}
/**
* {@inheritDoc}
*
* <p>The jump size is the equivalent of moving the state <em>backwards</em> by
* (2<sup>1024</sup> - 1) positions. It can provide up to 2<sup>128</sup>
* non-overlapping subsequences.
*/
@Override
public UniformRandomProvider jump() {
return super.jump();
}
/**
* {@inheritDoc}
*
* <p>The jump size is the equivalent of moving the state <em>backwards</em> by
* 2<sup>64</sup> (2<sup>1024</sup> - 1) positions. It can provide up to
* 2<sup>64</sup> non-overlapping subsequences of length 2<sup>64</sup>
* (2<sup>1024</sup> - 1); each subsequence can provide up to 2<sup>64</sup>
* non-overlapping subsequences of length (2<sup>1024</sup> - 1) using the
* {@link #jump()} method.
*/
@Override
public JumpableUniformRandomProvider longJump() {
return super.longJump();
}
/** {@inheritDoc} */
@Override
AbstractL128 copy() {
// This exists to ensure the jump function performed in the super class returns
// the correct class type. It should not be public.
return new L128X1024Mix(this);
}
/** {@inheritDoc} */
@Override
public SplittableUniformRandomProvider split(UniformRandomProvider source) {
return create(source.nextLong(), source);
}
/** {@inheritDoc} */
@Override
public Stream<SplittableUniformRandomProvider> splits(long streamSize, SplittableUniformRandomProvider source) {
return RandomStreams.generateWithSeed(streamSize, source, L128X1024Mix::create);
}
/**
* Create a new instance using the given {@code seed} and {@code source} of randomness
* to initialise the instance.
*
* @param seed Seed used to initialise the instance.
* @param source Source of randomness used to initialise the instance.
* @return A new instance.
*/
private static SplittableUniformRandomProvider create(long seed, UniformRandomProvider source) {
final long[] s = new long[SEED_SIZE];
// LCG state. The addition lower-half uses the input seed.
// The LCG addition parameter is set to odd so left-shift the seed.
s[0] = source.nextLong();
s[1] = seed << 1;
s[2] = source.nextLong();
s[3] = source.nextLong();
// XBG state must not be all zero
long x = 0;
for (int i = LCG_STATE_SIZE; i < s.length; i++) {
s[i] = source.nextLong();
x |= s[i];
}
if (x == 0) {
// SplitMix style seed ensures at least one non-zero value
x = s[LCG_STATE_SIZE - 1];
for (int i = LCG_STATE_SIZE; i < s.length; i++) {
s[i] = LXMSupport.lea64(x);
x += LXMSupport.GOLDEN_RATIO_64;
}
}
return new L128X1024Mix(s);
}
}
| 3,135 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/XoShiRo256StarStar.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
/**
* A fast all-purpose 64-bit generator.
*
* <p>This is a member of the Xor-Shift-Rotate family of generators. Memory footprint is 256 bits
* and the period is 2<sup>256</sup>-1.</p>
*
* @see <a href="http://xoshiro.di.unimi.it/xoshiro256starstar.c">Original source code</a>
* @see <a href="http://xoshiro.di.unimi.it/">xorshiro / xoroshiro generators</a>
* @since 1.3
*/
public class XoShiRo256StarStar extends AbstractXoShiRo256 {
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 4, only the first 4 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros will create a non-functional generator.
*/
public XoShiRo256StarStar(long[] seed) {
super(seed);
}
/**
* Creates a new instance using a 4 element seed.
* A seed containing all zeros will create a non-functional generator.
*
* @param seed0 Initial seed element 0.
* @param seed1 Initial seed element 1.
* @param seed2 Initial seed element 2.
* @param seed3 Initial seed element 3.
*/
public XoShiRo256StarStar(long seed0, long seed1, long seed2, long seed3) {
super(seed0, seed1, seed2, seed3);
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
protected XoShiRo256StarStar(XoShiRo256StarStar source) {
super(source);
}
/** {@inheritDoc} */
@Override
protected long nextOutput() {
return Long.rotateLeft(state1 * 5, 7) * 9;
}
/** {@inheritDoc} */
@Override
protected XoShiRo256StarStar copy() {
// This exists to ensure the jump function performed in the super class returns
// the correct class type. It should not be public.
return new XoShiRo256StarStar(this);
}
}
| 3,136 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/AbstractXoShiRo256.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
import org.apache.commons.rng.JumpableUniformRandomProvider;
import org.apache.commons.rng.LongJumpableUniformRandomProvider;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.core.util.NumberFactory;
/**
* This abstract class is a base for algorithms from the Xor-Shift-Rotate family of 64-bit
* generators with 256-bits of state.
*
* @see <a href="http://xoshiro.di.unimi.it/">xorshiro / xoroshiro generators</a>
* @since 1.3
*/
abstract class AbstractXoShiRo256 extends LongProvider implements LongJumpableUniformRandomProvider {
/** Size of the state vector. */
private static final int SEED_SIZE = 4;
/** The coefficients for the jump function. */
private static final long[] JUMP_COEFFICIENTS = {
0x180ec6d33cfd0abaL, 0xd5a61266f0c9392cL, 0xa9582618e03fc9aaL, 0x39abdc4529b1661cL
};
/** The coefficients for the long jump function. */
private static final long[] LONG_JUMP_COEFFICIENTS = {
0x76e15d3efefdcbbfL, 0xc5004e441c522fb3L, 0x77710069854ee241L, 0x39109bb02acbe635L
};
// State is maintained using variables rather than an array for performance
/** State 0 of the generator. */
protected long state0;
/** State 1 of the generator. */
protected long state1;
/** State 2 of the generator. */
protected long state2;
/** State 3 of the generator. */
protected long state3;
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 4, only the first 4 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros will create a non-functional generator.
*/
AbstractXoShiRo256(long[] seed) {
if (seed.length < SEED_SIZE) {
final long[] state = new long[SEED_SIZE];
fillState(state, seed);
setState(state);
} else {
setState(seed);
}
}
/**
* Creates a new instance using a 4 element seed.
* A seed containing all zeros will create a non-functional generator.
*
* @param seed0 Initial seed element 0.
* @param seed1 Initial seed element 1.
* @param seed2 Initial seed element 2.
* @param seed3 Initial seed element 3.
*/
AbstractXoShiRo256(long seed0, long seed1, long seed2, long seed3) {
state0 = seed0;
state1 = seed1;
state2 = seed2;
state3 = seed3;
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
protected AbstractXoShiRo256(AbstractXoShiRo256 source) {
super(source);
state0 = source.state0;
state1 = source.state1;
state2 = source.state2;
state3 = source.state3;
}
/**
* Copies the state from the array into the generator state.
*
* @param state the new state
*/
private void setState(long[] state) {
state0 = state[0];
state1 = state[1];
state2 = state[2];
state3 = state[3];
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
return composeStateInternal(NumberFactory.makeByteArray(
new long[] {state0, state1, state2, state3}),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] c = splitStateInternal(s, SEED_SIZE * 8);
setState(NumberFactory.makeLongArray(c[0]));
super.setStateInternal(c[1]);
}
/** {@inheritDoc} */
@Override
public long next() {
final long result = nextOutput();
final long t = state1 << 17;
state2 ^= state0;
state3 ^= state1;
state1 ^= state2;
state0 ^= state3;
state2 ^= t;
state3 = Long.rotateLeft(state3, 45);
return result;
}
/**
* Use the current state to compute the next output from the generator.
* The output function shall vary with respect to different generators.
* This method is called from {@link #next()} before the current state is updated.
*
* @return the next output
*/
protected abstract long nextOutput();
/**
* {@inheritDoc}
*
* <p>The jump size is the equivalent of 2<sup>128</sup>
* calls to {@link UniformRandomProvider#nextLong() nextLong()}. It can provide
* up to 2<sup>128</sup> non-overlapping subsequences.</p>
*/
@Override
public UniformRandomProvider jump() {
final UniformRandomProvider copy = copy();
performJump(JUMP_COEFFICIENTS);
return copy;
}
/**
* {@inheritDoc}
*
* <p>The jump size is the equivalent of 2<sup>192</sup> calls to
* {@link UniformRandomProvider#nextLong() nextLong()}. It can provide up to
* 2<sup>64</sup> non-overlapping subsequences of length 2<sup>192</sup>; each
* subsequence can provide up to 2<sup>64</sup> non-overlapping subsequences of
* length 2<sup>128</sup> using the {@link #jump()} method.</p>
*/
@Override
public JumpableUniformRandomProvider longJump() {
final JumpableUniformRandomProvider copy = copy();
performJump(LONG_JUMP_COEFFICIENTS);
return copy;
}
/**
* Create a copy.
*
* @return the copy
*/
protected abstract AbstractXoShiRo256 copy();
/**
* Perform the jump to advance the generator state. Resets the cached state of the generator.
*
* @param jumpCoefficients Jump coefficients.
*/
private void performJump(long[] jumpCoefficients) {
long s0 = 0;
long s1 = 0;
long s2 = 0;
long s3 = 0;
for (final long jc : jumpCoefficients) {
for (int b = 0; b < 64; b++) {
if ((jc & (1L << b)) != 0) {
s0 ^= state0;
s1 ^= state1;
s2 ^= state2;
s3 ^= state3;
}
next();
}
}
state0 = s0;
state1 = s1;
state2 = s2;
state3 = s3;
resetCachedState();
}
}
| 3,137 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/XoRoShiRo128StarStar.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
/**
* A fast all-purpose 64-bit generator.
*
* <p>This is a member of the Xor-Shift-Rotate family of generators. Memory footprint is 128 bits
* and the period is 2<sup>128</sup>-1. Speed is expected to be similar to
* {@link XoShiRo256StarStar}.</p>
*
* @see <a href="http://xoshiro.di.unimi.it/xoroshiro128starstar.c">Original source code</a>
* @see <a href="http://xoshiro.di.unimi.it/">xorshiro / xoroshiro generators</a>
* @since 1.3
*/
public class XoRoShiRo128StarStar extends AbstractXoRoShiRo128 {
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 2, only the first 2 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros will create a non-functional generator.
*/
public XoRoShiRo128StarStar(long[] seed) {
super(seed);
}
/**
* Creates a new instance using a 2 element seed.
* A seed containing all zeros will create a non-functional generator.
*
* @param seed0 Initial seed element 0.
* @param seed1 Initial seed element 1.
*/
public XoRoShiRo128StarStar(long seed0, long seed1) {
super(seed0, seed1);
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
protected XoRoShiRo128StarStar(XoRoShiRo128StarStar source) {
super(source);
}
/** {@inheritDoc} */
@Override
protected long nextOutput() {
return Long.rotateLeft(state0 * 5, 7) * 9;
}
/** {@inheritDoc} */
@Override
protected XoRoShiRo128StarStar copy() {
// This exists to ensure the jump function performed in the super class returns
// the correct class type. It should not be public.
return new XoRoShiRo128StarStar(this);
}
}
| 3,138 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/XorShift1024Star.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
import java.util.Arrays;
import org.apache.commons.rng.JumpableUniformRandomProvider;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.core.util.NumberFactory;
/**
* A fast RNG implementing the {@code XorShift1024*} algorithm.
*
* <p>Note: This has been superseded by {@link XorShift1024StarPhi}. The sequences emitted
* by both generators are correlated.</p>
*
* @see <a href="http://xorshift.di.unimi.it/xorshift1024star.c">Original source code</a>
* @see <a href="https://en.wikipedia.org/wiki/Xorshift">Xorshift (Wikipedia)</a>
* @since 1.0
*/
public class XorShift1024Star extends LongProvider implements JumpableUniformRandomProvider {
/** Size of the state vector. */
private static final int SEED_SIZE = 16;
/** The coefficients for the jump function. */
private static final long[] JUMP_COEFFICIENTS = {
0x84242f96eca9c41dL, 0xa3c65b8776f96855L, 0x5b34a39f070b5837L, 0x4489affce4f31a1eL,
0x2ffeeb0a48316f40L, 0xdc2d9891fe68c022L, 0x3659132bb12fea70L, 0xaac17d8efa43cab8L,
0xc4cb815590989b13L, 0x5ee975283d71c93bL, 0x691548c86c1bd540L, 0x7910c41d10a1e6a5L,
0x0b5fc64563b3e2a8L, 0x047f7684e9fc949dL, 0xb99181f2d8f685caL, 0x284600e3f30e38c3L
};
/** State. */
private final long[] state = new long[SEED_SIZE];
/** The multiplier for the XorShift1024 algorithm. */
private final long multiplier;
/** Index in "state" array. */
private int index;
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 16, only the first 16 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros will create a non-functional generator.
*/
public XorShift1024Star(long[] seed) {
this(seed, 1181783497276652981L);
}
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 16, only the first 16 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros will create a non-functional generator.
* @param multiplier The multiplier for the XorShift1024 algorithm.
* @since 1.3
*/
protected XorShift1024Star(long[] seed, long multiplier) {
setSeedInternal(seed);
this.multiplier = multiplier;
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
* @since 1.3
*/
protected XorShift1024Star(XorShift1024Star source) {
super(source);
System.arraycopy(source.state, 0, state, 0, SEED_SIZE);
multiplier = source.multiplier;
index = source.index;
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
final long[] s = Arrays.copyOf(state, SEED_SIZE + 1);
s[SEED_SIZE] = index;
return composeStateInternal(NumberFactory.makeByteArray(s),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] c = splitStateInternal(s, (SEED_SIZE + 1) * 8);
final long[] tmp = NumberFactory.makeLongArray(c[0]);
System.arraycopy(tmp, 0, state, 0, SEED_SIZE);
index = (int) tmp[SEED_SIZE];
super.setStateInternal(c[1]);
}
/**
* Seeds the RNG.
*
* @param seed Seed.
*/
private void setSeedInternal(long[] seed) {
// Reset the whole state of this RNG (i.e. "state" and "index").
// Filling procedure is not part of the reference code.
fillState(state, seed);
index = 0;
}
/** {@inheritDoc} */
@Override
public long next() {
final long s0 = state[index];
index = (index + 1) & 15;
long s1 = state[index];
s1 ^= s1 << 31; // a
state[index] = s1 ^ s0 ^ (s1 >>> 11) ^ (s0 >>> 30); // b,c
return state[index] * multiplier;
}
/**
* {@inheritDoc}
*
* <p>The jump size is the equivalent of 2<sup>512</sup>
* calls to {@link UniformRandomProvider#nextLong() nextLong()}. It can provide
* up to 2<sup>512</sup> non-overlapping subsequences.</p>
*
* @since 1.3
*/
@Override
public UniformRandomProvider jump() {
final UniformRandomProvider copy = copy();
performJump();
return copy;
}
/**
* Create a copy.
*
* @return the copy
* @since 1.3
*/
protected XorShift1024Star copy() {
// This exists to ensure the jump function returns
// the correct class type. It should not be public.
return new XorShift1024Star(this);
}
/**
* Perform the jump to advance the generator state. Resets the cached state of the generator.
*/
private void performJump() {
final long[] newState = new long[SEED_SIZE];
for (final long jc : JUMP_COEFFICIENTS) {
for (int b = 0; b < 64; b++) {
if ((jc & (1L << b)) != 0) {
for (int i = 0; i < SEED_SIZE; i++) {
newState[i] ^= state[(i + index) & 15];
}
}
next();
}
}
for (int j = 0; j < 16; j++) {
state[(j + index) & 15] = newState[j];
}
resetCachedState();
}
}
| 3,139 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/XoRoShiRo128Plus.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
/**
* A fast 64-bit generator suitable for {@code double} generation. This is slightly faster than the
* all-purpose generator {@link XoRoShiRo128StarStar}.
*
* <p>This is a member of the Xor-Shift-Rotate family of generators. Memory footprint is 128 bits
* and the period is 2<sup>128</sup>-1. Speed is expected to be similar to
* {@link XoShiRo256Plus}.</p>
*
* @see <a href="http://xoshiro.di.unimi.it/xoroshiro128plus.c">Original source code</a>
* @see <a href="http://xoshiro.di.unimi.it/">xorshiro / xoroshiro generators</a>
* @since 1.3
*/
public class XoRoShiRo128Plus extends AbstractXoRoShiRo128 {
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 2, only the first 2 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros will create a non-functional generator.
*/
public XoRoShiRo128Plus(long[] seed) {
super(seed);
}
/**
* Creates a new instance using a 2 element seed.
* A seed containing all zeros will create a non-functional generator.
*
* @param seed0 Initial seed element 0.
* @param seed1 Initial seed element 1.
*/
public XoRoShiRo128Plus(long seed0, long seed1) {
super(seed0, seed1);
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
protected XoRoShiRo128Plus(XoRoShiRo128Plus source) {
super(source);
}
/** {@inheritDoc} */
@Override
protected long nextOutput() {
return state0 + state1;
}
/** {@inheritDoc} */
@Override
protected XoRoShiRo128Plus copy() {
// This exists to ensure the jump function performed in the super class returns
// the correct class type. It should not be public.
return new XoRoShiRo128Plus(this);
}
}
| 3,140 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/AbstractXoShiRo512.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
import org.apache.commons.rng.JumpableUniformRandomProvider;
import org.apache.commons.rng.LongJumpableUniformRandomProvider;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.core.util.NumberFactory;
/**
* This abstract class is a base for algorithms from the Xor-Shift-Rotate family of 64-bit
* generators with 512-bits of state.
*
* @see <a href="http://xoshiro.di.unimi.it/">xorshiro / xoroshiro generators</a>
* @since 1.3
*/
abstract class AbstractXoShiRo512 extends LongProvider implements LongJumpableUniformRandomProvider {
/** Size of the state vector. */
private static final int SEED_SIZE = 8;
/** The coefficients for the jump function. */
private static final long[] JUMP_COEFFICIENTS = {
0x33ed89b6e7a353f9L, 0x760083d7955323beL, 0x2837f2fbb5f22faeL, 0x4b8c5674d309511cL,
0xb11ac47a7ba28c25L, 0xf1be7667092bcc1cL, 0x53851efdb6df0aafL, 0x1ebbc8b23eaf25dbL
};
/** The coefficients for the long jump function. */
private static final long[] LONG_JUMP_COEFFICIENTS = {
0x11467fef8f921d28L, 0xa2a819f2e79c8ea8L, 0xa8299fc284b3959aL, 0xb4d347340ca63ee1L,
0x1cb0940bedbff6ceL, 0xd956c5c4fa1f8e17L, 0x915e38fd4eda93bcL, 0x5b3ccdfa5d7daca5L
};
// State is maintained using variables rather than an array for performance
/** State 0 of the generator. */
protected long state0;
/** State 1 of the generator. */
protected long state1;
/** State 2 of the generator. */
protected long state2;
/** State 3 of the generator. */
protected long state3;
/** State 4 of the generator. */
protected long state4;
/** State 5 of the generator. */
protected long state5;
/** State 6 of the generator. */
protected long state6;
/** State 7 of the generator. */
protected long state7;
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 8, only the first 8 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros will create a non-functional generator.
*/
AbstractXoShiRo512(long[] seed) {
if (seed.length < SEED_SIZE) {
final long[] state = new long[SEED_SIZE];
fillState(state, seed);
setState(state);
} else {
setState(seed);
}
}
/**
* Creates a new instance using an 8 element seed.
* A seed containing all zeros will create a non-functional generator.
*
* @param seed0 Initial seed element 0.
* @param seed1 Initial seed element 1.
* @param seed2 Initial seed element 2.
* @param seed3 Initial seed element 3.
* @param seed4 Initial seed element 4.
* @param seed5 Initial seed element 5.
* @param seed6 Initial seed element 6.
* @param seed7 Initial seed element 7.
*/
AbstractXoShiRo512(long seed0, long seed1, long seed2, long seed3,
long seed4, long seed5, long seed6, long seed7) {
state0 = seed0;
state1 = seed1;
state2 = seed2;
state3 = seed3;
state4 = seed4;
state5 = seed5;
state6 = seed6;
state7 = seed7;
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
protected AbstractXoShiRo512(AbstractXoShiRo512 source) {
super(source);
state0 = source.state0;
state1 = source.state1;
state2 = source.state2;
state3 = source.state3;
state4 = source.state4;
state5 = source.state5;
state6 = source.state6;
state7 = source.state7;
}
/**
* Copies the state from the array into the generator state.
*
* @param state the new state
*/
private void setState(long[] state) {
state0 = state[0];
state1 = state[1];
state2 = state[2];
state3 = state[3];
state4 = state[4];
state5 = state[5];
state6 = state[6];
state7 = state[7];
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
return composeStateInternal(NumberFactory.makeByteArray(
new long[] {state0, state1, state2, state3,
state4, state5, state6, state7}),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] c = splitStateInternal(s, SEED_SIZE * 8);
setState(NumberFactory.makeLongArray(c[0]));
super.setStateInternal(c[1]);
}
/** {@inheritDoc} */
@Override
public long next() {
final long result = nextOutput();
final long t = state1 << 11;
state2 ^= state0;
state5 ^= state1;
state1 ^= state2;
state7 ^= state3;
state3 ^= state4;
state4 ^= state5;
state0 ^= state6;
state6 ^= state7;
state6 ^= t;
state7 = Long.rotateLeft(state7, 21);
return result;
}
/**
* Use the current state to compute the next output from the generator.
* The output function shall vary with respect to different generators.
* This method is called from {@link #next()} before the current state is updated.
*
* @return the next output
*/
protected abstract long nextOutput();
/**
* {@inheritDoc}
*
* <p>The jump size is the equivalent of 2<sup>256</sup>
* calls to {@link UniformRandomProvider#nextLong() nextLong()}. It can provide
* up to 2<sup>256</sup> non-overlapping subsequences.</p>
*/
@Override
public UniformRandomProvider jump() {
final UniformRandomProvider copy = copy();
performJump(JUMP_COEFFICIENTS);
return copy;
}
/**
* {@inheritDoc}
*
* <p>The jump size is the equivalent of 2<sup>384</sup> calls to
* {@link UniformRandomProvider#nextLong() nextLong()}. It can provide up to
* 2<sup>128</sup> non-overlapping subsequences of length 2<sup>384</sup>; each
* subsequence can provide up to 2<sup>128</sup> non-overlapping subsequences of
* length 2<sup>256</sup> using the {@link #jump()} method.</p>
*/
@Override
public JumpableUniformRandomProvider longJump() {
final JumpableUniformRandomProvider copy = copy();
performJump(LONG_JUMP_COEFFICIENTS);
return copy;
}
/**
* Create a copy.
*
* @return the copy
*/
protected abstract AbstractXoShiRo512 copy();
/**
* Perform the jump to advance the generator state. Resets the cached state of the generator.
*
* @param jumpCoefficients Jump coefficients.
*/
private void performJump(long[] jumpCoefficients) {
long s0 = 0;
long s1 = 0;
long s2 = 0;
long s3 = 0;
long s4 = 0;
long s5 = 0;
long s6 = 0;
long s7 = 0;
for (final long jc : jumpCoefficients) {
for (int b = 0; b < 64; b++) {
if ((jc & (1L << b)) != 0) {
s0 ^= state0;
s1 ^= state1;
s2 ^= state2;
s3 ^= state3;
s4 ^= state4;
s5 ^= state5;
s6 ^= state6;
s7 ^= state7;
}
next();
}
}
state0 = s0;
state1 = s1;
state2 = s2;
state3 = s3;
state4 = s4;
state5 = s5;
state6 = s6;
state7 = s7;
resetCachedState();
}
}
| 3,141 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/PcgRxsMXs64.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
import org.apache.commons.rng.core.util.NumberFactory;
/**
* A Permuted Congruential Generator (PCG) that is composed of a 64-bit Linear Congruential
* Generator (LCG) combined with the RXS-M-XS (random xorshift; multiply; xorshift) output
* transformation to create 64-bit output.
*
* <p>State size is 128 bits and the period is 2<sup>64</sup>.</p>
*
* <p><strong>Note:</strong> Although the seed size is 128 bits, only the first 64 are
* effective: in effect, two seeds that only differ by the last 64 bits may produce
* highly correlated sequences.
*
* @see <a href="http://www.pcg-random.org/">
* PCG, A Family of Better Random Number Generators</a>
* @since 1.3
*/
public class PcgRxsMXs64 extends LongProvider {
/** Size of the seed array. */
private static final int SEED_SIZE = 2;
/** The default increment. */
private static final long DEFAULT_INCREMENT = 1442695040888963407L;
/** The state of the LCG. */
private long state;
/** The increment of the LCG. */
private long increment;
/**
* Creates a new instance using a default increment.
*
* @param seed Initial state.
* @since 1.4
*/
public PcgRxsMXs64(Long seed) {
increment = DEFAULT_INCREMENT;
state = bump(seed + this.increment);
}
/**
* Creates a new instance.
*
* <p><strong>Note:</strong> Although the seed size is 128 bits, only the first 64 are
* effective: in effect, two seeds that only differ by the last 64 bits may produce
* highly correlated sequences.
*
* @param seed Initial seed.
* If the length is larger than 2, only the first 2 elements will
* be used; if smaller, the remaining elements will be automatically set.
*
* <p>The 1st element is used to set the LCG state. The 2nd element is used
* to set the LCG increment; the most significant bit
* is discarded by left shift and the increment is set to odd.</p>
*/
public PcgRxsMXs64(long[] seed) {
if (seed.length < SEED_SIZE) {
final long[] tmp = new long[SEED_SIZE];
fillState(tmp, seed);
setSeedInternal(tmp);
} else {
setSeedInternal(seed);
}
}
/**
* Seeds the RNG.
*
* @param seed Seed.
*/
private void setSeedInternal(long[] seed) {
// Ensure the increment is odd to provide a maximal period LCG.
this.increment = (seed[1] << 1) | 1;
this.state = bump(seed[0] + this.increment);
}
/**
* Provides the next state of the LCG.
*
* @param input Current state.
* @return next state
*/
private long bump(long input) {
return input * 6364136223846793005L + increment;
}
/** {@inheritDoc} */
@Override
public long next() {
final long x = state;
state = bump(state);
final long word = ((x >>> ((x >>> 59) + 5)) ^ x) * -5840758589994634535L;
return (word >>> 43) ^ word;
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
// The increment is divided by 2 before saving.
// This transform is used in the reference PCG code; it prevents restoring from
// a byte state a non-odd increment that results in a sub-maximal period generator.
return composeStateInternal(NumberFactory.makeByteArray(
new long[] {state, increment >>> 1}),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] c = splitStateInternal(s, SEED_SIZE * 8);
final long[] tempseed = NumberFactory.makeLongArray(c[0]);
state = tempseed[0];
// Reverse the transform performed during getState to make the increment odd again.
increment = tempseed[1] << 1 | 1;
super.setStateInternal(c[1]);
}
}
| 3,142 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/SplitMix64.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
import org.apache.commons.rng.core.util.NumberFactory;
/**
* A fast RNG, with 64 bits of state, that can be used to initialize the
* state of other generators.
*
* @see <a href="http://xorshift.di.unimi.it/splitmix64.c">
* Original source code</a>
*
* @since 1.0
*/
public class SplitMix64 extends LongProvider {
/** State. */
private long state;
/**
* Creates a new instance.
*
* @param seed Initial seed.
* @since 1.3
*/
public SplitMix64(long seed) {
state = seed;
}
/**
* Creates a new instance.
*
* @param seed Initial seed.
*/
public SplitMix64(Long seed) {
// Support for Long to allow instantiation through the
// rng.simple.RandomSource factory methods.
setSeedInternal(seed);
}
/**
* Seeds the RNG.
*
* @param seed Seed.
*/
private void setSeedInternal(Long seed) {
state = seed.longValue();
}
/** {@inheritDoc} */
@Override
public long next() {
long z = state += 0x9e3779b97f4a7c15L;
z = (z ^ (z >>> 30)) * 0xbf58476d1ce4e5b9L;
z = (z ^ (z >>> 27)) * 0x94d049bb133111ebL;
return z ^ (z >>> 31);
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
return composeStateInternal(NumberFactory.makeByteArray(state),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] c = splitStateInternal(s, 8);
state = NumberFactory.makeLong(c[0]);
super.setStateInternal(c[1]);
}
}
| 3,143 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/AbstractXoRoShiRo128.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
import org.apache.commons.rng.JumpableUniformRandomProvider;
import org.apache.commons.rng.LongJumpableUniformRandomProvider;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.core.util.NumberFactory;
/**
* This abstract class is a base for algorithms from the Xor-Shift-Rotate family of 64-bit
* generators with 128-bits of state.
*
* @see <a href="http://xoshiro.di.unimi.it/">xorshiro / xoroshiro generators</a>
* @since 1.3
*/
abstract class AbstractXoRoShiRo128 extends LongProvider implements LongJumpableUniformRandomProvider {
/** Size of the state vector. */
private static final int SEED_SIZE = 2;
/** The coefficients for the jump function. */
private static final long[] JUMP_COEFFICIENTS = {
0xdf900294d8f554a5L, 0x170865df4b3201fcL
};
/** The coefficients for the long jump function. */
private static final long[] LONG_JUMP_COEFFICIENTS = {
0xd2a98b26625eee7bL, 0xdddf9b1090aa7ac1L
};
// State is maintained using variables rather than an array for performance
/** State 0 of the generator. */
protected long state0;
/** State 1 of the generator. */
protected long state1;
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 2, only the first 2 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros will create a non-functional generator.
*/
AbstractXoRoShiRo128(long[] seed) {
if (seed.length < SEED_SIZE) {
final long[] state = new long[SEED_SIZE];
fillState(state, seed);
setState(state);
} else {
setState(seed);
}
}
/**
* Creates a new instance using a 2 element seed.
* A seed containing all zeros will create a non-functional generator.
*
* @param seed0 Initial seed element 0.
* @param seed1 Initial seed element 1.
*/
AbstractXoRoShiRo128(long seed0, long seed1) {
state0 = seed0;
state1 = seed1;
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
protected AbstractXoRoShiRo128(AbstractXoRoShiRo128 source) {
super(source);
state0 = source.state0;
state1 = source.state1;
}
/**
* Copies the state from the array into the generator state.
*
* @param state the new state
*/
private void setState(long[] state) {
state0 = state[0];
state1 = state[1];
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
return composeStateInternal(NumberFactory.makeByteArray(new long[] {state0, state1}),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] c = splitStateInternal(s, SEED_SIZE * 8);
setState(NumberFactory.makeLongArray(c[0]));
super.setStateInternal(c[1]);
}
/** {@inheritDoc} */
@Override
public long next() {
final long result = nextOutput();
final long s0 = state0;
long s1 = state1;
s1 ^= s0;
state0 = Long.rotateLeft(s0, 24) ^ s1 ^ (s1 << 16); // a, b
state1 = Long.rotateLeft(s1, 37); // c
return result;
}
/**
* Use the current state to compute the next output from the generator.
* The output function shall vary with respect to different generators.
* This method is called from {@link #next()} before the current state is updated.
*
* @return the next output
*/
protected abstract long nextOutput();
/**
* {@inheritDoc}
*
* <p>The jump size is the equivalent of 2<sup>64</sup>
* calls to {@link UniformRandomProvider#nextLong() nextLong()}. It can provide
* up to 2<sup>64</sup> non-overlapping subsequences.</p>
*/
@Override
public UniformRandomProvider jump() {
final UniformRandomProvider copy = copy();
performJump(JUMP_COEFFICIENTS);
return copy;
}
/**
* {@inheritDoc}
*
* <p>The jump size is the equivalent of 2<sup>96</sup> calls to
* {@link UniformRandomProvider#nextLong() nextLong()}. It can provide up to
* 2<sup>32</sup> non-overlapping subsequences of length 2<sup>96</sup>; each
* subsequence can provide up to 2<sup>32</sup> non-overlapping subsequences of
* length 2<sup>64</sup> using the {@link #jump()} method.</p>
*/
@Override
public JumpableUniformRandomProvider longJump() {
final JumpableUniformRandomProvider copy = copy();
performJump(LONG_JUMP_COEFFICIENTS);
return copy;
}
/**
* Create a copy.
*
* @return the copy
*/
protected abstract AbstractXoRoShiRo128 copy();
/**
* Perform the jump to advance the generator state. Resets the cached state of the generator.
*
* @param jumpCoefficients Jump coefficients.
*/
final void performJump(long[] jumpCoefficients) {
long s0 = 0;
long s1 = 0;
for (final long jc : jumpCoefficients) {
for (int b = 0; b < 64; b++) {
if ((jc & (1L << b)) != 0) {
s0 ^= state0;
s1 ^= state1;
}
next();
}
}
state0 = s0;
state1 = s1;
resetCachedState();
}
}
| 3,144 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/L64X1024Mix.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
import java.util.stream.Stream;
import org.apache.commons.rng.JumpableUniformRandomProvider;
import org.apache.commons.rng.SplittableUniformRandomProvider;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.core.util.NumberFactory;
import org.apache.commons.rng.core.util.RandomStreams;
/**
* A 64-bit all purpose generator.
*
* <p>This is a member of the LXM family of generators: L=Linear congruential generator;
* X=Xor based generator; and M=Mix. This member uses a 64-bit LCG and 1024-bit Xor-based
* generator. It is named as {@code "L64X1024MixRandom"} in the {@code java.util.random}
* package introduced in JDK 17; the LXM family is described in further detail in:
*
* <blockquote>Steele and Vigna (2021) LXM: better splittable pseudorandom number generators
* (and almost as fast). Proceedings of the ACM on Programming Languages, Volume 5,
* Article 148, pp 1–31.</blockquote>
*
* <p>Memory footprint is 1184 bits and the period is 2<sup>64</sup> (2<sup>1024</sup> - 1).
*
* <p>This generator implements
* {@link org.apache.commons.rng.LongJumpableUniformRandomProvider LongJumpableUniformRandomProvider}.
* In addition instances created with a different additive parameter for the LCG are robust
* against accidental correlation in a multi-threaded setting. The additive parameters must be
* different in the most significant 63-bits.
*
* <p>This generator implements
* {@link org.apache.commons.rng.SplittableUniformRandomProvider SplittableUniformRandomProvider}.
* The stream of generators created using the {@code splits} methods support parallelisation
* and are robust against accidental correlation by using unique values for the additive parameter
* for each instance in the same stream. The primitive streaming methods support parallelisation
* but with no assurances of accidental correlation; each thread uses a new instance with a
* randomly initialised state.
*
* @see <a href="https://doi.org/10.1145/3485525">Steele & Vigna (2021) Proc. ACM Programming
* Languages 5, 1-31</a>
* @see <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/random/package-summary.html">
* JDK 17 java.util.random javadoc</a>
* @since 1.5
*/
public class L64X1024Mix extends AbstractL64 implements SplittableUniformRandomProvider {
/** Size of the seed vector. */
private static final int SEED_SIZE = 18;
/** Size of the XBG state vector. */
private static final int XBG_STATE_SIZE = 16;
/** Size of the LCG state vector. */
private static final int LCG_STATE_SIZE = SEED_SIZE - XBG_STATE_SIZE;
/** LCG multiplier. */
private static final long M = LXMSupport.M64;
/** State of the XBG. */
private final long[] x = new long[XBG_STATE_SIZE];
/** Index in "state" array. */
private int index;
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 18, only the first 18 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros in the last 16 elements
* will create a non-functional XBG sub-generator and a low
* quality output with a period of 2<sup>64</sup>.
*
* <p>The 1st element is used to set the LCG increment; the least significant bit
* is set to odd to ensure a full period LCG. The 2nd element is used
* to set the LCG state.</p>
*/
public L64X1024Mix(long[] seed) {
super(seed = extendSeed(seed, SEED_SIZE));
System.arraycopy(seed, SEED_SIZE - XBG_STATE_SIZE, x, 0, XBG_STATE_SIZE);
// Initialising to 15 ensures that (index + 1) % 16 == 0 and the
// first state picked from the XBG generator is state[0].
index = XBG_STATE_SIZE - 1;
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
protected L64X1024Mix(L64X1024Mix source) {
super(source);
System.arraycopy(source.x, 0, x, 0, XBG_STATE_SIZE);
index = source.index;
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
final long[] s = new long[XBG_STATE_SIZE + 1];
System.arraycopy(x, 0, s, 0, XBG_STATE_SIZE);
s[XBG_STATE_SIZE] = index;
return composeStateInternal(NumberFactory.makeByteArray(s),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] c = splitStateInternal(s, (XBG_STATE_SIZE + 1) * Long.BYTES);
final long[] tmp = NumberFactory.makeLongArray(c[0]);
System.arraycopy(tmp, 0, x, 0, XBG_STATE_SIZE);
index = (int) tmp[XBG_STATE_SIZE];
super.setStateInternal(c[1]);
}
/** {@inheritDoc} */
@Override
public long next() {
// LXM generate.
// Old state is used for the output allowing parallel pipelining
// on processors that support multiple concurrent instructions.
final int q = index;
index = (q + 1) & 15;
final long s0 = x[index];
long s15 = x[q];
final long s = ls;
// Mix
final long z = LXMSupport.lea64(s + s0);
// LCG update
ls = M * s + la;
// XBG update
s15 ^= s0;
x[q] = Long.rotateLeft(s0, 25) ^ s15 ^ (s15 << 27);
x[index] = Long.rotateLeft(s15, 36);
return z;
}
/**
* {@inheritDoc}
*
* <p>The jump size is the equivalent of moving the state <em>backwards</em> by
* (2<sup>1024</sup> - 1) positions. It can provide up to 2<sup>64</sup>
* non-overlapping subsequences.
*/
@Override
public UniformRandomProvider jump() {
return super.jump();
}
/**
* {@inheritDoc}
*
* <p>The jump size is the equivalent of moving the state <em>backwards</em> by
* 2<sup>32</sup> (2<sup>1024</sup> - 1) positions. It can provide up to
* 2<sup>32</sup> non-overlapping subsequences of length 2<sup>32</sup>
* (2<sup>1024</sup> - 1); each subsequence can provide up to 2<sup>32</sup>
* non-overlapping subsequences of length (2<sup>1024</sup> - 1) using the
* {@link #jump()} method.
*/
@Override
public JumpableUniformRandomProvider longJump() {
return super.longJump();
}
/** {@inheritDoc} */
@Override
AbstractL64 copy() {
// This exists to ensure the jump function performed in the super class returns
// the correct class type. It should not be public.
return new L64X1024Mix(this);
}
/** {@inheritDoc} */
@Override
public SplittableUniformRandomProvider split(UniformRandomProvider source) {
return create(source.nextLong(), source);
}
/** {@inheritDoc} */
@Override
public Stream<SplittableUniformRandomProvider> splits(long streamSize, SplittableUniformRandomProvider source) {
return RandomStreams.generateWithSeed(streamSize, source, L64X1024Mix::create);
}
/**
* Create a new instance using the given {@code seed} and {@code source} of randomness
* to initialise the instance.
*
* @param seed Seed used to initialise the instance.
* @param source Source of randomness used to initialise the instance.
* @return A new instance.
*/
private static SplittableUniformRandomProvider create(long seed, UniformRandomProvider source) {
final long[] s = new long[SEED_SIZE];
// LCG state. The addition uses the input seed.
// The LCG addition parameter is set to odd so left-shift the seed.
s[0] = seed << 1;
s[1] = source.nextLong();
// XBG state must not be all zero
long x = 0;
for (int i = LCG_STATE_SIZE; i < s.length; i++) {
s[i] = source.nextLong();
x |= s[i];
}
if (x == 0) {
// SplitMix style seed ensures at least one non-zero value
x = s[LCG_STATE_SIZE - 1];
for (int i = LCG_STATE_SIZE; i < s.length; i++) {
s[i] = LXMSupport.lea64(x);
x += LXMSupport.GOLDEN_RATIO_64;
}
}
return new L64X1024Mix(s);
}
}
| 3,145 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/TwoCmres.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
import java.util.List;
import java.util.ArrayList;
import org.apache.commons.rng.core.util.NumberFactory;
/**
* Random number generator designed by Mark D. Overton.
*
* <p>It is one of the many generators described by the author in the following article series:</p>
* <ul>
* <li><a href="http://www.drdobbs.com/tools/fast-high-quality-parallel-random-number/229625477">Part one</a></li>
* <li><a href="http://www.drdobbs.com/tools/fast-high-quality-parallel-random-number/231000484">Part two</a></li>
* </ul>
*
* @since 1.0
*/
public class TwoCmres extends LongProvider {
/** Error message. */
private static final String INTERNAL_ERROR_MSG = "Internal error: Please file a bug report";
/** A small positive integer. */
private static final byte SEED_GUARD = 9;
/** Factory of instances of this class. Singleton. */
private static final Cmres.Factory FACTORY = new Cmres.Factory();
/** First subcycle generator. */
private final Cmres x;
/** Second subcycle generator. */
private final Cmres y;
/** State of first subcycle generator. */
private long xx;
/** State of second subcycle generator. */
private long yy;
/**
* Creates a new instance.
*
* @param seed Initial seed.
* @param x First subcycle generator.
* @param y Second subcycle generator.
* @throws IllegalArgumentException if {@code x == y}.
*/
private TwoCmres(int seed,
Cmres x,
Cmres y) {
if (x.equals(y)) {
throw new IllegalArgumentException("Subcycle generators must be different");
}
this.x = x;
this.y = y;
setSeedInternal(seed);
}
/**
* Creates a new instance.
*
* @param seed Seed.
*/
public TwoCmres(Integer seed) {
this(seed, 0, 1);
}
/**
* Creates a new instance.
*
* @param seed Seed.
* @param i Table entry for first subcycle generator.
* @param j Table entry for second subcycle generator.
* @throws IllegalArgumentException if {@code i == j}.
* @throws IndexOutOfBoundsException if {@code i < 0} or
* {@code i >= numberOfSubcycleGenerators()}.
* @throws IndexOutOfBoundsException if {@code j < 0} or
* {@code j >= numberOfSubcycleGenerators()}.
*/
public TwoCmres(Integer seed,
int i,
int j) {
this(seed, FACTORY.get(i), FACTORY.get(j));
}
/** {@inheritDoc} */
@Override
public long next() {
xx = x.transform(xx);
yy = y.transform(yy);
return xx + yy;
}
/** {@inheritDoc} */
@Override
public String toString() {
return super.toString() + " (" + x + " + " + y + ")";
}
/**
* @return the number of subcycle generators.
*/
public static int numberOfSubcycleGenerators() {
return FACTORY.numberOfSubcycleGenerators();
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
return composeStateInternal(NumberFactory.makeByteArray(new long[] {xx, yy}),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] c = splitStateInternal(s, 16);
final long[] state = NumberFactory.makeLongArray(c[0]);
xx = state[0];
yy = state[1];
super.setStateInternal(c[1]);
}
/**
* @param seed Seed.
*/
private void setSeedInternal(int seed) {
// The seeding procedure consists in going away from some
// point known to be in the cycle.
// The total number of calls to the "transform" method will
// not exceed about 130,000 (which is negligible as seeding
// will not occur more than once in normal usage).
// Make two positive 16-bits integers from the 32-bit seed.
// Add the small positive seed guard. The result will never be negative.
final int xMax = (seed & 0xffff) + (SEED_GUARD & 0xff);
final int yMax = (seed >>> 16) + (SEED_GUARD & 0xff);
xx = x.getStart();
for (int i = xMax; i > 0; i--) {
xx = x.transform(xx);
}
yy = y.getStart();
for (int i = yMax; i > 0; i--) {
yy = y.transform(yy);
}
}
/**
* Subcycle generator.
* Class is immutable.
*/
static class Cmres {
/** Separator. */
private static final String SEP = ", ";
/** Hexadecimal format. */
private static final String HEX_FORMAT = "0x%016xL";
/** Cycle start. */
private final int start;
/** Multiplier. */
private final long multiply;
/** Rotation. */
private final int rotate;
/**
* @param multiply Multiplier.
* @param rotate Positive number. Must be in {@code [0, 64]}.
* @param start Cycle start.
*/
Cmres(long multiply,
int rotate,
int start) {
this.multiply = multiply;
this.rotate = rotate;
this.start = start;
}
/** {@inheritDoc} */
@Override
public String toString() {
final String m = String.format((java.util.Locale) null, HEX_FORMAT, multiply);
return "Cmres: [" + m + SEP + rotate + SEP + start + "]";
}
/**
* @return the multiplier.
*/
public long getMultiply() {
return multiply;
}
/**
* @return the cycle start.
*/
public int getStart() {
return start;
}
/**
* @param state Current state.
* @return the new state.
*/
long transform(long state) {
long s = state;
s *= multiply;
s = Long.rotateLeft(s, rotate);
s -= state;
return s;
}
/** Factory. */
static class Factory {
/** List of good "Cmres" subcycle generators. */
private static final List<Cmres> TABLE = new ArrayList<>();
//
// Populates the table.
// It lists parameters known to be good (provided in
// the article referred to above).
// To maintain compatibility, new entries must be added
// only at the end of the table.
//
static {
add(0xedce446814d3b3d9L, 33, 0x13b572e7);
add(0xc5b3cf786c806df7L, 33, 0x13c8e18a);
add(0xdd91bbb8ab9e0e65L, 31, 0x06dd03a6);
add(0x7b69342c0790221dL, 31, 0x1646bb8b);
add(0x0c72c0d18614c32bL, 33, 0x06014a3d);
add(0xd8d98c13bebe26c9L, 33, 0x014e8475);
add(0xcb039dc328bbc40fL, 31, 0x008684bd);
add(0x858c5ef3c021ed2fL, 32, 0x0dc8d622);
add(0x4c8be96bfc23b127L, 33, 0x0b6b20cc);
add(0x11eab77f808cf641L, 32, 0x06534421);
add(0xbc9bd78810fd28fdL, 31, 0x1d9ba40d);
add(0x0f1505c780688cb5L, 33, 0x0b7b7b67);
add(0xadc174babc2053afL, 31, 0x267f4197);
add(0x900b6b82b31686d9L, 31, 0x023c6985);
// Add new entries here.
}
/**
* @return the number of subcycle generators.
*/
int numberOfSubcycleGenerators() {
return TABLE.size();
}
/**
* @param index Index into the list of available generators.
* @return the subcycle generator entry at index {@code index}.
*/
Cmres get(int index) {
if (index < 0 ||
index >= TABLE.size()) {
throw new IndexOutOfBoundsException("Out of interval [0, " +
(TABLE.size() - 1) + "]");
}
return TABLE.get(index);
}
/**
* Adds an entry to the {@link Factory#TABLE}.
*
* @param multiply Multiplier.
* @param rotate Rotate.
* @param start Cycle start.
*/
private static void add(long multiply,
int rotate,
int start) {
// Validity check: if there are duplicates, the class initialization
// will fail (and the JVM will report "NoClassDefFoundError").
checkUnique(TABLE, multiply);
TABLE.add(new Cmres(multiply, rotate, start));
}
/**
* Check the multiply parameter is unique (not contained in any entry in the provided
* table).
*
* @param table the table
* @param multiply the multiply parameter
*/
static void checkUnique(List<Cmres> table, long multiply) {
for (final Cmres sg : table) {
if (multiply == sg.getMultiply()) {
throw new IllegalStateException(INTERNAL_ERROR_MSG);
}
}
}
}
}
}
| 3,146 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/XoShiRo256Plus.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
/**
* A fast 64-bit generator suitable for {@code double} generation. This is slightly faster than the
* all-purpose generator {@link XoShiRo256StarStar}.
*
* <p>This is a member of the Xor-Shift-Rotate family of generators. Memory footprint is 256 bits
* and the period is 2<sup>256</sup>-1.</p>
*
* @see <a href="http://xoshiro.di.unimi.it/xoshiro256plus.c">Original source code</a>
* @see <a href="http://xoshiro.di.unimi.it/">xorshiro / xoroshiro generators</a>
* @since 1.3
*/
public class XoShiRo256Plus extends AbstractXoShiRo256 {
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 4, only the first 4 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros will create a non-functional generator.
*/
public XoShiRo256Plus(long[] seed) {
super(seed);
}
/**
* Creates a new instance using a 4 element seed.
* A seed containing all zeros will create a non-functional generator.
*
* @param seed0 Initial seed element 0.
* @param seed1 Initial seed element 1.
* @param seed2 Initial seed element 2.
* @param seed3 Initial seed element 3.
*/
public XoShiRo256Plus(long seed0, long seed1, long seed2, long seed3) {
super(seed0, seed1, seed2, seed3);
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
protected XoShiRo256Plus(XoShiRo256Plus source) {
super(source);
}
/** {@inheritDoc} */
@Override
protected long nextOutput() {
return state0 + state3;
}
/** {@inheritDoc} */
@Override
protected XoShiRo256Plus copy() {
// This exists to ensure the jump function performed in the super class returns
// the correct class type. It should not be public.
return new XoShiRo256Plus(this);
}
}
| 3,147 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/XoShiRo512Plus.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
/**
* A fast 64-bit generator suitable for {@code double} generation. This is slightly faster than the
* all-purpose generator {@link XoShiRo512StarStar}.
*
* <p>This is a member of the Xor-Shift-Rotate family of generators. Memory footprint is 512 bits
* and the period is 2<sup>512</sup>-1. Speed is expected to be slower than
* {@link XoShiRo256Plus}.</p>
*
* @see <a href="http://xoshiro.di.unimi.it/xoshiro512plus.c">Original source code</a>
* @see <a href="http://xoshiro.di.unimi.it/">xorshiro / xoroshiro generators</a>
* @since 1.3
*/
public class XoShiRo512Plus extends AbstractXoShiRo512 {
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 8, only the first 8 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros will create a non-functional generator.
*/
public XoShiRo512Plus(long[] seed) {
super(seed);
}
/**
* Creates a new instance using an 8 element seed.
* A seed containing all zeros will create a non-functional generator.
*
* @param seed0 Initial seed element 0.
* @param seed1 Initial seed element 1.
* @param seed2 Initial seed element 2.
* @param seed3 Initial seed element 3.
* @param seed4 Initial seed element 4.
* @param seed5 Initial seed element 5.
* @param seed6 Initial seed element 6.
* @param seed7 Initial seed element 7.
*/
public XoShiRo512Plus(long seed0, long seed1, long seed2, long seed3,
long seed4, long seed5, long seed6, long seed7) {
super(seed0, seed1, seed2, seed3, seed4, seed5, seed6, seed7);
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
protected XoShiRo512Plus(XoShiRo512Plus source) {
super(source);
}
/** {@inheritDoc} */
@Override
protected long nextOutput() {
return state0 + state2;
}
/** {@inheritDoc} */
@Override
protected XoShiRo512Plus copy() {
// This exists to ensure the jump function performed in the super class returns
// the correct class type. It should not be public.
return new XoShiRo512Plus(this);
}
}
| 3,148 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/XoRoShiRo1024Star.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
/**
* A large-state 64-bit generator suitable for {@code double} generation. This is slightly faster
* than the all-purpose generator {@link XoRoShiRo1024PlusPlus}.
*
* <p>This is a member of the Xor-Shift-Rotate family of generators. Memory footprint is 1024 bits
* and the period is 2<sup>1024</sup>-1.</p>
*
* @see <a href="http://xorshift.di.unimi.it/xoroshiro1024star.c">Original source code</a>
* @see <a href="http://xoshiro.di.unimi.it/">xorshiro / xoroshiro generators</a>
* @since 1.3
*/
public class XoRoShiRo1024Star extends AbstractXoRoShiRo1024 {
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 16, only the first 16 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros will create a non-functional generator.
*/
public XoRoShiRo1024Star(long[] seed) {
super(seed);
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
protected XoRoShiRo1024Star(XoRoShiRo1024Star source) {
super(source);
}
/** {@inheritDoc} */
@Override
protected long transform(long s0, long s15) {
return s0 * 0x9e3779b97f4a7c13L;
}
/** {@inheritDoc} */
@Override
protected XoRoShiRo1024Star copy() {
// This exists to ensure the jump function returns
// the correct class type. It should not be public.
return new XoRoShiRo1024Star(this);
}
}
| 3,149 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/RandomLongSource.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
/**
* Source of randomness that generates values of type {@code long}.
*
* @since 1.0
*/
public interface RandomLongSource {
/**
* @return the next random value.
*/
long next();
}
| 3,150 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/LongProvider.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
import org.apache.commons.rng.core.util.NumberFactory;
import org.apache.commons.rng.core.BaseProvider;
/**
* Base class for all implementations that provide a {@code long}-based
* source randomness.
*/
public abstract class LongProvider
extends BaseProvider
implements RandomLongSource {
/** Empty boolean source. This is the location of the sign-bit after 63 right shifts on
* the boolean source. */
private static final long EMPTY_BOOL_SOURCE = 1;
/** Empty int source. This requires a negative value as the sign-bit is used to
* trigger a refill. */
private static final long EMPTY_INT_SOURCE = -1;
/**
* Provides a bit source for booleans.
*
* <p>A cached value from a call to {@link #next()}.
*
* <p>Only stores 63-bits when full as 1 bit has already been consumed.
* The sign bit is a flag that shifts down so the source eventually equals 1
* when all bits are consumed and will trigger a refill.
*/
private long booleanSource = EMPTY_BOOL_SOURCE;
/**
* Provides a source for ints.
*
* <p>A cached half-value value from a call to {@link #next()}.
* The int is stored in the lower 32 bits with zeros in the upper bits.
* When empty this is set to negative to trigger a refill.
*/
private long intSource = EMPTY_INT_SOURCE;
/**
* Creates a new instance.
*/
public LongProvider() {
super();
}
/**
* Creates a new instance copying the state from the source.
*
* <p>This provides base functionality to allow a generator to create a copy, for example
* for use in the {@link org.apache.commons.rng.JumpableUniformRandomProvider
* JumpableUniformRandomProvider} interface.
*
* @param source Source to copy.
* @since 1.3
*/
protected LongProvider(LongProvider source) {
booleanSource = source.booleanSource;
intSource = source.intSource;
}
/**
* Reset the cached state used in the default implementation of {@link #nextBoolean()}
* and {@link #nextInt()}.
*
* <p>This should be used when the state is no longer valid, for example after a jump
* performed for the {@link org.apache.commons.rng.JumpableUniformRandomProvider
* JumpableUniformRandomProvider} interface.</p>
*
* @since 1.3
*/
protected void resetCachedState() {
booleanSource = EMPTY_BOOL_SOURCE;
intSource = EMPTY_INT_SOURCE;
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
final long[] state = {booleanSource, intSource};
return composeStateInternal(NumberFactory.makeByteArray(state),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] c = splitStateInternal(s, 2 * Long.BYTES);
final long[] state = NumberFactory.makeLongArray(c[0]);
booleanSource = state[0];
intSource = state[1];
super.setStateInternal(c[1]);
}
/** {@inheritDoc} */
@Override
public long nextLong() {
return next();
}
/** {@inheritDoc} */
@Override
public int nextInt() {
long bits = intSource;
if (bits < 0) {
// Refill
bits = next();
// Store high 32 bits, return low 32 bits
intSource = bits >>> 32;
return (int) bits;
}
// Reset and return previous low bits
intSource = -1;
return (int) bits;
}
/** {@inheritDoc} */
@Override
public boolean nextBoolean() {
long bits = booleanSource;
if (bits == 1) {
// Refill
bits = next();
// Store a refill flag in the sign bit and the unused 63 bits, return lowest bit
booleanSource = Long.MIN_VALUE | (bits >>> 1);
return (bits & 0x1) == 1;
}
// Shift down eventually triggering refill, return current lowest bit
booleanSource = bits >>> 1;
return (bits & 0x1) == 1;
}
}
| 3,151 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/L64X128Mix.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
import java.util.stream.Stream;
import org.apache.commons.rng.SplittableUniformRandomProvider;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.core.util.RandomStreams;
/**
* A 64-bit all purpose generator.
*
* <p>This is a member of the LXM family of generators: L=Linear congruential generator;
* X=Xor based generator; and M=Mix. This member uses a 64-bit LCG and 128-bit Xor-based
* generator. It is named as {@code "L64X128MixRandom"} in the {@code java.util.random}
* package introduced in JDK 17; the LXM family is described in further detail in:
*
* <blockquote>Steele and Vigna (2021) LXM: better splittable pseudorandom number generators
* (and almost as fast). Proceedings of the ACM on Programming Languages, Volume 5,
* Article 148, pp 1–31.</blockquote>
*
* <p>Memory footprint is 256 bits and the period is 2<sup>64</sup> (2<sup>128</sup> - 1).
*
* <p>This generator implements
* {@link org.apache.commons.rng.LongJumpableUniformRandomProvider LongJumpableUniformRandomProvider}.
* In addition instances created with a different additive parameter for the LCG are robust
* against accidental correlation in a multi-threaded setting. The additive parameters must be
* different in the most significant 63-bits.
*
* <p>This generator implements
* {@link org.apache.commons.rng.SplittableUniformRandomProvider SplittableUniformRandomProvider}.
* The stream of generators created using the {@code splits} methods support parallelisation
* and are robust against accidental correlation by using unique values for the additive parameter
* for each instance in the same stream. The primitive streaming methods support parallelisation
* but with no assurances of accidental correlation; each thread uses a new instance with a
* randomly initialised state.
*
* @see <a href="https://doi.org/10.1145/3485525">Steele & Vigna (2021) Proc. ACM Programming
* Languages 5, 1-31</a>
* @see <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/random/package-summary.html">
* JDK 17 java.util.random javadoc</a>
* @since 1.5
*/
public class L64X128Mix extends AbstractL64X128 implements SplittableUniformRandomProvider {
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 4, only the first 4 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros in the last two elements
* will create a non-functional XBG sub-generator and a low
* quality output with a period of 2<sup>64</sup>.
*
* <p>The 1st element is used to set the LCG increment; the least significant bit
* is set to odd to ensure a full period LCG. The 2nd element is used
* to set the LCG state.</p>
*/
public L64X128Mix(long[] seed) {
super(seed);
}
/**
* Creates a new instance using a 4 element seed.
* A seed containing all zeros in the last two elements
* will create a non-functional XBG sub-generator and a low
* quality output with a period of 2<sup>64</sup>.
*
* <p>The 1st element is used to set the LCG increment; the least significant bit
* is set to odd to ensure a full period LCG. The 2nd element is used
* to set the LCG state.</p>
*
* @param seed0 Initial seed element 0.
* @param seed1 Initial seed element 1.
* @param seed2 Initial seed element 2.
* @param seed3 Initial seed element 3.
*/
public L64X128Mix(long seed0, long seed1, long seed2, long seed3) {
super(seed0, seed1, seed2, seed3);
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
protected L64X128Mix(L64X128Mix source) {
super(source);
}
/** {@inheritDoc} */
@Override
public long next() {
// LXM generate.
// Old state is used for the output allowing parallel pipelining
// on processors that support multiple concurrent instructions.
final long s0 = x0;
final long s = ls;
// Mix
final long z = LXMSupport.lea64(s + s0);
// LCG update
ls = M * s + la;
// XBG update
long s1 = x1;
s1 ^= s0;
x0 = Long.rotateLeft(s0, 24) ^ s1 ^ (s1 << 16); // a, b
x1 = Long.rotateLeft(s1, 37); // c
return z;
}
/** {@inheritDoc} */
@Override
protected L64X128Mix copy() {
// This exists to ensure the jump function performed in the super class returns
// the correct class type. It should not be public.
return new L64X128Mix(this);
}
/** {@inheritDoc} */
@Override
public SplittableUniformRandomProvider split(UniformRandomProvider source) {
return create(source.nextLong(), source);
}
/** {@inheritDoc} */
@Override
public Stream<SplittableUniformRandomProvider> splits(long streamSize, SplittableUniformRandomProvider source) {
return RandomStreams.generateWithSeed(streamSize, source, L64X128Mix::create);
}
/**
* Create a new instance using the given {@code seed} and {@code source} of randomness
* to initialise the instance.
*
* @param seed Seed used to initialise the instance.
* @param source Source of randomness used to initialise the instance.
* @return A new instance.
*/
private static SplittableUniformRandomProvider create(long seed, UniformRandomProvider source) {
// LCG state. The addition uses the input seed.
// The LCG addition parameter is set to odd so left-shift the seed.
final long s0 = seed << 1;
final long s1 = source.nextLong();
// XBG state must not be all zero
long x0 = source.nextLong();
long x1 = source.nextLong();
if ((x0 | x1) == 0) {
// SplitMix style seed ensures at least one non-zero value
x0 = LXMSupport.lea64(s1);
x1 = LXMSupport.lea64(s1 + LXMSupport.GOLDEN_RATIO_64);
}
return new L64X128Mix(s0, s1, x0, x1);
}
}
| 3,152 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/XoRoShiRo1024PlusPlus.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
/**
* A large-state all-purpose 64-bit generator.
*
* <p>This is a member of the Xor-Shift-Rotate family of generators. Memory footprint is 1024 bits
* and the period is 2<sup>1024</sup>-1.</p>
*
* <p>Note: This can be used as a replacement for {@link XorShift1024Star}.</p>
*
* @see <a href="http://xorshift.di.unimi.it/xoroshiro1024plusplus.c">Original source code</a>
* @see <a href="http://xoshiro.di.unimi.it/">xorshiro / xoroshiro generators</a>
* @since 1.3
*/
public class XoRoShiRo1024PlusPlus extends AbstractXoRoShiRo1024 {
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 16, only the first 16 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros will create a non-functional generator.
*/
public XoRoShiRo1024PlusPlus(long[] seed) {
super(seed);
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
protected XoRoShiRo1024PlusPlus(XoRoShiRo1024PlusPlus source) {
super(source);
}
/** {@inheritDoc} */
@Override
protected long transform(long s0, long s15) {
return Long.rotateLeft(s0 + s15, 23) + s15;
}
/** {@inheritDoc} */
@Override
protected XoRoShiRo1024PlusPlus copy() {
// This exists to ensure the jump function returns
// the correct class type. It should not be public.
return new XoRoShiRo1024PlusPlus(this);
}
}
| 3,153 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/DotyHumphreySmallFastCounting64.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
import org.apache.commons.rng.core.util.NumberFactory;
/**
* Implement the Small, Fast, Counting (SFC) 64-bit generator of Chris Doty-Humphrey.
* The original source is the PractRand test suite by the same author.
*
* <p>The state size is 256-bits; the period is a minimum of 2<sup>64</sup> and an
* average of approximately 2<sup>255</sup>.</p>
*
* @see <a href="http://pracrand.sourceforge.net/">PractRand</a>
* @since 1.3
*/
public class DotyHumphreySmallFastCounting64 extends LongProvider {
/** Size of the seed. */
private static final int SEED_SIZE = 3;
/** State a. */
private long a;
/** State b. */
private long b;
/** State c. */
private long c;
/** Counter. */
private long counter;
/**
* Creates an instance with the given seed.
*
* @param seed Initial seed.
* If the length is larger than 3, only the first 3 elements will
* be used; if smaller, the remaining elements will be automatically set.
*/
public DotyHumphreySmallFastCounting64(long[] seed) {
if (seed.length < SEED_SIZE) {
final long[] state = new long[SEED_SIZE];
fillState(state, seed);
setSeedInternal(state);
} else {
setSeedInternal(seed);
}
}
/**
* Seeds the RNG.
*
* @param seed Seed.
*/
private void setSeedInternal(long[] seed) {
a = seed[0];
b = seed[1];
c = seed[2];
counter = 1L;
for (int i = 0; i < 18; i++) {
next();
}
}
/** {@inheritDoc} */
@Override
public final long next() {
final long tmp = a + b + counter++;
a = b ^ (b >>> 11);
b = c + (c << 3);
c = Long.rotateLeft(c, 24) + tmp;
return tmp;
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
return composeStateInternal(NumberFactory.makeByteArray(new long[] {a, b, c, counter}),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] parts = splitStateInternal(s, 4 * 8);
final long[] tmp = NumberFactory.makeLongArray(parts[0]);
a = tmp[0];
b = tmp[1];
c = tmp[2];
counter = tmp[3];
super.setStateInternal(parts[1]);
}
}
| 3,154 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/AbstractL128.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
import org.apache.commons.rng.JumpableUniformRandomProvider;
import org.apache.commons.rng.LongJumpableUniformRandomProvider;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.core.util.NumberFactory;
/**
* This abstract class is a base for algorithms from the LXM family of
* generators with a 128-bit LCG sub-generator. The class implements
* the jump functions.
*
* @since 1.5
*/
abstract class AbstractL128 extends LongProvider implements LongJumpableUniformRandomProvider {
/** Size of the seed vector. */
private static final int SEED_SIZE = 4;
/** Low half of 128-bit LCG multiplier. */
private static final long ML = LXMSupport.M128L;
/** High half of the 128-bit per-instance LCG additive parameter.
* Cannot be final to support RestorableUniformRandomProvider. */
protected long lah;
/** Low half of the 128-bit per-instance LCG additive parameter (must be odd).
* Cannot be final to support RestorableUniformRandomProvider. */
protected long lal;
/** High half of the 128-bit state of the LCG generator. */
protected long lsh;
/** Low half of the 128-bit state of the LCG generator. */
protected long lsl;
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 4, only the first 4 elements will
* be used; if smaller, the remaining elements will be automatically
* set.
*
* <p>The 1st and 2nd elements are used to set the LCG increment; the least significant bit
* is set to odd to ensure a full period LCG. The 3rd and 4th elements are used
* to set the LCG state.</p>
*/
AbstractL128(long[] seed) {
setState(extendSeed(seed, SEED_SIZE));
}
/**
* Creates a new instance using a 4 element seed.
*
* <p>The 1st and 2nd elements are used to set the LCG increment; the least significant bit
* is set to odd to ensure a full period LCG. The 3rd and 4th elements are used
* to set the LCG state.</p>
*
* @param seed0 Initial seed element 0.
* @param seed1 Initial seed element 1.
* @param seed2 Initial seed element 2.
* @param seed3 Initial seed element 3.
*/
AbstractL128(long seed0, long seed1, long seed2, long seed3) {
lah = seed0;
// Additive parameter must be odd
lal = seed1 | 1;
lsh = seed2;
lsl = seed3;
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
AbstractL128(AbstractL128 source) {
super(source);
lah = source.lah;
lal = source.lal;
lsh = source.lsh;
lsl = source.lsl;
}
/**
* Copies the state into the generator state.
*
* @param state the new state
*/
private void setState(long[] state) {
lah = state[0];
// Additive parameter must be odd
lal = state[1] | 1;
lsh = state[2];
lsl = state[3];
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
return composeStateInternal(NumberFactory.makeByteArray(
new long[] {lah, lal, lsh, lsl}),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] c = splitStateInternal(s, SEED_SIZE * Long.BYTES);
setState(NumberFactory.makeLongArray(c[0]));
super.setStateInternal(c[1]);
}
/**
* Creates a copy of the UniformRandomProvider and then <em>retreats</em> the state of the
* current instance. The copy is returned.
*
* <p>The jump is performed by advancing the state of the LCG sub-generator by 1 cycle.
* The XBG state is unchanged.
*/
@Override
public UniformRandomProvider jump() {
final UniformRandomProvider copy = copy();
// Advance the LCG 1 step.
// The LCG is, in effect, "s = m * s + a" where m = ((1LL << 64) + ML)
final long sh = lsh;
final long sl = lsl;
final long u = ML * sl;
// High half
lsh = ML * sh + LXMSupport.unsignedMultiplyHigh(ML, sl) + sl + lah +
// Carry propagation
LXMSupport.unsignedAddHigh(u, lal);
// Low half
lsl = u + lal;
resetCachedState();
return copy;
}
/**
* Creates a copy of the UniformRandomProvider and then <em>retreats</em> the state of the
* current instance. The copy is returned.
*
* <p>The jump is performed by advancing the state of the LCG sub-generator by
* 2<sup>64</sup> cycles. The XBG state is unchanged.
*/
@Override
public JumpableUniformRandomProvider longJump() {
final JumpableUniformRandomProvider copy = copy();
// Advance the LCG 2^64 steps
// s = m' * s + c' * c
// Specialised routine given M128PL=1, C128PL=0 and many terms
// can be dropped as the low half is unchanged and there is no carry
// sh = m'l * sh // sh
// + high(m'l * sl) // dropped as m'l=1 and there is no high part
// + m'h * sl
// + c'l * ah // dropped as c'l=0
// + high(c'l * ah) // dropped as c'l=0
// + c'h * al
// sl = m'l * sl + c'l * al
// = sl
lsh = lsh + LXMSupport.M128PH * lsl + LXMSupport.C128PH * lal;
resetCachedState();
return copy;
}
/**
* Create a copy.
*
* @return the copy
*/
abstract AbstractL128 copy();
}
| 3,155 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/AbstractXoRoShiRo1024.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
import java.util.Arrays;
import org.apache.commons.rng.JumpableUniformRandomProvider;
import org.apache.commons.rng.LongJumpableUniformRandomProvider;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.core.util.NumberFactory;
/**
* This abstract class is a base for algorithms from the Xor-Shift-Rotate family of 64-bit
* generators with 1024-bits of state.
*
* @see <a href="http://xoshiro.di.unimi.it/">xorshiro / xoroshiro generators</a>
* @since 1.3
*/
abstract class AbstractXoRoShiRo1024 extends LongProvider implements LongJumpableUniformRandomProvider {
/** Size of the state vector. */
private static final int SEED_SIZE = 16;
/** The coefficients for the jump function. */
private static final long[] JUMP_COEFFICIENTS = {
0x931197d8e3177f17L, 0xb59422e0b9138c5fL, 0xf06a6afb49d668bbL, 0xacb8a6412c8a1401L,
0x12304ec85f0b3468L, 0xb7dfe7079209891eL, 0x405b7eec77d9eb14L, 0x34ead68280c44e4aL,
0xe0e4ba3e0ac9e366L, 0x8f46eda8348905b7L, 0x328bf4dbad90d6ffL, 0xc8fd6fb31c9effc3L,
0xe899d452d4b67652L, 0x45f387286ade3205L, 0x03864f454a8920bdL, 0xa68fa28725b1b384L,
};
/** The coefficients for the long jump function. */
private static final long[] LONG_JUMP_COEFFICIENTS = {
0x7374156360bbf00fL, 0x4630c2efa3b3c1f6L, 0x6654183a892786b1L, 0x94f7bfcbfb0f1661L,
0x27d8243d3d13eb2dL, 0x9701730f3dfb300fL, 0x2f293baae6f604adL, 0xa661831cb60cd8b6L,
0x68280c77d9fe008cL, 0x50554160f5ba9459L, 0x2fc20b17ec7b2a9aL, 0x49189bbdc8ec9f8fL,
0x92a65bca41852cc1L, 0xf46820dd0509c12aL, 0x52b00c35fbf92185L, 0x1e5b3b7f589e03c1L,
};
/** State. */
private final long[] state = new long[SEED_SIZE];
/** Index in "state" array. */
private int index;
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 16, only the first 16 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros will create a non-functional generator.
*/
AbstractXoRoShiRo1024(long[] seed) {
setSeedInternal(seed);
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
protected AbstractXoRoShiRo1024(AbstractXoRoShiRo1024 source) {
super(source);
System.arraycopy(source.state, 0, state, 0, SEED_SIZE);
index = source.index;
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
final long[] s = Arrays.copyOf(state, SEED_SIZE + 1);
s[SEED_SIZE] = index;
return composeStateInternal(NumberFactory.makeByteArray(s),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] c = splitStateInternal(s, (SEED_SIZE + 1) * 8);
final long[] tmp = NumberFactory.makeLongArray(c[0]);
System.arraycopy(tmp, 0, state, 0, SEED_SIZE);
index = (int) tmp[SEED_SIZE];
super.setStateInternal(c[1]);
}
/**
* Seeds the RNG.
*
* @param seed Seed.
*/
private void setSeedInternal(long[] seed) {
// Reset the whole state of this RNG (i.e. "state" and "index").
// Filling procedure is not part of the reference code.
fillState(state, seed);
index = 0;
}
/** {@inheritDoc} */
@Override
public long next() {
final int q = index;
index = (index + 1) & 15;
final long s0 = state[index];
long s15 = state[q];
final long result = transform(s0, s15);
s15 ^= s0;
state[q] = Long.rotateLeft(s0, 25) ^ s15 ^ (s15 << 27);
state[index] = Long.rotateLeft(s15, 36);
return result;
}
/**
* Transform the two consecutive 64-bit states of the generator to a 64-bit output.
* The transformation function shall vary with respect to different generators.
*
* @param s0 The current state.
* @param s15 The previous state.
* @return the output
*/
protected abstract long transform(long s0, long s15);
/**
* {@inheritDoc}
*
* <p>The jump size is the equivalent of 2<sup>512</sup>
* calls to {@link UniformRandomProvider#nextLong() nextLong()}. It can provide
* up to 2<sup>512</sup> non-overlapping subsequences.</p>
*/
@Override
public UniformRandomProvider jump() {
final UniformRandomProvider copy = copy();
performJump(JUMP_COEFFICIENTS);
return copy;
}
/**
* {@inheritDoc}
*
*
* <p>The jump size is the equivalent of 2<sup>768</sup> calls to
* {@link UniformRandomProvider#nextLong() nextLong()}. It can provide up to
* 2<sup>256</sup> non-overlapping subsequences of length 2<sup>768</sup>; each
* subsequence can provide up to 2<sup>256</sup> non-overlapping subsequences of
* length 2<sup>512</sup> using the {@link #jump()} method.</p>
*/
@Override
public JumpableUniformRandomProvider longJump() {
final JumpableUniformRandomProvider copy = copy();
performJump(LONG_JUMP_COEFFICIENTS);
return copy;
}
/**
* Create a copy.
*
* @return the copy
*/
protected abstract AbstractXoRoShiRo1024 copy();
/**
* Perform the jump to advance the generator state. Resets the cached state of the generator.
*
* @param jumpCoefficients the jump coefficients
*/
private void performJump(long[] jumpCoefficients) {
final long[] newState = new long[SEED_SIZE];
for (final long jc : jumpCoefficients) {
for (int b = 0; b < 64; b++) {
if ((jc & (1L << b)) != 0) {
for (int i = 0; i < SEED_SIZE; i++) {
newState[i] ^= state[(i + index) & 15];
}
}
next();
}
}
// Note: Calling the next() function updates 'index'.
// The present index effectively becomes 0.
for (int j = 0; j < 16; j++) {
state[(j + index) & 15] = newState[j];
}
resetCachedState();
}
}
| 3,156 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/MersenneTwister64.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
import java.util.Arrays;
import org.apache.commons.rng.core.util.NumberFactory;
/**
* This class provides the 64-bits version of the originally 32-bits
* {@link org.apache.commons.rng.core.source32.MersenneTwister
* Mersenne Twister}.
*
* <p>
* This class is mainly a Java port of
* <a href="http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt64.html">
* the 2014/2/23 version of the generator
* </a> written in C by Takuji Nishimura and Makoto Matsumoto.
* </p>
*
* <p>
* Here is their original copyright:
* </p>
*
* <table style="background-color: #E0E0E0; width: 80%">
* <caption>Mersenne Twister licence</caption>
* <tr><td style="padding: 10px">Copyright (C) 2004, Makoto Matsumoto and Takuji Nishimura,
* All rights reserved.</td></tr>
*
* <tr><td style="padding: 10px">Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* <ol>
* <li>Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.</li>
* <li>Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.</li>
* <li>The names of its contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.</li>
* </ol></td></tr>
*
* <tr><td style="padding: 10px"><strong>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.</strong></td></tr>
* </table>
*
* @see <a href="https://en.wikipedia.org/wiki/Mersenne_Twister">Mersenne Twister (Wikipedia)</a>
* @since 1.0
*/
public class MersenneTwister64 extends LongProvider {
/** Size of the bytes pool. */
private static final int NN = 312;
/** Period second parameter. */
private static final int MM = 156;
/** X * MATRIX_A for X = {0, 1}. */
private static final long[] MAG01 = {0x0L, 0xb5026f5aa96619e9L};
/** Most significant 33 bits. */
private static final long UM = 0xffffffff80000000L;
/** Least significant 31 bits. */
private static final long LM = 0x7fffffffL;
/** Bytes pool. */
private final long[] mt = new long[NN];
/** Current index in the bytes pool. */
private int mti;
/**
* Creates a new random number generator.
*
* @param seed Initial seed.
*/
public MersenneTwister64(long[] seed) {
setSeedInternal(seed);
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
final long[] s = Arrays.copyOf(mt, NN + 1);
s[NN] = mti;
return composeStateInternal(NumberFactory.makeByteArray(s),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] c = splitStateInternal(s, (NN + 1) * 8);
final long[] tmp = NumberFactory.makeLongArray(c[0]);
System.arraycopy(tmp, 0, mt, 0, NN);
mti = (int) tmp[NN];
super.setStateInternal(c[1]);
}
/**
* Initializes the generator with the given seed.
*
* @param inputSeed Initial seed.
*/
private void setSeedInternal(long[] inputSeed) {
// Accept empty seed.
final long[] seed = (inputSeed.length == 0) ? new long[1] : inputSeed;
initState(19650218L);
int i = 1;
int j = 0;
for (int k = Math.max(NN, seed.length); k != 0; k--) {
final long mm1 = mt[i - 1];
mt[i] = (mt[i] ^ ((mm1 ^ (mm1 >>> 62)) * 0x369dea0f31a53f85L)) + seed[j] + j; // non linear
i++;
j++;
if (i >= NN) {
mt[0] = mt[NN - 1];
i = 1;
}
if (j >= seed.length) {
j = 0;
}
}
for (int k = NN - 1; k != 0; k--) {
final long mm1 = mt[i - 1];
mt[i] = (mt[i] ^ ((mm1 ^ (mm1 >>> 62)) * 0x27bb2ee687b0b0fdL)) - i; // non linear
i++;
if (i >= NN) {
mt[0] = mt[NN - 1];
i = 1;
}
}
mt[0] = 0x8000000000000000L; // MSB is 1; assuring non-zero initial array
}
/**
* Initialize the internal state of this instance.
*
* @param seed Seed.
*/
private void initState(long seed) {
mt[0] = seed;
for (mti = 1; mti < NN; mti++) {
final long mm1 = mt[mti - 1];
mt[mti] = 0x5851f42d4c957f2dL * (mm1 ^ (mm1 >>> 62)) + mti;
}
}
/** {@inheritDoc} */
@Override
public long next() {
long x;
if (mti >= NN) { // generate NN words at one time
for (int i = 0; i < NN - MM; i++) {
x = (mt[i] & UM) | (mt[i + 1] & LM);
mt[i] = mt[i + MM] ^ (x >>> 1) ^ MAG01[(int)(x & 0x1L)];
}
for (int i = NN - MM; i < NN - 1; i++) {
x = (mt[i] & UM) | (mt[i + 1] & LM);
mt[i] = mt[ i + (MM - NN)] ^ (x >>> 1) ^ MAG01[(int)(x & 0x1L)];
}
x = (mt[NN - 1] & UM) | (mt[0] & LM);
mt[NN - 1] = mt[MM - 1] ^ (x >>> 1) ^ MAG01[(int)(x & 0x1L)];
mti = 0;
}
x = mt[mti++];
x ^= (x >>> 29) & 0x5555555555555555L;
x ^= (x << 17) & 0x71d67fffeda60000L;
x ^= (x << 37) & 0xfff7eee000000000L;
x ^= x >>> 43;
return x;
}
}
| 3,157 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/AbstractL64X128.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
import org.apache.commons.rng.JumpableUniformRandomProvider;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.core.util.NumberFactory;
/**
* This abstract class is a base for algorithms from the LXM family of
* generators with a 64-bit LCG and 128-bit XBG sub-generator. The class implements
* the state save/restore functions.
*
* @since 1.5
*/
abstract class AbstractL64X128 extends AbstractL64 {
/** LCG multiplier. */
protected static final long M = LXMSupport.M64;
/** Size of the seed vector. */
private static final int SEED_SIZE = 4;
/** Size of the XBG state vector. */
private static final int XBG_STATE_SIZE = 2;
/** State 0 of the XBG. */
protected long x0;
/** State 1 of the XBG. */
protected long x1;
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 4, only the first 4 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros in the last two elements
* will create a non-functional XBG sub-generator and a low
* quality output with a period of 2<sup>64</sup>.
*
* <p>The 1st element is used to set the LCG increment; the least significant bit
* is set to odd to ensure a full period LCG. The 2nd element is used
* to set the LCG state.</p>
*/
AbstractL64X128(long[] seed) {
super(seed = extendSeed(seed, SEED_SIZE));
x0 = seed[2];
x1 = seed[3];
}
/**
* Creates a new instance using a 4 element seed.
* A seed containing all zeros in the last two elements
* will create a non-functional XBG sub-generator and a low
* quality output with a period of 2<sup>64</sup>.
*
* <p>The 1st element is used to set the LCG increment; the least significant bit
* is set to odd to ensure a full period LCG. The 2nd element is used
* to set the LCG state.</p>
*
* @param seed0 Initial seed element 0.
* @param seed1 Initial seed element 1.
* @param seed2 Initial seed element 2.
* @param seed3 Initial seed element 3.
*/
AbstractL64X128(long seed0, long seed1, long seed2, long seed3) {
super(seed0, seed1);
x0 = seed2;
x1 = seed3;
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
AbstractL64X128(AbstractL64X128 source) {
super(source);
x0 = source.x0;
x1 = source.x1;
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
return composeStateInternal(NumberFactory.makeByteArray(
new long[] {x0, x1}),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] c = splitStateInternal(s, XBG_STATE_SIZE * Long.BYTES);
final long[] tmp = NumberFactory.makeLongArray(c[0]);
x0 = tmp[0];
x1 = tmp[1];
super.setStateInternal(c[1]);
}
/**
* {@inheritDoc}
*
* <p>The jump size is the equivalent of moving the state <em>backwards</em> by
* (2<sup>128</sup> - 1) positions. It can provide up to 2<sup>64</sup>
* non-overlapping subsequences.
*/
@Override
public UniformRandomProvider jump() {
return super.jump();
}
/**
* {@inheritDoc}
*
* <p>The jump size is the equivalent of moving the state <em>backwards</em> by
* 2<sup>32</sup> (2<sup>128</sup> - 1) positions. It can provide up to
* 2<sup>32</sup> non-overlapping subsequences of length 2<sup>32</sup>
* (2<sup>128</sup> - 1); each subsequence can provide up to 2<sup>32</sup>
* non-overlapping subsequences of length (2<sup>128</sup> - 1) using the
* {@link #jump()} method.
*/
@Override
public JumpableUniformRandomProvider longJump() {
return super.longJump();
}
}
| 3,158 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/L128X128Mix.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
import java.util.stream.Stream;
import org.apache.commons.rng.JumpableUniformRandomProvider;
import org.apache.commons.rng.SplittableUniformRandomProvider;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.core.util.NumberFactory;
import org.apache.commons.rng.core.util.RandomStreams;
/**
* A 64-bit all purpose generator.
*
* <p>This is a member of the LXM family of generators: L=Linear congruential generator;
* X=Xor based generator; and M=Mix. This member uses a 128-bit LCG and 128-bit Xor-based
* generator. It is named as {@code "L128X128MixRandom"} in the {@code java.util.random}
* package introduced in JDK 17; the LXM family is described in further detail in:
*
* <blockquote>Steele and Vigna (2021) LXM: better splittable pseudorandom number generators
* (and almost as fast). Proceedings of the ACM on Programming Languages, Volume 5,
* Article 148, pp 1–31.</blockquote>
*
* <p>Memory footprint is 384 bits and the period is 2<sup>128</sup> (2<sup>128</sup> - 1).
*
* <p>This generator implements
* {@link org.apache.commons.rng.LongJumpableUniformRandomProvider LongJumpableUniformRandomProvider}.
* In addition instances created with a different additive parameter for the LCG are robust
* against accidental correlation in a multi-threaded setting. The additive parameters must be
* different in the most significant 127-bits.
*
* <p>This generator implements
* {@link org.apache.commons.rng.SplittableUniformRandomProvider SplittableUniformRandomProvider}.
* The stream of generators created using the {@code splits} methods support parallelisation
* and are robust against accidental correlation by using unique values for the additive parameter
* for each instance in the same stream. The primitive streaming methods support parallelisation
* but with no assurances of accidental correlation; each thread uses a new instance with a
* randomly initialised state.
*
* @see <a href="https://doi.org/10.1145/3485525">Steele & Vigna (2021) Proc. ACM Programming
* Languages 5, 1-31</a>
* @see <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/random/package-summary.html">
* JDK 17 java.util.random javadoc</a>
* @since 1.5
*/
public class L128X128Mix extends AbstractL128 implements SplittableUniformRandomProvider {
/** Size of the seed vector. */
private static final int SEED_SIZE = 6;
/** Size of the XBG state vector. */
private static final int XBG_STATE_SIZE = 2;
/** Low half of 128-bit LCG multiplier. */
private static final long ML = LXMSupport.M128L;
/** State 0 of the XBG. */
private long x0;
/** State 1 of the XBG. */
private long x1;
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 6, only the first 6 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros in the last four elements
* will create a non-functional XBG sub-generator and a low
* quality output with a period of 2<sup>128</sup>.
*
* <p>The 1st and 2nd elements are used to set the LCG increment; the least significant bit
* is set to odd to ensure a full period LCG. The 3rd and 4th elements are used
* to set the LCG state.</p>
*/
public L128X128Mix(long[] seed) {
super(seed = extendSeed(seed, SEED_SIZE));
x0 = seed[4];
x1 = seed[5];
}
/**
* Creates a new instance using a 6 element seed.
* A seed containing all zeros in the last four elements
* will create a non-functional XBG sub-generator and a low
* quality output with a period of 2<sup>128</sup>.
*
* <p>The 1st and 2nd elements are used to set the LCG increment; the least significant bit
* is set to odd to ensure a full period LCG. The 3rd and 4th elements are used
* to set the LCG state.</p>
*
* @param seed0 Initial seed element 0.
* @param seed1 Initial seed element 1.
* @param seed2 Initial seed element 2.
* @param seed3 Initial seed element 3.
* @param seed4 Initial seed element 4.
* @param seed5 Initial seed element 5.
*/
public L128X128Mix(long seed0, long seed1, long seed2, long seed3,
long seed4, long seed5) {
super(seed0, seed1, seed2, seed3);
x0 = seed4;
x1 = seed5;
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
protected L128X128Mix(L128X128Mix source) {
super(source);
x0 = source.x0;
x1 = source.x1;
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
return composeStateInternal(NumberFactory.makeByteArray(
new long[] {x0, x1}),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] c = splitStateInternal(s, XBG_STATE_SIZE * Long.BYTES);
final long[] tmp = NumberFactory.makeLongArray(c[0]);
x0 = tmp[0];
x1 = tmp[1];
super.setStateInternal(c[1]);
}
/** {@inheritDoc} */
@Override
public long next() {
// LXM generate.
// Old state is used for the output allowing parallel pipelining
// on processors that support multiple concurrent instructions.
final long s0 = x0;
final long sh = lsh;
// Mix
final long z = LXMSupport.lea64(sh + s0);
// LCG update
// The LCG is, in effect, "s = m * s + a" where m = ((1LL << 64) + ML)
final long sl = lsl;
final long al = lal;
final long u = ML * sl;
// High half
lsh = ML * sh + LXMSupport.unsignedMultiplyHigh(ML, sl) + sl + lah +
// Carry propagation
LXMSupport.unsignedAddHigh(u, al);
// Low half
lsl = u + al;
// XBG update
long s1 = x1;
s1 ^= s0;
x0 = Long.rotateLeft(s0, 24) ^ s1 ^ (s1 << 16); // a, b
x1 = Long.rotateLeft(s1, 37); // c
return z;
}
/**
* {@inheritDoc}
*
* <p>The jump size is the equivalent of moving the state <em>backwards</em> by
* (2<sup>128</sup> - 1) positions. It can provide up to 2<sup>128</sup>
* non-overlapping subsequences.
*/
@Override
public UniformRandomProvider jump() {
return super.jump();
}
/**
* {@inheritDoc}
*
* <p>The jump size is the equivalent of moving the state <em>backwards</em> by
* 2<sup>64</sup> (2<sup>128</sup> - 1) positions. It can provide up to
* 2<sup>64</sup> non-overlapping subsequences of length 2<sup>64</sup>
* (2<sup>128</sup> - 1); each subsequence can provide up to 2<sup>64</sup>
* non-overlapping subsequences of length (2<sup>128</sup> - 1) using the
* {@link #jump()} method.
*/
@Override
public JumpableUniformRandomProvider longJump() {
return super.longJump();
}
/** {@inheritDoc} */
@Override
AbstractL128 copy() {
// This exists to ensure the jump function performed in the super class returns
// the correct class type. It should not be public.
return new L128X128Mix(this);
}
/** {@inheritDoc} */
@Override
public SplittableUniformRandomProvider split(UniformRandomProvider source) {
return create(source.nextLong(), source);
}
/** {@inheritDoc} */
@Override
public Stream<SplittableUniformRandomProvider> splits(long streamSize, SplittableUniformRandomProvider source) {
return RandomStreams.generateWithSeed(streamSize, source, L128X128Mix::create);
}
/**
* Create a new instance using the given {@code seed} and {@code source} of randomness
* to initialise the instance.
*
* @param seed Seed used to initialise the instance.
* @param source Source of randomness used to initialise the instance.
* @return A new instance.
*/
private static SplittableUniformRandomProvider create(long seed, UniformRandomProvider source) {
// LCG state. The addition lower-half uses the input seed.
// The LCG addition parameter is set to odd so left-shift the seed.
final long s0 = source.nextLong();
final long s1 = seed << 1;
final long s2 = source.nextLong();
final long s3 = source.nextLong();
// XBG state must not be all zero
long x0 = source.nextLong();
long x1 = source.nextLong();
if ((x0 | x1) == 0) {
// SplitMix style seed ensures at least one non-zero value
final long z = s3;
x0 = LXMSupport.lea64(z);
x1 = LXMSupport.lea64(z + LXMSupport.GOLDEN_RATIO_64);
}
return new L128X128Mix(s0, s1, s2, s3, x0, x1);
}
}
| 3,159 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/L64X128StarStar.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
import java.util.stream.Stream;
import org.apache.commons.rng.SplittableUniformRandomProvider;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.core.util.RandomStreams;
/**
* A 64-bit all purpose generator.
*
* <p>This is a member of the LXM family of generators: L=Linear congruential generator;
* X=Xor based generator; and M=Mix. This member uses a 64-bit LCG and 128-bit Xor-based
* generator. It is named as {@code "L64X128StarStarRandom"} in the {@code java.util.random}
* package introduced in JDK 17; the LXM family is described in further detail in:
*
* <blockquote>Steele and Vigna (2021) LXM: better splittable pseudorandom number generators
* (and almost as fast). Proceedings of the ACM on Programming Languages, Volume 5,
* Article 148, pp 1–31.</blockquote>
*
* <p>Memory footprint is 256 bits and the period is 2<sup>64</sup> (2<sup>128</sup> - 1).
*
* <p>This generator implements
* {@link org.apache.commons.rng.LongJumpableUniformRandomProvider LongJumpableUniformRandomProvider}.
* In addition instances created with a different additive parameter for the LCG are robust
* against accidental correlation in a multi-threaded setting. The additive parameters must be
* different in the most significant 63-bits.
*
* @see <a href="https://doi.org/10.1145/3485525">Steele & Vigna (2021) Proc. ACM Programming
* Languages 5, 1-31</a>
* @see <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/random/package-summary.html">
* JDK 17 java.util.random javadoc</a>
* @since 1.5
*/
public class L64X128StarStar extends AbstractL64X128 implements SplittableUniformRandomProvider {
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 4, only the first 4 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros in the last two elements
* will create a non-functional XBG sub-generator and a low
* quality output with a period of 2<sup>64</sup>.
*
* <p>The 1st element is used to set the LCG increment; the least significant bit
* is set to odd to ensure a full period LCG. The 2nd element is used
* to set the LCG state.</p>
*/
public L64X128StarStar(long[] seed) {
super(seed);
}
/**
* Creates a new instance using a 4 element seed.
* A seed containing all zeros in the last two elements
* will create a non-functional XBG sub-generator and a low
* quality output with a period of 2<sup>64</sup>.
*
* <p>The 1st element is used to set the LCG increment; the least significant bit
* is set to odd to ensure a full period LCG. The 2nd element is used
* to set the LCG state.</p>
*
* @param seed0 Initial seed element 0.
* @param seed1 Initial seed element 1.
* @param seed2 Initial seed element 2.
* @param seed3 Initial seed element 3.
*/
public L64X128StarStar(long seed0, long seed1, long seed2, long seed3) {
super(seed0, seed1, seed2, seed3);
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
protected L64X128StarStar(L64X128StarStar source) {
super(source);
}
/** {@inheritDoc} */
@Override
public long next() {
// LXM generate.
// Old state is used for the output allowing parallel pipelining
// on processors that support multiple concurrent instructions.
final long s0 = x0;
final long s = ls;
// Mix
final long z = Long.rotateLeft((s + s0) * 5, 7) * 9;
// LCG update
ls = M * s + la;
// XBG update
long s1 = x1;
s1 ^= s0;
x0 = Long.rotateLeft(s0, 24) ^ s1 ^ (s1 << 16); // a, b
x1 = Long.rotateLeft(s1, 37); // c
return z;
}
/** {@inheritDoc} */
@Override
protected L64X128StarStar copy() {
// This exists to ensure the jump function performed in the super class returns
// the correct class type. It should not be public.
return new L64X128StarStar(this);
}
/** {@inheritDoc} */
@Override
public SplittableUniformRandomProvider split(UniformRandomProvider source) {
return create(source.nextLong(), source);
}
/** {@inheritDoc} */
@Override
public Stream<SplittableUniformRandomProvider> splits(long streamSize, SplittableUniformRandomProvider source) {
return RandomStreams.generateWithSeed(streamSize, source, L64X128StarStar::create);
}
/**
* Create a new instance using the given {@code seed} and {@code source} of randomness
* to initialise the instance.
*
* @param seed Seed used to initialise the instance.
* @param source Source of randomness used to initialise the instance.
* @return A new instance.
*/
private static SplittableUniformRandomProvider create(long seed, UniformRandomProvider source) {
// LCG state. The addition uses the input seed.
// The LCG addition parameter is set to odd so left-shift the seed.
final long s0 = seed << 1;
final long s1 = source.nextLong();
// XBG state must not be all zero
long x0 = source.nextLong();
long x1 = source.nextLong();
if ((x0 | x1) == 0) {
// SplitMix style seed ensures at least one non-zero value
x0 = LXMSupport.lea64(s1);
x1 = LXMSupport.lea64(s1 + LXMSupport.GOLDEN_RATIO_64);
}
return new L64X128StarStar(s0, s1, x0, x1);
}
}
| 3,160 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/JenkinsSmallFast64.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
import org.apache.commons.rng.core.util.NumberFactory;
/**
* Implement Bob Jenkins's small fast (JSF) 64-bit generator.
*
* <p>The state size is 256-bits.</p>
*
* @see <a href="https://burtleburtle.net/bob/rand/smallprng.html">A small noncryptographic PRNG</a>
* @since 1.3
*/
public class JenkinsSmallFast64 extends LongProvider {
/** State a. */
private long a;
/** State b. */
private long b;
/** State c. */
private long c;
/** Statd d. */
private long d;
/**
* Creates an instance with the given seed.
*
* @param seed Initial seed.
*/
public JenkinsSmallFast64(Long seed) {
setSeedInternal(seed);
}
/**
* Seeds the RNG.
*
* @param seed Seed.
*/
private void setSeedInternal(long seed) {
a = 0xf1ea5eedL;
b = c = d = seed;
for (int i = 0; i < 20; i++) {
next();
}
}
/** {@inheritDoc} */
@Override
public final long next() {
final long e = a - Long.rotateLeft(b, 7);
a = b ^ Long.rotateLeft(c, 13);
b = c + Long.rotateLeft(d, 37);
c = d + e;
d = e + a;
return d;
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
return composeStateInternal(NumberFactory.makeByteArray(new long[] {a, b, c, d}),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] parts = splitStateInternal(s, 4 * 8);
final long[] tmp = NumberFactory.makeLongArray(parts[0]);
a = tmp[0];
b = tmp[1];
c = tmp[2];
d = tmp[3];
super.setStateInternal(parts[1]);
}
}
| 3,161 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/L64X256Mix.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
import java.util.stream.Stream;
import org.apache.commons.rng.JumpableUniformRandomProvider;
import org.apache.commons.rng.SplittableUniformRandomProvider;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.core.util.NumberFactory;
import org.apache.commons.rng.core.util.RandomStreams;
/**
* A 64-bit all purpose generator.
*
* <p>This is a member of the LXM family of generators: L=Linear congruential generator;
* X=Xor based generator; and M=Mix. This member uses a 64-bit LCG and 256-bit Xor-based
* generator. It is named as {@code "L64X256MixRandom"} in the {@code java.util.random}
* package introduced in JDK 17; the LXM family is described in further detail in:
*
* <blockquote>Steele and Vigna (2021) LXM: better splittable pseudorandom number generators
* (and almost as fast). Proceedings of the ACM on Programming Languages, Volume 5,
* Article 148, pp 1–31.</blockquote>
*
* <p>Memory footprint is 384 bits and the period is 2<sup>64</sup> (2<sup>256</sup> - 1).
*
* <p>This generator implements
* {@link org.apache.commons.rng.LongJumpableUniformRandomProvider LongJumpableUniformRandomProvider}.
* In addition instances created with a different additive parameter for the LCG are robust
* against accidental correlation in a multi-threaded setting. The additive parameters must be
* different in the most significant 63-bits.
*
* <p>This generator implements
* {@link org.apache.commons.rng.SplittableUniformRandomProvider SplittableUniformRandomProvider}.
* The stream of generators created using the {@code splits} methods support parallelisation
* and are robust against accidental correlation by using unique values for the additive parameter
* for each instance in the same stream. The primitive streaming methods support parallelisation
* but with no assurances of accidental correlation; each thread uses a new instance with a
* randomly initialised state.
*
* @see <a href="https://doi.org/10.1145/3485525">Steele & Vigna (2021) Proc. ACM Programming
* Languages 5, 1-31</a>
* @see <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/random/package-summary.html">
* JDK 17 java.util.random javadoc</a>
* @since 1.5
*/
public class L64X256Mix extends AbstractL64 implements SplittableUniformRandomProvider {
/** Size of the seed vector. */
private static final int SEED_SIZE = 6;
/** Size of the XBG state vector. */
private static final int XBG_STATE_SIZE = 4;
/** LCG multiplier. */
private static final long M = LXMSupport.M64;
/** State 0 of the XBG. */
private long x0;
/** State 1 of the XBG. */
private long x1;
/** State 2 of the XBG. */
private long x2;
/** State 3 of the XBG. */
private long x3;
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 6, only the first 6 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros in the last four elements
* will create a non-functional XBG sub-generator and a low
* quality output with a period of 2<sup>64</sup>.
*
* <p>The 1st element is used to set the LCG increment; the least significant bit
* is set to odd to ensure a full period LCG. The 2nd element is used
* to set the LCG state.</p>
*/
public L64X256Mix(long[] seed) {
super(seed = extendSeed(seed, SEED_SIZE));
x0 = seed[2];
x1 = seed[3];
x2 = seed[4];
x3 = seed[5];
}
/**
* Creates a new instance using a 6 element seed.
* A seed containing all zeros in the last four elements
* will create a non-functional XBG sub-generator and a low
* quality output with a period of 2<sup>64</sup>.
*
* <p>The 1st element is used to set the LCG increment; the least significant bit
* is set to odd to ensure a full period LCG. The 2nd element is used
* to set the LCG state.</p>
*
* @param seed0 Initial seed element 0.
* @param seed1 Initial seed element 1.
* @param seed2 Initial seed element 2.
* @param seed3 Initial seed element 3.
* @param seed4 Initial seed element 4.
* @param seed5 Initial seed element 5.
*/
public L64X256Mix(long seed0, long seed1, long seed2, long seed3,
long seed4, long seed5) {
super(seed0, seed1);
x0 = seed2;
x1 = seed3;
x2 = seed4;
x3 = seed5;
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
protected L64X256Mix(L64X256Mix source) {
super(source);
x0 = source.x0;
x1 = source.x1;
x2 = source.x2;
x3 = source.x3;
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
return composeStateInternal(NumberFactory.makeByteArray(
new long[] {x0, x1, x2, x3}),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] c = splitStateInternal(s, XBG_STATE_SIZE * Long.BYTES);
final long[] tmp = NumberFactory.makeLongArray(c[0]);
x0 = tmp[0];
x1 = tmp[1];
x2 = tmp[2];
x3 = tmp[3];
super.setStateInternal(c[1]);
}
/** {@inheritDoc} */
@Override
public long next() {
// LXM generate.
// Old state is used for the output allowing parallel pipelining
// on processors that support multiple concurrent instructions.
long s0 = x0;
final long s = ls;
// Mix
final long z = LXMSupport.lea64(s + s0);
// LCG update
ls = M * s + la;
// XBG update
long s1 = x1;
long s2 = x2;
long s3 = x3;
final long t = s1 << 17;
s2 ^= s0;
s3 ^= s1;
s1 ^= s2;
s0 ^= s3;
s2 ^= t;
s3 = Long.rotateLeft(s3, 45);
x0 = s0;
x1 = s1;
x2 = s2;
x3 = s3;
return z;
}
/**
* {@inheritDoc}
*
* <p>The jump size is the equivalent of moving the state <em>backwards</em> by
* (2<sup>256</sup> - 1) positions. It can provide up to 2<sup>64</sup>
* non-overlapping subsequences.
*/
@Override
public UniformRandomProvider jump() {
return super.jump();
}
/**
* {@inheritDoc}
*
* <p>The jump size is the equivalent of moving the state <em>backwards</em> by
* 2<sup>32</sup> (2<sup>256</sup> - 1) positions. It can provide up to
* 2<sup>32</sup> non-overlapping subsequences of length 2<sup>32</sup>
* (2<sup>256</sup> - 1); each subsequence can provide up to 2<sup>32</sup>
* non-overlapping subsequences of length (2<sup>256</sup> - 1) using the
* {@link #jump()} method.
*/
@Override
public JumpableUniformRandomProvider longJump() {
return super.longJump();
}
/** {@inheritDoc} */
@Override
AbstractL64 copy() {
// This exists to ensure the jump function performed in the super class returns
// the correct class type. It should not be public.
return new L64X256Mix(this);
}
/** {@inheritDoc} */
@Override
public SplittableUniformRandomProvider split(UniformRandomProvider source) {
return create(source.nextLong(), source);
}
/** {@inheritDoc} */
@Override
public Stream<SplittableUniformRandomProvider> splits(long streamSize, SplittableUniformRandomProvider source) {
return RandomStreams.generateWithSeed(streamSize, source, L64X256Mix::create);
}
/**
* Create a new instance using the given {@code seed} and {@code source} of randomness
* to initialise the instance.
*
* @param seed Seed used to initialise the instance.
* @param source Source of randomness used to initialise the instance.
* @return A new instance.
*/
private static SplittableUniformRandomProvider create(long seed, UniformRandomProvider source) {
// LCG state. The addition uses the input seed.
// The LCG addition parameter is set to odd so left-shift the seed.
final long s0 = seed << 1;
final long s1 = source.nextLong();
// XBG state must not be all zero
long x0 = source.nextLong();
long x1 = source.nextLong();
long x2 = source.nextLong();
long x3 = source.nextLong();
if ((x0 | x1 | x2 | x3) == 0) {
// SplitMix style seed ensures at least one non-zero value
long z = s1;
x0 = LXMSupport.lea64(z);
x1 = LXMSupport.lea64(z += LXMSupport.GOLDEN_RATIO_64);
x2 = LXMSupport.lea64(z += LXMSupport.GOLDEN_RATIO_64);
x3 = LXMSupport.lea64(z + LXMSupport.GOLDEN_RATIO_64);
}
return new L64X256Mix(s0, s1, x0, x1, x2, x3);
}
}
| 3,162 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/L128X256Mix.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
import java.util.stream.Stream;
import org.apache.commons.rng.JumpableUniformRandomProvider;
import org.apache.commons.rng.SplittableUniformRandomProvider;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.core.util.NumberFactory;
import org.apache.commons.rng.core.util.RandomStreams;
/**
* A 64-bit all purpose generator.
*
* <p>This is a member of the LXM family of generators: L=Linear congruential generator;
* X=Xor based generator; and M=Mix. This member uses a 128-bit LCG and 256-bit Xor-based
* generator. It is named as {@code "L128X256MixRandom"} in the {@code java.util.random}
* package introduced in JDK 17; the LXM family is described in further detail in:
*
* <blockquote>Steele and Vigna (2021) LXM: better splittable pseudorandom number generators
* (and almost as fast). Proceedings of the ACM on Programming Languages, Volume 5,
* Article 148, pp 1–31.</blockquote>
*
* <p>Memory footprint is 512 bits and the period is 2<sup>128</sup> (2<sup>256</sup> - 1).
*
* <p>This generator implements
* {@link org.apache.commons.rng.LongJumpableUniformRandomProvider LongJumpableUniformRandomProvider}.
* In addition instances created with a different additive parameter for the LCG are robust
* against accidental correlation in a multi-threaded setting. The additive parameters must be
* different in the most significant 127-bits.
*
* <p>This generator implements
* {@link org.apache.commons.rng.SplittableUniformRandomProvider SplittableUniformRandomProvider}.
* The stream of generators created using the {@code splits} methods support parallelisation
* and are robust against accidental correlation by using unique values for the additive parameter
* for each instance in the same stream. The primitive streaming methods support parallelisation
* but with no assurances of accidental correlation; each thread uses a new instance with a
* randomly initialised state.
*
* @see <a href="https://doi.org/10.1145/3485525">Steele & Vigna (2021) Proc. ACM Programming
* Languages 5, 1-31</a>
* @see <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/random/package-summary.html">
* JDK 17 java.util.random javadoc</a>
* @since 1.5
*/
public class L128X256Mix extends AbstractL128 implements SplittableUniformRandomProvider {
/** Size of the seed vector. */
private static final int SEED_SIZE = 8;
/** Size of the XBG state vector. */
private static final int XBG_STATE_SIZE = 4;
/** Low half of 128-bit LCG multiplier. */
private static final long ML = LXMSupport.M128L;
/** State 0 of the XBG. */
private long x0;
/** State 1 of the XBG. */
private long x1;
/** State 2 of the XBG. */
private long x2;
/** State 3 of the XBG. */
private long x3;
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 8, only the first 8 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros in the last four elements
* will create a non-functional XBG sub-generator and a low
* quality output with a period of 2<sup>128</sup>.
*
* <p>The 1st and 2nd elements are used to set the LCG increment; the least significant bit
* is set to odd to ensure a full period LCG. The 3rd and 4th elements are used
* to set the LCG state.</p>
*/
public L128X256Mix(long[] seed) {
super(seed = extendSeed(seed, SEED_SIZE));
x0 = seed[4];
x1 = seed[5];
x2 = seed[6];
x3 = seed[7];
}
/**
* Creates a new instance using an 8 element seed.
* A seed containing all zeros in the last four elements
* will create a non-functional XBG sub-generator and a low
* quality output with a period of 2<sup>128</sup>.
*
* <p>The 1st and 2nd elements are used to set the LCG increment; the least significant bit
* is set to odd to ensure a full period LCG. The 3rd and 4th elements are used
* to set the LCG state.</p>
*
* @param seed0 Initial seed element 0.
* @param seed1 Initial seed element 1.
* @param seed2 Initial seed element 2.
* @param seed3 Initial seed element 3.
* @param seed4 Initial seed element 4.
* @param seed5 Initial seed element 5.
* @param seed6 Initial seed element 6.
* @param seed7 Initial seed element 7.
*/
public L128X256Mix(long seed0, long seed1, long seed2, long seed3,
long seed4, long seed5, long seed6, long seed7) {
super(seed0, seed1, seed2, seed3);
x0 = seed4;
x1 = seed5;
x2 = seed6;
x3 = seed7;
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
protected L128X256Mix(L128X256Mix source) {
super(source);
x0 = source.x0;
x1 = source.x1;
x2 = source.x2;
x3 = source.x3;
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
return composeStateInternal(NumberFactory.makeByteArray(
new long[] {x0, x1, x2, x3}),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] c = splitStateInternal(s, XBG_STATE_SIZE * Long.BYTES);
final long[] tmp = NumberFactory.makeLongArray(c[0]);
x0 = tmp[0];
x1 = tmp[1];
x2 = tmp[2];
x3 = tmp[3];
super.setStateInternal(c[1]);
}
/** {@inheritDoc} */
@Override
public long next() {
// LXM generate.
// Old state is used for the output allowing parallel pipelining
// on processors that support multiple concurrent instructions.
long s0 = x0;
final long sh = lsh;
// Mix
final long z = LXMSupport.lea64(sh + s0);
// LCG update
// The LCG is, in effect, "s = m * s + a" where m = ((1LL << 64) + ML)
final long sl = lsl;
final long al = lal;
final long u = ML * sl;
// High half
lsh = ML * sh + LXMSupport.unsignedMultiplyHigh(ML, sl) + sl + lah +
// Carry propagation
LXMSupport.unsignedAddHigh(u, al);
// Low half
lsl = u + al;
// XBG update
long s1 = x1;
long s2 = x2;
long s3 = x3;
final long t = s1 << 17;
s2 ^= s0;
s3 ^= s1;
s1 ^= s2;
s0 ^= s3;
s2 ^= t;
s3 = Long.rotateLeft(s3, 45);
x0 = s0;
x1 = s1;
x2 = s2;
x3 = s3;
return z;
}
/**
* {@inheritDoc}
*
* <p>The jump size is the equivalent of moving the state <em>backwards</em> by
* (2<sup>256</sup> - 1) positions. It can provide up to 2<sup>128</sup>
* non-overlapping subsequences.
*/
@Override
public UniformRandomProvider jump() {
return super.jump();
}
/**
* {@inheritDoc}
*
* <p>The jump size is the equivalent of moving the state <em>backwards</em> by
* 2<sup>64</sup> (2<sup>256</sup> - 1) positions. It can provide up to
* 2<sup>64</sup> non-overlapping subsequences of length 2<sup>64</sup>
* (2<sup>256</sup> - 1); each subsequence can provide up to 2<sup>64</sup>
* non-overlapping subsequences of length (2<sup>256</sup> - 1) using the
* {@link #jump()} method.
*/
@Override
public JumpableUniformRandomProvider longJump() {
return super.longJump();
}
/** {@inheritDoc} */
@Override
AbstractL128 copy() {
// This exists to ensure the jump function performed in the super class returns
// the correct class type. It should not be public.
return new L128X256Mix(this);
}
/** {@inheritDoc} */
@Override
public SplittableUniformRandomProvider split(UniformRandomProvider source) {
return create(source.nextLong(), source);
}
/** {@inheritDoc} */
@Override
public Stream<SplittableUniformRandomProvider> splits(long streamSize, SplittableUniformRandomProvider source) {
return RandomStreams.generateWithSeed(streamSize, source, L128X256Mix::create);
}
/**
* Create a new instance using the given {@code seed} and {@code source} of randomness
* to initialise the instance.
*
* @param seed Seed used to initialise the instance.
* @param source Source of randomness used to initialise the instance.
* @return A new instance.
*/
private static SplittableUniformRandomProvider create(long seed, UniformRandomProvider source) {
// LCG state. The addition lower-half uses the input seed.
// The LCG addition parameter is set to odd so left-shift the seed.
final long s0 = source.nextLong();
final long s1 = seed << 1;
final long s2 = source.nextLong();
final long s3 = source.nextLong();
// XBG state must not be all zero
long x0 = source.nextLong();
long x1 = source.nextLong();
long x2 = source.nextLong();
long x3 = source.nextLong();
if ((x0 | x1 | x2 | x3) == 0) {
// SplitMix style seed ensures at least one non-zero value
long z = s3;
x0 = LXMSupport.lea64(z);
x1 = LXMSupport.lea64(z += LXMSupport.GOLDEN_RATIO_64);
x2 = LXMSupport.lea64(z += LXMSupport.GOLDEN_RATIO_64);
x3 = LXMSupport.lea64(z + LXMSupport.GOLDEN_RATIO_64);
}
// The LCG addition parameter is set to odd so left-shift the seed
return new L128X256Mix(s0, s1, s2, s3, x0, x1, x2, x3);
}
}
| 3,163 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/XoRoShiRo1024StarStar.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
/**
* A large-state all-purpose 64-bit generator.
*
* <p>This is a member of the Xor-Shift-Rotate family of generators. Memory footprint is 1024 bits
* and the period is 2<sup>1024</sup>-1.</p>
*
* <p>Note: This can be used as a replacement for {@link XorShift1024Star}.</p>
*
* @see <a href="http://xorshift.di.unimi.it/xoroshiro1024starstar.c">Original source code</a>
* @see <a href="http://xoshiro.di.unimi.it/">xorshiro / xoroshiro generators</a>
* @since 1.3
*/
public class XoRoShiRo1024StarStar extends AbstractXoRoShiRo1024 {
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 16, only the first 16 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros will create a non-functional generator.
*/
public XoRoShiRo1024StarStar(long[] seed) {
super(seed);
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
protected XoRoShiRo1024StarStar(XoRoShiRo1024StarStar source) {
super(source);
}
/** {@inheritDoc} */
@Override
protected long transform(long s0, long s15) {
return Long.rotateLeft(s0 * 5, 7) * 9;
}
/** {@inheritDoc} */
@Override
protected XoRoShiRo1024StarStar copy() {
// This exists to ensure the jump function returns
// the correct class type. It should not be public.
return new XoRoShiRo1024StarStar(this);
}
}
| 3,164 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/LXMSupport.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
/**
* Utility support for the LXM family of generators. The LXM family is described
* in further detail in:
*
* <blockquote>Steele and Vigna (2021) LXM: better splittable pseudorandom number generators
* (and almost as fast). Proceedings of the ACM on Programming Languages, Volume 5,
* Article 148, pp 1–31.</blockquote>
*
* <p>Contains methods to compute unsigned multiplication of 64-bit
* and 128-bit values to create 128-bit results for use in a 128-bit
* linear congruential generator (LCG). Constants are provided to advance the state
* of an LCG by a power of 2 in a single multiply operation to support jump
* operations.
*
* @see <a href="https://doi.org/10.1145/3485525">Steele & Vigna (2021) Proc. ACM Programming
* Languages 5, 1-31</a>
* @since 1.5
*/
final class LXMSupport {
/** 64-bit LCG multiplier. Note: (M % 8) = 5. */
static final long M64 = 0xd1342543de82ef95L;
/** Jump constant {@code m'} for an advance of the 64-bit LCG by 2^32.
* Computed as: {@code m' = m^(2^32) (mod 2^64)}. */
static final long M64P = 0x8d23804c00000001L;
/** Jump constant precursor for {@code c'} for an advance of the 64-bit LCG by 2^32.
* Computed as:
* <pre>
* product_{i=0}^{31} { M^(2^i) + 1 } (mod 2^64)
* </pre>
* <p>The jump is computed for the LCG with an update step of {@code s = m * s + c} as:
* <pre>
* s = m' * s + c' * c
* </pre>
*/
static final long C64P = 0x16691c9700000000L;
/** Low half of 128-bit LCG multiplier. The upper half is {@code 1L}. */
static final long M128L = 0xd605bbb58c8abbfdL;
/** High half of the jump constant {@code m'} for an advance of the 128-bit LCG by 2^64.
* The low half is 1. Computed as: {@code m' = m^(2^64) (mod 2^128)}. */
static final long M128PH = 0x31f179f5224754f4L;
/** High half of the jump constant for an advance of the 128-bit LCG by 2^64.
* The low half is zero. Computed as:
* <pre>
* product_{i=0}^{63} { M^(2^i) + 1 } (mod 2^128)
* </pre>
* <p>The jump is computed for the LCG with an update step of {@code s = m * s + c} as:
* <pre>
* s = m' * s + c' * c
* </pre>
*/
static final long C128PH = 0x61139b28883277c3L;
/**
* The fractional part of the golden ratio, phi, scaled to 64-bits and rounded to odd.
* <pre>
* phi = (sqrt(5) - 1) / 2) * 2^64
* </pre>
* @see <a href="https://en.wikipedia.org/wiki/Golden_ratio">Golden ratio</a>
*/
static final long GOLDEN_RATIO_64 = 0x9e3779b97f4a7c15L;
/** A mask to convert an {@code int} to an unsigned integer stored as a {@code long}. */
private static final long INT_TO_UNSIGNED_BYTE_MASK = 0xffff_ffffL;
/** No instances. */
private LXMSupport() {}
/**
* Perform a 64-bit mixing function using Doug Lea's 64-bit mix constants and shifts.
*
* <p>This is based on the original 64-bit mix function of Austin Appleby's
* MurmurHash3 modified to use a single mix constant and 32-bit shifts, which may have
* a performance advantage on some processors. The code is provided in Steele and
* Vigna's paper.
*
* @param x the input value
* @return the output value
*/
static long lea64(long x) {
x = (x ^ (x >>> 32)) * 0xdaba0b6eb09322e3L;
x = (x ^ (x >>> 32)) * 0xdaba0b6eb09322e3L;
return x ^ (x >>> 32);
}
/**
* Multiply the two values as if unsigned 64-bit longs to produce the high 64-bits
* of the 128-bit unsigned result.
*
* <p>This method computes the equivalent of:
* <pre>{@code
* Math.multiplyHigh(a, b) + ((a >> 63) & b) + ((b >> 63) & a)
* }</pre>
*
* <p>Note: The method {@code Math.multiplyHigh} was added in JDK 9
* and should be used as above when the source code targets Java 11
* to exploit the intrinsic method.
*
* <p>Note: The method {@code Math.unsignedMultiplyHigh} was added in JDK 18
* and should be used when the source code target allows.
*
* @param value1 the first value
* @param value2 the second value
* @return the high 64-bits of the 128-bit result
*/
static long unsignedMultiplyHigh(long value1, long value2) {
// Computation is based on the following observation about the upper (a and x)
// and lower (b and y) bits of unsigned big-endian integers:
// ab * xy
// = b * y
// + b * x0
// + a0 * y
// + a0 * x0
// = b * y
// + b * x * 2^32
// + a * y * 2^32
// + a * x * 2^64
//
// Summation using a character for each byte:
//
// byby byby
// + bxbx bxbx 0000
// + ayay ayay 0000
// + axax axax 0000 0000
//
// The summation can be rearranged to ensure no overflow given
// that the result of two unsigned 32-bit integers multiplied together
// plus two full 32-bit integers cannot overflow 64 bits:
// > long x = (1L << 32) - 1
// > x * x + x + x == -1 (all bits set, no overflow)
//
// The carry is a composed intermediate which will never overflow:
//
// byby byby
// + bxbx 0000
// + ayay ayay 0000
//
// + bxbx 0000 0000
// + axax axax 0000 0000
final long a = value1 >>> 32;
final long b = value1 & INT_TO_UNSIGNED_BYTE_MASK;
final long x = value2 >>> 32;
final long y = value2 & INT_TO_UNSIGNED_BYTE_MASK;
final long by = b * y;
final long bx = b * x;
final long ay = a * y;
final long ax = a * x;
// Cannot overflow
final long carry = (by >>> 32) +
(bx & INT_TO_UNSIGNED_BYTE_MASK) +
ay;
// Note:
// low = (carry << 32) | (by & INT_TO_UNSIGNED_BYTE_MASK)
// Benchmarking shows outputting low to a long[] output argument
// has no benefit over computing 'low = value1 * value2' separately.
return (bx >>> 32) + (carry >>> 32) + ax;
}
/**
* Add the two values as if unsigned 64-bit longs to produce the high 64-bits
* of the 128-bit unsigned result.
*
* <h2>Warning</h2>
*
* <p>This method is computing a carry bit for a 128-bit linear congruential
* generator (LCG). The method is <em>not</em> applicable to all arguments.
* Some computations can be dropped if the {@code right} argument is assumed to
* be the LCG addition, which should be odd to ensure a full period LCG.
*
* @param left the left argument
* @param right the right argument (assumed to have the lowest bit set to 1)
* @return the carry (either 0 or 1)
*/
static long unsignedAddHigh(long left, long right) {
// Method compiles to 13 bytes as Java byte code.
// This is below the default of 35 for code inlining.
//
// The unsigned add of left + right may have a 65-bit result.
// If both values are shifted right by 1 then the sum will be
// within a 64-bit long. The right is assumed to have a low
// bit of 1 which has been lost in the shift. The method must
// compute if a 1 was shifted off the left which would have
// triggered a carry when adding to the right's assumed 1.
// The intermediate 64-bit result is shifted
// 63 bits to obtain the most significant bit of the 65-bit result.
// Using -1 is the same as a shift of (64 - 1) as only the last 6 bits
// are used by the shift but requires 1 less byte in java byte code.
//
// 01100001 left
// + 10011111 right always has low bit set to 1
//
// 0110000 1 carry last bit of left
// + 1001111 |
// + 1 <-+
// = 10000000 carry bit generated
return ((left >>> 1) + (right >>> 1) + (left & 1)) >>> -1;
}
}
| 3,165 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/XoShiRo512PlusPlus.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
/**
* A fast all-purpose generator.
*
* <p>This is a member of the Xor-Shift-Rotate family of generators. Memory footprint is 512 bits
* and the period is 2<sup>512</sup>-1. Speed is expected to be slower than
* {@link XoShiRo256StarStar}.</p>
*
* @see <a href="http://xoshiro.di.unimi.it/xoshiro512plusplus.c">Original source code</a>
* @see <a href="http://xoshiro.di.unimi.it/">xorshiro / xoroshiro generators</a>
* @since 1.3
*/
public class XoShiRo512PlusPlus extends AbstractXoShiRo512 {
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 8, only the first 8 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros will create a non-functional generator.
*/
public XoShiRo512PlusPlus(long[] seed) {
super(seed);
}
/**
* Creates a new instance using an 8 element seed.
* A seed containing all zeros will create a non-functional generator.
*
* @param seed0 Initial seed element 0.
* @param seed1 Initial seed element 1.
* @param seed2 Initial seed element 2.
* @param seed3 Initial seed element 3.
* @param seed4 Initial seed element 4.
* @param seed5 Initial seed element 5.
* @param seed6 Initial seed element 6.
* @param seed7 Initial seed element 7.
*/
public XoShiRo512PlusPlus(long seed0, long seed1, long seed2, long seed3,
long seed4, long seed5, long seed6, long seed7) {
super(seed0, seed1, seed2, seed3, seed4, seed5, seed6, seed7);
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
protected XoShiRo512PlusPlus(XoShiRo512PlusPlus source) {
super(source);
}
/** {@inheritDoc} */
@Override
protected long nextOutput() {
return Long.rotateLeft(state0 + state2, 17) + state2;
}
/** {@inheritDoc} */
@Override
protected XoShiRo512PlusPlus copy() {
// This exists to ensure the jump function performed in the super class returns
// the correct class type. It should not be public.
return new XoShiRo512PlusPlus(this);
}
}
| 3,166 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/AbstractL64.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
import org.apache.commons.rng.JumpableUniformRandomProvider;
import org.apache.commons.rng.LongJumpableUniformRandomProvider;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.core.util.NumberFactory;
/**
* This abstract class is a base for algorithms from the LXM family of
* generators with a 64-bit LCG sub-generator. The class implements
* the jump functions.
*
* @since 1.5
*/
abstract class AbstractL64 extends LongProvider implements LongJumpableUniformRandomProvider {
/** Size of the seed vector. */
private static final int SEED_SIZE = 2;
/** Per-instance LCG additive parameter (must be odd).
* Cannot be final to support RestorableUniformRandomProvider. */
protected long la;
/** State of the LCG generator. */
protected long ls;
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 2, only the first 2 elements will
* be used; if smaller, the remaining elements will be automatically
* set.
*
* <p>The 1st element is used to set the LCG increment; the least significant bit
* is set to odd to ensure a full period LCG. The 2nd element is used
* to set the LCG state.</p>
*/
AbstractL64(long[] seed) {
setState(extendSeed(seed, SEED_SIZE));
}
/**
* Creates a new instance using a 2 element seed.
*
* <p>The 1st element is used to set the LCG increment; the least significant bit
* is set to odd to ensure a full period LCG. The 2nd element is used
* to set the LCG state.</p>
*
* @param seed0 Initial seed element 0.
* @param seed1 Initial seed element 1.
*/
AbstractL64(long seed0, long seed1) {
// Additive parameter must be odd
la = seed0 | 1;
ls = seed1;
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
AbstractL64(AbstractL64 source) {
super(source);
la = source.la;
ls = source.ls;
}
/**
* Copies the state into the generator state.
*
* @param state the new state
*/
private void setState(long[] state) {
// Additive parameter must be odd
la = state[0] | 1;
ls = state[1];
}
/** {@inheritDoc} */
@Override
protected byte[] getStateInternal() {
return composeStateInternal(NumberFactory.makeByteArray(
new long[] {la, ls}),
super.getStateInternal());
}
/** {@inheritDoc} */
@Override
protected void setStateInternal(byte[] s) {
final byte[][] c = splitStateInternal(s, SEED_SIZE * Long.BYTES);
setState(NumberFactory.makeLongArray(c[0]));
super.setStateInternal(c[1]);
}
/**
* Creates a copy of the UniformRandomProvider and then <em>retreats</em> the state of the
* current instance. The copy is returned.
*
* <p>The jump is performed by advancing the state of the LCG sub-generator by 1 cycle.
* The XBG state is unchanged.
*/
@Override
public UniformRandomProvider jump() {
final UniformRandomProvider copy = copy();
// Advance the LCG 1 step
ls = LXMSupport.M64 * ls + la;
resetCachedState();
return copy;
}
/**
* Creates a copy of the UniformRandomProvider and then <em>retreats</em> the state of the
* current instance. The copy is returned.
*
* <p>The jump is performed by advancing the state of the LCG sub-generator by
* 2<sup>32</sup> cycles. The XBG state is unchanged.
*/
@Override
public JumpableUniformRandomProvider longJump() {
final JumpableUniformRandomProvider copy = copy();
// Advance the LCG 2^32 steps
ls = LXMSupport.M64P * ls + LXMSupport.C64P * la;
resetCachedState();
return copy;
}
/**
* Create a copy.
*
* @return the copy
*/
abstract AbstractL64 copy();
}
| 3,167 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/XorShift1024StarPhi.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
/**
* A fast RNG implementing the {@code XorShift1024*} algorithm.
*
* <p>Note: This supersedes {@link XorShift1024Star}. The sequences emitted by both
* generators are correlated.</p>
*
* <p>This generator differs only in the final multiplier (a fixed-point representation
* of the golden ratio), which eliminates linear dependencies from one of the lowest
* bits.</p>
*
* @see <a href="http://xorshift.di.unimi.it/xorshift1024star.c">Original source code</a>
* @see <a href="https://en.wikipedia.org/wiki/Xorshift">Xorshift (Wikipedia)</a>
* @since 1.3
*/
public class XorShift1024StarPhi extends XorShift1024Star {
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 16, only the first 16 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros will create a non-functional generator.
*/
public XorShift1024StarPhi(long[] seed) {
super(seed, 0x9e3779b97f4a7c13L);
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
protected XorShift1024StarPhi(XorShift1024StarPhi source) {
super(source);
}
/** {@inheritDoc} */
@Override
protected XorShift1024StarPhi copy() {
// This exists to ensure the jump function performed in the super class returns
// the correct class type. It should not be public.
return new XorShift1024StarPhi(this);
}
}
| 3,168 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/package-info.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Concrete algorithms for {@code long}-based sources of randomness.
*
* <p>
* <b>For internal use only:</b> Direct access to classes in this package
* is discouraged, as they could be modified without notice.
* </p>
*
* <p><b>Notes for developers</b></p>
*
* <ul>
* <li>
* A source of randomness must inherit from
* {@link org.apache.commons.rng.core.source64.LongProvider}
* </li>
* <li>
* The "provider" must specify <em>one</em> way for setting the seed.
* For a given seed, the generated sequence must always be the same.
* </li>
* <li>
* The "provider" must implement methods {@code getStateInternal} and
* {@code setStateInternal} in order to save and restore the state of an
* instance (cf. {@link org.apache.commons.rng.core.BaseProvider}).
* </li>
* <li>
* When a new class is implemented here, user-access to it must be
* provided through associated {@code RandomSource} factory methods
* defined in module "commons-rng-simple".
* </li>
* </ul>
*/
package org.apache.commons.rng.core.source64;
| 3,169 |
0 | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core | Create_ds/commons-rng/commons-rng-core/src/main/java/org/apache/commons/rng/core/source64/XoShiRo512StarStar.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.core.source64;
/**
* A fast all-purpose generator.
*
* <p>This is a member of the Xor-Shift-Rotate family of generators. Memory footprint is 512 bits
* and the period is 2<sup>512</sup>-1. Speed is expected to be slower than
* {@link XoShiRo256StarStar}.</p>
*
* @see <a href="http://xoshiro.di.unimi.it/xoshiro512starstar.c">Original source code</a>
* @see <a href="http://xoshiro.di.unimi.it/">xorshiro / xoroshiro generators</a>
* @since 1.3
*/
public class XoShiRo512StarStar extends AbstractXoShiRo512 {
/**
* Creates a new instance.
*
* @param seed Initial seed.
* If the length is larger than 8, only the first 8 elements will
* be used; if smaller, the remaining elements will be automatically
* set. A seed containing all zeros will create a non-functional generator.
*/
public XoShiRo512StarStar(long[] seed) {
super(seed);
}
/**
* Creates a new instance using an 8 element seed.
* A seed containing all zeros will create a non-functional generator.
*
* @param seed0 Initial seed element 0.
* @param seed1 Initial seed element 1.
* @param seed2 Initial seed element 2.
* @param seed3 Initial seed element 3.
* @param seed4 Initial seed element 4.
* @param seed5 Initial seed element 5.
* @param seed6 Initial seed element 6.
* @param seed7 Initial seed element 7.
*/
public XoShiRo512StarStar(long seed0, long seed1, long seed2, long seed3,
long seed4, long seed5, long seed6, long seed7) {
super(seed0, seed1, seed2, seed3, seed4, seed5, seed6, seed7);
}
/**
* Creates a copy instance.
*
* @param source Source to copy.
*/
protected XoShiRo512StarStar(XoShiRo512StarStar source) {
super(source);
}
/** {@inheritDoc} */
@Override
protected long nextOutput() {
return Long.rotateLeft(state1 * 5, 7) * 9;
}
/** {@inheritDoc} */
@Override
protected XoShiRo512StarStar copy() {
// This exists to ensure the jump function performed in the super class returns
// the correct class type. It should not be public.
return new XoShiRo512StarStar(this);
}
}
| 3,170 |
0 | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn/provisioner/ProvisionerPostgreSQLInitializer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.provisioner;
import com.opentable.db.postgres.embedded.EmbeddedPostgres;
import org.junit.rules.ExternalResource;
import java.io.IOException;
/**
* @author Myrle Krantz
*/
public class ProvisionerPostgreSQLInitializer extends ExternalResource {
private static EmbeddedPostgres EMBEDDED_POSTGRESQL_DB;
@Override
protected void before() throws IOException {
try {
EMBEDDED_POSTGRESQL_DB = EmbeddedPostgres.builder().setPort(5432).start();
}
catch (IOException ioex) {
System.out.println(ioex);
}
}
@Override
protected void after() {
try {
EMBEDDED_POSTGRESQL_DB.close();
} catch (IOException io) {
System.out.println(io);
}
}
}
| 3,171 |
0 | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn/provisioner/ProvisionerCassandraInitializer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.provisioner;
import org.apache.thrift.transport.TTransportException;
import org.cassandraunit.utils.EmbeddedCassandraServerHelper;
import org.junit.rules.ExternalResource;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
/**
* @author Myrle Krantz
*/
public class ProvisionerCassandraInitializer extends ExternalResource {
@Override
protected void before() throws InterruptedException, IOException, TTransportException {
EmbeddedCassandraServerHelper.startEmbeddedCassandra(TimeUnit.SECONDS.toMillis(30L));
}
@Override
protected void after() {
EmbeddedCassandraServerHelper.cleanEmbeddedCassandra();
}
}
| 3,172 |
0 | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn/provisioner/AbstractServiceTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.provisioner;
import org.apache.fineract.cn.provisioner.api.v1.client.Provisioner;
import org.apache.fineract.cn.provisioner.config.ProvisionerServiceConfig;
import org.apache.fineract.cn.test.env.TestEnvironment;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,
classes = {AbstractServiceTest.TestConfiguration.class})
public class AbstractServiceTest {
private static final String APP_NAME = "provisioner-v1";
private static final String CLIENT_ID = "sillyRabbit";
@Configuration
@EnableFeignClients(basePackages = {"org.apache.fineract.cn.provisioner.api.v1.client"})
// @RibbonClient(name = APP_NAME)
@Import({ProvisionerServiceConfig.class})
public static class TestConfiguration {
public TestConfiguration() {
super();
}
@Bean()
public Logger logger() {
return LoggerFactory.getLogger("test-logger");
}
}
private static TestEnvironment testEnvironment = new TestEnvironment(APP_NAME);
private static ProvisionerPostgreSQLInitializer postgreSQLInitializer = new ProvisionerPostgreSQLInitializer();
private static ProvisionerCassandraInitializer cassandraInitializer = new ProvisionerCassandraInitializer();
@ClassRule
public static TestRule orderClassRules = RuleChain
.outerRule(testEnvironment)
.around(postgreSQLInitializer)
.around(cassandraInitializer);
@SuppressWarnings("SpringAutowiredFieldsWarningInspection")
@Autowired
protected Provisioner provisioner;
public AbstractServiceTest() {
super();
}
@BeforeClass
public static void setup() throws Exception {
System.setProperty("system.privateKey.modulus", testEnvironment.getSystemPrivateKey().getModulus().toString());
System.setProperty("system.privateKey.exponent", testEnvironment.getSystemPrivateKey().getPrivateExponent().toString());
System.setProperty("system.initialclientid", CLIENT_ID);
}
protected String getClientId() {
return CLIENT_ID;
}
} | 3,173 |
0 | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn/provisioner | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn/provisioner/tenant/TestTenantApplicationAssignment.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.provisioner.tenant;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.anyObject;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.when;
import com.google.gson.Gson;
import org.apache.fineract.cn.provisioner.ProvisionerCassandraInitializer;
import org.apache.fineract.cn.provisioner.ProvisionerPostgreSQLInitializer;
import org.apache.fineract.cn.provisioner.api.v1.client.Provisioner;
import org.apache.fineract.cn.provisioner.api.v1.domain.Application;
import org.apache.fineract.cn.provisioner.api.v1.domain.AssignedApplication;
import org.apache.fineract.cn.provisioner.api.v1.domain.AuthenticationResponse;
import org.apache.fineract.cn.provisioner.api.v1.domain.IdentityManagerInitialization;
import org.apache.fineract.cn.provisioner.api.v1.domain.Tenant;
import org.apache.fineract.cn.provisioner.config.ProvisionerConstants;
import org.apache.fineract.cn.provisioner.config.ProvisionerServiceConfig;
import org.apache.fineract.cn.provisioner.internal.listener.IdentityListener;
import org.apache.fineract.cn.provisioner.internal.service.applications.ApplicationCallContextProvider;
import org.apache.fineract.cn.provisioner.internal.util.TokenProvider;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.finearct.cn.permittedfeignclient.api.v1.client.ApplicationPermissionRequirements;
import org.apache.finearct.cn.permittedfeignclient.api.v1.domain.ApplicationPermission;
import org.apache.fineract.cn.anubis.api.v1.client.Anubis;
import org.apache.fineract.cn.anubis.api.v1.domain.AllowedOperation;
import org.apache.fineract.cn.anubis.api.v1.domain.ApplicationSignatureSet;
import org.apache.fineract.cn.anubis.api.v1.domain.PermittableEndpoint;
import org.apache.fineract.cn.anubis.api.v1.domain.Signature;
import org.apache.fineract.cn.anubis.test.v1.SystemSecurityEnvironment;
import org.apache.fineract.cn.api.context.AutoSeshat;
import org.apache.fineract.cn.api.util.ApiConstants;
import org.apache.fineract.cn.api.util.ApiFactory;
import org.apache.fineract.cn.identity.api.v1.client.IdentityManager;
import org.apache.fineract.cn.identity.api.v1.domain.CallEndpointSet;
import org.apache.fineract.cn.identity.api.v1.domain.Permission;
import org.apache.fineract.cn.identity.api.v1.domain.PermittableGroup;
import org.apache.fineract.cn.identity.api.v1.events.ApplicationSignatureEvent;
import org.apache.fineract.cn.lang.AutoTenantContext;
import org.apache.fineract.cn.lang.security.RsaKeyPairFactory;
import org.apache.fineract.cn.test.env.TestEnvironment;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Myrle Krantz
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class TestTenantApplicationAssignment {
private static final String APP_NAME = "provisioner-v1";
private static final String CLIENT_ID = "sillyRabbit";
@Configuration
@EnableFeignClients(basePackages = {"org.apache.fineract.cn.provisioner.api.v1.client"})
// @RibbonClient(name = APP_NAME)
@Import({ProvisionerServiceConfig.class})
public static class TestConfiguration {
public TestConfiguration() {
super();
}
@Bean()
public Logger logger() {
return LoggerFactory.getLogger("test-logger");
}
@Bean()
public ApplicationCallContextProvider applicationCallContextProvider(
final ApiFactory apiFactory,
final @Qualifier("tokenProviderSpy") TokenProvider tokenProviderSpy)
{
return Mockito.spy(new ApplicationCallContextProvider(apiFactory, tokenProviderSpy));
}
@Bean(name = "tokenProviderSpy")
public TokenProvider tokenProviderSpy(final @Qualifier("tokenProvider") TokenProvider tokenProvider)
{
return Mockito.spy(tokenProvider);
}
}
private static TestEnvironment testEnvironment = new TestEnvironment(APP_NAME);
private static ProvisionerPostgreSQLInitializer postgreSQLInitializer = new ProvisionerPostgreSQLInitializer();
private static ProvisionerCassandraInitializer cassandraInitializer = new ProvisionerCassandraInitializer();
private static SystemSecurityEnvironment systemSecurityEnvironment
= new SystemSecurityEnvironment(testEnvironment.getSystemKeyTimestamp(), testEnvironment.getSystemPublicKey(), testEnvironment.getSystemPrivateKey());
@ClassRule
public static TestRule orderClassRules = RuleChain
.outerRule(testEnvironment)
.around(postgreSQLInitializer)
.around(cassandraInitializer);
@SuppressWarnings("SpringAutowiredFieldsWarningInspection")
@Autowired
private Provisioner provisioner;
@SuppressWarnings("SpringAutowiredFieldsWarningInspection")
@Autowired
private ApplicationCallContextProvider applicationCallContextProviderSpy;
@SuppressWarnings("SpringAutowiredFieldsWarningInspection")
@Autowired
private IdentityListener identityListener;
@SuppressWarnings("SpringAutowiredFieldsWarningInspection")
@Autowired
private Gson gson;
private AutoSeshat autoSeshat;
public TestTenantApplicationAssignment() {
super();
}
@BeforeClass
public static void setup() throws Exception {
System.setProperty("system.privateKey.modulus", testEnvironment.getSystemPrivateKey().getModulus().toString());
System.setProperty("system.privateKey.exponent", testEnvironment.getSystemPrivateKey().getPrivateExponent().toString());
System.setProperty("system.initialclientid", CLIENT_ID);
}
@Before
public void before()
{
final AuthenticationResponse authentication = this.provisioner.authenticate(
CLIENT_ID, ApiConstants.SYSTEM_SU, ProvisionerConstants.INITIAL_PWD);
autoSeshat = new AutoSeshat(authentication.getToken());
}
@After
public void after() throws InterruptedException {
this.provisioner.deleteTenant(Fixture.getCompTestTenant().getIdentifier());
Thread.sleep(500L);
autoSeshat.close();
}
private class VerifyIsisInitializeContext implements Answer<ApplicationSignatureSet> {
private final String keyTimestamp;
private final BigInteger modulus;
private final BigInteger exponent;
private final String tenantIdentifier;
private boolean validSecurityContext = false;
VerifyIsisInitializeContext(
final String keyTimestamp,
final BigInteger modulus,
final BigInteger exponent,
final String tenantIdentifier) {
this.keyTimestamp = keyTimestamp;
this.modulus = modulus;
this.exponent = exponent;
this.tenantIdentifier = tenantIdentifier;
}
@Override
public ApplicationSignatureSet answer(final InvocationOnMock invocation) throws Throwable {
validSecurityContext = systemSecurityEnvironment.isValidSystemSecurityContext("identity", "1", tenantIdentifier);
final Signature fakeSignature = new Signature();
fakeSignature.setPublicKeyMod(modulus);
fakeSignature.setPublicKeyExp(exponent);
final ApplicationSignatureSet ret = new ApplicationSignatureSet();
ret.setTimestamp(keyTimestamp);
ret.setApplicationSignature(fakeSignature);
ret.setIdentityManagerSignature(fakeSignature);
return ret;
}
String getKeyTimestamp() {
return keyTimestamp;
}
boolean isValidSecurityContext() {
return validSecurityContext;
}
}
private class VerifyAnubisInitializeContext implements Answer<Void> {
private boolean validSecurityContext = false;
final private String target;
private final String tenantIdentifier;
private VerifyAnubisInitializeContext(final String target, String tenantIdentifier) {
this.target = target;
this.tenantIdentifier = tenantIdentifier;
}
@Override
public Void answer(final InvocationOnMock invocation) throws Throwable {
validSecurityContext = systemSecurityEnvironment.isValidSystemSecurityContext(target, "1", tenantIdentifier);
return null;
}
boolean isValidSecurityContext() {
return validSecurityContext;
}
}
private class VerifyCreateSignatureSetContext implements Answer<ApplicationSignatureSet> {
private final RsaKeyPairFactory.KeyPairHolder answer;
private boolean validSecurityContext = false;
final private String target;
private final String tenantIdentifier;
private VerifyCreateSignatureSetContext(final RsaKeyPairFactory.KeyPairHolder answer, final String target, final String tenantIdentifier) {
this.answer = answer;
this.target = target;
this.tenantIdentifier = tenantIdentifier;
}
@Override
public ApplicationSignatureSet answer(final InvocationOnMock invocation) throws Throwable {
final String timestamp = invocation.getArgumentAt(0, String.class);
final Signature identityManagerSignature = invocation.getArgumentAt(1, Signature.class);
validSecurityContext = systemSecurityEnvironment.isValidSystemSecurityContext(target, "1", tenantIdentifier);
return new ApplicationSignatureSet(
timestamp,
new Signature(answer.getPublicKeyMod(), answer.getPublicKeyExp()),
identityManagerSignature);
}
boolean isValidSecurityContext() {
return validSecurityContext;
}
}
private class VerifyAnubisPermittablesContext implements Answer<List<PermittableEndpoint>> {
private boolean validSecurityContext = false;
private final List<PermittableEndpoint> answer;
private final String tenantIdentifier;
private VerifyAnubisPermittablesContext(final List<PermittableEndpoint> answer, final String tenantIdentifier) {
this.answer = answer;
this.tenantIdentifier = tenantIdentifier;
}
@Override
public List<PermittableEndpoint> answer(final InvocationOnMock invocation) throws Throwable {
validSecurityContext = systemSecurityEnvironment.isValidGuestSecurityContext(tenantIdentifier);
return answer;
}
boolean isValidSecurityContext() {
return validSecurityContext;
}
}
private class VerifyAnputRequiredPermissionsContext implements Answer<List<ApplicationPermission>> {
private boolean validSecurityContext = false;
private final List<ApplicationPermission> answer;
private final String tenantIdentifier;
private VerifyAnputRequiredPermissionsContext(final List<ApplicationPermission> answer, final String tenantIdentifier) {
this.answer = answer;
this.tenantIdentifier = tenantIdentifier;
}
@Override
public List<ApplicationPermission> answer(final InvocationOnMock invocation) throws Throwable {
validSecurityContext = systemSecurityEnvironment.isValidGuestSecurityContext(tenantIdentifier);
return answer;
}
boolean isValidSecurityContext() {
return validSecurityContext;
}
}
private class VerifyIsisCreatePermittableGroup implements Answer<Void> {
private boolean validSecurityContext = true;
private final String tenantIdentifier;
private int callCount = 0;
private VerifyIsisCreatePermittableGroup(final String tenantIdentifier) {
this.tenantIdentifier = tenantIdentifier;
}
@Override
public Void answer(final InvocationOnMock invocation) throws Throwable {
final boolean validSecurityContextForThisCall = systemSecurityEnvironment.isValidSystemSecurityContext("identity", "1", tenantIdentifier);
validSecurityContext = validSecurityContext && validSecurityContextForThisCall;
callCount++;
final PermittableGroup arg = invocation.getArgumentAt(0, PermittableGroup.class);
identityListener.onCreatePermittableGroup(tenantIdentifier, arg.getIdentifier());
return null;
}
boolean isValidSecurityContext() {
return validSecurityContext;
}
int getCallCount() {
return callCount;
}
}
private class VerifyIsisSetApplicationSignature implements Answer<Void> {
private boolean validSecurityContext = false;
private final String tenantIdentifier;
private VerifyIsisSetApplicationSignature(final String tenantIdentifier) {
this.tenantIdentifier = tenantIdentifier;
}
@Override
public Void answer(final InvocationOnMock invocation) throws Throwable {
validSecurityContext = systemSecurityEnvironment.isValidSystemSecurityContext("identity", "1", tenantIdentifier);
final String applicationIdentifier = invocation.getArgumentAt(0, String.class);
final String keyTimestamp = invocation.getArgumentAt(1, String.class);
identityListener.onSetApplicationSignature(tenantIdentifier,
gson.toJson(new ApplicationSignatureEvent(applicationIdentifier, keyTimestamp)));
return null;
}
boolean isValidSecurityContext() {
return validSecurityContext;
}
}
private class VerifyIsisCreateApplicationPermission implements Answer<Void> {
private boolean validSecurityContext = true;
private final String tenantIdentifier;
private final String applicationIdentifier;
private int callCount = 0;
private VerifyIsisCreateApplicationPermission(final String tenantIdentifier, final String applicationIdentifier) {
this.tenantIdentifier = tenantIdentifier;
this.applicationIdentifier = applicationIdentifier;
}
@Override
public Void answer(final InvocationOnMock invocation) throws Throwable {
final boolean validSecurityContextForThisCall = systemSecurityEnvironment.isValidSystemSecurityContext("identity", "1", tenantIdentifier);
validSecurityContext = validSecurityContext && validSecurityContextForThisCall;
callCount++;
final String callApplicationIdentifier = invocation.getArgumentAt(0, String.class);
Assert.assertEquals(this.applicationIdentifier, callApplicationIdentifier);
return null;
}
boolean isValidSecurityContext() {
return validSecurityContext;
}
int getCallCount() {
return callCount;
}
}
@Test
public void testTenantApplicationAssignment() throws Exception {
//Create org.apache.fineract.cn.provisioner.tenant
final Tenant tenant = Fixture.getCompTestTenant();
provisioner.createTenant(tenant);
//Create identity service application
final Application identityServiceApp = new Application();
identityServiceApp.setName("identity-v1");
identityServiceApp.setHomepage("http://xyz.identity:2020/v1");
identityServiceApp.setDescription("identity manager");
identityServiceApp.setVendor("fineract");
provisioner.createApplication(identityServiceApp);
//Assign identity service application. This requires some mocking since we can't actually call initialize in a component test.
final AssignedApplication identityServiceAssigned = new AssignedApplication();
identityServiceAssigned.setName("identity-v1");
final IdentityManager identityServiceMock = Mockito.mock(IdentityManager.class);
when(applicationCallContextProviderSpy.getApplication(IdentityManager.class, "http://xyz.identity:2020/v1")).thenReturn(identityServiceMock);
final VerifyIsisInitializeContext verifyInitializeContextAndReturnSignature;
try (final AutoTenantContext ignored = new AutoTenantContext(tenant.getIdentifier())) {
verifyInitializeContextAndReturnSignature = new VerifyIsisInitializeContext(
systemSecurityEnvironment.tenantKeyTimestamp(),
systemSecurityEnvironment.tenantPublicKey().getModulus(),
systemSecurityEnvironment.tenantPublicKey().getPublicExponent(), tenant.getIdentifier());
}
doAnswer(verifyInitializeContextAndReturnSignature).when(identityServiceMock).initialize(anyString());
{
final IdentityManagerInitialization identityServiceAdminInitialization
= provisioner.assignIdentityManager(tenant.getIdentifier(), identityServiceAssigned);
Assert.assertTrue(verifyInitializeContextAndReturnSignature.isValidSecurityContext());
Assert.assertNotNull(identityServiceAdminInitialization);
Assert.assertNotNull(identityServiceAdminInitialization.getAdminPassword());
}
//Create horus application.
final Application officeApp = new Application();
officeApp.setName("office-v1");
officeApp.setHomepage("http://xyz.office:2021/v1");
officeApp.setDescription("organization manager");
officeApp.setVendor("fineract");
provisioner.createApplication(officeApp);
//Assign horus application.
final AssignedApplication officeAssigned = new AssignedApplication();
officeAssigned.setName("office-v1");
final Anubis anubisMock = Mockito.mock(Anubis.class);
when(applicationCallContextProviderSpy.getApplication(Anubis.class, "http://xyz.office:2021/v1")).thenReturn(anubisMock);
final ApplicationPermissionRequirements anputMock = Mockito.mock(ApplicationPermissionRequirements.class);
when(applicationCallContextProviderSpy.getApplication(ApplicationPermissionRequirements.class, "http://xyz.office:2021/v1")).thenReturn(anputMock);
final RsaKeyPairFactory.KeyPairHolder keysInApplicationSignature = RsaKeyPairFactory.createKeyPair();
final PermittableEndpoint xxPermittableEndpoint = new PermittableEndpoint("/x/y", "POST", "x");
final PermittableEndpoint xyPermittableEndpoint = new PermittableEndpoint("/y/z", "POST", "x");
final PermittableEndpoint xyGetPermittableEndpoint = new PermittableEndpoint("/y/z", "GET", "x");
final PermittableEndpoint mPermittableEndpoint = new PermittableEndpoint("/m/n", "GET", "m");
final ApplicationPermission forFooPermission = new ApplicationPermission("forPurposeFoo", new Permission("x", AllowedOperation.ALL));
final ApplicationPermission forBarPermission = new ApplicationPermission("forPurposeBar", new Permission("m", Collections.singleton(AllowedOperation.READ)));
final VerifyAnubisInitializeContext verifyAnubisInitializeContext;
final VerifyCreateSignatureSetContext verifyCreateSignatureSetContext;
final VerifyAnubisPermittablesContext verifyAnubisPermittablesContext;
final VerifyAnputRequiredPermissionsContext verifyAnputRequiredPermissionsContext;
final VerifyIsisCreatePermittableGroup verifyIsisCreatePermittableGroup;
final VerifyIsisSetApplicationSignature verifyIsisSetApplicationSignature;
final VerifyIsisCreateApplicationPermission verifyIsisCreateApplicationPermission;
try (final AutoTenantContext ignored = new AutoTenantContext(tenant.getIdentifier())) {
verifyAnubisInitializeContext = new VerifyAnubisInitializeContext("office", tenant.getIdentifier());
verifyCreateSignatureSetContext = new VerifyCreateSignatureSetContext(keysInApplicationSignature, "office", tenant.getIdentifier());
verifyAnubisPermittablesContext = new VerifyAnubisPermittablesContext(Arrays.asList(xxPermittableEndpoint, xxPermittableEndpoint, xyPermittableEndpoint, xyGetPermittableEndpoint, mPermittableEndpoint), tenant.getIdentifier());
verifyAnputRequiredPermissionsContext = new VerifyAnputRequiredPermissionsContext(Arrays.asList(forFooPermission, forBarPermission), tenant.getIdentifier());
verifyIsisCreatePermittableGroup = new VerifyIsisCreatePermittableGroup(tenant.getIdentifier());
verifyIsisSetApplicationSignature = new VerifyIsisSetApplicationSignature(tenant.getIdentifier());
verifyIsisCreateApplicationPermission = new VerifyIsisCreateApplicationPermission(tenant.getIdentifier(), "office-v1");
}
doAnswer(verifyAnubisInitializeContext).when(anubisMock).initializeResources();
doAnswer(verifyCreateSignatureSetContext).when(anubisMock).createSignatureSet(anyString(), anyObject());
doAnswer(verifyAnubisPermittablesContext).when(anubisMock).getPermittableEndpoints();
doAnswer(verifyAnputRequiredPermissionsContext).when(anputMock).getRequiredPermissions();
doAnswer(verifyIsisCreatePermittableGroup).when(identityServiceMock).createPermittableGroup(new PermittableGroup("x", Arrays.asList(xxPermittableEndpoint, xyPermittableEndpoint, xyGetPermittableEndpoint)));
doAnswer(verifyIsisCreatePermittableGroup).when(identityServiceMock).createPermittableGroup(new PermittableGroup("m", Collections.singletonList(mPermittableEndpoint)));
doAnswer(verifyIsisSetApplicationSignature).when(identityServiceMock).setApplicationSignature(
"office-v1",
verifyInitializeContextAndReturnSignature.getKeyTimestamp(),
new Signature(keysInApplicationSignature.getPublicKeyMod(), keysInApplicationSignature.getPublicKeyExp()));
doAnswer(verifyIsisCreateApplicationPermission).when(identityServiceMock).createApplicationPermission("office-v1", new Permission("x", AllowedOperation.ALL));
doAnswer(verifyIsisCreateApplicationPermission).when(identityServiceMock).createApplicationPermission("office-v1", new Permission("m", Collections.singleton(AllowedOperation.READ)));
doAnswer(verifyIsisCreateApplicationPermission).when(identityServiceMock).createApplicationCallEndpointSet("office-v1", new CallEndpointSet("forPurposeFoo", Collections.singletonList("x")));
doAnswer(verifyIsisCreateApplicationPermission).when(identityServiceMock).createApplicationCallEndpointSet("office-v1", new CallEndpointSet("forPurposeBar", Collections.singletonList("m")));
{
provisioner.assignApplications(tenant.getIdentifier(), Collections.singletonList(officeAssigned));
Thread.sleep(1500L); //Application assigning is asynchronous and I have no message queue.
}
Assert.assertTrue(verifyAnubisInitializeContext.isValidSecurityContext());
Assert.assertTrue(verifyCreateSignatureSetContext.isValidSecurityContext());
Assert.assertTrue(verifyAnubisPermittablesContext.isValidSecurityContext());
Assert.assertTrue(verifyAnputRequiredPermissionsContext.isValidSecurityContext());
Assert.assertEquals(2, verifyIsisCreatePermittableGroup.getCallCount());
Assert.assertTrue(verifyIsisCreatePermittableGroup.isValidSecurityContext());
Assert.assertTrue(verifyIsisSetApplicationSignature.isValidSecurityContext());
Assert.assertEquals(4, verifyIsisCreateApplicationPermission.getCallCount());
Assert.assertTrue(verifyIsisCreateApplicationPermission.isValidSecurityContext());
}
}
| 3,174 |
0 | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn/provisioner | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn/provisioner/tenant/TenantApiDocumentation.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.provisioner.tenant;
import com.google.gson.Gson;
import org.apache.fineract.cn.api.context.AutoSeshat;
import org.apache.fineract.cn.api.util.ApiConstants;
import org.apache.fineract.cn.provisioner.AbstractServiceTest;
import org.apache.fineract.cn.provisioner.api.v1.domain.*;
import org.apache.fineract.cn.provisioner.config.ProvisionerConstants;
import org.junit.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.restdocs.JUnitRestDocumentation;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.delete;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
public class TenantApiDocumentation extends AbstractServiceTest {
@Rule
public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation("build/doc/generated-snippets/test-tenant");
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
private AutoSeshat autoSeshat;
@Before
public void setUp ( ) {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
.apply(documentationConfiguration(this.restDocumentation))
.build();
}
@Before
public void before ( ) {
final AuthenticationResponse authentication = provisioner.authenticate(
this.getClientId(), ApiConstants.SYSTEM_SU, ProvisionerConstants.INITIAL_PWD);
autoSeshat = new AutoSeshat(authentication.getToken());
}
@After
public void after ( ) throws InterruptedException {
//provisioner.deleteTenant(Fixture.getCompTestTenant().getIdentifier());
autoSeshat.close();
}
@Test
public void documentCreateTenant ( ) throws Exception {
final Tenant myTenant = Fixture.getCompTestTenant();
Gson gson = new Gson();
this.mockMvc.perform(post("/tenants")
.accept(MediaType.APPLICATION_JSON_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(gson.toJson(myTenant)))
.andExpect(status().isAccepted())
.andDo(document("document-create-tenant", preprocessRequest(prettyPrint()),
requestFields(
fieldWithPath("identifier").description("Tenant's Identifier"),
fieldWithPath("name").description("Tenant's name"),
fieldWithPath("description").description("Tenant's description"),
fieldWithPath("cassandraConnectionInfo").type("CassandraConnectionInfo").description("Tenant's Cassandra Connection Information +\n" +
" +\n" +
"*class* _CassandraConnectionInfo_ { +\n" +
" String clusterName; +\n" +
" String contactPoints; +\n" +
" String keyspace; +\n" +
" String replicationType; +\n" +
" String replicas; +\n" +
" } +"),
fieldWithPath("databaseConnectionInfo").type("_DatabaseConnectionInfo_").description("Tenant's Database Connection Information +\n" +
" +\n" +
"*class* _DatabaseConnectionInfo_ { +\n" +
" String driverClass; +\n" +
" String databaseName; +\n" +
" String host; +\n" +
" String port; +\n" +
" String user; +\n" +
" String password; +\n" +
" } +")
)
));
}
@Test
public void documentFindTenant ( ) throws Exception {
final Tenant mytenant = Fixture.getCompTestTenant();
provisioner.createTenant(mytenant);
this.mockMvc.perform(get("/tenants/" + mytenant.getIdentifier())
.accept(MediaType.APPLICATION_JSON_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk())
.andDo(document("document-find-tenant", preprocessResponse(prettyPrint()),
responseFields(
fieldWithPath("identifier").description("Tenant's Identifier"),
fieldWithPath("name").description("Tenant's name"),
fieldWithPath("description").description("Tenant's description"),
fieldWithPath("cassandraConnectionInfo").type("CassandraConnectionInfo").description("Tenant's Cassandra Connection Information +\n" +
" +\n" +
"*class* _CassandraConnectionInfo_ { +\n" +
" String clusterName; +\n" +
" String contactPoints; +\n" +
" String keyspace; +\n" +
" String replicationType; +\n" +
" String replicas; +\n" +
" } +"),
fieldWithPath("databaseConnectionInfo").type("_DatabaseConnectionInfo_").description("Tenant's Database Connection Information +\n" +
" +\n" +
"*class* _DatabaseConnectionInfo_ { +\n" +
" String driverClass; +\n" +
" String databaseName; +\n" +
" String host; +\n" +
" String port; +\n" +
" String user; +\n" +
" String password; +\n" +
" } +")
)
));
}
@Test
public void documentFetchTenants ( ) throws Exception {
final Tenant firstTenant = Fixture.getCompTestTenant();
provisioner.createTenant(firstTenant);
final Tenant secondTenant = Fixture.getCompTestTenant();
provisioner.createTenant(secondTenant);
this.mockMvc.perform(get("/tenants")
.accept(MediaType.APPLICATION_JSON_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk())
.andDo(document("document-fetch-tenants", preprocessResponse(prettyPrint()),
responseFields(
fieldWithPath("[].identifier").description("Tenant's Identifier"),
fieldWithPath("[].name").description("Tenant's name"),
fieldWithPath("[].description").description("Tenant's description"),
fieldWithPath("[].cassandraConnectionInfo").type("CassandraConnectionInfo").description("Tenant's Cassandra Connection Information +\n" +
" +\n" +
"*class* _CassandraConnectionInfo_ { +\n" +
" String clusterName; +\n" +
" String contactPoints; +\n" +
" String keyspace; +\n" +
" String replicationType; +\n" +
" String replicas; +\n" +
" } +"),
fieldWithPath("[].databaseConnectionInfo").type("_DatabaseConnectionInfo_").description("Tenant's Database Connection Information +\n" +
" +\n" +
"*class* _DatabaseConnectionInfo_ { +\n" +
" String driverClass; +\n" +
" String databaseName; +\n" +
" String host; +\n" +
" String port; +\n" +
" String user; +\n" +
" String password; +\n" +
" } +"),
fieldWithPath("[1].identifier").description("Tenant's Identifier"),
fieldWithPath("[1].name").description("Tenant's name"),
fieldWithPath("[1].description").description("Tenant's description"),
fieldWithPath("[1].cassandraConnectionInfo").type("CassandraConnectionInfo").description("Tenant's Cassandra Connection Information +\n" +
" +\n" +
"*class* _CassandraConnectionInfo_ { +\n" +
" String clusterName; +\n" +
" String contactPoints; +\n" +
" String keyspace; +\n" +
" String replicationType; +\n" +
" String replicas; +\n" +
" } +"),
fieldWithPath("[1].databaseConnectionInfo").type("_DatabaseConnectionInfo_").description("Tenant's Database Connection Information +\n" +
" +\n" +
"*class* _DatabaseConnectionInfo_ { +\n" +
" String driverClass; +\n" +
" String databaseName; +\n" +
" String host; +\n" +
" String port; +\n" +
" String user; +\n" +
" String password; +\n" +
" } +")
)
));
}
@Test
public void documentDeleteTenant ( ) throws Exception {
final Tenant firstTenant = Fixture.getCompTestTenant();
provisioner.createTenant(firstTenant);
this.mockMvc.perform(delete("/tenants/" + firstTenant.getIdentifier())
.accept(MediaType.APPLICATION_JSON_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isAccepted())
.andDo(document("document-delete-tenant"));
}
}
| 3,175 |
0 | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn/provisioner | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn/provisioner/tenant/TestTenants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.provisioner.tenant;
import org.apache.fineract.cn.provisioner.AbstractServiceTest;
import org.apache.fineract.cn.provisioner.api.v1.client.DuplicateIdentifierException;
import org.apache.fineract.cn.provisioner.api.v1.domain.AuthenticationResponse;
import org.apache.fineract.cn.provisioner.api.v1.domain.Tenant;
import org.apache.fineract.cn.provisioner.config.ProvisionerConstants;
import java.util.List;
import org.apache.fineract.cn.api.context.AutoSeshat;
import org.apache.fineract.cn.api.util.ApiConstants;
import org.apache.fineract.cn.api.util.NotFoundException;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class TestTenants extends AbstractServiceTest {
public TestTenants() {
super();
}
private AutoSeshat autoSeshat;
@Before
public void before()
{
final AuthenticationResponse authentication = provisioner.authenticate(
this.getClientId(), ApiConstants.SYSTEM_SU, ProvisionerConstants.INITIAL_PWD);
autoSeshat = new AutoSeshat(authentication.getToken());
}
@After
public void after() throws InterruptedException {
//provisioner.deleteTenant(Fixture.getCompTestTenant().getIdentifier());
autoSeshat.close();
}
@Test
public void shouldCreateTenant() throws Exception {
final Tenant tenant = Fixture.getCompTestTenant();
provisioner.createTenant(tenant);
final Tenant tenantCreated = provisioner.getTenant(tenant.getIdentifier());
Assert.assertNotNull(tenantCreated);
Assert.assertEquals(tenant.getIdentifier(), tenantCreated.getIdentifier());
Assert.assertEquals(tenant.getName(), tenantCreated.getName());
Assert.assertEquals(tenant.getDescription(), tenantCreated.getDescription());
Assert.assertEquals(tenant.getCassandraConnectionInfo(), tenantCreated.getCassandraConnectionInfo());
}
@Test(expected = DuplicateIdentifierException.class)
public void shouldFailCreateDuplicate() {
final Tenant tenant = Fixture.getCompTestTenant();
provisioner.createTenant(tenant);
provisioner.createTenant(tenant);
}
@Test
public void shouldFindTenant() {
final Tenant tenant = Fixture.getCompTestTenant();
provisioner.createTenant(tenant);
final Tenant foundTenant = provisioner.getTenant(tenant.getIdentifier());
Assert.assertNotNull(foundTenant);
Assert.assertEquals(tenant, foundTenant);
}
@Test(expected = NotFoundException.class)
public void shouldFailFindUnknown() {
provisioner.getTenant("unknown");
}
@Test
public void shouldFetchAll() {
final Tenant tenant = Fixture.getCompTestTenant();
provisioner.createTenant(tenant);
final List<Tenant> tenants = provisioner.getTenants();
Assert.assertFalse(tenants.isEmpty());
Assert.assertTrue(tenants.contains(tenant));
}
}
| 3,176 |
0 | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn/provisioner | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn/provisioner/tenant/Fixture.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.provisioner.tenant;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.fineract.cn.postgresql.util.PostgreSQLConstants;
import org.apache.fineract.cn.provisioner.api.v1.domain.CassandraConnectionInfo;
import org.apache.fineract.cn.provisioner.api.v1.domain.DatabaseConnectionInfo;
import org.apache.fineract.cn.provisioner.api.v1.domain.Tenant;
import org.apache.fineract.cn.test.env.TestEnvironment;
class Fixture {
static Tenant getCompTestTenant() {
final Tenant compTestTenant = new Tenant();
compTestTenant.setIdentifier(TestEnvironment.getRandomTenantName());
compTestTenant.setName("Comp Test " + RandomStringUtils.randomAlphanumeric(4));
compTestTenant.setDescription("Component Test Tenant " + RandomStringUtils.randomAlphabetic(4));
final CassandraConnectionInfo cassandraConnectionInfo = new CassandraConnectionInfo();
compTestTenant.setCassandraConnectionInfo(cassandraConnectionInfo);
cassandraConnectionInfo.setClusterName("Test Cluster" + RandomStringUtils.randomAlphabetic(3));
cassandraConnectionInfo.setContactPoints("127.0.0.1:9142");
cassandraConnectionInfo.setKeyspace(compTestTenant.getIdentifier());
cassandraConnectionInfo.setReplicas("3");
cassandraConnectionInfo.setReplicationType("Simple");
final DatabaseConnectionInfo databaseConnectionInfo = new DatabaseConnectionInfo();
compTestTenant.setDatabaseConnectionInfo(databaseConnectionInfo);
databaseConnectionInfo.setDriverClass("org.postgresql.Driver");
databaseConnectionInfo.setDatabaseName(compTestTenant.getIdentifier());
databaseConnectionInfo.setHost("localhost");
databaseConnectionInfo.setPort("5432");
databaseConnectionInfo.setUser("postgres");
databaseConnectionInfo.setPassword("postgres");
return compTestTenant;
}
}
| 3,177 |
0 | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn/provisioner | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn/provisioner/security/TestAuthentication.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.provisioner.security;
import org.apache.fineract.cn.provisioner.AbstractServiceTest;
import org.apache.fineract.cn.provisioner.api.v1.client.InvalidProvisionerCredentialsException;
import org.apache.fineract.cn.provisioner.api.v1.domain.AuthenticationResponse;
import org.apache.fineract.cn.provisioner.config.ProvisionerConstants;
import org.apache.fineract.cn.api.util.ApiConstants;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.util.Base64Utils;
public class TestAuthentication extends AbstractServiceTest {
public TestAuthentication() {
super();
}
@Test
public void shouldLoginAdmin() {
final AuthenticationResponse authenticate
= provisioner.authenticate(this.getClientId(), ApiConstants.SYSTEM_SU, ProvisionerConstants.INITIAL_PWD);
Assert.assertNotNull(authenticate.getToken());
}
@Test(expected = InvalidProvisionerCredentialsException.class)
public void shouldFailLoginWrongClientId() {
provisioner.authenticate("wrong-client", ApiConstants.SYSTEM_SU, ProvisionerConstants.INITIAL_PWD);
}
@Test(expected = InvalidProvisionerCredentialsException.class)
public void shouldFailLoginWrongUser() {
provisioner.authenticate(this.getClientId(), "wrong-user", ProvisionerConstants.INITIAL_PWD);
}
@Test(expected = InvalidProvisionerCredentialsException.class)
public void shouldFailLoginWrongPassword() {
provisioner.authenticate(this.getClientId(), ApiConstants.SYSTEM_SU, Base64Utils.encodeToString("wrong-pwd".getBytes()));
}
}
| 3,178 |
0 | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn/provisioner | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn/provisioner/security/TestPasswordPolicy.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.provisioner.security;
import org.apache.fineract.cn.provisioner.AbstractServiceTest;
import org.apache.fineract.cn.provisioner.api.v1.domain.AuthenticationResponse;
import org.apache.fineract.cn.provisioner.api.v1.domain.PasswordPolicy;
import org.apache.fineract.cn.provisioner.config.ProvisionerConstants;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import org.apache.fineract.cn.api.context.AutoUserContext;
import org.apache.fineract.cn.api.util.ApiConstants;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.util.Base64Utils;
/**
* @author Myrle Krantz
*/
public class TestPasswordPolicy extends AbstractServiceTest {
static private String currentPassword = ProvisionerConstants.INITIAL_PWD;
@Test
public void shouldUpdatePassword() {
final PasswordPolicy passwordPolicy = new PasswordPolicy();
passwordPolicy.setNewPassword(Base64Utils.encodeToString("new-pwd".getBytes()));
setPasswordPolicy(passwordPolicy);
currentPassword = Base64Utils.encodeToString("new-pwd".getBytes());
final AuthenticationResponse authenticate =
provisioner.authenticate(this.getClientId(), ApiConstants.SYSTEM_SU, currentPassword);
checkAuthenticationResponse(authenticate);
}
@Test
public void shouldUpdatePasswordExpiration() {
final PasswordPolicy passwordPolicy = new PasswordPolicy();
passwordPolicy.setExpiresInDays(10);
setPasswordPolicy(passwordPolicy);
final AuthenticationResponse authenticate =
provisioner.authenticate(this.getClientId(), ApiConstants.SYSTEM_SU, currentPassword);
checkAuthenticationResponse(authenticate);
}
@Test
public void shouldUpdatePasswordPolicy() {
final PasswordPolicy passwordPolicy = new PasswordPolicy();
passwordPolicy.setNewPassword(Base64Utils.encodeToString("new-pwd".getBytes()));
passwordPolicy.setExpiresInDays(10);
setPasswordPolicy(passwordPolicy);
currentPassword = Base64Utils.encodeToString("new-pwd".getBytes());
final AuthenticationResponse authenticate =
provisioner.authenticate(this.getClientId(), ApiConstants.SYSTEM_SU, currentPassword);
checkAuthenticationResponse(authenticate);
}
private void setPasswordPolicy(final PasswordPolicy passwordPolicy)
{
final AuthenticationResponse authenticate = provisioner.authenticate(this.getClientId(), ApiConstants.SYSTEM_SU, currentPassword);
try (final AutoUserContext ignore = new AutoUserContext(ApiConstants.SYSTEM_SU, authenticate.getToken())) {
provisioner.updatePasswordPolicy(ApiConstants.SYSTEM_SU, passwordPolicy);
}
}
private void checkAuthenticationResponse(final AuthenticationResponse authenticate)
{
Assert.assertNotNull(authenticate.getToken());
final String passwordExpiresAt = authenticate.getAccessTokenExpiration();
Assert.assertNotNull(passwordExpiresAt);
final LocalDateTime expires
= LocalDateTime.parse(passwordExpiresAt, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
Assert.assertTrue(expires.isAfter(LocalDateTime.now(ZoneId.of("UTC"))));
}
} | 3,179 |
0 | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn/provisioner | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn/provisioner/internal/TestProvision.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.provisioner.internal;
import com.datastax.driver.core.KeyspaceMetadata;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Session;
import org.apache.fineract.cn.provisioner.AbstractServiceTest;
import org.apache.fineract.cn.cassandra.core.CassandraSessionProvider;
import org.apache.fineract.cn.cassandra.util.CassandraConnectorConstants;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
public class TestProvision extends AbstractServiceTest {
public TestProvision() {
super();
}
@Autowired
protected CassandraSessionProvider cassandraSessionProvider;
@Test
public void dataModelExists() throws Exception {
try (final Session session = cassandraSessionProvider.getAdminSession()) {
final KeyspaceMetadata keyspace = session.getCluster().getMetadata().getKeyspace(CassandraConnectorConstants.KEYSPACE_PROP_DEFAULT);
Assert.assertTrue(keyspace != null);
Assert.assertTrue(keyspace.getTable("config") != null);
Assert.assertTrue(keyspace.getTable("users") != null);
Assert.assertTrue(keyspace.getTable("tenants") != null);
Assert.assertTrue(keyspace.getTable("applications") != null);
Assert.assertTrue(keyspace.getTable("tenant_applications") != null);
Assert.assertTrue(keyspace.getTable("clients") != null);
session.execute("USE " + CassandraConnectorConstants.KEYSPACE_PROP_DEFAULT);
final ResultSet configResultSet = session.execute("SELECT * FROM config WHERE name = 'org.apache.fineract.cn.provisioner.internal'");
Assert.assertNotNull(configResultSet.one());
final ResultSet userResultSet = session.execute("SELECT * FROM users WHERE name = 'wepemnefret'");
Assert.assertNotNull(userResultSet.one());
final ResultSet clientResultSet = session.execute("SELECT * FROM clients");
Assert.assertNotNull(clientResultSet.one());
}
}
}
| 3,180 |
0 | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn/provisioner | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn/provisioner/application/ApplicationsApiDocumentation.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.provisioner.application;
import com.google.gson.Gson;
import org.apache.fineract.cn.api.context.AutoSeshat;
import org.apache.fineract.cn.api.util.ApiConstants;
import org.apache.fineract.cn.provisioner.api.v1.domain.Application;
import org.apache.fineract.cn.provisioner.api.v1.domain.AuthenticationResponse;
import org.apache.fineract.cn.provisioner.config.ProvisionerConstants;
import org.junit.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.restdocs.JUnitRestDocumentation;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.delete;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
import org.apache.fineract.cn.provisioner.AbstractServiceTest;
public class ApplicationsApiDocumentation extends AbstractServiceTest {
@Rule
public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation("build/doc/generated-snippets/test-application");
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
private AutoSeshat autoSeshat;
@Before
public void setUp ( ) {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
.apply(documentationConfiguration(this.restDocumentation))
.build();
}
@Before
public void before ( ) {
final AuthenticationResponse authentication = provisioner.authenticate(
this.getClientId(), ApiConstants.SYSTEM_SU, ProvisionerConstants.INITIAL_PWD);
autoSeshat = new AutoSeshat(authentication.getToken());
}
@After
public void after ( ) {
provisioner.deleteApplication(Fixture.getApplication().getName());
autoSeshat.close();
}
@Test
public void documentCreateApplication ( ) throws Exception {
final Application application = Fixture.getApplication();
Gson gson = new Gson();
this.mockMvc.perform(post("/applications")
.accept(MediaType.APPLICATION_JSON_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(gson.toJson(application)))
.andExpect(status().isAccepted())
.andDo(document("document-create-application", preprocessRequest(prettyPrint()),
requestFields(
fieldWithPath("name").description("Application's name"),
fieldWithPath("description").description("Application's description"),
fieldWithPath("vendor").description("Application's vendor"),
fieldWithPath("homepage").description("Application's homepage")
)
));
}
@Test
public void shouldFindApplication ( ) throws Exception {
Application application = new Application();
application.setName("comp-test-app");
application.setDescription("Component Test Application");
application.setHomepage("http://www.component.test");
application.setVendor("Component Test");
provisioner.createApplication(application);
this.mockMvc.perform(get("/applications/" + application.getName())
.accept(MediaType.APPLICATION_JSON_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk())
.andDo(document("document-find-application", preprocessResponse(prettyPrint()),
responseFields(
fieldWithPath("name").description("Application's name"),
fieldWithPath("description").description("Application's description"),
fieldWithPath("vendor").description("Application's vendor"),
fieldWithPath("homepage").description("Application's homepage")
)
));
}
@Test
public void documentFetchApplications ( ) throws Exception {
Application firstApplication = new Application();
firstApplication.setName("first-comp-test-app");
firstApplication.setDescription("First Component Test Application");
firstApplication.setHomepage("http://www.first-component.test");
firstApplication.setVendor("First Component Test");
Application secondApplication = new Application();
secondApplication.setName("second-comp-test-app");
secondApplication.setDescription("Second Component Test Application");
secondApplication.setHomepage("http://www.second-component.test");
secondApplication.setVendor("Second Component Test");
provisioner.createApplication(firstApplication);
provisioner.createApplication(secondApplication);
this.mockMvc.perform(get("/applications")
.accept(MediaType.APPLICATION_JSON_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk())
.andDo(document("document-fetch-applications", preprocessResponse(prettyPrint()),
responseFields(
fieldWithPath("[].name").description("First Application's name"),
fieldWithPath("[].description").description("First Application's description"),
fieldWithPath("[].vendor").description("First Application's vendor"),
fieldWithPath("[].homepage").description("First Application's homepage"),
fieldWithPath("[1].name").description("Second Application's name"),
fieldWithPath("[1].description").description("Second Application's description"),
fieldWithPath("[1].vendor").description("Second Application's vendor"),
fieldWithPath("[1].homepage").description("Second Application's homepage")
)
));
}
@Test
public void documentDeleteApplication ( ) throws Exception {
Application randApplication = new Application();
randApplication.setName("random-comp-test-app");
randApplication.setDescription("Random Component Test Application");
randApplication.setHomepage("http://www.random-component.test");
randApplication.setVendor("Random Component Test");
provisioner.createApplication(randApplication);
this.mockMvc.perform(delete("/applications/" + randApplication.getName())
.accept(MediaType.APPLICATION_JSON_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isAccepted())
.andDo(document("document-delete-application"));
}
}
| 3,181 |
0 | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn/provisioner | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn/provisioner/application/TestApplications.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.provisioner.application;
import org.apache.fineract.cn.provisioner.AbstractServiceTest;
import org.apache.fineract.cn.provisioner.api.v1.client.DuplicateIdentifierException;
import org.apache.fineract.cn.provisioner.api.v1.domain.Application;
import org.apache.fineract.cn.provisioner.api.v1.domain.AuthenticationResponse;
import org.apache.fineract.cn.provisioner.config.ProvisionerConstants;
import org.apache.fineract.cn.api.context.AutoSeshat;
import org.apache.fineract.cn.api.util.ApiConstants;
import org.apache.fineract.cn.api.util.NotFoundException;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class TestApplications extends AbstractServiceTest {
private AutoSeshat autoSeshat;
public TestApplications() {
super();
}
@Before
public void before()
{
final AuthenticationResponse authentication = provisioner.authenticate(
this.getClientId(), ApiConstants.SYSTEM_SU, ProvisionerConstants.INITIAL_PWD);
autoSeshat = new AutoSeshat(authentication.getToken());
}
@After
public void after() {
provisioner.deleteApplication(Fixture.getApplication().getName());
autoSeshat.close();
}
@Test
public void shouldCreateApplication() {
final Application application = Fixture.getApplication();
provisioner.createApplication(application);
final Application createdApplication = provisioner.getApplication(application.getName());
Assert.assertNotNull(createdApplication);
Assert.assertEquals(application.getName(), createdApplication.getName());
Assert.assertEquals(application.getDescription(), createdApplication.getDescription());
Assert.assertEquals(application.getVendor(), createdApplication.getVendor());
Assert.assertEquals(application.getHomepage(), createdApplication.getHomepage());
}
@Test
public void shouldFindApplication() {
provisioner.createApplication(Fixture.getApplication());
Assert.assertNotNull(provisioner.getApplication(Fixture.getApplication().getName()));
}
@Test
public void shouldFetchAll() {
provisioner.createApplication(Fixture.getApplication());
Assert.assertFalse(provisioner.getApplications().isEmpty());
}
@Test(expected = DuplicateIdentifierException.class)
public void shouldFailCreateDuplicate() {
provisioner.createApplication(Fixture.getApplication());
provisioner.createApplication(Fixture.getApplication());
}
@Test(expected = NotFoundException.class)
public void shouldFailFindUnknown() {
provisioner.getApplication("unknown");
}
@Test
public void shouldDeleteApplication() {
final Application applicationToDelete = new Application();
applicationToDelete.setName("deleteme");
provisioner.createApplication(applicationToDelete);
try {
provisioner.getApplication(applicationToDelete.getName());
} catch (final RuntimeException ignored) {
Assert.fail();
}
provisioner.deleteApplication(applicationToDelete.getName());
try {
provisioner.getApplication(applicationToDelete.getName());
Assert.fail();
}
catch (final RuntimeException ex) {
Assert.assertTrue(ex instanceof NotFoundException);
}
}
}
| 3,182 |
0 | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn/provisioner | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn/provisioner/application/Fixture.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.provisioner.application;
import org.apache.fineract.cn.provisioner.api.v1.domain.Application;
class Fixture {
private static Application application = new Application();
static {
application.setName("comp-test-app");
application.setDescription("Component Test Application");
application.setHomepage("http://www.example.org");
application.setVendor("Component Test");
}
private Fixture() {
super();
}
static Application getApplication() {
return application;
}
}
| 3,183 |
0 | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn/provisioner | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn/provisioner/client/TestClients.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.provisioner.client;
import org.apache.fineract.cn.provisioner.AbstractServiceTest;
import org.apache.fineract.cn.provisioner.api.v1.client.DuplicateIdentifierException;
import org.apache.fineract.cn.provisioner.api.v1.domain.AuthenticationResponse;
import org.apache.fineract.cn.provisioner.api.v1.domain.Client;
import org.apache.fineract.cn.provisioner.config.ProvisionerConstants;
import org.apache.fineract.cn.api.context.AutoSeshat;
import org.apache.fineract.cn.api.util.ApiConstants;
import org.apache.fineract.cn.api.util.NotFoundException;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class TestClients extends AbstractServiceTest {
private AutoSeshat autoSeshat;
public TestClients() {
super();
}
@Before
public void before()
{
final AuthenticationResponse authentication = provisioner.authenticate(
this.getClientId(), ApiConstants.SYSTEM_SU, ProvisionerConstants.INITIAL_PWD);
autoSeshat = new AutoSeshat(authentication.getToken());
}
@After
public void after() {
provisioner.deleteClient(Fixture.getCompTestClient().getName());
autoSeshat.close();
}
@Test
public void shouldCreateClient() {
final Client client = Fixture.getCompTestClient();
provisioner.createClient(client);
//TODO: add waiting?
final Client newlyCreatedClient = provisioner.getClient(client.getName());
Assert.assertEquals(client.getName(), newlyCreatedClient.getName());
Assert.assertEquals(client.getDescription(), newlyCreatedClient.getDescription());
Assert.assertEquals(client.getHomepage(), newlyCreatedClient.getHomepage());
Assert.assertEquals(client.getVendor(), newlyCreatedClient.getVendor());
Assert.assertEquals(client.getRedirectUri(), newlyCreatedClient.getRedirectUri());
}
@Test(expected = DuplicateIdentifierException.class)
public void shouldFailCreateClientAlreadyExists() {
final Client client = new Client();
client.setName("duplicate-client");
provisioner.createClient(client);
provisioner.createClient(client);
}
@Test
public void shouldFindClient() {
provisioner.createClient(Fixture.getCompTestClient());
Assert.assertNotNull(provisioner.getClient(Fixture.getCompTestClient().getName()));
}
@Test(expected = NotFoundException.class)
public void shouldNotFindClientUnknown() {
provisioner.getClient("unknown-client");
}
@Test
public void shouldFetchAllClients() {
Assert.assertFalse(provisioner.getClients().isEmpty());
}
@Test
public void shouldDeleteClient() {
final Client clientToDelete = new Client();
clientToDelete.setName("deleteme");
provisioner.createClient(clientToDelete);
try {
provisioner.getClient(clientToDelete.getName());
} catch (final Exception ex) {
Assert.fail();
}
provisioner.deleteClient(clientToDelete.getName());
try {
provisioner.getClient(clientToDelete.getName());
Assert.fail();
}
catch (final RuntimeException ex) {
Assert.assertTrue(ex instanceof NotFoundException);
}
}
} | 3,184 |
0 | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn/provisioner | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn/provisioner/client/ClientsApiDocumentation.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.provisioner.client;
import com.google.gson.Gson;
import org.apache.fineract.cn.api.context.AutoSeshat;
import org.apache.fineract.cn.api.util.ApiConstants;
import org.apache.fineract.cn.provisioner.AbstractServiceTest;
import org.apache.fineract.cn.provisioner.api.v1.domain.AuthenticationResponse;
import org.apache.fineract.cn.provisioner.api.v1.domain.Client;
import org.apache.fineract.cn.provisioner.config.ProvisionerConstants;
import org.junit.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.restdocs.JUnitRestDocumentation;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.delete;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
public class ClientsApiDocumentation extends AbstractServiceTest {
@Rule
public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation("build/doc/generated-snippets/test-client");
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
private AutoSeshat autoSeshat;
@Before
public void setUp ( ) {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
.apply(documentationConfiguration(this.restDocumentation))
.build();
}
@Before
public void before ( ) {
final AuthenticationResponse authentication = provisioner.authenticate(
this.getClientId(), ApiConstants.SYSTEM_SU, ProvisionerConstants.INITIAL_PWD);
autoSeshat = new AutoSeshat(authentication.getToken());
}
@After
public void after ( ) {
provisioner.deleteClient(Fixture.getCompTestClient().getName());
autoSeshat.close();
}
@Test
public void documentCreateClient ( ) throws Exception {
final Client client = Fixture.getCompTestClient();
Gson gson = new Gson();
this.mockMvc.perform(post("/clients")
.accept(MediaType.APPLICATION_JSON_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(gson.toJson(client)))
.andExpect(status().isAccepted())
.andDo(document("document-create-client", preprocessRequest(prettyPrint()),
requestFields(
fieldWithPath("name").description("Client's name"),
fieldWithPath("description").description("Client's description"),
fieldWithPath("redirectUri").description("Client's Redirect URI"),
fieldWithPath("vendor").description("Client's vendor"),
fieldWithPath("homepage").description("Client's Homepage"))));
}
@Test
public void documentFindClient ( ) throws Exception {
final Client client = Fixture.getCompTestClient();
provisioner.createClient(client);
this.mockMvc.perform(get("/clients/" + client.getName())
.accept(MediaType.APPLICATION_JSON_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk())
.andDo(document("document-find-client", preprocessResponse(prettyPrint()),
responseFields(
fieldWithPath("name").description("Client's name"),
fieldWithPath("description").description("Client's description"),
fieldWithPath("redirectUri").description("Client's Redirect URI"),
fieldWithPath("vendor").description("Client's vendor"),
fieldWithPath("homepage").description("Client's Homepage"))));
}
@Test
public void documentFetchClients ( ) throws Exception {
final Client firstClient = new Client();
firstClient.setName("client-comp-test-hd8");
firstClient.setDescription("Component Test Client Descr hd8");
firstClient.setHomepage("http://hd8.example.org");
firstClient.setVendor("Component Test Vendor hd8");
firstClient.setRedirectUri("http://hd8.redirect.me");
provisioner.createClient(firstClient);
final Client secondClient = Fixture.getCompTestClient();
secondClient.setName("client-comp-test-832");
secondClient.setDescription("Component Test Client Descr 832");
secondClient.setHomepage("http://832.example.org");
secondClient.setVendor("Component Test Vendor 832");
secondClient.setRedirectUri("http://832.redirect.me");
provisioner.createClient(secondClient);
this.mockMvc.perform(get("/clients")
.accept(MediaType.APPLICATION_JSON_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk())
.andDo(document("document-fetch-clients", preprocessResponse(prettyPrint()),
responseFields(
fieldWithPath("[].name").description("First Client's name"),
fieldWithPath("[].description").description("First Client's description"),
fieldWithPath("[].redirectUri").description("First Client's Redirect URI"),
fieldWithPath("[].vendor").description("First Client's vendor"),
fieldWithPath("[].homepage").description("First Client's Homepage"),
fieldWithPath("[1].name").description("Second Client's name"),
fieldWithPath("[1].description").description("Second Client's description"),
fieldWithPath("[1].redirectUri").description("Second Client's Redirect URI"),
fieldWithPath("[1].vendor").description("Second Client's vendor"),
fieldWithPath("[1].homepage").description("Second Client's Homepage")
)));
}
@Test
public void documentDeleteClient ( ) throws Exception {
final Client firstClient = Fixture.getCompTestClient();
provisioner.createClient(firstClient);
this.mockMvc.perform(delete("/clients/" + firstClient.getName())
.accept(MediaType.APPLICATION_JSON_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isAccepted())
.andDo(document("document-delete-client"));
}
}
| 3,185 |
0 | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn/provisioner | Create_ds/fineract-cn-provisioner/component-test/src/main/java/org/apache/fineract/cn/provisioner/client/Fixture.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.provisioner.client;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.fineract.cn.provisioner.api.v1.domain.Client;
class Fixture {
private static Client compTestClient = new Client();
static {
compTestClient.setName("client-comp-test-" + RandomStringUtils.randomAlphanumeric(5));
compTestClient.setDescription("Component Test Client Descr " + RandomStringUtils.randomAlphanumeric(5));
compTestClient.setHomepage("http://" + RandomStringUtils.randomAlphanumeric(5) + ".example.org");
compTestClient.setVendor("Component Test Vendor " + RandomStringUtils.randomAlphanumeric(5));
compTestClient.setRedirectUri("http://" + RandomStringUtils.randomAlphanumeric(5) + ".redirect.me");
}
private Fixture() {
super();
}
static Client getCompTestClient() {
return compTestClient;
}
}
| 3,186 |
0 | Create_ds/fineract-cn-provisioner/api/src/test/java/org/apache/fineract/cn/provisioner/api/v1 | Create_ds/fineract-cn-provisioner/api/src/test/java/org/apache/fineract/cn/provisioner/api/v1/domain/TenantTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.provisioner.api.v1.domain;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.fineract.cn.test.domain.ValidationTest;
import org.apache.fineract.cn.test.domain.ValidationTestCase;
import org.junit.runners.Parameterized;
/**
* @author Myrle Krantz
*/
public class TenantTest extends ValidationTest<Tenant> {
public TenantTest(ValidationTestCase<Tenant> testCase) {
super(testCase);
}
@Override
protected Tenant createValidTestSubject() {
final Tenant ret = new Tenant();
ret.setIdentifier("identifier");
ret.setName("bebop-v3");
final CassandraConnectionInfo cassandraConnectionInfo = new CassandraConnectionInfo();
cassandraConnectionInfo.setClusterName("");
cassandraConnectionInfo.setContactPoints("");
cassandraConnectionInfo.setKeyspace("");
cassandraConnectionInfo.setReplicas("");
cassandraConnectionInfo.setReplicationType("");
ret.setCassandraConnectionInfo(cassandraConnectionInfo);
ret.setDatabaseConnectionInfo(new DatabaseConnectionInfo());
return ret;
}
@Parameterized.Parameters
public static Collection testCases() {
final Collection<ValidationTestCase> ret = new ArrayList<>();
ret.add(new ValidationTestCase<Tenant>("basicCase")
.adjustment(x -> {})
.valid(true));
ret.add(new ValidationTestCase<Tenant>("invalidIdentifier")
.adjustment(x -> x.setIdentifier(RandomStringUtils.randomAlphanumeric(33)))
.valid(false));
return ret;
}
} | 3,187 |
0 | Create_ds/fineract-cn-provisioner/api/src/test/java/org/apache/fineract/cn/provisioner/api/v1 | Create_ds/fineract-cn-provisioner/api/src/test/java/org/apache/fineract/cn/provisioner/api/v1/domain/AssignedApplicationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.provisioner.api.v1.domain;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.fineract.cn.test.domain.ValidationTest;
import org.apache.fineract.cn.test.domain.ValidationTestCase;
import org.junit.runners.Parameterized;
/**
* @author Myrle Krantz
*/
public class AssignedApplicationTest extends ValidationTest<AssignedApplication> {
public AssignedApplicationTest(ValidationTestCase<AssignedApplication> testCase) {
super(testCase);
}
@Override
protected AssignedApplication createValidTestSubject() {
final AssignedApplication ret = new AssignedApplication();
ret.setName("bebop-v3");
return ret;
}
@Parameterized.Parameters
public static Collection testCases() {
final Collection<ValidationTestCase> ret = new ArrayList<>();
ret.add(new ValidationTestCase<AssignedApplication>("basicCase")
.adjustment(x -> {})
.valid(true));
ret.add(new ValidationTestCase<AssignedApplication>("invalidApplicationName")
.adjustment(x -> x.setName("bebop-dowop"))
.valid(false));
ret.add(new ValidationTestCase<AssignedApplication>("nullApplicationName")
.adjustment(x -> x.setName(null))
.valid(false));
return ret;
}
} | 3,188 |
0 | Create_ds/fineract-cn-provisioner/api/src/test/java/org/apache/fineract/cn/provisioner/api/v1 | Create_ds/fineract-cn-provisioner/api/src/test/java/org/apache/fineract/cn/provisioner/api/v1/domain/ApplicationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.provisioner.api.v1.domain;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.fineract.cn.test.domain.ValidationTest;
import org.apache.fineract.cn.test.domain.ValidationTestCase;
import org.junit.runners.Parameterized;
/**
* @author Myrle Krantz
*/
public class ApplicationTest extends ValidationTest<Application> {
public ApplicationTest(ValidationTestCase<Application> testCase) {
super(testCase);
}
@Override
protected Application createValidTestSubject() {
final Application ret = new Application();
ret.setName("bebop-v3");
ret.setHomepage("http://xyz.bebop:2021/v1");
ret.setDescription("bebop manager");
ret.setVendor("fineract");
return ret;
}
@Parameterized.Parameters
public static Collection testCases() {
final Collection<ValidationTestCase> ret = new ArrayList<>();
ret.add(new ValidationTestCase<Application>("basicCase")
.adjustment(x -> {})
.valid(true));
ret.add(new ValidationTestCase<Application>("invalidApplicationName")
.adjustment(x -> x.setName("bebop-dowop"))
.valid(false));
ret.add(new ValidationTestCase<Application>("nullApplicationName")
.adjustment(x -> x.setName(null))
.valid(false));
return ret;
}
} | 3,189 |
0 | Create_ds/fineract-cn-provisioner/api/src/main/java/org/apache/fineract/cn/provisioner/api/v1 | Create_ds/fineract-cn-provisioner/api/src/main/java/org/apache/fineract/cn/provisioner/api/v1/domain/IdentityManagerInitialization.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.provisioner.api.v1.domain;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
public final class IdentityManagerInitialization {
private String adminPassword;
public IdentityManagerInitialization() { }
public String getAdminPassword() {
return adminPassword;
}
public void setAdminPassword(String adminPassword) {
this.adminPassword = adminPassword;
}
}
| 3,190 |
0 | Create_ds/fineract-cn-provisioner/api/src/main/java/org/apache/fineract/cn/provisioner/api/v1 | Create_ds/fineract-cn-provisioner/api/src/main/java/org/apache/fineract/cn/provisioner/api/v1/domain/Client.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.provisioner.api.v1.domain;
import org.springframework.util.Assert;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.validation.constraints.NotNull;
@SuppressWarnings("unused")
public final class Client {
@NotNull
private String name;
private String description;
private String redirectUri;
private String vendor;
private String homepage;
public Client() {
super();
}
@Nonnull
public String getName() {
return name;
}
public void setName(@Nonnull final String name) {
Assert.notNull(name, "Client name must be given!");
this.name = name;
}
@Nullable
public String getDescription() {
return description;
}
public void setDescription(@Nullable final String description) {
this.description = description;
}
@Nullable
public String getRedirectUri() {
return redirectUri;
}
public void setRedirectUri(@Nullable final String redirectUri) {
this.redirectUri = redirectUri;
}
@Nullable
public String getVendor() {
return vendor;
}
public void setVendor(@Nullable final String vendor) {
this.vendor = vendor;
}
@Nullable
public String getHomepage() {
return homepage;
}
public void setHomepage(@Nullable final String homepage) {
this.homepage = homepage;
}
}
| 3,191 |
0 | Create_ds/fineract-cn-provisioner/api/src/main/java/org/apache/fineract/cn/provisioner/api/v1 | Create_ds/fineract-cn-provisioner/api/src/main/java/org/apache/fineract/cn/provisioner/api/v1/domain/ClientCredentials.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.provisioner.api.v1.domain;
@SuppressWarnings("unused")
public final class ClientCredentials {
private final String id;
private final String secret;
public ClientCredentials(String id, String secret) {
super();
this.id = id;
this.secret = secret;
}
public String getId() {
return id;
}
public String getSecret() {
return secret;
}
}
| 3,192 |
0 | Create_ds/fineract-cn-provisioner/api/src/main/java/org/apache/fineract/cn/provisioner/api/v1 | Create_ds/fineract-cn-provisioner/api/src/main/java/org/apache/fineract/cn/provisioner/api/v1/domain/Application.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.provisioner.api.v1.domain;
import org.apache.fineract.cn.lang.validation.constraints.ValidApplicationName;
@SuppressWarnings({"unused", "WeakerAccess"})
public class Application {
@ValidApplicationName
private String name;
private String description;
private String vendor;
private String homepage;
public Application() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getVendor() {
return vendor;
}
public void setVendor(String vendor) {
this.vendor = vendor;
}
public String getHomepage() {
return homepage;
}
public void setHomepage(String homepage) {
this.homepage = homepage;
}
}
| 3,193 |
0 | Create_ds/fineract-cn-provisioner/api/src/main/java/org/apache/fineract/cn/provisioner/api/v1 | Create_ds/fineract-cn-provisioner/api/src/main/java/org/apache/fineract/cn/provisioner/api/v1/domain/DatabaseConnectionInfo.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.provisioner.api.v1.domain;
import javax.annotation.Nonnull;
import javax.validation.constraints.NotNull;
import java.util.Objects;
@SuppressWarnings({"unused", "WeakerAccess"})
public final class DatabaseConnectionInfo {
@NotNull
private String driverClass;
@NotNull
private String databaseName;
@NotNull
private String host;
@NotNull
private String port;
@NotNull
private String user;
@NotNull
private String password;
public DatabaseConnectionInfo() {
super();
}
@Nonnull
public String getDriverClass() {
return driverClass;
}
public void setDriverClass(@Nonnull final String driverClass) {
this.driverClass = driverClass;
}
public String getDatabaseName() {
return databaseName;
}
public void setDatabaseName(final String databaseName) {
this.databaseName = databaseName;
}
@Nonnull
public String getHost() {
return host;
}
public void setHost(@Nonnull final String host) {
this.host = host;
}
@Nonnull
public String getPort() {
return port;
}
public void setPort(@Nonnull final String port) {
this.port = port;
}
@Nonnull
public String getUser() {
return user;
}
public void setUser(@Nonnull final String user) {
this.user = user;
}
@Nonnull
public String getPassword() {
return password;
}
public void setPassword(@Nonnull final String password) {
this.password = password;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DatabaseConnectionInfo that = (DatabaseConnectionInfo) o;
return Objects.equals(driverClass, that.driverClass) &&
Objects.equals(databaseName, that.databaseName) &&
Objects.equals(host, that.host) &&
Objects.equals(port, that.port) &&
Objects.equals(user, that.user) &&
Objects.equals(password, that.password);
}
@Override
public int hashCode() {
return Objects.hash(driverClass, databaseName, host, port, user, password);
}
@Override
public String toString() {
return "DatabaseConnectionInfo{" +
"driverClass='" + driverClass + '\'' +
", databaseName='" + databaseName + '\'' +
", host='" + host + '\'' +
", port='" + port + '\'' +
", user='" + user + '\'' +
", password='" + password + '\'' +
'}';
}
}
| 3,194 |
0 | Create_ds/fineract-cn-provisioner/api/src/main/java/org/apache/fineract/cn/provisioner/api/v1 | Create_ds/fineract-cn-provisioner/api/src/main/java/org/apache/fineract/cn/provisioner/api/v1/domain/CassandraConnectionInfo.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.provisioner.api.v1.domain;
import javax.annotation.Nonnull;
import javax.validation.constraints.NotNull;
@SuppressWarnings({"unused", "WeakerAccess"})
public final class CassandraConnectionInfo {
@NotNull
private String clusterName;
@NotNull
private String contactPoints;
@NotNull
private String keyspace;
@NotNull
private String replicationType;
@NotNull
private String replicas;
public CassandraConnectionInfo() {
super();
}
@Nonnull
public String getClusterName() {
return clusterName;
}
public void setClusterName(@Nonnull final String clusterName) {
this.clusterName = clusterName;
}
@Nonnull
public String getContactPoints() {
return contactPoints;
}
public void setContactPoints(@Nonnull final String contactPoints) {
this.contactPoints = contactPoints;
}
@Nonnull
public String getKeyspace() {
return keyspace;
}
public void setKeyspace(@Nonnull final String keyspace) {
this.keyspace = keyspace;
}
@Nonnull
public String getReplicationType() {
return replicationType;
}
public void setReplicationType(@Nonnull final String replicationType) {
this.replicationType = replicationType;
}
@Nonnull
public String getReplicas() {
return replicas;
}
public void setReplicas(@Nonnull final String replicas) {
this.replicas = replicas;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CassandraConnectionInfo that = (CassandraConnectionInfo) o;
return clusterName.equals(that.clusterName)
&& contactPoints.equals(that.contactPoints)
&& keyspace.equals(that.keyspace)
&& replicationType.equals(that.replicationType)
&& replicas.equals(that.replicas);
}
@Override
public int hashCode() {
int result = clusterName.hashCode();
result = 31 * result + contactPoints.hashCode();
result = 31 * result + keyspace.hashCode();
result = 31 * result + replicationType.hashCode();
result = 31 * result + replicas.hashCode();
return result;
}
@Override
public String toString() {
return "CassandraConnectionInfo{" +
"clusterName='" + clusterName + '\'' +
", contactPoints='" + contactPoints + '\'' +
", keyspace='" + keyspace + '\'' +
", replicationType='" + replicationType + '\'' +
", replicas='" + replicas + '\'' +
'}';
}
}
| 3,195 |
0 | Create_ds/fineract-cn-provisioner/api/src/main/java/org/apache/fineract/cn/provisioner/api/v1 | Create_ds/fineract-cn-provisioner/api/src/main/java/org/apache/fineract/cn/provisioner/api/v1/domain/AuthenticationResponse.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.provisioner.api.v1.domain;
@SuppressWarnings("unused")
public class AuthenticationResponse {
private final String token;
private final String accessTokenExpiration;
public AuthenticationResponse(final String token, final String accessTokenExpiration) {
super();
this.token = token;
this.accessTokenExpiration = accessTokenExpiration;
}
public String getToken() {
return token;
}
public String getAccessTokenExpiration() {
return accessTokenExpiration;
}
}
| 3,196 |
0 | Create_ds/fineract-cn-provisioner/api/src/main/java/org/apache/fineract/cn/provisioner/api/v1 | Create_ds/fineract-cn-provisioner/api/src/main/java/org/apache/fineract/cn/provisioner/api/v1/domain/PasswordPolicy.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.provisioner.api.v1.domain;
@SuppressWarnings("unused")
public class PasswordPolicy {
private String newPassword;
private Integer expiresInDays;
public PasswordPolicy() {
super();
}
public String getNewPassword() {
return newPassword;
}
public void setNewPassword(String newPassword) {
this.newPassword = newPassword;
}
public Integer getExpiresInDays() {
return expiresInDays;
}
public void setExpiresInDays(Integer expiresInDays) {
this.expiresInDays = expiresInDays;
}
}
| 3,197 |
0 | Create_ds/fineract-cn-provisioner/api/src/main/java/org/apache/fineract/cn/provisioner/api/v1 | Create_ds/fineract-cn-provisioner/api/src/main/java/org/apache/fineract/cn/provisioner/api/v1/domain/Tenant.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.provisioner.api.v1.domain;
import javax.validation.constraints.NotNull;
import java.util.Objects;
import org.apache.fineract.cn.lang.validation.constraints.ValidIdentifier;
@SuppressWarnings({"unused", "WeakerAccess"})
public final class Tenant {
@ValidIdentifier
private String identifier;
@NotNull
private String name;
private String description;
@NotNull
private CassandraConnectionInfo cassandraConnectionInfo;
@NotNull
private DatabaseConnectionInfo databaseConnectionInfo;
public Tenant() {
super();
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public CassandraConnectionInfo getCassandraConnectionInfo() {
return cassandraConnectionInfo;
}
public void setCassandraConnectionInfo(CassandraConnectionInfo cassandraConnectionInfo) {
this.cassandraConnectionInfo = cassandraConnectionInfo;
}
public DatabaseConnectionInfo getDatabaseConnectionInfo() {
return databaseConnectionInfo;
}
public void setDatabaseConnectionInfo(DatabaseConnectionInfo databaseConnectionInfo) {
this.databaseConnectionInfo = databaseConnectionInfo;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Tenant tenant = (Tenant) o;
return Objects.equals(identifier, tenant.identifier) &&
Objects.equals(name, tenant.name) &&
Objects.equals(description, tenant.description) &&
Objects.equals(cassandraConnectionInfo, tenant.cassandraConnectionInfo) &&
Objects.equals(databaseConnectionInfo, tenant.databaseConnectionInfo);
}
@Override
public int hashCode() {
return Objects.hash(identifier, name, description, cassandraConnectionInfo, databaseConnectionInfo);
}
@Override
public String toString() {
return "Tenant{" +
"identifier='" + identifier + '\'' +
", name='" + name + '\'' +
", description='" + description + '\'' +
", cassandraConnectionInfo=" + cassandraConnectionInfo +
", databaseConnectionInfo=" + databaseConnectionInfo +
'}';
}
}
| 3,198 |
0 | Create_ds/fineract-cn-provisioner/api/src/main/java/org/apache/fineract/cn/provisioner/api/v1 | Create_ds/fineract-cn-provisioner/api/src/main/java/org/apache/fineract/cn/provisioner/api/v1/domain/AssignedApplication.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.provisioner.api.v1.domain;
import org.apache.fineract.cn.lang.validation.constraints.ValidApplicationName;
@SuppressWarnings({"unused", "WeakerAccess"})
public class AssignedApplication {
@ValidApplicationName
private String name;
public AssignedApplication() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| 3,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.