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-examples/examples-sampling/src/main/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-sampling/src/main/java/org/apache/commons/rng/examples/sampling/StandardOptions.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.examples.sampling; import picocli.CommandLine.Command; /** * Standard options for all commands. This sets the formatting for usage messages and * adds common parameters (help, version). */ @Command(sortOptions = true, mixinStandardHelpOptions = true, versionProvider = ManifestVersionProvider.class, synopsisHeading = "%n", descriptionHeading = "%n", parameterListHeading = "%nParameters:%n", optionListHeading = "%nOptions:%n", commandListHeading = "%nCommands:%n") class StandardOptions { // Empty class used for annotations }
2,800
0
Create_ds/commons-rng/commons-rng-examples/examples-sampling/src/main/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-sampling/src/main/java/org/apache/commons/rng/examples/sampling/ExamplesSamplingCommand.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.examples.sampling; import picocli.CommandLine.Command; import picocli.CommandLine.Mixin; import picocli.CommandLine.Model.CommandSpec; import picocli.CommandLine.Spec; import java.util.concurrent.Callable; /** * Specification for the top-level command in the examples sampling application. * * <p>This command is will print the top-level help message.</p> */ @Command(name = "examples-sampling", description = "Apache Commons RNG Examples Sampling Utilities.") class ExamplesSamplingCommand implements Callable<Void> { /** The command specification. Used to print the usage built by Picocli. */ @Spec private CommandSpec spec; /** The standard options. */ @Mixin private StandardOptions reusableOptions; @Override public Void call() { // All work is done in sub-commands so just print the usage spec.commandLine().usage(System.out); return null; } }
2,801
0
Create_ds/commons-rng/commons-rng-examples/examples-sampling/src/main/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-sampling/src/main/java/org/apache/commons/rng/examples/sampling/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. */ /** * This package contains usage examples of the samplers provided in the * <a href="https://commons.apache.org/rng">Commons RNG</a> library. */ package org.apache.commons.rng.examples.sampling;
2,802
0
Create_ds/commons-rng/commons-rng-examples/examples-sampling/src/main/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-sampling/src/main/java/org/apache/commons/rng/examples/sampling/UniformSamplingVisualCheckCommand.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.examples.sampling; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.simple.RandomSource; import picocli.CommandLine.Command; import picocli.CommandLine.Mixin; import picocli.CommandLine.Option; import java.util.concurrent.Callable; import org.apache.commons.rng.sampling.distribution.ZigguratNormalizedGaussianSampler; import org.apache.commons.rng.sampling.distribution.ZigguratSampler; import org.apache.commons.rng.sampling.distribution.MarsagliaNormalizedGaussianSampler; import org.apache.commons.rng.sampling.distribution.BoxMullerNormalizedGaussianSampler; import org.apache.commons.rng.sampling.distribution.ContinuousSampler; /** * Creates 2D plot of sampling output. * It is a "manual" check that could help ensure that no artifacts * exist in some tiny region of the expected range, due to loss of * accuracy, e.g. when porting C code based on 32-bits "float" to * "Commons RNG" that uses Java "double" (64-bits). */ @Command(name = "visual", description = "Show output from a tiny region of the sampler.") class UniformSamplingVisualCheckCommand implements Callable<Void> { /** The standard options. */ @Mixin private StandardOptions reusableOptions; /** The lower bound of the tiny range. */ @Option(names = {"-l", "--low"}, description = "The lower bound (default: ${DEFAULT-VALUE}).") private float lo = 0.1f; /** The number of bands of the tiny range. */ @Option(names = {"-b", "--bands"}, description = "The number of bands for the range (default: ${DEFAULT-VALUE}).") private int bands = 2; /** Number of samples to be generated. */ @Option(names = {"-s", "--samples"}, description = "The number of samples in the tiny range (default: ${DEFAULT-VALUE}).") private int numSamples = 50; /** RNG. */ private final UniformRandomProvider rng = RandomSource.XOR_SHIFT_1024_S_PHI.create(); /** Samplers. */ private final ContinuousSampler[] samplers = { ZigguratNormalizedGaussianSampler.of(rng), MarsagliaNormalizedGaussianSampler.of(rng), BoxMullerNormalizedGaussianSampler.of(rng), ZigguratSampler.NormalizedGaussian.of(rng), }; // Allow System.out // CHECKSTYLE: stop RegexpCheck /** * Prints a template generators list to stdout. */ @Override public Void call() { float hi = lo; for (int i = 0; i < bands; i++) { hi = Math.nextUp(hi); } System.out.printf("# lower=%.16e%n", lo); System.out.printf("# upper=%.16e%n", hi); for (int i = 0; i < samplers.length; i++) { System.out.printf("# [%d] %s%n", i, samplers[i].getClass().getSimpleName()); } for (int n = 0; n < numSamples; n++) { System.out.printf("[%d]", n); for (final ContinuousSampler s : samplers) { double r = s.sample(); while (r < lo || r > hi) { // Discard numbers outside the tiny region. r = s.sample(); } System.out.printf("\t%.16e", r); } System.out.println(); } return null; } }
2,803
0
Create_ds/commons-rng/commons-rng-examples/examples-quadrature/src/main/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-quadrature/src/main/java/org/apache/commons/rng/examples/quadrature/ComputePi.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.examples.quadrature; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.simple.RandomSource; /** * Computation of \( \pi \) using Monte-Carlo integration. * * The computation estimates the value by computing the probability that * a point \( p = (x, y) \) will lie in the circle of radius \( r = 1 \) * inscribed in the square of side \( r = 1 \). * The probability could be computed by \[ area_{circle} / area_{square} \], * where \( area_{circle} = \pi * r^2 \) and \( area_{square} = 4 r^2 \). * Hence, the probability is \( \frac{\pi}{4} \). * * The Monte Carlo simulation will produce \( N \) points. * Defining \( N_c \) as the number of point that satisfy \( x^2 + y^2 \le 1 \), * we will have \( \frac{N_c}{N} \approx \frac{\pi}{4} \). */ public class ComputePi extends MonteCarloIntegration { /** Expected number of arguments. */ private static final int EXPECTED_ARGUMENTS = 2; /** Domain dimension. */ private static final int DIMENSION = 2; /** * @param rng RNG. */ public ComputePi(UniformRandomProvider rng) { super(rng, DIMENSION); } /** * Program entry point. * * @param args Arguments. * The order is as follows: * <ol> * <li> * Number of random 2-dimensional points to generate. * </li> * <li> * {@link RandomSource Random source identifier}. * </li> * </ol> */ public static void main(String[] args) { if (args.length != EXPECTED_ARGUMENTS) { throw new IllegalStateException("Require arguments: [points] [RNG name]"); } final long numPoints = Long.parseLong(args[0]); final RandomSource randomSource = RandomSource.valueOf(args[1]); final ComputePi piApp = new ComputePi(randomSource.create()); final double piMC = piApp.compute(numPoints); //CHECKSTYLE: stop all System.out.printf("After generating %d random numbers, the error on |𝛑 - %s| is %s%n", DIMENSION * numPoints, piMC, Math.abs(piMC - Math.PI)); //CHECKSTYLE: resume all } /** * @param numPoints Number of random points to generate. * @return the approximate value of pi. */ public double compute(long numPoints) { return 4 * integrate(numPoints); } /** {@inheritDoc} */ @Override protected boolean isInside(double... rand) { final double r2 = rand[0] * rand[0] + rand[1] * rand[1]; return r2 <= 1; } }
2,804
0
Create_ds/commons-rng/commons-rng-examples/examples-quadrature/src/main/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-quadrature/src/main/java/org/apache/commons/rng/examples/quadrature/MonteCarloIntegration.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.examples.quadrature; import org.apache.commons.rng.UniformRandomProvider; /** * <a href="https://en.wikipedia.org/wiki/Monte_Carlo_integration">Monte-Carlo method</a> * for approximating an integral on a n-dimensional unit cube. */ public abstract class MonteCarloIntegration { /** RNG. */ private final UniformRandomProvider rng; /** Integration domain dimension. */ private final int dimension; /** * Simulation constructor. * * @param rng RNG. * @param dimension Integration domain dimension. */ public MonteCarloIntegration(UniformRandomProvider rng, int dimension) { this.rng = rng; this.dimension = dimension; } /** * Run the Monte-Carlo integration. * * @param n Number of random points to generate. * @return the integral. */ public double integrate(long n) { long inside = 0; for (long i = 0; i < n; i++) { if (isInside(generateU01())) { ++inside; } } return inside / (double) n; } /** * Indicates whether the given points is inside the region whose * integral is computed. * * @param point Point whose coordinates are random numbers uniformly * distributed in the unit interval. * @return {@code true} if the {@code point} is inside. */ protected abstract boolean isInside(double... point); /** * @return a value from a random sequence uniformly distributed * in the {@code [0, 1)} interval. */ private double[] generateU01() { final double[] rand = new double[dimension]; for (int i = 0; i < dimension; i++) { rand[i] = rng.nextDouble(); } return rand; } }
2,805
0
Create_ds/commons-rng/commons-rng-examples/examples-quadrature/src/main/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-quadrature/src/main/java/org/apache/commons/rng/examples/quadrature/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. */ /** * This package contains a simple application that uses many * uniformly-distributed random numbers for Monte-Carlo integration. */ package org.apache.commons.rng.examples.quadrature;
2,806
0
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/test/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/test/java/org/apache/commons/rng/examples/stress/RngDataOutputTest.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.examples.stress; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.core.source32.IntProvider; import org.apache.commons.rng.core.source32.RandomIntSource; import org.apache.commons.rng.core.source64.RandomLongSource; import org.apache.commons.rng.simple.RandomSource; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteOrder; import java.util.function.BiConsumer; import java.util.function.UnaryOperator; /** * Tests for {@link RngDataOutput}. */ class RngDataOutputTest { /** * A factory for creating RngDataOutput objects. */ interface RngDataOutputFactory { /** * Create a new instance. * * @param out Output stream. * @param size Number of values to write. * @param byteOrder Byte order. * @return the data output */ RngDataOutput create(OutputStream out, int size, ByteOrder byteOrder); } @Test void testIntBigEndian() throws IOException { assertRngOutput(RandomSource.PCG_MCG_XSH_RS_32, UnaryOperator.identity(), RngDataOutputTest::writeInt, RngDataOutput::ofInt, ByteOrder.BIG_ENDIAN); } @Test void testIntLittleEndian() throws IOException { assertRngOutput(RandomSource.PCG_MCG_XSH_RS_32, RNGUtils::createReverseBytesProvider, RngDataOutputTest::writeInt, RngDataOutput::ofInt, ByteOrder.LITTLE_ENDIAN); } @Test void testLongBigEndian() throws IOException { assertRngOutput(RandomSource.SPLIT_MIX_64, UnaryOperator.identity(), RngDataOutputTest::writeLong, RngDataOutput::ofLong, ByteOrder.BIG_ENDIAN); } @Test void testLongLittleEndian() throws IOException { assertRngOutput(RandomSource.SPLIT_MIX_64, RNGUtils::createReverseBytesProvider, RngDataOutputTest::writeLong, RngDataOutput::ofLong, ByteOrder.LITTLE_ENDIAN); } @Test void testLongAsHLIntBigEndian() throws IOException { assertRngOutput(RandomSource.SPLIT_MIX_64, // Convert to an int provider so it is detected as requiring double the // length output. rng -> new HiLoCachingIntProvider(rng), RngDataOutputTest::writeInt, RngDataOutput::ofLongAsHLInt, ByteOrder.BIG_ENDIAN); } @Test void testLongAsHLIntLittleEndian() throws IOException { assertRngOutput(RandomSource.SPLIT_MIX_64, // Convert SplitMix64 to an int provider so it is detected as requiring double the // length output. Then reverse the bytes. rng -> new HiLoCachingIntProvider(rng) { @Override public int next() { return Integer.reverseBytes(super.next()); } }, RngDataOutputTest::writeInt, RngDataOutput::ofLongAsHLInt, ByteOrder.LITTLE_ENDIAN); } @Test void testLongAsLHIntBigEndian() throws IOException { assertRngOutput(RandomSource.SPLIT_MIX_64, // Convert to an int provider so it is detected as requiring double the // length output. rng -> new LoHiCachingIntProvider(rng), RngDataOutputTest::writeInt, RngDataOutput::ofLongAsLHInt, ByteOrder.BIG_ENDIAN); } @Test void testLongAsLHIntLittleEndian() throws IOException { assertRngOutput(RandomSource.SPLIT_MIX_64, // Convert to an int provider so it is detected as requiring double the // length output. Then reverse the bytes. rng -> new LoHiCachingIntProvider(rng) { @Override public int next() { return Integer.reverseBytes(super.next()); } }, RngDataOutputTest::writeInt, RngDataOutput::ofLongAsLHInt, ByteOrder.LITTLE_ENDIAN); } private static void writeInt(DataOutputStream sink, UniformRandomProvider rng) { try { sink.writeInt(rng.nextInt()); } catch (IOException e) { Assertions.fail(); } } private static void writeLong(DataOutputStream sink, UniformRandomProvider rng) { try { sink.writeLong(rng.nextLong()); } catch (IOException e) { Assertions.fail(); } } /** * Assert the byte output from the source is the same. Creates two instances of the same * RNG with the same seed. The first is converted to a new RNG using the {@code rngConverter}. * This is used to output raw bytes using a {@link DataOutputStream} via the specified * {@code pipe}. The second is used to output raw bytes via the {@link RngDataOutput} class * created using the {@code factory}. * * <p>The random source should output native {@code int} or {@code long} values. * * @param source Random source. * @param rngConverter Converter for the raw RNG. * @param pipe Pipe to send data from the RNG to the DataOutputStream. * @param factory Factory for the RngDataOutput. * @param byteOrder Byte order for the RngDataOutput. * @throws IOException Signals that an I/O exception has occurred. */ private static void assertRngOutput(RandomSource source, UnaryOperator<UniformRandomProvider> rngConverter, BiConsumer<DataOutputStream, UniformRandomProvider> pipe, RngDataOutputFactory factory, ByteOrder byteOrder) throws IOException { final long seed = RandomSource.createLong(); UniformRandomProvider rng1 = source.create(seed); UniformRandomProvider rng2 = source.create(seed); final int size = 37; for (int repeats = 1; repeats <= 2; repeats++) { byte[] expected = createBytes(rng1, size, repeats, rngConverter, pipe); byte[] actual = writeRngOutput(rng2, size, repeats, byteOrder, factory); Assertions.assertArrayEquals(expected, actual); } } /** * Convert the RNG and then creates bytes from the RNG using the pipe. * * @param rng RNG. * @param size The number of values to send to the pipe. * @param repeats The number of repeat iterations. * @param rngConverter Converter for the raw RNG. * @param pipe Pipe to send data from the RNG to the DataOutputStream. * @return the bytes * @throws IOException Signals that an I/O exception has occurred. */ private static byte[] createBytes(UniformRandomProvider rng, int size, int repeats, UnaryOperator<UniformRandomProvider> rngConverter, BiConsumer<DataOutputStream, UniformRandomProvider> pipe) throws IOException { UniformRandomProvider rng2 = rngConverter.apply(rng); // If the factory converts to an IntProvider then output twice the size if (rng instanceof RandomLongSource && rng2 instanceof RandomIntSource) { size *= 2; } ByteArrayOutputStream out = new ByteArrayOutputStream(); try (DataOutputStream sink = new DataOutputStream(out)) { for (int j = 0; j < repeats; j++) { for (int i = 0; i < size; i++) { pipe.accept(sink, rng2); } } } return out.toByteArray(); } /** * Write the RNG to the RngDataOutput built by the factory. * * @param rng RNG. * @param size The number of values to send to the RngDataOutput. * @param repeats The number of repeat iterations. * @param byteOrder Byte order for the RngDataOutput. * @param factory Factory for the RngDataOutput. * @return the bytes * @throws IOException Signals that an I/O exception has occurred. */ private static byte[] writeRngOutput(UniformRandomProvider rng, int size, int repeats, ByteOrder byteOrder, RngDataOutputFactory factory) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); try (RngDataOutput sink = factory.create(out, size, byteOrder)) { for (int j = 0; j < repeats; j++) { sink.write(rng); } } return out.toByteArray(); } private static class LoHiCachingIntProvider extends IntProvider { private long source = -1; private final UniformRandomProvider rng; LoHiCachingIntProvider(UniformRandomProvider rng) { this.rng = rng; } @Override public int next() { long next = source; if (next < 0) { // refill next = rng.nextLong(); // store hi source = next >>> 32; // extract low return (int) next; } final int v = (int) next; // reset source = -1; return v; } } private static class HiLoCachingIntProvider extends IntProvider { private long source = -1; private final UniformRandomProvider rng; HiLoCachingIntProvider(UniformRandomProvider rng) { this.rng = rng; } @Override public int next() { long next = source; if (next < 0) { // refill next = rng.nextLong(); // store low source = next & 0xffff_ffffL; // extract hi return (int) (next >>> 32); } final int v = (int) next; // reset source = -1; return v; } } }
2,807
0
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/test/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/test/java/org/apache/commons/rng/examples/stress/HexTest.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.examples.stress; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Locale; import java.util.concurrent.ThreadLocalRandom; /** * Tests for {@link Hex}. */ class HexTest { /** Upper-case hex digits. */ private static final char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; /** * Test a round-trip hex encode and decode of a byte[] seed. * * <p>This test ensures that a generated byte[] seed recorded by the stress command * in the results file can be used to create the same seed. */ @Test void testHexEncodeAndDecode() { // Empty bytes for (int size = 0; size < 10; size++) { assertHexEncodeAndDecode(new byte[size]); } // Random bytes for (int size : new int[] {3, 4, 5, 8, 16, 31}) { final byte[] bytes = new byte[size]; for (int i = 0; i < 5; i++) { ThreadLocalRandom.current().nextBytes(bytes); assertHexEncodeAndDecode(bytes); } } } /** * Assert the bytes can be encoded and decoded. * * @param bytes the bytes */ private static void assertHexEncodeAndDecode(byte[] bytes) { // Use a StringBuilder to append the chars as this is the method used in the stress command. final StringBuilder sb = new StringBuilder(); sb.append(Hex.encodeHex(bytes)); final byte[] decoded = Hex.decodeHex(sb); Assertions.assertArrayEquals(bytes, decoded); } /** * Test a round-trip hex decode and encode of a char[] seed. * * <p>This test ensures that a user input random hex seed passed to the stress command * can be converted to bytes and then recorded in the results file. */ @Test void testHexDecodeAndEncode() { // Note: char[] must be an even length. // Empty chars. for (int size = 0; size < 10; size++) { final char[] chars = new char[size * 2]; Arrays.fill(chars, '0'); assertHexDecodeAndEncode(chars); } // Random bytes for (int size : new int[] {3, 4, 5, 8, 16, 31}) { final char[] chars = new char[size * 2]; for (int i = 0; i < 5; i++) { // Encode upper case for (int j = 0; j < chars.length; j++) { chars[j] = DIGITS[ThreadLocalRandom.current().nextInt(16)]; } assertHexDecodeAndEncode(chars); } } } /** * Assert the characters can be decoded and encoded. * * @param chars the chars */ private static void assertHexDecodeAndEncode(char[] chars) { final String text = String.valueOf(chars); final byte[] decoded = Hex.decodeHex(text); // Test the encoding is lower case Assertions.assertArrayEquals(text.toLowerCase(Locale.US).toCharArray(), Hex.encodeHex(decoded)); } @Test void testHexThrowsWithOddNumberOfCharacters() { Assertions.assertThrows(IllegalArgumentException.class, () -> Hex.decodeHex("0")); } @Test void testHexThrowsWithIllegalHexCharacters() { Assertions.assertThrows(IllegalArgumentException.class, () -> Hex.decodeHex("0g")); } }
2,808
0
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/test/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/test/java/org/apache/commons/rng/examples/stress/RNGUtilsTest.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.examples.stress; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.core.source64.SplitMix64; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Tests for {@link RNGUtils}. */ class RNGUtilsTest { @Test void testCreateIntProviderLongThrows() { final SplitMix64 rng = new SplitMix64(42); Assertions.assertThrows(IllegalArgumentException.class, () -> RNGUtils.createIntProvider(rng, Source64Mode.LONG)); } @Test void testCreateIntProviderInt() { final long seed = 236784264237894L; final UniformRandomProvider rng1 = new SplitMix64(seed); final UniformRandomProvider rng2 = RNGUtils.createIntProvider(new SplitMix64(seed), Source64Mode.INT); for (int i = 0; i < 50; i++) { Assertions.assertEquals(rng1.nextInt(), rng2.nextInt()); } } @Test void testCreateIntProviderLoHi() { final long seed = 236784264237894L; final UniformRandomProvider rng1 = new SplitMix64(seed); final UniformRandomProvider rng2 = RNGUtils.createIntProvider(new SplitMix64(seed), Source64Mode.LO_HI); for (int i = 0; i < 50; i++) { final long l = rng1.nextLong(); final int hi = (int) (l >>> 32); final int lo = (int) l; Assertions.assertEquals(lo, rng2.nextInt()); Assertions.assertEquals(hi, rng2.nextInt()); } } @Test void testCreateIntProviderHiLo() { final long seed = 2367234237894L; final UniformRandomProvider rng1 = new SplitMix64(seed); final UniformRandomProvider rng2 = RNGUtils.createIntProvider(new SplitMix64(seed), Source64Mode.HI_LO); for (int i = 0; i < 50; i++) { final long l = rng1.nextLong(); final int hi = (int) (l >>> 32); final int lo = (int) l; Assertions.assertEquals(hi, rng2.nextInt()); Assertions.assertEquals(lo, rng2.nextInt()); } } @Test void testCreateIntProviderHi() { final long seed = 2367234237894L; final UniformRandomProvider rng1 = new SplitMix64(seed); final UniformRandomProvider rng2 = RNGUtils.createIntProvider(new SplitMix64(seed), Source64Mode.HI); for (int i = 0; i < 50; i++) { final int hi = (int) (rng1.nextLong() >>> 32); Assertions.assertEquals(hi, rng2.nextInt()); } } @Test void testCreateIntProviderLo() { final long seed = 2367234237894L; final UniformRandomProvider rng1 = new SplitMix64(seed); final UniformRandomProvider rng2 = RNGUtils.createIntProvider(new SplitMix64(seed), Source64Mode.LO); for (int i = 0; i < 50; i++) { final int lo = (int) rng1.nextLong(); Assertions.assertEquals(lo, rng2.nextInt()); } } /** * Test that the default source64 mode matches the nextInt implementation for a LongProvider. * If this changes then the default mode should be updated. The value is used as * the default for the stress test application. */ @Test void testCreateIntProviderDefault() { final long seed = 236784264237894L; final UniformRandomProvider rng1 = new SplitMix64(seed); final UniformRandomProvider rng2 = RNGUtils.createIntProvider(new SplitMix64(seed), RNGUtils.getSource64Default()); for (int i = 0; i < 50; i++) { final int a = rng1.nextInt(); final int b = rng1.nextInt(); Assertions.assertEquals(a, rng2.nextInt()); Assertions.assertEquals(b, rng2.nextInt()); } } }
2,809
0
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/StressTestCommand.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.examples.stress; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.core.source64.RandomLongSource; import org.apache.commons.rng.simple.RandomSource; import picocli.CommandLine.Command; import picocli.CommandLine.Mixin; import picocli.CommandLine.Option; import picocli.CommandLine.Parameters; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.nio.ByteOrder; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.Formatter; import java.util.List; import java.util.Locale; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; /** * Specification for the "stress" command. * * <p>This command loads a list of random generators and tests each generator by * piping the values returned by its {@link UniformRandomProvider#nextInt()} * method to a program that reads {@code int} values from its standard input and * writes an analysis report to standard output.</p> */ @Command(name = "stress", description = {"Run repeat trials of random data generators using a provided test application.", "Data is transferred to the application sub-process via standard input."}) class StressTestCommand implements Callable<Void> { /** 1000. Any value below this can be exactly represented to 3 significant figures. */ private static final int ONE_THOUSAND = 1000; /** The standard options. */ @Mixin private StandardOptions reusableOptions; /** The executable. */ @Parameters(index = "0", description = "The stress test executable.") private File executable; /** The executable arguments. */ @Parameters(index = "1..*", description = "The arguments to pass to the executable.", paramLabel = "<argument>") private List<String> executableArguments = new ArrayList<>(); /** The file output prefix. */ @Option(names = {"--prefix"}, description = "Results file prefix (default: ${DEFAULT-VALUE}).") private File fileOutputPrefix = new File("test_"); /** The stop file. */ @Option(names = {"--stop-file"}, description = {"Stop file (default: <Results file prefix>.stop).", "When created it will prevent new tasks from starting " + "but running tasks will complete."}) private File stopFile; /** The output mode for existing files. */ @Option(names = {"-o", "--output-mode"}, description = {"Output mode for existing files (default: ${DEFAULT-VALUE}).", "Valid values: ${COMPLETION-CANDIDATES}."}) private StressTestCommand.OutputMode outputMode = OutputMode.ERROR; /** The list of random generators. */ @Option(names = {"-l", "--list"}, description = {"List of random generators.", "The default list is all known generators."}, paramLabel = "<genList>") private File generatorsListFile; /** The number of trials to put in the template list of random generators. */ @Option(names = {"-t", "--trials"}, description = {"The number of trials for each random generator.", "Used only for the default list (default: ${DEFAULT-VALUE})."}) private int trials = 1; /** The trial offset. */ @Option(names = {"--trial-offset"}, description = {"Offset to add to the trial number for output files (default: ${DEFAULT-VALUE}).", "Use for parallel tests with the same output prefix."}) private int trialOffset; /** The number of available processors. */ @Option(names = {"-p", "--processors"}, description = {"Number of available processors (default: ${DEFAULT-VALUE}).", "Number of concurrent tasks = ceil(processors / threadsPerTask)", "threadsPerTask = applicationThreads + (ignoreJavaThread ? 0 : 1)"}) private int processors = Math.max(1, Runtime.getRuntime().availableProcessors()); /** The number of threads to use for each test task. */ @Option(names = {"--ignore-java-thread"}, description = {"Ignore the java RNG thread when computing concurrent tasks."}) private boolean ignoreJavaThread; /** The number of threads to use for each testing application. */ @Option(names = {"--threads"}, description = {"Number of threads to use for each application (default: ${DEFAULT-VALUE}).", "Total threads per task includes an optional java thread."}) private int applicationThreads = 1; /** The size of the byte buffer for the binary data. */ @Option(names = {"--buffer-size"}, description = {"Byte-buffer size for the transferred data (default: ${DEFAULT-VALUE})."}) private int bufferSize = 8192; /** The output byte order of the binary data. */ @Option(names = {"-b", "--byte-order"}, description = {"Byte-order of the transferred data (default: ${DEFAULT-VALUE}).", "Valid values: BIG_ENDIAN, LITTLE_ENDIAN."}) private ByteOrder byteOrder = ByteOrder.nativeOrder(); /** Flag to indicate the output should be bit-reversed. */ @Option(names = {"-r", "--reverse-bits"}, description = {"Reverse the bits in the data (default: ${DEFAULT-VALUE}).", "Note: Generators may fail tests for a reverse sequence " + "when passing using the standard sequence."}) private boolean reverseBits; /** Flag to use 64-bit long output. */ @Option(names = {"--raw64"}, description = {"Use 64-bit output (default is 32-bit).", "This is ignored if not a native 64-bit generator.", "Set to true sets the source64 mode to LONG."}) private boolean raw64; /** Output mode for 64-bit long output. * * <p>Note: The default is set as the default caching implementation. * It passes the full output of the RNG to the stress test application. * Any combination random sources are performed on the full 64-bit output. * * <p>If using INT this will use the RNG's nextInt method. * Any combination random sources are performed on the 32-bit output. Without * a combination random source the output should be the same as the default if * the generator uses the default caching implementation. * * <p>LONG and LO_HI should match binary output when LITTLE_ENDIAN. LONG and HI_LO * should match binary output when BIG_ENDIAN. * * <p>Changing from HI_LO to LO_HI should not effect the stress test as many values are consumed * per test. Using HI or LO may have a different outcome as parts of the generator output * may be weak, e.g. the lower bits of linear congruential generators. */ @Option(names = {"--source64"}, description = {"Output mode for 64-bit generators (default: ${DEFAULT-VALUE}).", "This is ignored if not a native 64-bit generator.", "In 32-bit mode the output uses a combination of upper and " + "lower bits of the 64-bit value.", "Valid values: ${COMPLETION-CANDIDATES}."}) private Source64Mode source64 = RNGUtils.getSource64Default(); /** The random seed as a byte[]. */ @Option(names = {"-x", "--hex-seed"}, description = {"The hex-encoded random seed.", "Seed conversion for multi-byte primitives use little-endian format.", "Use to repeat tests. Not recommended for batch testing."}) private String byteSeed; /** * Flag to indicate the output should be combined with a hash code from a new object. * This is a method previously used in the * {@link org.apache.commons.rng.simple.internal.SeedFactory SeedFactory}. * * @see System#identityHashCode(Object) */ @Option(names = {"--hashcode"}, description = {"Combine the bits with a hash code (default: ${DEFAULT-VALUE}).", "System.identityHashCode(new Object()) ^ rng.nextInt()."}) private boolean xorHashCode; /** * Flag to indicate the output should be combined with output from ThreadLocalRandom. */ @Option(names = {"--local-random"}, description = {"Combine the bits with ThreadLocalRandom (default: ${DEFAULT-VALUE}).", "ThreadLocalRandom.current().nextInt() ^ rng.nextInt()."}) private boolean xorThreadLocalRandom; /** * Optional second generator to be combined with the primary generator. */ @Option(names = {"--xor-rng"}, description = {"Combine the bits with a second generator.", "xorRng.nextInt() ^ rng.nextInt().", "Valid values: Any known RandomSource enum value."}) private RandomSource xorRandomSource; /** The flag to indicate a dry run. */ @Option(names = {"--dry-run"}, description = "Perform a dry run where the generators and output files are created " + "but the stress test is not executed.") private boolean dryRun; /** The locl to hold when checking the stop file. */ private ReentrantLock stopFileLock = new ReentrantLock(false); /** The stop file exists flag. This should be read/updated when holding the lock. */ private boolean stopFileExists; /** * The timestamp when the stop file was last checked. * This should be read/updated when holding the lock. */ private long stopFileTimestamp; /** * The output mode for existing files. */ enum OutputMode { /** Error if the files exists. */ ERROR, /** Skip existing files. */ SKIP, /** Append to existing files. */ APPEND, /** Overwrite existing files. */ OVERWRITE } /** * Validates the run command arguments, creates the list of generators and runs the * stress test tasks. */ @Override public Void call() { LogUtils.setLogLevel(reusableOptions.logLevel); ProcessUtils.checkExecutable(executable); ProcessUtils.checkOutputDirectory(fileOutputPrefix); checkStopFileDoesNotExist(); final Iterable<StressTestData> stressTestData = createStressTestData(); printStressTestData(stressTestData); runStressTest(stressTestData); return null; } /** * Initialise the stop file to a default unless specified by the user, then check it * does not currently exist. * * @throws ApplicationException If the stop file exists */ private void checkStopFileDoesNotExist() { if (stopFile == null) { stopFile = new File(fileOutputPrefix + ".stop"); } if (stopFile.exists()) { throw new ApplicationException("Stop file exists: " + stopFile); } } /** * Check if the stop file exists. * * <p>This method is thread-safe. It will log a message if the file exists one time only. * * @return true if the stop file exists */ private boolean isStopFileExists() { stopFileLock.lock(); try { if (!stopFileExists) { // This should hit the filesystem each time it is called. // To prevent this happening a lot when all the first set of tasks run use // a timestamp to limit the check to 1 time each interval. final long timestamp = System.currentTimeMillis(); if (timestamp > stopFileTimestamp) { checkStopFile(timestamp); } } return stopFileExists; } finally { stopFileLock.unlock(); } } /** * Check if the stop file exists. Update the timestamp for the next check. If the stop file * does exists then log a message. * * @param timestamp Timestamp of the last check. */ private void checkStopFile(final long timestamp) { stopFileTimestamp = timestamp + TimeUnit.SECONDS.toMillis(2); stopFileExists = stopFile.exists(); if (stopFileExists) { LogUtils.info("Stop file detected: %s", stopFile); LogUtils.info("No further tasks will start"); } } /** * Creates the test data. * * <p>If the input file is null then a default list is created. * * @return the stress test data * @throws ApplicationException if an error occurred during the file read. */ private Iterable<StressTestData> createStressTestData() { if (generatorsListFile == null) { return new StressTestDataList("", trials); } // Read data into a list try (BufferedReader reader = Files.newBufferedReader(generatorsListFile.toPath())) { return ListCommand.readStressTestData(reader); } catch (final IOException ex) { throw new ApplicationException("Failed to read generators list: " + generatorsListFile, ex); } } /** * Prints the stress test data if the verbosity allows. This is used to debug the list * of generators to be tested. * * @param stressTestData List of generators to be tested. */ private static void printStressTestData(Iterable<StressTestData> stressTestData) { if (!LogUtils.isLoggable(LogUtils.LogLevel.DEBUG)) { return; } try { final StringBuilder sb = new StringBuilder("Testing generators").append(System.lineSeparator()); ListCommand.writeStressTestData(sb, stressTestData); LogUtils.debug(sb.toString()); } catch (final IOException ex) { throw new ApplicationException("Failed to show list of generators", ex); } } /** * Creates the tasks and starts the processes. * * @param stressTestData List of generators to be tested. */ private void runStressTest(Iterable<StressTestData> stressTestData) { final List<String> command = ProcessUtils.buildSubProcessCommand(executable, executableArguments); LogUtils.info("Set-up stress test ..."); // Check existing output files before starting the tasks. final String basePath = fileOutputPrefix.getAbsolutePath(); checkExistingOutputFiles(basePath, stressTestData); final int parallelTasks = getParallelTasks(); final ProgressTracker progressTracker = new ProgressTracker(parallelTasks); final List<Runnable> tasks = createTasks(command, basePath, stressTestData, progressTracker); // Run tasks with parallel execution. final ExecutorService service = Executors.newFixedThreadPool(parallelTasks); LogUtils.info("Running stress test ..."); LogUtils.info("Shutdown by creating stop file: %s", stopFile); progressTracker.setTotal(tasks.size()); final List<Future<?>> taskList = submitTasks(service, tasks); // Wait for completion (ignoring return value). try { for (final Future<?> f : taskList) { try { f.get(); } catch (final ExecutionException ex) { // Log the error. Do not re-throw as other tasks may be processing that // can still complete successfully. LogUtils.error(ex.getCause(), ex.getMessage()); } } } catch (final InterruptedException ex) { // Restore interrupted state... Thread.currentThread().interrupt(); throw new ApplicationException("Unexpected interruption: " + ex.getMessage(), ex); } finally { // Terminate all threads. service.shutdown(); } LogUtils.info("Finished stress test"); } /** * Check for existing output files. * * @param basePath The base path to the output results files. * @param stressTestData List of generators to be tested. * @throws ApplicationException If an output file exists and the output mode is error */ private void checkExistingOutputFiles(String basePath, Iterable<StressTestData> stressTestData) { if (outputMode == StressTestCommand.OutputMode.ERROR) { for (final StressTestData testData : stressTestData) { for (int trial = 1; trial <= testData.getTrials(); trial++) { // Create the output file final File output = createOutputFile(basePath, testData, trial); if (output.exists()) { throw new ApplicationException(createExistingFileMessage(output)); } } } } } /** * Creates the named output file. * * <p>Note: The trial will be combined with the trial offset to create the file name. * * @param basePath The base path to the output results files. * @param testData The test data. * @param trial The trial. * @return the file */ private File createOutputFile(String basePath, StressTestData testData, int trial) { return new File(String.format("%s%s_%d", basePath, testData.getId(), trial + trialOffset)); } /** * Creates the existing file message. * * @param output The output file. * @return the message */ private static String createExistingFileMessage(File output) { return "Existing output file: " + output; } /** * Gets the number of parallel tasks. This uses the number of available processors and * the number of threads to use per task. * * <pre> * threadsPerTask = applicationThreads + (ignoreJavaThread ? 0 : 1) * parallelTasks = ceil(processors / threadsPerTask) * </pre> * * @return the parallel tasks */ private int getParallelTasks() { // Avoid zeros in the fraction numberator and denominator final int availableProcessors = Math.max(1, processors); final int threadsPerTask = Math.max(1, applicationThreads + (ignoreJavaThread ? 0 : 1)); final int parallelTasks = (int) Math.ceil((double) availableProcessors / threadsPerTask); LogUtils.debug("Parallel tasks = %d (%d / %d)", parallelTasks, availableProcessors, threadsPerTask); return parallelTasks; } /** * Create the tasks for the test data. The output file for the sub-process will be * constructed using the base path, the test identifier and the trial number. * * @param command The command for the test application. * @param basePath The base path to the output results files. * @param stressTestData List of generators to be tested. * @param progressTracker Progress tracker. * @return the list of tasks */ private List<Runnable> createTasks(List<String> command, String basePath, Iterable<StressTestData> stressTestData, ProgressTracker progressTracker) { // raw64 flag overrides the source64 mode if (raw64) { source64 = Source64Mode.LONG; } final List<Runnable> tasks = new ArrayList<>(); for (final StressTestData testData : stressTestData) { for (int trial = 1; trial <= testData.getTrials(); trial++) { // Create the output file final File output = createOutputFile(basePath, testData, trial); if (output.exists()) { // In case the file was created since the last check if (outputMode == StressTestCommand.OutputMode.ERROR) { throw new ApplicationException(createExistingFileMessage(output)); } // Log the decision LogUtils.info("%s existing output file: %s", outputMode, output); if (outputMode == StressTestCommand.OutputMode.SKIP) { continue; } } // Create the generator. Explicitly create a seed so it can be recorded. final byte[] seed = createSeed(testData.getRandomSource()); UniformRandomProvider rng = testData.createRNG(seed); if (source64 == Source64Mode.LONG && !(rng instanceof RandomLongSource)) { throw new ApplicationException("Not a 64-bit RNG: " + rng); } // Upper or lower bits from 64-bit generators must be created first before // any further combination operators. // Note this does not test source64 != Source64Mode.LONG as the full long // output split into hi-lo or lo-hi is supported by the RngDataOutput. if (rng instanceof RandomLongSource && (source64 == Source64Mode.HI || source64 == Source64Mode.LO || source64 == Source64Mode.INT)) { rng = RNGUtils.createIntProvider((UniformRandomProvider & RandomLongSource) rng, source64); } // Combination generators. Mainly used for testing. // These operations maintain the native output type (int/long). if (xorHashCode) { rng = RNGUtils.createHashCodeProvider(rng); } if (xorThreadLocalRandom) { rng = RNGUtils.createThreadLocalRandomProvider(rng); } if (xorRandomSource != null) { rng = RNGUtils.createXorProvider( xorRandomSource.create(), rng); } if (reverseBits) { rng = RNGUtils.createReverseBitsProvider(rng); } // ------- // Note: Manipulation of the byte order for the platform is done during output. // ------- // Run the test final Runnable r = new StressTestTask(testData.getRandomSource(), rng, seed, output, command, this, progressTracker); tasks.add(r); } } return tasks; } /** * Creates the seed. This will call {@link RandomSource#createSeed()} unless a hex seed has * been explicitly specified on the command line. * * @param randomSource Random source. * @return the seed */ private byte[] createSeed(RandomSource randomSource) { if (byteSeed != null) { try { return Hex.decodeHex(byteSeed); } catch (IllegalArgumentException ex) { throw new ApplicationException("Invalid hex seed: " + ex.getMessage(), ex); } } return randomSource.createSeed(); } /** * Submit the tasks to the executor service. * * @param service The executor service. * @param tasks The list of tasks. * @return the list of submitted tasks */ private static List<Future<?>> submitTasks(ExecutorService service, List<Runnable> tasks) { final List<Future<?>> taskList = new ArrayList<>(tasks.size()); tasks.forEach(r -> taskList.add(service.submit(r))); return taskList; } /** * Class for reporting total progress of tasks to the console. * * <p>This stores the start and end time of tasks to allow it to estimate the time remaining * for all the tests. */ static class ProgressTracker { /** The interval at which to report progress (in milliseconds). */ private static final long PROGRESS_INTERVAL = 500; /** The total. */ private int total; /** The level of parallelisation. */ private final int parallelTasks; /** The task id. */ private int taskId; /** The start time of tasks (in milliseconds from the epoch). */ private long[] startTimes; /** The durations of all completed tasks (in milliseconds). This is sorted. */ private long[] sortedDurations; /** The number of completed tasks. */ private int completed; /** The timestamp of the next progress report. */ private long nextReportTimestamp; /** * Create a new instance. The total number of tasks must be initialized before use. * * @param parallelTasks The number of parallel tasks. */ ProgressTracker(int parallelTasks) { this.parallelTasks = parallelTasks; } /** * Sets the total number of tasks to track. * * @param total The total tasks. */ synchronized void setTotal(int total) { this.total = total; startTimes = new long[total]; sortedDurations = new long[total]; } /** * Submit a task for progress tracking. The task start time is recorded and the * task is allocated an identifier. * * @return the task Id */ int submitTask() { int id; synchronized (this) { final long current = System.currentTimeMillis(); id = taskId++; startTimes[id] = current; reportProgress(current); } return id; } /** * Signal that a task has completed. The task duration will be returned. * * @param id Task Id. * @return the task time in milliseconds */ long endTask(int id) { long duration; synchronized (this) { final long current = System.currentTimeMillis(); duration = current - startTimes[id]; sortedDurations[completed++] = duration; reportProgress(current); } return duration; } /** * Report the progress. This uses the current state and should be done within a * synchronized block. * * @param current Current time (in milliseconds). */ private void reportProgress(long current) { // Determine the current state of tasks final int pending = total - taskId; final int running = taskId - completed; // Report progress in the following conditions: // - All tasks have completed (i.e. the end); or // - The current timestamp is above the next reporting time and either: // -- The number of running tasks is equal to the level of parallel tasks // (i.e. the system is running at capacity, so not the end of a task but the start // of a new one) // -- There are no pending tasks (i.e. the final submission or the end of a final task) if (completed >= total || (current >= nextReportTimestamp && running == parallelTasks || pending == 0)) { // Report nextReportTimestamp = current + PROGRESS_INTERVAL; final StringBuilder sb = createStringBuilderWithTimestamp(current, pending, running, completed); try (Formatter formatter = new Formatter(sb)) { formatter.format(" (%.2f%%)", 100.0 * completed / total); appendRemaining(sb, current, pending, running); LogUtils.info(sb.toString()); } } } /** * Creates the string builder for the progress message with a timestamp prefix. * * <pre> * [HH:mm:ss] Pending [pending]. Running [running]. Completed [completed] * </pre> * * @param current Current time (in milliseconds) * @param pending Pending tasks. * @param running Running tasks. * @param completed Completed tasks. * @return the string builder */ private static StringBuilder createStringBuilderWithTimestamp(long current, int pending, int running, int completed) { final StringBuilder sb = new StringBuilder(80); // Use local time to adjust for timezone final LocalDateTime time = LocalDateTime.ofInstant( Instant.ofEpochMilli(current), ZoneId.systemDefault()); sb.append('['); append00(sb, time.getHour()).append(':'); append00(sb, time.getMinute()).append(':'); append00(sb, time.getSecond()); return sb.append("] Pending ").append(pending) .append(". Running ").append(running) .append(". Completed ").append(completed); } /** * Compute an estimate of the time remaining and append to the progress. Updates * the estimated time of arrival (ETA). * * @param sb String Builder. * @param current Current time (in milliseconds) * @param pending Pending tasks. * @param running Running tasks. * @return the string builder */ private StringBuilder appendRemaining(StringBuilder sb, long current, int pending, int running) { final long millis = getRemainingTime(current, pending, running); if (millis == 0) { // Unknown. return sb; } // HH:mm:ss format sb.append(". Remaining = "); hms(sb, millis); return sb; } /** * Gets the remaining time (in milliseconds). * * @param current Current time (in milliseconds) * @param pending Pending tasks. * @param running Running tasks. * @return the remaining time */ private long getRemainingTime(long current, int pending, int running) { final long taskTime = getEstimatedTaskTime(); if (taskTime == 0) { // No estimate possible return 0; } // The start times are sorted. This method assumes the most recent start times // are still running tasks. // If this is wrong (more recently submitted tasks finished early) the result // is the estimate is too high. This could be corrected by storing the tasks // that have finished and finding the times of only running tasks. // The remaining time is: // The time for all running tasks to finish // + The time for pending tasks to run // The id of the most recently submitted task. // Guard with a minimum index of zero to get a valid index. final int id = Math.max(0, taskId - 1); // If there is a running task assume the youngest task is still running // and estimate the time left. long millis = (running == 0) ? 0 : getTimeRemaining(taskTime, current, startTimes[id]); // If additional tasks must also be submitted then the time must include // the estimated time for running tasks to finish before new submissions // in the batch can be made. // now // s1 --------------->| // s2 -----------|--------> // s3 -------|------------> // s4 --------------> // // Assume parallel batch execution. // E.g. 3 additional tasks with parallelisation 4 is 0 batches final int batches = pending / parallelTasks; millis += batches * taskTime; // Compute the expected end time of the final batch based on it starting when // a currently running task ends. // E.g. 3 remaining tasks requires the end time of the 3rd oldest running task. final int remainder = pending % parallelTasks; if (remainder != 0) { // Guard with a minimum index of zero to get a valid index. final int nthOldest = Math.max(0, id - parallelTasks + remainder); millis += getTimeRemaining(taskTime, current, startTimes[nthOldest]); } return millis; } /** * Gets the estimated task time. * * @return the estimated task time */ private long getEstimatedTaskTime() { Arrays.sort(sortedDurations, 0, completed); // Return median of small lists. If no tasks have finished this returns zero. // as the durations is zero initialized. if (completed < 4) { return sortedDurations[completed / 2]; } // Dieharder and BigCrush run in approximately constant time. // Speed varies with the speed of the RNG by about 2-fold, and // for Dieharder it may repeat suspicious tests. // PractRand may fail very fast for bad generators which skews // using the mean or even the median. So look at the longest // running tests. // Find long running tests (>50% of the max run-time) int upper = completed - 1; final long halfMax = sortedDurations[upper] / 2; // Binary search for the approximate cut-off int lower = 0; while (lower + 1 < upper) { final int mid = (lower + upper) >>> 1; if (sortedDurations[mid] < halfMax) { lower = mid; } else { upper = mid; } } // Use the median of all tasks within approximately 50% of the max. return sortedDurations[(upper + completed - 1) / 2]; } /** * Gets the time remaining for the task. * * @param taskTime Estimated task time. * @param current Current time. * @param startTime Start time. * @return the time remaining */ private static long getTimeRemaining(long taskTime, long current, long startTime) { final long endTime = startTime + taskTime; // Ensure the time is positive in the case where the estimate is too low. return Math.max(0, endTime - current); } /** * Append the milliseconds using {@code HH::mm:ss} format. * * @param sb String Builder. * @param millis Milliseconds. * @return the string builder */ static StringBuilder hms(StringBuilder sb, final long millis) { final long hours = TimeUnit.MILLISECONDS.toHours(millis); long minutes = TimeUnit.MILLISECONDS.toMinutes(millis); long seconds = TimeUnit.MILLISECONDS.toSeconds(millis); // Truncate to interval [0,59] seconds -= TimeUnit.MINUTES.toSeconds(minutes); minutes -= TimeUnit.HOURS.toMinutes(hours); append00(sb, hours).append(':'); append00(sb, minutes).append(':'); return append00(sb, seconds); } /** * Append the ticks to the string builder in the format {@code %02d}. * * @param sb String Builder. * @param ticks Ticks. * @return the string builder */ static StringBuilder append00(StringBuilder sb, long ticks) { if (ticks == 0) { sb.append("00"); } else { if (ticks < 10) { sb.append('0'); } sb.append(ticks); } return sb; } } /** * Pipes random numbers to the standard input of an analyzer executable. */ private static class StressTestTask implements Runnable { /** Comment prefix. */ private static final String C = "# "; /** New line. */ private static final String N = System.lineSeparator(); /** The date format. */ private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; /** The SI units for bytes in increments of 10^3. */ private static final String[] SI_UNITS = {"B", "kB", "MB", "GB", "TB", "PB", "EB"}; /** The SI unit base for bytes (10^3). */ private static final long SI_UNIT_BASE = 1000; /** The random source. */ private final RandomSource randomSource; /** RNG to be tested. */ private final UniformRandomProvider rng; /** The seed used to create the RNG. */ private final byte[] seed; /** Output report file of the sub-process. */ private final File output; /** The sub-process command to run. */ private final List<String> command; /** The stress test command. */ private final StressTestCommand cmd; /** The progress tracker. */ private final ProgressTracker progressTracker; /** The count of bytes used by the sub-process. */ private long bytesUsed; /** * Creates the task. * * @param randomSource The random source. * @param rng RNG to be tested. * @param seed The seed used to create the RNG. * @param output Output report file. * @param command The sub-process command to run. * @param cmd The run command. * @param progressTracker The progress tracker. */ StressTestTask(RandomSource randomSource, UniformRandomProvider rng, byte[] seed, File output, List<String> command, StressTestCommand cmd, ProgressTracker progressTracker) { this.randomSource = randomSource; this.rng = rng; this.seed = seed; this.output = output; this.command = command; this.cmd = cmd; this.progressTracker = progressTracker; } /** {@inheritDoc} */ @Override public void run() { if (cmd.isStopFileExists()) { // Do nothing return; } try { printHeader(); Object exitValue; long millis; final int taskId = progressTracker.submitTask(); if (cmd.dryRun) { // Do not do anything. Ignore the runtime. exitValue = "N/A"; progressTracker.endTask(taskId); millis = 0; } else { // Run the sub-process exitValue = runSubProcess(); millis = progressTracker.endTask(taskId); } printFooter(millis, exitValue); } catch (final IOException ex) { throw new ApplicationException("Failed to run task: " + ex.getMessage(), ex); } } /** * Run the analyzer sub-process command. * * @return The exit value. * @throws IOException Signals that an I/O exception has occurred. */ private Integer runSubProcess() throws IOException { // Start test suite. final ProcessBuilder builder = new ProcessBuilder(command); builder.redirectOutput(ProcessBuilder.Redirect.appendTo(output)); builder.redirectErrorStream(true); final Process testingProcess = builder.start(); // Use a custom data output to write the RNG. try (RngDataOutput sink = RNGUtils.createDataOutput(rng, cmd.source64, testingProcess.getOutputStream(), cmd.bufferSize, cmd.byteOrder)) { for (;;) { sink.write(rng); bytesUsed++; } } catch (final IOException ignored) { // Hopefully getting here when the analyzing software terminates. } bytesUsed *= cmd.bufferSize; // Get the exit value. // Wait for up to 60 seconds. // If an application does not exit after this time then something is wrong. // Dieharder and TestU01 BigCrush exit within 1 second. // PractRand has been observed to take longer than 1 second. It calls std::exit(0) // when failing a test so the length of time may be related to freeing memory. return ProcessUtils.getExitValue(testingProcess, TimeUnit.SECONDS.toMillis(60)); } /** * Prints the header. * * @throws IOException if there was a problem opening or writing to the * {@code output} file. */ private void printHeader() throws IOException { final StringBuilder sb = new StringBuilder(200); sb.append(C).append(N) .append(C).append("RandomSource: ").append(randomSource.name()).append(N) .append(C).append("RNG: ").append(rng.toString()).append(N) .append(C).append("Seed: ").append(Hex.encodeHex(seed)).append(N) .append(C).append(N) // Match the output of 'java -version', e.g. // java version "1.8.0_131" // Java(TM) SE Runtime Environment (build 1.8.0_131-b11) // Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode) .append(C).append("Java: ").append(System.getProperty("java.version")).append(N); appendNameAndVersion(sb, "Runtime", "java.runtime.name", "java.runtime.version"); appendNameAndVersion(sb, "JVM", "java.vm.name", "java.vm.version", "java.vm.info"); sb.append(C).append("OS: ").append(System.getProperty("os.name")) .append(' ').append(System.getProperty("os.version")) .append(' ').append(System.getProperty("os.arch")).append(N) .append(C).append("Native byte-order: ").append(ByteOrder.nativeOrder()).append(N) .append(C).append("Output byte-order: ").append(cmd.byteOrder).append(N); if (rng instanceof RandomLongSource) { sb.append(C).append("64-bit output: ").append(cmd.source64).append(N); } sb.append(C).append(N) .append(C).append("Analyzer: "); for (final String s : command) { sb.append(s).append(' '); } sb.append(N) .append(C).append(N); appendDate(sb, "Start").append(C).append(N); write(sb, output, cmd.outputMode == StressTestCommand.OutputMode.APPEND); } /** * Prints the footer. * * @param millis Duration of the run (in milliseconds). * @param exitValue The process exit value. * @throws IOException if there was a problem opening or writing to the * {@code output} file. */ private void printFooter(long millis, Object exitValue) throws IOException { final StringBuilder sb = new StringBuilder(200); sb.append(C).append(N); appendDate(sb, "End").append(C).append(N); sb.append(C).append("Exit value: ").append(exitValue).append(N) .append(C).append("Bytes used: ").append(bytesUsed) .append(" >= 2^").append(log2(bytesUsed)) .append(" (").append(bytesToString(bytesUsed)).append(')').append(N) .append(C).append(N); final double duration = millis * 1e-3 / 60; sb.append(C).append("Test duration: ").append(duration).append(" minutes").append(N) .append(C).append(N); write(sb, output, true); } /** * Write the string builder to the output file. * * @param sb The string builder. * @param output The output file. * @param append Set to {@code true} to append to the file. * @throws IOException Signals that an I/O exception has occurred. */ private static void write(StringBuilder sb, File output, boolean append) throws IOException { try (BufferedWriter w = append ? Files.newBufferedWriter(output.toPath(), StandardOpenOption.APPEND) : Files.newBufferedWriter(output.toPath())) { w.write(sb.toString()); } } /** * Append prefix and then name and version from System properties, finished with * a new line. The format is: * * <pre>{@code # <prefix>: <name> (build <version>[, <info>, ...])}</pre> * * @param sb The string builder. * @param prefix The prefix. * @param nameKey The name key. * @param versionKey The version key. * @param infoKeys The additional information keys. * @return the StringBuilder. */ private static StringBuilder appendNameAndVersion(StringBuilder sb, String prefix, String nameKey, String versionKey, String... infoKeys) { appendPrefix(sb, prefix) .append(System.getProperty(nameKey, "?")) .append(" (build ") .append(System.getProperty(versionKey, "?")); for (final String key : infoKeys) { final String value = System.getProperty(key, ""); if (!value.isEmpty()) { sb.append(", ").append(value); } } return sb.append(')').append(N); } /** * Append a comment with the current date to the {@link StringBuilder}, finished with * a new line. The format is: * * <pre>{@code # <prefix>: yyyy-MM-dd HH:mm:ss}</pre> * * @param sb The StringBuilder. * @param prefix The prefix used before the formatted date, e.g. "Start". * @return the StringBuilder. */ private static StringBuilder appendDate(StringBuilder sb, String prefix) { // Use local date format. It is not thread safe. final SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.US); return appendPrefix(sb, prefix).append(dateFormat.format(new Date())).append(N); } /** * Append a comment with the current date to the {@link StringBuilder}. * * <pre> * {@code # <prefix>: yyyy-MM-dd HH:mm:ss} * </pre> * * @param sb The StringBuilder. * @param prefix The prefix used before the formatted date, e.g. "Start". * @return the StringBuilder. */ private static StringBuilder appendPrefix(StringBuilder sb, String prefix) { return sb.append(C).append(prefix).append(": "); } /** * Convert bytes to a human readable string. Example output: * * <pre> * SI * 0: 0 B * 27: 27 B * 999: 999 B * 1000: 1.0 kB * 1023: 1.0 kB * 1024: 1.0 kB * 1728: 1.7 kB * 110592: 110.6 kB * 7077888: 7.1 MB * 452984832: 453.0 MB * 28991029248: 29.0 GB * 1855425871872: 1.9 TB * 9223372036854775807: 9.2 EB (Long.MAX_VALUE) * </pre> * * @param bytes the bytes * @return the string * @see <a * href="https://stackoverflow.com/questions/3758606/how-to-convert-byte-size-into-human-readable-format-in-java">How * to convert byte size into human readable format in java?</a> */ static String bytesToString(long bytes) { // When using the smallest unit no decimal point is needed, because it's the exact number. if (bytes < ONE_THOUSAND) { return bytes + " " + SI_UNITS[0]; } final int exponent = (int) (Math.log(bytes) / Math.log(SI_UNIT_BASE)); final String unit = SI_UNITS[exponent]; return String.format(Locale.US, "%.1f %s", bytes / Math.pow(SI_UNIT_BASE, exponent), unit); } /** * Return the log2 of a {@code long} value rounded down to a power of 2. * * @param x the value * @return {@code floor(log2(x))} */ static int log2(long x) { return 63 - Long.numberOfLeadingZeros(x); } } }
2,810
0
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/ManifestVersionProvider.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.examples.stress; import picocli.CommandLine.IVersionProvider; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Enumeration; import java.util.jar.Attributes; import java.util.jar.Manifest; /** * {@link IVersionProvider} implementation that returns version information from * the package jar file's {@code /META-INF/MANIFEST.MF} file. * * @see <a * href="https://github.com/remkop/picocli/blob/master/picocli-examples/src/main/java/picocli/examples/VersionProviderDemo2.java">PicoCLI * version provider demo</a> */ class ManifestVersionProvider implements IVersionProvider { /** {@inheritDoc} */ @Override public String[] getVersion() throws Exception { final Enumeration<URL> resources = Thread.currentThread().getContextClassLoader() .getResources("META-INF/MANIFEST.MF"); while (resources.hasMoreElements()) { final URL url = resources.nextElement(); try (InputStream stream = url.openStream()) { final Manifest manifest = new Manifest(stream); if (isApplicableManifest(manifest)) { final Attributes attr = manifest.getMainAttributes(); return new String[] {get(attr, "Implementation-Title") + " version \"" + get(attr, "Implementation-Version") + "\""}; } } catch (final IOException ex) { return new String[] {"Unable to read from " + url + ". " + ex}; } } return new String[0]; } /** * Checks if this is the applicable manifest for the package. * * @param manifest The manifest. * @return true if is the applicable manifest */ private static boolean isApplicableManifest(Manifest manifest) { final Attributes attributes = manifest.getMainAttributes(); return "org.apache.commons.rng.examples.stress".equals(get(attributes, "Automatic-Module-Name")); } /** * Gets the named object from the attributes using the key. * * @param attributes The attributes. * @param key The key. * @return the object */ private static Object get(Attributes attributes, String key) { return attributes.get(new Attributes.Name(key)); } }
2,811
0
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/ResultsCommand.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.examples.stress; import org.apache.commons.rng.simple.RandomSource; import picocli.CommandLine.Command; import picocli.CommandLine.Mixin; import picocli.CommandLine.Option; import picocli.CommandLine.Parameters; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.Formatter; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.ListIterator; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.Callable; import java.util.function.Function; import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * Specification for the "results" command. * * <p>This command creates a summary of the results from known test applications.</p> * * <ul> * <li>Dieharder * <li>Test U01 (BigCrush, Crush, SmallCrush) * </ul> */ @Command(name = "results", description = {"Collate results from stress test applications."}) class ResultsCommand implements Callable<Void> { /** The pattern to identify the RandomSource in the stress test result header. */ private static final Pattern RANDOM_SOURCE_PATTERN = Pattern.compile("^# RandomSource: (.*)"); /** The pattern to identify the RNG in the stress test result header. */ private static final Pattern RNG_PATTERN = Pattern.compile("^# RNG: (.*)"); /** The pattern to identify the test exit code in the stress test result footer. */ private static final Pattern TEST_EXIT_PATTERN = Pattern.compile("^# Exit value: (\\d+)"); /** The pattern to identify the Dieharder test format. */ private static final Pattern DIEHARDER_PATTERN = Pattern.compile("^# *dieharder version"); /** The pattern to identify a Dieharder failed test result. */ private static final Pattern DIEHARDER_FAILED_PATTERN = Pattern.compile("FAILED *$"); /** The pattern to identify the Test U01 test format. */ private static final Pattern TESTU01_PATTERN = Pattern.compile("^ *Version: TestU01"); /** The pattern to identify the Test U01 summary header. */ private static final Pattern TESTU01_SUMMARY_PATTERN = Pattern.compile("^========= Summary results of (\\S*) "); /** The pattern to identify the Test U01 failed test result. */ private static final Pattern TESTU01_TEST_RESULT_PATTERN = Pattern.compile("^ ?(\\d+ .*) "); /** The pattern to identify the Test U01 test starting entry. */ private static final Pattern TESTU01_STARTING_PATTERN = Pattern.compile("^ *Starting (\\S*)"); /** The pattern to identify the PractRand test format. */ private static final Pattern PRACTRAND_PATTERN = Pattern.compile("PractRand version"); /** The pattern to identify the PractRand output byte size. */ private static final Pattern PRACTRAND_OUTPUT_SIZE_PATTERN = Pattern.compile("\\(2\\^(\\d+) bytes\\)"); /** The pattern to identify a PractRand failed test result. */ private static final Pattern PRACTRAND_FAILED_PATTERN = Pattern.compile("FAIL *!* *$"); /** The name of the Dieharder sums test. */ private static final String DIEHARDER_SUMS = "diehard_sums"; /** The string identifying a bit-reversed generator. */ private static final String BIT_REVERSED = "Bit-reversed"; /** Character '\'. */ private static final char FORWARD_SLASH = '\\'; /** Character '/'. */ private static final char BACK_SLASH = '\\'; /** Character '|'. */ private static final char PIPE = '|'; /** The column name for the RNG. */ private static final String COLUMN_RNG = "RNG"; /** Constant for conversion of bytes to binary units, prefixed with a space. */ private static final String[] BINARY_UNITS = {" B", " KiB", " MiB", " GiB", " TiB", " PiB", " EiB"}; /** The standard options. */ @Mixin private StandardOptions reusableOptions; /** The results files. */ @Parameters(arity = "1..*", description = "The results files.", paramLabel = "<file>") private List<File> resultsFiles = new ArrayList<>(); /** The file output prefix. */ @Option(names = {"-o", "--out"}, description = "The output file (default: stdout).") private File fileOutput; /** The output format. */ @Option(names = {"-f", "--format"}, description = {"Output format (default: ${DEFAULT-VALUE}).", "Valid values: ${COMPLETION-CANDIDATES}."}) private ResultsCommand.OutputFormat outputFormat = OutputFormat.TXT; /** The flag to show failed tests. */ @Option(names = {"--failed"}, description = {"Output failed tests (support varies by format).", "CSV: List individual test failures.", "APT: Count of systematic test failures."}) private boolean showFailedTests; /** The flag to include the Dieharder sums test. */ @Option(names = {"--include-sums"}, description = "Include Dieharder sums test.") private boolean includeDiehardSums; /** The common file path prefix used when outputting file paths. */ @Option(names = {"--path-prefix"}, description = {"Common path prefix.", "If specified this will replace the common prefix from all " + "files when the path is output, e.g. for the APT report."}) private String pathPrefix = ""; /** The flag to ignore partial results. */ @Option(names = {"-i", "--ignore"}, description = "Ignore partial results.") private boolean ignorePartialResults; /** The flag to delete partial results files. */ @Option(names = {"--delete"}, description = {"Delete partial results files.", "This is not reversible!"}) private boolean deletePartialResults; /** * The output mode for the results. */ enum OutputFormat { /** Comma-Separated Values (CSV) output. */ CSV, /** Almost Plain Text (APT) output. */ APT, /** Text table output. */ TXT, /** Systematic failures output. */ FAILURES, } /** * The test application file format. */ enum TestFormat { /** Dieharder. */ DIEHARDER, /** Test U01. */ TESTU01, /** PractRand. */ PRACTRAND, } /** * Encapsulate the results of a test application. */ private static class TestResult { /** The result file. */ private final File resultFile; /** The random source. */ private final RandomSource randomSource; /** Flag indicating the generator was bit reversed. */ private final boolean bitReversed; /** The test application format. */ private final TestFormat testFormat; /** The names of the failed tests. */ private final List<String> failedTests = new ArrayList<>(); /** The test application name. */ private String testApplicationName; /** * Store the exit code. * Initialised to {@link Integer#MIN_VALUE}. Exit values are expected to be 8-bit numbers * with zero for success. */ private int exitCode = Integer.MIN_VALUE; /** * @param resultFile the result file * @param randomSource the random source * @param bitReversed the bit reversed flag * @param testFormat the test format */ TestResult(File resultFile, RandomSource randomSource, boolean bitReversed, TestFormat testFormat) { this.resultFile = resultFile; this.randomSource = randomSource; this.bitReversed = bitReversed; this.testFormat = testFormat; } /** * Adds the failed test. * * @param testId the test id */ void addFailedTest(String testId) { failedTests.add(testId); } /** * Gets the result file. * * @return the result file */ File getResultFile() { return resultFile; } /** * Gets the random source. * * @return the random source */ RandomSource getRandomSource() { return randomSource; } /** * Checks if the generator was bit reversed. * * @return true if bit reversed */ boolean isBitReversed() { return bitReversed; } /** * Gets the test format. * * @return the test format */ TestFormat getTestFormat() { return testFormat; } /** * Gets the failed tests. * * @return the failed tests */ List<String> getFailedTests() { return failedTests; } /** * Gets the failure count. * * @return the failure count */ int getFailureCount() { return failedTests.size(); } /** * Gets the a failure summary string. * * <p>The default implementation is the count of the number of failures. * This will be negative if the test is not complete.</p> * * @return the failure summary */ String getFailureSummaryString() { return (isComplete()) ? Integer.toString(failedTests.size()) : "-" + failedTests.size(); } /** * Sets the test application name. * * @param testApplicationName the new test application name */ void setTestApplicationName(String testApplicationName) { this.testApplicationName = testApplicationName; } /** * Gets the test application name. * * @return the test application name */ String getTestApplicationName() { return testApplicationName == null ? String.valueOf(getTestFormat()) : testApplicationName; } /** * Checks if the test result is complete. * This is {@code true} only if the exit code was found and is zero. * * @return true if complete */ boolean isComplete() { return exitCode == 0; } /** * Sets the exit code flag. * * @param exitCode the new exit code */ void setExitCode(int exitCode) { this.exitCode = exitCode; } } /** * Encapsulate the results of a PractRand test application. This is a specialisation that * allows handling PractRand results which are linked to the output length used by the RNG. */ private static class PractRandTestResult extends TestResult { /** The length of the RNG output used to generate failed tests. */ private int lengthExponent; /** * @param resultFile the result file * @param randomSource the random source * @param bitReversed the bit reversed flag * @param testFormat the test format */ PractRandTestResult(File resultFile, RandomSource randomSource, boolean bitReversed, TestFormat testFormat) { super(resultFile, randomSource, bitReversed, testFormat); } /** * Gets the length of the RNG output used to generate failed tests. * If this is zero then no failures occurred. * * @return the length exponent */ int getLengthExponent() { return lengthExponent; } /** * Sets the length of the RNG output used to generate failed tests. * * @param lengthExponent the length exponent */ void setLengthExponent(int lengthExponent) { this.lengthExponent = lengthExponent; } /** * {@inheritDoc} * * <p>The PractRand summary is the exponent of the length of byte output from the RNG where * a failure occurred. */ @Override String getFailureSummaryString() { return lengthExponent == 0 ? "-" : Integer.toString(lengthExponent); } } /** * Reads the results files and outputs in the chosen format. */ @Override public Void call() { LogUtils.setLogLevel(reusableOptions.logLevel); // Read the results final List<TestResult> results = readResults(); if (deletePartialResults) { deleteIfIncomplete(results); return null; } try (OutputStream out = createOutputStream()) { switch (outputFormat) { case CSV: writeCSVData(out, results); break; case APT: writeAPT(out, results); break; case TXT: writeTXT(out, results); break; case FAILURES: writeFailures(out, results); break; default: throw new ApplicationException("Unknown output format: " + outputFormat); } } catch (final IOException ex) { throw new ApplicationException("IO error: " + ex.getMessage(), ex); } return null; } /** * Read the results. * * @return the results */ private List<TestResult> readResults() { final ArrayList<TestResult> results = new ArrayList<>(); for (final File resultFile : resultsFiles) { readResults(results, resultFile); } return results; } /** * Read the file and extract any test results. * * @param results Results. * @param resultFile Result file. * @throws ApplicationException If the results cannot be parsed. */ private void readResults(List<TestResult> results, File resultFile) { final List<String> contents = readFileContents(resultFile); // Files may have multiple test results per file (i.e. appended output) final List<List<String>> outputs = splitContents(contents); if (outputs.isEmpty()) { LogUtils.error("No test output in file: %s", resultFile); } else { for (final List<String> testOutput : outputs) { final TestResult result = readResult(resultFile, testOutput); if (!result.isComplete()) { LogUtils.info("Partial results in file: %s", resultFile); if (ignorePartialResults) { continue; } } results.add(result); } } } /** * Read the file contents. * * @param resultFile Result file. * @return the file contents * @throws ApplicationException If the file cannot be read. */ private static List<String> readFileContents(File resultFile) { final ArrayList<String> contents = new ArrayList<>(); try (BufferedReader reader = Files.newBufferedReader(resultFile.toPath())) { for (String line = reader.readLine(); line != null; line = reader.readLine()) { contents.add(line); } } catch (final IOException ex) { throw new ApplicationException("Failed to read file contents: " + resultFile, ex); } return contents; } /** * Split the file contents into separate test output. This is used in the event * that results have been appended to the same file. * * @param contents File contents. * @return the test output */ private static List<List<String>> splitContents(List<String> contents) { final ArrayList<List<String>> testOutputs = new ArrayList<>(); // Assume each output begins with e.g. # RandomSource: SPLIT_MIX_64 // Note each beginning. int begin = -1; for (int i = 0; i < contents.size(); i++) { if (RANDOM_SOURCE_PATTERN.matcher(contents.get(i)).matches()) { if (begin >= 0) { testOutputs.add(contents.subList(begin, i)); } begin = i; } } if (begin >= 0) { testOutputs.add(contents.subList(begin, contents.size())); } return testOutputs; } /** * Read the file into a test result. * * @param resultFile Result file. * @param testOutput Test output. * @return the test result * @throws ApplicationException If the result cannot be parsed. */ private TestResult readResult(File resultFile, List<String> testOutput) { // Use an iterator for a single pass over the test output final ListIterator<String> iter = testOutput.listIterator(); // Identify the RandomSource and bit reversed flag from the header: final RandomSource randomSource = getRandomSource(resultFile, iter); final boolean bitReversed = getBitReversed(resultFile, iter); // Identify the test application format. This may return null. final TestFormat testFormat = getTestFormat(resultFile, iter); // Read the application results final TestResult testResult = createTestResult(resultFile, randomSource, bitReversed, testFormat); if (testFormat == TestFormat.DIEHARDER) { readDieharder(iter, testResult); } else if (testFormat == TestFormat.TESTU01) { readTestU01(resultFile, iter, testResult); } else { readPractRand(iter, (PractRandTestResult) testResult); } return testResult; } /** * Creates the test result. * * @param resultFile Result file. * @param randomSource Random source. * @param bitReversed True if the random source was bit reversed. * @param testFormat Test format. * @return the test result */ private static TestResult createTestResult(File resultFile, RandomSource randomSource, boolean bitReversed, TestFormat testFormat) { return testFormat == TestFormat.PRACTRAND ? new PractRandTestResult(resultFile, randomSource, bitReversed, testFormat) : new TestResult(resultFile, randomSource, bitReversed, testFormat); } /** * Gets the random source from the output header. * * @param resultFile Result file (for the exception message). * @param iter Iterator of the test output. * @return the random source * @throws ApplicationException If the RandomSource header line cannot be found. */ private static RandomSource getRandomSource(File resultFile, Iterator<String> iter) { while (iter.hasNext()) { final Matcher matcher = RANDOM_SOURCE_PATTERN.matcher(iter.next()); if (matcher.matches()) { return RandomSource.valueOf(matcher.group(1)); } } throw new ApplicationException("Failed to find RandomSource header line: " + resultFile); } /** * Gets the bit-reversed flag from the output header. * * @param resultFile Result file (for the exception message). * @param iter Iterator of the test output. * @return the bit-reversed flag * @throws ApplicationException If the RNG header line cannot be found. */ private static boolean getBitReversed(File resultFile, Iterator<String> iter) { while (iter.hasNext()) { final Matcher matcher = RNG_PATTERN.matcher(iter.next()); if (matcher.matches()) { return matcher.group(1).contains(BIT_REVERSED); } } throw new ApplicationException("Failed to find RNG header line: " + resultFile); } /** * Gets the test format from the output. This scans the stdout produced by a test application. * If it is not recognized this may be a valid partial result or an unknown result. Throw * an exception if not allowing partial results, otherwise log an error. * * @param resultFile Result file (for the exception message). * @param iter Iterator of the test output. * @return the test format (or null) * @throws ApplicationException If the test format cannot be found. */ private TestFormat getTestFormat(File resultFile, Iterator<String> iter) { while (iter.hasNext()) { final String line = iter.next(); if (DIEHARDER_PATTERN.matcher(line).find()) { return TestFormat.DIEHARDER; } if (TESTU01_PATTERN.matcher(line).find()) { return TestFormat.TESTU01; } if (PRACTRAND_PATTERN.matcher(line).find()) { return TestFormat.PRACTRAND; } } if (!ignorePartialResults) { throw new ApplicationException("Failed to identify the test application format: " + resultFile); } LogUtils.error("Failed to identify the test application format: %s", resultFile); return null; } /** * Read the result output from the Dieharder test application. * * @param iter Iterator of the test output. * @param testResult Test result. */ private void readDieharder(Iterator<String> iter, TestResult testResult) { // Dieharder results are printed in-line using the following format: //#=============================================================================# // test_name |ntup| tsamples |psamples| p-value |Assessment //#=============================================================================# // diehard_birthdays| 0| 100| 100|0.97484422| PASSED // ... // diehard_oqso| 0| 2097152| 100|0.00000000| FAILED testResult.setTestApplicationName("Dieharder"); // Identify any line containing FAILED and then get the test ID using // the first two columns (test_name + ntup). while (iter.hasNext()) { final String line = iter.next(); if (DIEHARDER_FAILED_PATTERN.matcher(line).find()) { // Optionally include the flawed Dieharder sums test if (!includeDiehardSums && line.contains(DIEHARDER_SUMS)) { continue; } final int index1 = line.indexOf('|'); final int index2 = line.indexOf('|', index1 + 1); testResult.addFailedTest(line.substring(0, index1).trim() + ":" + line.substring(index1 + 1, index2).trim()); } else if (findExitCode(testResult, line)) { return; } } } /** * Find the exit code in the line. Update the test result with the code if found. * * @param testResult Test result. * @param line Line from the test result output. * @return true, if the exit code was found */ private static boolean findExitCode(TestResult testResult, String line) { final Matcher matcher = TEST_EXIT_PATTERN.matcher(line); if (matcher.find()) { testResult.setExitCode(Integer.parseInt(matcher.group(1))); return true; } return false; } /** * Read the result output from the Test U01 test application. * * <p>Test U01 outputs a summary of results at the end of the test output. If this cannot * be found the method will throw an exception unless partial results are allowed.</p> * * @param resultFile Result file (for the exception message). * @param iter Iterator of the test output. * @param testResult Test result. * @throws ApplicationException If the TestU01 summary cannot be found. */ private void readTestU01(File resultFile, ListIterator<String> iter, TestResult testResult) { // Results are summarised at the end of the file: //========= Summary results of BigCrush ========= // //Version: TestU01 1.2.3 //Generator: stdin //Number of statistics: 155 //Total CPU time: 06:14:50.43 //The following tests gave p-values outside [0.001, 0.9990]: //(eps means a value < 1.0e-300): //(eps1 means a value < 1.0e-15): // // Test p-value //---------------------------------------------- // 1 SerialOver, r = 0 eps // 3 CollisionOver, t = 2 1 - eps1 // 5 CollisionOver, t = 3 1 - eps1 // 7 CollisionOver, t = 7 eps // Identify the summary line final String testSuiteName = skipToTestU01Summary(resultFile, iter); // This may not be present if the results are not complete if (testSuiteName == null) { // Rewind while (iter.hasPrevious()) { iter.previous(); } updateTestU01ApplicationName(iter, testResult); return; } setTestU01ApplicationName(testResult, testSuiteName); // Read test results using the entire line except the p-value for the test Id // Note: // This will count sub-parts of the same test as distinct failures. while (iter.hasNext()) { final String line = iter.next(); final Matcher matcher = TESTU01_TEST_RESULT_PATTERN.matcher(line); if (matcher.find()) { testResult.addFailedTest(matcher.group(1).trim()); } else if (findExitCode(testResult, line)) { return; } } } /** * Sets the Test U01 application name using the provide test suite name. * * @param testResult Test result. * @param testSuiteName Test suite name. */ private static void setTestU01ApplicationName(TestResult testResult, String testSuiteName) { testResult.setTestApplicationName("TestU01 (" + testSuiteName + ")"); } /** * Skip to the Test U01 result summary. * * <p>If this cannot be found the method will throw an exception unless partial results * are allowed.</p> * * @param resultFile Result file (for the exception message). * @param iter Iterator of the test output. * @return the name of the test suite * @throws ApplicationException If the TestU01 summary cannot be found. */ private String skipToTestU01Summary(File resultFile, Iterator<String> iter) { final String testSuiteName = findMatcherGroup1(iter, TESTU01_SUMMARY_PATTERN); // Allow the partial result to be ignored if (testSuiteName != null || ignorePartialResults) { return testSuiteName; } throw new ApplicationException("Failed to identify the Test U01 result summary: " + resultFile); } /** * Update the test application name from the Test U01 results. This can be used to identify * the test suite from the start of the results in the event that the results summary has * not been output. * * @param iter Iterator of the test output. * @param testResult Test result. */ private static void updateTestU01ApplicationName(Iterator<String> iter, TestResult testResult) { final String testSuiteName = findMatcherGroup1(iter, TESTU01_STARTING_PATTERN); if (testSuiteName != null) { setTestU01ApplicationName(testResult, testSuiteName); } } /** * Create a matcher for each item in the iterator and if a match is identified return * group 1. * * @param iter Iterator of text to match. * @param pattern Pattern to match. * @return the string (or null) */ private static String findMatcherGroup1(Iterator<String> iter, Pattern pattern) { while (iter.hasNext()) { final String line = iter.next(); final Matcher matcher = pattern.matcher(line); if (matcher.find()) { return matcher.group(1); } } return null; } /** * Read the result output from the PractRand test application. * * @param iter Iterator of the test output. * @param testResult Test result. */ private static void readPractRand(Iterator<String> iter, PractRandTestResult testResult) { // PractRand results are printed for blocks of byte output that double in size. // The results report 'unusual' and 'suspicious' output and the test stops // at the first failure. // Results are typically reported as the size of output that failed, e.g. // the JDK random fails at 256KiB. // // rng=RNG_stdin32, seed=0xfc6c7332 // length= 128 kilobytes (2^17 bytes), time= 5.9 seconds // no anomalies in 118 test result(s) // // rng=RNG_stdin32, seed=0xfc6c7332 // length= 256 kilobytes (2^18 bytes), time= 7.6 seconds // Test Name Raw Processed Evaluation // [Low1/64]Gap-16:A R= +12.4 p = 8.7e-11 VERY SUSPICIOUS // [Low1/64]Gap-16:B R= +13.4 p = 3.0e-11 FAIL // [Low8/32]DC6-9x1Bytes-1 R= +7.6 p = 5.7e-4 unusual // ...and 136 test result(s) without anomalies testResult.setTestApplicationName("PractRand"); // Store the exponent of the current output length. int exp = 0; // Identify any line containing FAIL and then get the test name using // the first token in the line. while (iter.hasNext()) { String line = iter.next(); final Matcher matcher = PRACTRAND_OUTPUT_SIZE_PATTERN.matcher(line); if (matcher.find()) { // Store the current output length exp = Integer.parseInt(matcher.group(1)); } else if (PRACTRAND_FAILED_PATTERN.matcher(line).find()) { // Record the output length where failures occurred. testResult.setLengthExponent(exp); // Add the failed test name. This does not include the length exponent // allowing meta-processing of systematic failures. // Remove initial whitespace line = line.trim(); final int index = line.indexOf(' '); testResult.addFailedTest(line.substring(0, index)); } else if (findExitCode(testResult, line)) { return; } } } /** * Delete any result file if incomplete. * * @param results Results. * @throws ApplicationException If a file could not be deleted. */ private static void deleteIfIncomplete(List<TestResult> results) { results.forEach(ResultsCommand::deleteIfIncomplete); } /** * Delete the result file if incomplete. * * @param result Test result. * @throws ApplicationException If the file could not be deleted. */ private static void deleteIfIncomplete(TestResult result) { if (!result.isComplete()) { try { Files.delete(result.getResultFile().toPath()); LogUtils.info("Deleted file: %s", result.getResultFile()); } catch (IOException ex) { throw new ApplicationException("Failed to delete file: " + result.getResultFile(), ex); } } } /** * Creates the output stream. This will not be buffered. * * @return the output stream */ private OutputStream createOutputStream() { if (fileOutput != null) { try { return Files.newOutputStream(fileOutput.toPath()); } catch (final IOException ex) { throw new ApplicationException("Failed to create output: " + fileOutput, ex); } } return new FilterOutputStream(System.out) { @Override public void close() { // Do not close stdout } }; } /** * Write the results to a table in Comma Separated Value (CSV) format. * * @param out Output stream. * @param results Results. * @throws IOException Signals that an I/O exception has occurred. */ private void writeCSVData(OutputStream out, List<TestResult> results) throws IOException { // Sort by columns Collections.sort(results, (o1, o2) -> { int result = Integer.compare(o1.getRandomSource().ordinal(), o2.getRandomSource().ordinal()); if (result != 0) { return result; } result = Boolean.compare(o1.isBitReversed(), o2.isBitReversed()); if (result != 0) { return result; } result = o1.getTestApplicationName().compareTo(o2.getTestApplicationName()); if (result != 0) { return result; } return Integer.compare(o1.getFailureCount(), o2.getFailureCount()); }); try (BufferedWriter output = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8))) { output.write("RandomSource,Bit-reversed,Test,Failures"); if (showFailedTests) { output.write(",Failed"); } output.newLine(); for (final TestResult result : results) { output.write(result.getRandomSource().toString()); output.write(','); output.write(Boolean.toString(result.isBitReversed())); output.write(','); output.write(result.getTestApplicationName()); output.write(','); output.write(result.getFailureSummaryString()); // Optionally write out failed test names. if (showFailedTests) { output.write(','); output.write(result.getFailedTests().stream().collect(Collectors.joining("|"))); } output.newLine(); } } } /** * Write the results using the Almost Plain Text (APT) format for a table. This * table can be included in the documentation for the Commons RNG site. * * @param out Output stream. * @param results Results. * @throws IOException Signals that an I/O exception has occurred. */ private void writeAPT(OutputStream out, List<TestResult> results) throws IOException { // Identify all: // RandomSources, bit-reversed, test names, final List<RandomSource> randomSources = getRandomSources(results); final List<Boolean> bitReversed = getBitReversed(results); final List<String> testNames = getTestNames(results); // Identify the common path prefix to be replaced final int prefixLength = (pathPrefix.isEmpty()) ? 0 : findCommonPathPrefixLength(results); // Create a function to update the file path and then output the failure count // as a link to the file using the APT format. final Function<TestResult, String> toAPTString = result -> { String path = result.getResultFile().getPath(); // Remove common path prefix path = path.substring(prefixLength); // Build the APT relative link final StringBuilder sb = new StringBuilder() .append("{{{").append(pathPrefix).append(path).append('}') .append(result.getFailureSummaryString()).append("}}"); // Convert to web-link name separators for (int i = 0; i < sb.length(); i++) { if (sb.charAt(i) == BACK_SLASH) { sb.setCharAt(i, FORWARD_SLASH); } } return sb.toString(); }; // Create columns for RandomSource, bit-reversed, each test name. // Make bit-reversed column optional if no generators are bit reversed. final boolean showBitReversedColumn = bitReversed.contains(Boolean.TRUE); final String header = createAPTHeader(showBitReversedColumn, testNames); final String separator = createAPTSeparator(header); // Output try (BufferedWriter output = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8))) { // For the first line using '*' (centre) character instead of '+' (left align) output.write(separator.replace('+', '*')); output.write(header); output.newLine(); output.write(separator); final StringBuilder sb = new StringBuilder(); // This will collate results for each combination of 'RandomSource + bitReversed' for (final RandomSource randomSource : randomSources) { for (final boolean reversed : bitReversed) { // Highlight in bold a RNG with no systematic failures boolean highlight = true; // Buffer the column output sb.setLength(0); if (showBitReversedColumn) { writeAPTColumn(sb, Boolean.toString(reversed), false); } for (final String testName : testNames) { final List<TestResult> testResults = getTestResults(results, randomSource, reversed, testName); String text = testResults.stream() .map(toAPTString) .collect(Collectors.joining(", ")); // Summarise the failures across all tests final String summary = getFailuresSummary(testResults); if (!summary.isEmpty()) { // Identify RNGs with no systematic failures highlight = false; if (showFailedTests) { // Add summary in brackets text += " (" + summary + ")"; } } writeAPTColumn(sb, text, false); } output.write('|'); writeAPTColumn(output, randomSource.toString(), highlight); output.write(sb.toString()); output.newLine(); output.write(separator); } } } } /** * Gets the random sources present in the results. * * @param results Results. * @return the random sources */ private static List<RandomSource> getRandomSources(List<TestResult> results) { final EnumSet<RandomSource> set = EnumSet.noneOf(RandomSource.class); for (final TestResult result : results) { set.add(result.getRandomSource()); } final ArrayList<RandomSource> list = new ArrayList<>(set); Collections.sort(list); return list; } /** * Gets the bit-reversed options present in the results. * * @param results Results. * @return the bit-reversed options */ private static List<Boolean> getBitReversed(List<TestResult> results) { final ArrayList<Boolean> list = new ArrayList<>(2); if (results.isEmpty()) { // Default to no bit-reversed results list.add(Boolean.FALSE); } else { final boolean first = results.get(0).isBitReversed(); list.add(first); for (final TestResult result : results) { if (first != result.isBitReversed()) { list.add(!first); break; } } } Collections.sort(list); return list; } /** * Gets the test names present in the results. These are returned in encountered order. * * @param results Results. * @return the test names */ private static List<String> getTestNames(List<TestResult> results) { // Enforce encountered order with a linked hash set. final Set<String> set = new LinkedHashSet<>(); for (final TestResult result : results) { set.add(result.getTestApplicationName()); } return new ArrayList<>(set); } /** * Find the common path prefix for all result files. This is returned as the length of the * common prefix. * * @param results Results. * @return the length */ private static int findCommonPathPrefixLength(List<TestResult> results) { if (results.isEmpty()) { return 0; } // Find the first prefix final String prefix1 = getPathPrefix(results.get(0)); int length = prefix1.length(); for (int i = 1; i < results.size() && length != 0; i++) { final String prefix2 = getPathPrefix(results.get(i)); // Update final int size = Math.min(prefix2.length(), length); length = 0; while (length < size && prefix1.charAt(length) == prefix2.charAt(length)) { length++; } } return length; } /** * Gets the path prefix. * * @param testResult Test result. * @return the path prefix (or the empty string) */ private static String getPathPrefix(TestResult testResult) { final String parent = testResult.getResultFile().getParent(); return parent == null ? "" : parent; } /** * Creates the APT header. * * @param showBitReversedColumn Set to true to the show bit reversed column. * @param testNames Test names. * @return the header */ private static String createAPTHeader(boolean showBitReversedColumn, List<String> testNames) { final StringBuilder sb = new StringBuilder(100).append("|| RNG identifier ||"); if (showBitReversedColumn) { sb.append(" Bit-reversed ||"); } for (final String name : testNames) { sb.append(' ').append(name).append(" ||"); } return sb.toString(); } /** * Creates the APT separator for each table row. * * <p>The separator is created using the '+' character to left align the columns. * * @param header Header. * @return the separator */ private static String createAPTSeparator(String header) { // Replace everything with '-' except '|' which is replaced with "*-" for the first // character, "+-" for all other occurrences except "-+" at the end final StringBuilder sb = new StringBuilder(header); for (int i = 0; i < header.length(); i++) { if (sb.charAt(i) == PIPE) { sb.setCharAt(i, i == 0 ? '*' : '+'); sb.setCharAt(i + 1, '-'); } else { sb.setCharAt(i, '-'); } } // Fix the end sb.setCharAt(header.length() - 2, '-'); sb.setCharAt(header.length() - 1, '+'); sb.append(System.lineSeparator()); return sb.toString(); } /** * Write the column text to the output. * * @param output Output. * @param text Text. * @param highlight If {@code true} highlight the text in bold. * @throws IOException Signals that an I/O exception has occurred. */ private static void writeAPTColumn(Appendable output, String text, boolean highlight) throws IOException { output.append(' '); if (highlight) { output.append("<<"); } output.append(text); if (highlight) { output.append(">>"); } output.append(" |"); } /** * Gets the test results that match the arguments. * * @param results Results. * @param randomSource Random source. * @param bitReversed Bit reversed flag. * @param testName Test name. * @return the matching results */ private static List<TestResult> getTestResults(List<TestResult> results, RandomSource randomSource, boolean bitReversed, String testName) { final ArrayList<TestResult> list = new ArrayList<>(); for (final TestResult result : results) { if (result.getRandomSource() == randomSource && result.bitReversed == bitReversed && result.getTestApplicationName().equals(testName)) { list.add(result); } } return list; } /** * Gets the systematic failures (tests that fail in every test result). * * @param results Results. * @return the systematic failures */ private static List<String> getSystematicFailures(List<TestResult> results) { final HashMap<String, Integer> map = new HashMap<>(); for (final TestResult result : results) { // Ignore partial results if (!result.isComplete()) { continue; } // Some named tests can fail more than once on different statistics. // For example TestU01 BigCrush LongestHeadRun can output in the summary: // 86 LongestHeadRun, r = 0 eps // 86 LongestHeadRun, r = 0 1 - eps1 // This will be counted as 2 failed tests. For the purpose of systematic // failures the name of the test is the same and should be counted once. final HashSet<String> unique = new HashSet<>(result.getFailedTests()); for (final String test : unique) { map.merge(test, 1, (i, j) -> i + j); } } final int completeCount = (int) results.stream().filter(TestResult::isComplete).count(); final List<String> list = map.entrySet().stream() .filter(e -> e.getValue() == completeCount) .map(Entry::getKey) .collect(Collectors.toCollection( (Supplier<List<String>>) ArrayList::new)); // Special case for PractRand. Add the maximum RNG output length before failure. // This is because some PractRand tests may not be counted as systematic failures // as they have not been run to the same output length due to earlier failure of // another test. final int max = getMaxLengthExponent(results); if (max != 0) { list.add(bytesToString(max)); } return list; } /** * Gets the maximum length exponent from the PractRand results if <strong>all</strong> failed. * Otherwise return zero (i.e. some passed the full length of the test). * * <p>This method excludes those results that are not complete. It assumes all complete * tests are for the same length of RNG output. Thus if all failed then the max exponent * is the systematic failure length.</p> * * @param results Results. * @return the maximum length exponent (or zero) */ private static int getMaxLengthExponent(List<TestResult> results) { if (results.isEmpty()) { return 0; } // [0] = count of zeros // [1] = max non-zero final int[] data = new int[2]; results.stream() .filter(TestResult::isComplete) .filter(r -> r instanceof PractRandTestResult) .mapToInt(r -> ((PractRandTestResult) r).getLengthExponent()) .forEach(i -> { if (i == 0) { // Count results that passed data[0]++; } else { // Find the max of the failures data[1] = Math.max(i, data[1]); } }); // If all failed (i.e. no zeros) then return the max, otherwise zero. return data[0] == 0 ? data[1] : 0; } /** * Gets a summary of the failures across all results. The text is empty if there are no * failures to report. * * <p>For Dieharder and TestU01 this is the number of systematic failures (tests that fail * in every test result). For PractRand it is the maximum byte output size that was reached * before failure. * * <p>It is assumed all the results are for the same test suite.</p> * * @param results Results. * @return the failures summary */ private static String getFailuresSummary(List<TestResult> results) { if (results.isEmpty()) { return ""; } if (results.get(0).getTestFormat() == TestFormat.PRACTRAND) { final int max = getMaxLengthExponent(results); return max == 0 ? "" : bytesToString(max); } final int count = getSystematicFailures(results).size(); return count == 0 ? "" : Integer.toString(count); } /** * Write the results as a text table. * * @param out Output stream. * @param results Results. * @throws IOException Signals that an I/O exception has occurred. */ private static void writeTXT(OutputStream out, List<TestResult> results) throws IOException { // Identify all: // RandomSources, bit-reversed, test names, final List<RandomSource> randomSources = getRandomSources(results); final List<Boolean> bitReversed = getBitReversed(results); final List<String> testNames = getTestNames(results); // Create columns for RandomSource, bit-reversed, each test name. // Make bit-reversed column optional if no generators are bit reversed. final boolean showBitReversedColumn = bitReversed.contains(Boolean.TRUE); final List<List<String>> columns = createTXTColumns(testNames, showBitReversedColumn); // Add all data // This will collate results for each combination of 'RandomSource + bitReversed' for (final RandomSource randomSource : randomSources) { for (final boolean reversed : bitReversed) { int i = 0; columns.get(i++).add(randomSource.toString()); if (showBitReversedColumn) { columns.get(i++).add(Boolean.toString(reversed)); } for (final String testName : testNames) { final List<TestResult> testResults = getTestResults(results, randomSource, reversed, testName); columns.get(i++).add(testResults.stream() .map(TestResult::getFailureSummaryString) .collect(Collectors.joining(","))); columns.get(i++).add(getFailuresSummary(testResults)); } } } writeColumns(out, columns); } /** * Creates the columns for the text output. * * @param testNames the test names * @param showBitReversedColumn Set to true to show the bit reversed column * @return the list of columns */ private static List<List<String>> createTXTColumns(final List<String> testNames, final boolean showBitReversedColumn) { final ArrayList<List<String>> columns = new ArrayList<>(); columns.add(createColumn(COLUMN_RNG)); if (showBitReversedColumn) { columns.add(createColumn(BIT_REVERSED)); } for (final String testName : testNames) { columns.add(createColumn(testName)); columns.add(createColumn("∩")); } return columns; } /** * Creates the column. * * @param columnName Column name. * @return the list */ private static List<String> createColumn(String columnName) { final ArrayList<String> list = new ArrayList<>(); list.add(columnName); return list; } /** * Creates the text format from column widths. * * @param columns Columns. * @return the text format string */ private static String createTextFormatFromColumnWidths(final List<List<String>> columns) { final StringBuilder sb = new StringBuilder(); try (Formatter formatter = new Formatter(sb)) { for (int i = 0; i < columns.size(); i++) { if (i != 0) { sb.append('\t'); } formatter.format("%%-%ds", getColumnWidth(columns.get(i))); } } sb.append(System.lineSeparator()); return sb.toString(); } /** * Gets the column width using the maximum length of the column items. * * @param column Column. * @return the column width */ private static int getColumnWidth(List<String> column) { int width = 0; for (final String text : column) { width = Math.max(width, text.length()); } return width; } /** * Write the columns as fixed width text to the output. * * @param out Output stream. * @param columns Columns * @throws IOException Signals that an I/O exception has occurred. */ private static void writeColumns(OutputStream out, List<List<String>> columns) throws IOException { // Create format using the column widths final String format = createTextFormatFromColumnWidths(columns); // Output try (BufferedWriter output = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8)); Formatter formatter = new Formatter(output)) { final int rows = columns.get(0).size(); final Object[] args = new Object[columns.size()]; for (int row = 0; row < rows; row++) { for (int i = 0; i < args.length; i++) { args[i] = columns.get(i).get(row); } formatter.format(format, args); } } } /** * Write the systematic failures as a text table. * * @param out Output stream. * @param results Results. * @throws IOException Signals that an I/O exception has occurred. */ private static void writeFailures(OutputStream out, List<TestResult> results) throws IOException { // Identify all: // RandomSources, bit-reversed, test names, final List<RandomSource> randomSources = getRandomSources(results); final List<Boolean> bitReversed = getBitReversed(results); final List<String> testNames = getTestNames(results); // Create columns for RandomSource, bit-reversed, each test name. // Make bit-reversed column optional if no generators are bit reversed. final boolean showBitReversedColumn = bitReversed.contains(Boolean.TRUE); final List<List<String>> columns = createFailuresColumns(testNames, showBitReversedColumn); final AlphaNumericComparator cmp = new AlphaNumericComparator(); // Add all data for each combination of 'RandomSource + bitReversed' for (final RandomSource randomSource : randomSources) { for (final boolean reversed : bitReversed) { for (final String testName : testNames) { final List<TestResult> testResults = getTestResults(results, randomSource, reversed, testName); final List<String> failures = getSystematicFailures(testResults); if (failures.isEmpty()) { continue; } Collections.sort(failures, cmp); for (final String failed : failures) { int i = 0; columns.get(i++).add(randomSource.toString()); if (showBitReversedColumn) { columns.get(i++).add(Boolean.toString(reversed)); } columns.get(i++).add(testName); columns.get(i).add(failed); } } } } writeColumns(out, columns); } /** * Creates the columns for the failures output. * * @param testNames the test names * @param showBitReversedColumn Set to true to show the bit reversed column * @return the list of columns */ private static List<List<String>> createFailuresColumns(final List<String> testNames, final boolean showBitReversedColumn) { final ArrayList<List<String>> columns = new ArrayList<>(); columns.add(createColumn(COLUMN_RNG)); if (showBitReversedColumn) { columns.add(createColumn(BIT_REVERSED)); } columns.add(createColumn("Test Suite")); columns.add(createColumn("Test")); return columns; } /** * Convert bytes to a human readable string. The byte size is expressed in powers of 2. * The output units use the ISO binary prefix for increments of 2<sup>10</sup> or 1024. * * <p>This is a utility function used for reporting PractRand output sizes. * Example output: * * <pre> * exponent Binary * 0 0 B * 10 1 KiB * 13 8 KiB * 20 1 MiB * 27 128 MiB * 30 1 GiB * 40 1 TiB * 50 1 PiB * 60 1 EiB * </pre> * * @param exponent Exponent of the byte size (i.e. 2^exponent). * @return the string */ static String bytesToString(int exponent) { final int unit = exponent / 10; final int size = 1 << (exponent - 10 * unit); return size + BINARY_UNITS[unit]; } }
2,812
0
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/ListCommand.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.examples.stress; import org.apache.commons.rng.simple.RandomSource; import picocli.CommandLine.Command; import picocli.CommandLine.Mixin; import picocli.CommandLine.Option; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Formatter; import java.util.HashSet; import java.util.List; import java.util.NoSuchElementException; import java.util.Scanner; import java.util.concurrent.Callable; /** * Specification for the "list" command. * * <p>This command prints a list of available random generators to the console.</p> */ @Command(name = "list", description = "List random generators.") class ListCommand implements Callable<Void> { /** The standard options. */ @Mixin private StandardOptions reusableOptions; /** The list format. */ @Option(names = {"-f", "--format"}, description = {"The list format (default: ${DEFAULT-VALUE}).", "Valid values: ${COMPLETION-CANDIDATES}."}, paramLabel = "<format>") private ListFormat listFormat = ListFormat.STRESS_TEST; /** The provider type. */ @Option(names = {"--provider"}, description = {"The provider type (default: ${DEFAULT-VALUE}).", "Valid values: ${COMPLETION-CANDIDATES}."}, paramLabel = "<provider>") private ProviderType providerType = ProviderType.ALL; /** The minimum entry in the provider enum. */ @Option(names = {"--min"}, description = {"The minimum entry in the provider enum (inclusive)."}) private int min = 0; /** The maximum entry in the provider enum. */ @Option(names = {"--max"}, description = {"The maximum entry in the provider enum (inclusive)."}) private int max = Integer.MAX_VALUE; /** The prefix for each ID in the template list of random generators. */ @Option(names = {"-p", "--prefix"}, description = {"The ID prefix.", "Used for the stress test format."}) private String idPrefix = ""; /** The number of trials to put in the template list of random generators. */ @Option(names = {"-t", "--trials"}, description = {"The number of trials for each random generator.", "Used for the stress test format."}) private int trials = 1; /** * The list format. */ enum ListFormat { /** The stress test format lists the data required for the stress test. */ STRESS_TEST, /** The plain format lists only the name and optional arguments. */ PLAIN } /** * The type of provider. */ enum ProviderType { /** List all providers. */ ALL, /** List int providers. */ INT, /** List long providers. */ LONG, } /** * Prints a template generators list to stdout. */ @Override public Void call() throws Exception { LogUtils.setLogLevel(reusableOptions.logLevel); StressTestDataList list = new StressTestDataList(idPrefix, trials); if (providerType == ProviderType.INT) { list = list.subsetIntSource(); } else if (providerType == ProviderType.LONG) { list = list.subsetLongSource(); } if (min != 0 || max != Integer.MAX_VALUE) { list = list.subsetRandomSource(min, max); } // Write in one call to the output final StringBuilder sb = new StringBuilder(); switch (listFormat) { case PLAIN: writePlainData(sb, list); break; case STRESS_TEST: default: writeStressTestData(sb, list); break; } // CHECKSTYLE: stop regexp System.out.append(sb); // CHECKSTYLE: resume regexp return null; } /** * Write the test data. * * <p>Note: If the {@link Appendable} implements {@link java.io.Closeable Closeable} it * is <strong>not</strong> closed by this method. * * @param appendable The appendable. * @param testData The test data. * @throws IOException Signals that an I/O exception has occurred. */ static void writePlainData(Appendable appendable, Iterable<StressTestData> testData) throws IOException { final String newLine = System.lineSeparator(); for (final StressTestData data : testData) { appendable.append(data.getRandomSource().name()); if (data.getArgs() != null) { appendable.append(' '); appendable.append(Arrays.toString(data.getArgs())); } appendable.append(newLine); } } /** * Write the test data. * * <p>Performs adjustment of the number of trials for each item: * * <ul> * <li>Any item with trials {@code <= 0} will be written as zero. * <li>Any item with trials {@code > 0} will be written as the maximum of the value and * the input parameter {@code numberOfTrials}. * </ul> * * <p>This allows the output to contain a configurable number of trials for the * list of data. * * <p>Note: If the {@link Appendable} implements {@link java.io.Closeable Closeable} it * is <strong>not</strong> closed by this method. * * @param appendable The appendable. * @param testData The test data. * @throws IOException Signals that an I/O exception has occurred. */ static void writeStressTestData(Appendable appendable, Iterable<StressTestData> testData) throws IOException { // Build the widths for each column int idWidth = 1; int randomSourceWidth = 15; for (final StressTestData data : testData) { idWidth = Math.max(idWidth, data.getId().length()); randomSourceWidth = Math.max(randomSourceWidth, data.getRandomSource().name().length()); } final String newLine = System.lineSeparator(); appendable.append("# Random generators list.").append(newLine); appendable.append("# Any generator with no trials is ignored during testing.").append(newLine); appendable.append("#").append(newLine); String format = String.format("# %%-%ds %%-%ds trials [constructor arguments ...]%%n", idWidth, randomSourceWidth); // Do not use try-with-resources or the Formatter will close the Appendable // if it implements Closeable. Just flush at the end. @SuppressWarnings("resource") final Formatter formatter = new Formatter(appendable); formatter.format(format, "ID", "RandomSource"); format = String.format("%%-%ds %%-%ds ", idWidth + 2, randomSourceWidth); for (final StressTestData data : testData) { formatter.format(format, data.getId(), data.getRandomSource().name()); if (data.getArgs() == null) { appendable.append(Integer.toString(data.getTrials())); } else { formatter.format("%-6d %s", data.getTrials(), Arrays.toString(data.getArgs())); } appendable.append(newLine); } formatter.flush(); } /** * Reads the test data. The {@link Readable} is not closed by this method. * * @param readable The readable. * @return The test data. * @throws IOException Signals that an I/O exception has occurred. * @throws ApplicationException If there was an error parsing the expected format. * @see java.io.Reader#close() Reader.close() */ static Iterable<StressTestData> readStressTestData(Readable readable) throws IOException { final List<StressTestData> list = new ArrayList<>(); // Validate that all IDs are unique. final HashSet<String> ids = new HashSet<>(); // Do not use try-with-resources as the readable must not be closed @SuppressWarnings("resource") final Scanner scanner = new Scanner(readable); try { while (scanner.hasNextLine()) { // Expected format: // //# ID RandomSource trials [constructor arguments ...] //12 TWO_CMRES 1 //13 TWO_CMRES_SELECT 0 [1, 2] final String id = scanner.next(); // Skip empty lines and comments if (id.isEmpty() || id.charAt(0) == '#') { scanner.nextLine(); continue; } if (!ids.add(id)) { throw new ApplicationException("Non-unique ID in strest test data: " + id); } final RandomSource randomSource = RandomSource.valueOf(scanner.next()); final int trials = scanner.nextInt(); // The arguments are the rest of the line final String arguments = scanner.nextLine().trim(); final Object[] args = parseArguments(randomSource, arguments); list.add(new StressTestData(id, randomSource, args, trials)); } } catch (NoSuchElementException | IllegalArgumentException ex) { if (scanner.ioException() != null) { throw scanner.ioException(); } throw new ApplicationException("Failed to read stress test data", ex); } return list; } /** * Parses the arguments string into an array of {@link Object}. * * <p>Returns {@code null} if the string is empty. * * @param randomSource the random source * @param arguments the arguments * @return the arguments {@code Object[]} */ static Object[] parseArguments(RandomSource randomSource, String arguments) { // Empty string is null arguments if (arguments.isEmpty()) { return null; } // Expected format: // [data1, data2, ...] final int len = arguments.length(); if (len < 2 || arguments.charAt(0) != '[' || arguments.charAt(len - 1) != ']') { throw new ApplicationException("RandomSource arguments should be an [array]: " + arguments); } // Split the text between the [] on commas final String[] tokens = arguments.substring(1, len - 1).split(", *"); final ArrayList<Object> args = new ArrayList<>(); for (final String token : tokens) { args.add(RNGUtils.parseArgument(token)); } return args.toArray(); } }
2,813
0
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/Source64Mode.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.examples.stress; /** * The mode to output a 64-bit source of randomness. */ enum Source64Mode { /** The 64-bit output from nextLong. */ LONG, /** The 32-bit output from nextInt. */ INT, /** The high 32-bits, then low 32-bits of the 64-bit output. */ HI_LO, /** The low 32-bits, then high 32-bits of the 64-bit output. */ LO_HI, /** The low 32-bits of the 64-bit output. */ LO, /** The high 32-bits of the 64-bit output. */ HI; }
2,814
0
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/ExamplesStressCommand.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.examples.stress; import picocli.CommandLine.Command; import picocli.CommandLine.Mixin; import picocli.CommandLine.Model.CommandSpec; import picocli.CommandLine.Spec; import java.util.concurrent.Callable; /** * Specification for the top-level command in the examples stress application. * * <p>This command is will print the top-level help message.</p> */ @Command(name = "examples-stress", description = "Apache Commons RNG Examples Stress Utilities.") class ExamplesStressCommand implements Callable<Void> { /** The command specification. Used to print the usage built by Picocli. */ @Spec private CommandSpec spec; /** The standard options. */ @Mixin private StandardOptions reusableOptions; @Override public Void call() { // All work is done in sub-commands so just print the usage spec.commandLine().usage(System.out); return null; } }
2,815
0
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/Hex.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.examples.stress; /** * Encodes and decodes bytes as hexadecimal characters. * * <p>Adapted from commons-codec.</p> */ final class Hex { /** * Used to build 4-bit numbers as Hex. */ private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; /** No public construction. */ private Hex() {} /** * Converts an array of bytes into an array of characters representing the hexadecimal * values of each byte in order. The returned array will be double the length of the * passed array, as it takes two characters to represent any given byte. * * <p>This can be used to encode byte array seeds into a text representation.</p> * * @param data A byte[] to convert to Hex characters * @return A char[] containing the lower-case Hex representation */ static char[] encodeHex(final byte[] data) { final int l = data.length; final char[] out = new char[l << 1]; // Two characters form the hex value for (int i = 0; i < l; i++) { // Upper 4-bits out[2 * i] = HEX_DIGITS[(0xf0 & data[i]) >>> 4]; // Lower 4-bits out[2 * i + 1] = HEX_DIGITS[ 0x0f & data[i]]; } return out; } /** * Converts an array of characters representing hexadecimal values into an array * of bytes of those same values. The returned array will be half the length of * the passed array, as it takes two characters to represent any given byte. An * exception is thrown if the passed char array has an odd number of elements. * * @param data An array of characters containing hexadecimal digits * @return A byte array containing binary data decoded from the supplied char array. * @throws IllegalArgumentException Thrown if an odd number or illegal of * characters is supplied */ static byte[] decodeHex(final CharSequence data) { final int len = data.length(); if ((len & 0x01) != 0) { throw new IllegalArgumentException("Odd number of characters."); } final byte[] out = new byte[len >> 1]; // Two characters form the hex value for (int j = 0; j < len; j += 2) { final int f = (toDigit(data, j) << 4) | toDigit(data, j + 1); out[j / 2] = (byte) f; } return out; } /** * Converts a hexadecimal character to an integer. * * @param data An array of characters containing hexadecimal digits * @param index The index of the character in the source * @return An integer * @throws IllegalArgumentException Thrown if ch is an illegal hex character */ private static int toDigit(final CharSequence data, final int index) { final char ch = data.charAt(index); final int digit = Character.digit(ch, 16); if (digit == -1) { throw new IllegalArgumentException("Illegal hexadecimal character " + ch + " at index " + index); } return digit; } }
2,816
0
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/BridgeTestCommand.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.examples.stress; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.core.source32.IntProvider; import picocli.CommandLine.Command; import picocli.CommandLine.Mixin; import picocli.CommandLine.Option; import picocli.CommandLine.Parameters; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.io.Writer; import java.nio.ByteOrder; import java.nio.IntBuffer; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ThreadLocalRandom; /** * Specification for the "bridge" command. * * <p>This command tests that {@code int} values can be piped to a * program that reads {@code int} values from its standard input. Only * a limited number of {@code int} values will be written.</p> */ @Command(name = "bridge", description = {"Transfer test 32-bit data to a test application sub-process via standard input."}) class BridgeTestCommand implements Callable<Void> { /** The standard options. */ @Mixin private StandardOptions reusableOptions; /** The executable. */ @Parameters(index = "0", description = "The stress test executable.") private File executable; /** The executable arguments. */ @Parameters(index = "1..*", description = "The arguments to pass to the executable.", paramLabel = "<argument>") private List<String> executableArguments = new ArrayList<>(); /** The file output prefix. */ @Option(names = {"--prefix"}, description = "Results file prefix (default: ${DEFAULT-VALUE}).") private File fileOutputPrefix = new File("bridge"); /** The output byte order of the binary data. */ @Option(names = {"-b", "--byte-order"}, description = {"Byte-order of the transferred data (default: ${DEFAULT-VALUE}).", "Valid values: BIG_ENDIAN, LITTLE_ENDIAN."}) private ByteOrder byteOrder = ByteOrder.nativeOrder(); /** * Validates the run command arguments and and runs the bridge test. */ @Override public Void call() { LogUtils.setLogLevel(reusableOptions.logLevel); ProcessUtils.checkExecutable(executable); ProcessUtils.checkOutputDirectory(fileOutputPrefix); runBridgeTest(); return null; } /** * Starts the executable process and writes {@code int} values to a data file and the stdin * of the executable. Captures stdout of the executable to a file. */ private void runBridgeTest() { final List<String> command = ProcessUtils.buildSubProcessCommand(executable, executableArguments); try { final File dataFile = new File(fileOutputPrefix + ".data"); final File outputFile = new File(fileOutputPrefix + ".out"); final File errorFile = new File(fileOutputPrefix + ".err"); // Store int values final IntBuffer buffer = IntBuffer.allocate(Integer.SIZE * 2); try (BufferedWriter textOutput = Files.newBufferedWriter(dataFile.toPath())) { // Write int data using a single bit in all possible positions int value = 1; for (int i = 0; i < Integer.SIZE; i++) { writeInt(textOutput, buffer, value); value <<= 1; } // Write random int data while (buffer.remaining() != 0) { writeInt(textOutput, buffer, ThreadLocalRandom.current().nextInt()); } } // Pass the same values to the output application buffer.flip(); final UniformRandomProvider rng = new IntProvider() { @Override public int next() { return buffer.get(); } }; // Start the application. final ProcessBuilder builder = new ProcessBuilder(command); builder.redirectOutput(ProcessBuilder.Redirect.to(outputFile)); builder.redirectError(ProcessBuilder.Redirect.to(errorFile)); final Process testingProcess = builder.start(); // Open the stdin of the process and write to a custom data sink. // Note: The 'bridge' command only supports 32-bit data in order to // demonstrate passing suitable data for TestU01 BigCrush. final Source64Mode source64 = null; try (RngDataOutput sink = RNGUtils.createDataOutput(rng, source64, testingProcess.getOutputStream(), buffer.capacity() * 4, byteOrder)) { sink.write(rng); } final Integer exitValue = ProcessUtils.getExitValue(testingProcess); if (exitValue == null) { LogUtils.error("%s did not exit. Process was killed.", command.get(0)); } else { final int value = exitValue; if (value != 0) { LogUtils.error("%s exit code = %d", command.get(0), value); } } } catch (IOException ex) { throw new ApplicationException("Failed to run process: " + ex.getMessage(), ex); } } /** * Write an {@code int} value to the writer and the buffer output. The native Java * value will be written to the writer using the debugging output of the * {@link OutputCommand}. * * @param textOutput the text data writer. * @param buffer the buffer. * @param value the value. * @throws IOException Signals that an I/O exception has occurred. * @see OutputCommand#writeInt(java.io.Writer, int) */ private static void writeInt(Writer textOutput, IntBuffer buffer, int value) throws IOException { OutputCommand.writeInt(textOutput, value); buffer.put(value); } }
2,817
0
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/RngDataOutput.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.examples.stress; import org.apache.commons.rng.UniformRandomProvider; import java.io.Closeable; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteOrder; /** * A specialised data output class that combines the functionality of * {@link java.io.DataOutputStream DataOutputStream} and * {@link java.io.BufferedOutputStream BufferedOutputStream} to write byte data from a RNG * to an OutputStream. Large blocks of byte data are written in a single operation for efficiency. * The byte data endianness can be configured. * * <p>This class is the functional equivalent of:</p> * * <pre> * <code> * OutputStream out = ... * UniformRandomProvider rng = ... * int size = 2048; * DataOutputStream sink = new DataOutputStream(new BufferedOutputStream(out, size * 4)); * for (int i = 0; i &lt; size; i++) { * sink.writeInt(rng.nextInt()); * } * * // Replaced with * RngDataOutput output = RngDataOutput.ofInt(out, size, ByteOrder.BIG_ENDIAN); * output.write(rng); * </code> * </pre> * * <p>Use of this class avoids the synchronized write operations in * {@link java.io.BufferedOutputStream BufferedOutputStream}. In particular it avoids the * 4 synchronized write operations to * {@link java.io.BufferedOutputStream#write(int) BufferedOutputStream#write(int)} that * occur for each {@code int} value that is written to * {@link java.io.DataOutputStream#writeInt(int) DataOutputStream#writeInt(int)}.</p> * * <p>This class has adaptors to write the long output from a RNG to two int values. * To match the caching implementation in the core LongProvider class this is tested * to output int values in the same order as an instance of the LongProvider. Currently * this outputs in order: low 32-bits, high 32-bits. */ abstract class RngDataOutput implements Closeable { /** The data buffer. */ protected final byte[] buffer; /** The underlying output stream. */ private final OutputStream out; /** * Write big-endian {@code int} data. * <pre>{@code * 3210 -> 3210 * }</pre> */ private static class BIntRngDataOutput extends RngDataOutput { /** * @param out Output stream. * @param size Buffer size. */ BIntRngDataOutput(OutputStream out, int size) { super(out, size); } @Override public void fillBuffer(UniformRandomProvider rng) { for (int i = 0; i < buffer.length; i += 4) { writeIntBE(i, rng.nextInt()); } } } /** * Write little-endian {@code int} data. * <pre>{@code * 3210 -> 0123 * }</pre> */ private static class LIntRngDataOutput extends RngDataOutput { /** * @param out Output stream. * @param size Buffer size. */ LIntRngDataOutput(OutputStream out, int size) { super(out, size); } @Override public void fillBuffer(UniformRandomProvider rng) { for (int i = 0; i < buffer.length; i += 4) { writeIntLE(i, rng.nextInt()); } } } /** * Write big-endian {@code long} data. * <pre>{@code * 76543210 -> 76543210 * }</pre> */ private static class BLongRngDataOutput extends RngDataOutput { /** * @param out Output stream. * @param size Buffer size. */ BLongRngDataOutput(OutputStream out, int size) { super(out, size); } @Override public void fillBuffer(UniformRandomProvider rng) { for (int i = 0; i < buffer.length; i += 8) { writeLongBE(i, rng.nextLong()); } } } /** * Write little-endian {@code long} data. * <pre>{@code * 76543210 -> 01234567 * }</pre> */ private static class LLongRngDataOutput extends RngDataOutput { /** * @param out Output stream. * @param size Buffer size. */ LLongRngDataOutput(OutputStream out, int size) { super(out, size); } @Override public void fillBuffer(UniformRandomProvider rng) { for (int i = 0; i < buffer.length; i += 8) { writeLongLE(i, rng.nextLong()); } } } /** * Write {@code long} data as two little-endian {@code int} values, high 32-bits then * low 32-bits. * <pre>{@code * 76543210 -> 4567 0123 * }</pre> * * <p>This is a specialisation that allows the Java big-endian representation to be split * into two little-endian values in the original order of upper then lower bits. In * comparison the {@link LLongRngDataOutput} will output the same data as: * * <pre>{@code * 76543210 -> 0123 4567 * }</pre> */ private static class LLongAsIntRngDataOutput extends RngDataOutput { /** * @param out Output stream. * @param size Buffer size. */ LLongAsIntRngDataOutput(OutputStream out, int size) { super(out, size); } @Override public void fillBuffer(UniformRandomProvider rng) { for (int i = 0; i < buffer.length; i += 8) { writeLongAsHighLowIntLE(i, rng.nextLong()); } } } /** * Write {@code long} data as two big-endian {@code int} values, low 32-bits then * high 32-bits. * <pre>{@code * 76543210 -> 3210 7654 * }</pre> * * <p>This is a specialisation that allows the Java big-endian representation to be split * into two big-endian values in the original order of lower then upper bits. In * comparison the {@link BLongRngDataOutput} will output the same data as: * * <pre>{@code * 76543210 -> 7654 3210 * }</pre> */ private static class BLongAsLoHiIntRngDataOutput extends RngDataOutput { /** * @param out Output stream. * @param size Buffer size. */ BLongAsLoHiIntRngDataOutput(OutputStream out, int size) { super(out, size); } @Override public void fillBuffer(UniformRandomProvider rng) { for (int i = 0; i < buffer.length; i += 8) { writeLongAsLowHighIntBE(i, rng.nextLong()); } } } /** * Create a new instance. * * @param out Output stream. * @param size Buffer size. */ RngDataOutput(OutputStream out, int size) { this.out = out; buffer = new byte[size]; } /** * Write the configured amount of byte data from the specified RNG to the output. * * @param rng Source of randomness. * @exception IOException if an I/O error occurs. */ public void write(UniformRandomProvider rng) throws IOException { fillBuffer(rng); out.write(buffer); } /** * Fill the buffer from the specified RNG. * * @param rng Source of randomness. */ public abstract void fillBuffer(UniformRandomProvider rng); /** * Writes an {@code int} to the buffer as four bytes, high byte first (big-endian). * * @param index the index to start writing. * @param value an {@code int} to be written. */ final void writeIntBE(int index, int value) { buffer[index ] = (byte) (value >>> 24); buffer[index + 1] = (byte) (value >>> 16); buffer[index + 2] = (byte) (value >>> 8); buffer[index + 3] = (byte) value; } /** * Writes an {@code int} to the buffer as four bytes, low byte first (little-endian). * * @param index the index to start writing. * @param value an {@code int} to be written. */ final void writeIntLE(int index, int value) { buffer[index ] = (byte) value; buffer[index + 1] = (byte) (value >>> 8); buffer[index + 2] = (byte) (value >>> 16); buffer[index + 3] = (byte) (value >>> 24); } /** * Writes an {@code long} to the buffer as eight bytes, high byte first (big-endian). * * @param index the index to start writing. * @param value an {@code long} to be written. */ final void writeLongBE(int index, long value) { buffer[index ] = (byte) (value >>> 56); buffer[index + 1] = (byte) (value >>> 48); buffer[index + 2] = (byte) (value >>> 40); buffer[index + 3] = (byte) (value >>> 32); buffer[index + 4] = (byte) (value >>> 24); buffer[index + 5] = (byte) (value >>> 16); buffer[index + 6] = (byte) (value >>> 8); buffer[index + 7] = (byte) value; } /** * Writes an {@code long} to the buffer as eight bytes, low byte first (little-endian). * * @param index the index to start writing. * @param value an {@code long} to be written. */ final void writeLongLE(int index, long value) { buffer[index ] = (byte) value; buffer[index + 1] = (byte) (value >>> 8); buffer[index + 2] = (byte) (value >>> 16); buffer[index + 3] = (byte) (value >>> 24); buffer[index + 4] = (byte) (value >>> 32); buffer[index + 5] = (byte) (value >>> 40); buffer[index + 6] = (byte) (value >>> 48); buffer[index + 7] = (byte) (value >>> 56); } /** * Writes an {@code long} to the buffer as two integers of four bytes, each * low byte first (little-endian). The long is written as the high 32-bits, * then the low 32-bits. * * <p>Note: A LowHigh little-endian output is the same as {@link #writeLongLE(int, long)}. * * @param index the index to start writing. * @param value an {@code long} to be written. */ final void writeLongAsHighLowIntLE(int index, long value) { // high buffer[index ] = (byte) (value >>> 32); buffer[index + 1] = (byte) (value >>> 40); buffer[index + 2] = (byte) (value >>> 48); buffer[index + 3] = (byte) (value >>> 56); // low buffer[index + 4] = (byte) value; buffer[index + 5] = (byte) (value >>> 8); buffer[index + 6] = (byte) (value >>> 16); buffer[index + 7] = (byte) (value >>> 24); } /** * Writes an {@code long} to the buffer as two integers of four bytes, each * high byte first (big-endian). The long is written as the low 32-bits, * then the high 32-bits. * * <p>Note: A HighLow big-endian output is the same as {@link #writeLongBE(int, long)}. * * @param index the index to start writing. * @param value an {@code long} to be written. */ final void writeLongAsLowHighIntBE(int index, long value) { // low buffer[index ] = (byte) (value >>> 24); buffer[index + 1] = (byte) (value >>> 16); buffer[index + 2] = (byte) (value >>> 8); buffer[index + 3] = (byte) value; // high buffer[index + 4] = (byte) (value >>> 56); buffer[index + 5] = (byte) (value >>> 48); buffer[index + 6] = (byte) (value >>> 40); buffer[index + 7] = (byte) (value >>> 32); } @Override public void close() throws IOException { try (OutputStream ostream = out) { ostream.flush(); } } /** * Create a new instance to write batches of data from * {@link UniformRandomProvider#nextInt()} to the specified output. * * @param out Output stream. * @param size Number of values to write. * @param byteOrder Byte order. * @return the data output */ @SuppressWarnings("resource") static RngDataOutput ofInt(OutputStream out, int size, ByteOrder byteOrder) { // Ensure the buffer is positive and a factor of 4 final int bytes = Math.max(size * 4, 4); return byteOrder == ByteOrder.LITTLE_ENDIAN ? new LIntRngDataOutput(out, bytes) : new BIntRngDataOutput(out, bytes); } /** * Create a new instance to write batches of data from * {@link UniformRandomProvider#nextLong()} to the specified output. * * @param out Output stream. * @param size Number of values to write. * @param byteOrder Byte order. * @return the data output */ @SuppressWarnings("resource") static RngDataOutput ofLong(OutputStream out, int size, ByteOrder byteOrder) { // Ensure the buffer is positive and a factor of 8 final int bytes = Math.max(size * 8, 8); return byteOrder == ByteOrder.LITTLE_ENDIAN ? new LLongRngDataOutput(out, bytes) : new BLongRngDataOutput(out, bytes); } /** * Create a new instance to write batches of data from * {@link UniformRandomProvider#nextLong()} to the specified output as two sequential * {@code int} values, high 32-bits then low 32-bits. * * <p>This will output the following bytes:</p> * * <pre>{@code * // Little-endian * 76543210 -> 4567 0123 * * // Big-endian * 76543210 -> 7654 3210 * }</pre> * * <p>This ensures the output from the generator is the original upper then lower order bits * for each endianess. * * @param out Output stream. * @param size Number of values to write. * @param byteOrder Byte order. * @return the data output */ @SuppressWarnings("resource") static RngDataOutput ofLongAsHLInt(OutputStream out, int size, ByteOrder byteOrder) { // Ensure the buffer is positive and a factor of 8 final int bytes = Math.max(size * 8, 8); return byteOrder == ByteOrder.LITTLE_ENDIAN ? new LLongAsIntRngDataOutput(out, bytes) : new BLongRngDataOutput(out, bytes); } /** * Create a new instance to write batches of data from * {@link UniformRandomProvider#nextLong()} to the specified output as two sequential * {@code int} values, low 32-bits then high 32-bits. * * <p>This will output the following bytes:</p> * * <pre>{@code * // Little-endian * 76543210 -> 0123 4567 * * // Big-endian * 76543210 -> 3210 7654 * }</pre> * * <p>This ensures the output from the generator is the original lower then upper order bits * for each endianess. * * @param out Output stream. * @param size Number of values to write. * @param byteOrder Byte order. * @return the data output */ @SuppressWarnings("resource") static RngDataOutput ofLongAsLHInt(OutputStream out, int size, ByteOrder byteOrder) { // Ensure the buffer is positive and a factor of 8 final int bytes = Math.max(size * 8, 8); return byteOrder == ByteOrder.LITTLE_ENDIAN ? new LLongRngDataOutput(out, bytes) : new BLongAsLoHiIntRngDataOutput(out, bytes); } }
2,818
0
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/OutputCommand.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.examples.stress; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.core.source64.RandomLongSource; import org.apache.commons.rng.simple.RandomSource; import picocli.CommandLine.Command; import picocli.CommandLine.Mixin; import picocli.CommandLine.Option; import picocli.CommandLine.Parameters; import java.io.BufferedWriter; import java.io.File; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; import java.util.Formatter; import java.util.List; import java.util.concurrent.Callable; /** * Specification for the "output" command. * * <p>This command creates a named random generator and outputs data in a specified format.</p> */ @Command(name = "output", description = {"Output data from a named random data generator."}) class OutputCommand implements Callable<Void> { /** The new line characters. */ private static final String NEW_LINE = System.lineSeparator(); /** Character '['. */ private static final char LEFT_SQUARE_BRACKET = '['; /** Character ']'. */ private static final char RIGHT_SQUARE_BRACKET = ']'; /** Lookup table for binary representation of bytes. */ private static final String[] BIT_REP = { "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111", }; /** The standard options. */ @Mixin private StandardOptions reusableOptions; /** The random source. */ @Parameters(index = "0", description = "The random source.") private RandomSource randomSource; /** The executable arguments. */ @Parameters(index = "1..*", description = "The arguments to pass to the constructor.", paramLabel = "<argument>") private List<String> arguments = new ArrayList<>(); /** The file output prefix. */ @Option(names = {"-o", "--out"}, description = "The output file (default: stdout).") private File fileOutput; /** The output format. */ @Option(names = {"-f", "--format"}, description = {"Output format (default: ${DEFAULT-VALUE}).", "Valid values: ${COMPLETION-CANDIDATES}."}) private OutputCommand.OutputFormat outputFormat = OutputFormat.DIEHARDER; /** The random seed. */ @Option(names = {"-s", "--seed"}, description = {"The 64-bit number random seed (default: auto)."}) private Long seed; /** The random seed as a byte[]. */ @Option(names = {"-x", "--hex-seed"}, description = {"The hex-encoded random seed.", "Seed conversion for multi-byte primitives use little-endian format.", "Over-rides the --seed parameter."}) private String byteSeed; /** The count of numbers to output. */ @Option(names = {"-n", "--count"}, description = {"The count of numbers to output.", "Use negative for an unlimited stream."}) private long count = 10; /** The size of the byte buffer for the binary data. */ @Option(names = {"--buffer-size"}, description = {"Byte-buffer size for binary data (default: ${DEFAULT-VALUE}).", "When outputing binary data the count parameter controls the " + "number of buffers written."}) private int bufferSize = 8192; /** The output byte order of the binary data. */ @Option(names = {"-b", "--byte-order"}, description = {"Byte-order of the output data (default: ${DEFAULT-VALUE}).", "Uses the Java default of big-endian. This may not match the platform byte-order.", "Valid values: BIG_ENDIAN, LITTLE_ENDIAN."}) private ByteOrder byteOrder = ByteOrder.BIG_ENDIAN; /** The output byte order of the binary data. */ @Option(names = {"-r", "--reverse-bits"}, description = {"Reverse the bits in the data (default: ${DEFAULT-VALUE})."}) private boolean reverseBits; /** Flag to use 64-bit long output. */ @Option(names = {"--raw64"}, description = {"Use 64-bit output (default is 32-bit).", "This is ignored if not a native 64-bit generator.", "Set to true sets the source64 mode to LONG."}) private boolean raw64; /** Output mode for 64-bit long output. */ @Option(names = {"--source64"}, description = {"Output mode for 64-bit generators (default: ${DEFAULT-VALUE}).", "This is ignored if not a native 64-bit generator.", "In 32-bit mode the output uses a combination of upper and " + "lower bits of the 64-bit value.", "Valid values: ${COMPLETION-CANDIDATES}."}) private Source64Mode source64 = RNGUtils.getSource64Default(); /** * The output mode for existing files. */ enum OutputFormat { /** Binary output. */ BINARY, /** Use the Dieharder text format. */ DIEHARDER, /** Output the bits in a text format. */ BITS, } /** * Validates the command arguments, creates the generator and outputs numbers. */ @Override public Void call() { LogUtils.setLogLevel(reusableOptions.logLevel); final Object objectSeed = createSeed(); UniformRandomProvider rng = createRNG(objectSeed); // raw64 flag overrides the source64 mode if (raw64) { source64 = Source64Mode.LONG; } if (source64 == Source64Mode.LONG && !(rng instanceof RandomLongSource)) { throw new ApplicationException("Not a 64-bit RNG: " + rng); } // Upper or lower bits from 64-bit generators must be created first. // Note this does not test source64 != Source64Mode.LONG as the full long // output split into hi-lo or lo-hi is supported by the RngDataOutput. if (rng instanceof RandomLongSource && (source64 == Source64Mode.HI || source64 == Source64Mode.LO || source64 == Source64Mode.INT)) { rng = RNGUtils.createIntProvider((UniformRandomProvider & RandomLongSource) rng, source64); } if (reverseBits) { rng = RNGUtils.createReverseBitsProvider(rng); } // ------- // Note: Manipulation of the byte order for the platform is done during output // for the binary format. Otherwise do it in Java. // ------- if (outputFormat != OutputFormat.BINARY) { rng = toOutputFormat(rng); } try (OutputStream out = createOutputStream()) { switch (outputFormat) { case BINARY: writeBinaryData(rng, out); break; case DIEHARDER: writeDieharder(rng, out); break; case BITS: writeBitData(rng, out); break; default: throw new ApplicationException("Unknown output format: " + outputFormat); } } catch (IOException ex) { throw new ApplicationException("IO error: " + ex.getMessage(), ex); } return null; } /** * Creates the seed. * * @return the seed */ private Object createSeed() { if (byteSeed != null) { try { return Hex.decodeHex(byteSeed); } catch (IllegalArgumentException ex) { throw new ApplicationException("Invalid hex seed: " + ex.getMessage(), ex); } } if (seed != null) { return seed; } // Let the factory constructor create the native seed. return null; } /** * Creates the seed. * * @return the seed */ private String createSeedString() { if (byteSeed != null) { return byteSeed; } if (seed != null) { return seed.toString(); } return "auto"; } /** * Creates the RNG. * * @param objectSeed Seed. * @return the uniform random provider * @throws ApplicationException If the RNG cannot be created */ private UniformRandomProvider createRNG(Object objectSeed) { if (randomSource == null) { throw new ApplicationException("Random source is null"); } final ArrayList<Object> data = new ArrayList<>(); // Note: The list command outputs arguments as an array bracketed by [ and ] // Strip these for convenience. stripArrayFormatting(arguments); for (final String argument : arguments) { data.add(RNGUtils.parseArgument(argument)); } try { return randomSource.create(objectSeed, data.toArray()); } catch (IllegalStateException | IllegalArgumentException ex) { throw new ApplicationException("Failed to create RNG: " + randomSource + ". " + ex.getMessage(), ex); } } /** * Strip leading bracket from the first argument, trailing bracket from the last * argument, and any trailing commas from any argument. * * <p>This is used to remove the array formatting used by the list command. * * @param arguments the arguments */ private static void stripArrayFormatting(List<String> arguments) { final int size = arguments.size(); if (size > 1) { // These will not be empty as they were created from command-line args. final String first = arguments.get(0); if (first.charAt(0) == LEFT_SQUARE_BRACKET) { arguments.set(0, first.substring(1)); } final String last = arguments.get(size - 1); if (last.charAt(last.length() - 1) == RIGHT_SQUARE_BRACKET) { arguments.set(size - 1, last.substring(0, last.length() - 1)); } } for (int i = 0; i < size; i++) { final String argument = arguments.get(i); if (argument.endsWith(",")) { arguments.set(i, argument.substring(0, argument.length() - 1)); } } } /** * Convert the native RNG to the requested output format. This will convert a 64-bit * generator to a 32-bit generator unless the 64-bit mode is active. It then optionally * reverses the byte order of the output. * * @param rng The random generator. * @return the uniform random provider */ private UniformRandomProvider toOutputFormat(UniformRandomProvider rng) { UniformRandomProvider convertedRng = rng; if (rng instanceof RandomLongSource && source64 != Source64Mode.LONG) { // Convert to 32-bit generator convertedRng = RNGUtils.createIntProvider((UniformRandomProvider & RandomLongSource) rng, source64); } if (byteOrder == ByteOrder.LITTLE_ENDIAN) { convertedRng = RNGUtils.createReverseBytesProvider(convertedRng); } return convertedRng; } /** * Creates the output stream. This will not be buffered. * * @return the output stream */ private OutputStream createOutputStream() { if (fileOutput != null) { try { return Files.newOutputStream(fileOutput.toPath()); } catch (IOException ex) { throw new ApplicationException("Failed to create output: " + fileOutput, ex); } } return new FilterOutputStream(System.out) { @Override public void close() { // Do not close stdout } }; } /** * Check the count is positive, otherwise create an error message for the provided format. * * @param count The count of numbers to output. * @param format The format. * @throws ApplicationException If the count is not positive. */ private static void checkCount(long count, OutputFormat format) { if (count <= 0) { throw new ApplicationException(format + " format requires a positive count: " + count); } } /** * Write int data to the specified output using the dieharder text format. * * @param rng The random generator. * @param out The output. * @throws IOException Signals that an I/O exception has occurred. * @throws ApplicationException If the count is not positive. */ private void writeDieharder(final UniformRandomProvider rng, final OutputStream out) throws IOException { checkCount(count, OutputFormat.DIEHARDER); // Use dieharder output, e.g. //#================================================================== //# generator mt19937 seed = 1 //#================================================================== //type: d //count: 1 //numbit: 32 //1791095845 try (BufferedWriter output = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8))) { writeHeaderLine(output); output.write("# generator "); output.write(rng.toString()); output.write(" seed = "); output.write(createSeedString()); output.write(NEW_LINE); writeHeaderLine(output); output.write("type: d"); output.write(NEW_LINE); output.write("count: "); output.write(Long.toString(count)); output.write(NEW_LINE); output.write("numbit: 32"); output.write(NEW_LINE); for (long c = 0; c < count; c++) { // Unsigned integers final String text = Long.toString(rng.nextInt() & 0xffffffffL); // Left pad with spaces for (int i = 10 - text.length(); i > 0; i--) { output.write(' '); } output.write(text); output.write(NEW_LINE); } } } /** * Write a header line to the output. * * @param output the output * @throws IOException Signals that an I/O exception has occurred. */ private static void writeHeaderLine(Writer output) throws IOException { output.write("#=================================================================="); output.write(NEW_LINE); } /** * Write raw binary data to the output. * * @param rng The random generator. * @param out The output. * @throws IOException Signals that an I/O exception has occurred. */ private void writeBinaryData(final UniformRandomProvider rng, final OutputStream out) throws IOException { // If count is not positive use max value. // This is effectively unlimited: program must be killed. final long limit = (count < 1) ? Long.MAX_VALUE : count; try (RngDataOutput data = RNGUtils.createDataOutput(rng, source64, out, bufferSize, byteOrder)) { for (long c = 0; c < limit; c++) { data.write(rng); } } } /** * Write binary bit data to the specified file. * * @param rng The random generator. * @param out The output. * @throws IOException Signals that an I/O exception has occurred. * @throws ApplicationException If the count is not positive. */ private void writeBitData(final UniformRandomProvider rng, final OutputStream out) throws IOException { checkCount(count, OutputFormat.BITS); final boolean asLong = rng instanceof RandomLongSource; try (BufferedWriter output = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8))) { for (long c = 0; c < count; c++) { if (asLong) { writeLong(output, rng.nextLong()); } else { writeInt(output, rng.nextInt()); } } } } /** * Write an {@code long} value to the output. The native Java value will be * written to the writer on a single line using: a binary string representation * of the bytes; the unsigned integer; and the signed integer. * * <pre> * 10011010 01010011 01011010 11100100 01000111 00010000 01000011 11000101 11120331841399178181 -7326412232310373435 * </pre> * * @param out The output. * @param value The value. * @throws IOException Signals that an I/O exception has occurred. */ @SuppressWarnings("resource") static void writeLong(Writer out, long value) throws IOException { // Write out as 8 bytes with spaces between them, high byte first. writeByte(out, (int)(value >>> 56) & 0xff); out.write(' '); writeByte(out, (int)(value >>> 48) & 0xff); out.write(' '); writeByte(out, (int)(value >>> 40) & 0xff); out.write(' '); writeByte(out, (int)(value >>> 32) & 0xff); out.write(' '); writeByte(out, (int)(value >>> 24) & 0xff); out.write(' '); writeByte(out, (int)(value >>> 16) & 0xff); out.write(' '); writeByte(out, (int)(value >>> 8) & 0xff); out.write(' '); writeByte(out, (int)(value >>> 0) & 0xff); // Write the unsigned and signed int value new Formatter(out).format(" %20s %20d%n", Long.toUnsignedString(value), value); } /** * Write an {@code int} value to the output. The native Java value will be * written to the writer on a single line using: a binary string representation * of the bytes; the unsigned integer; and the signed integer. * * <pre> * 11001101 00100011 01101111 01110000 3441651568 -853315728 * </pre> * * @param out The output. * @param value The value. * @throws IOException Signals that an I/O exception has occurred. */ @SuppressWarnings("resource") static void writeInt(Writer out, int value) throws IOException { // Write out as 4 bytes with spaces between them, high byte first. writeByte(out, (value >>> 24) & 0xff); out.write(' '); writeByte(out, (value >>> 16) & 0xff); out.write(' '); writeByte(out, (value >>> 8) & 0xff); out.write(' '); writeByte(out, (value >>> 0) & 0xff); // Write the unsigned and signed int value new Formatter(out).format(" %10d %11d%n", value & 0xffffffffL, value); } /** * Write the lower 8 bits of an {@code int} value to the buffered writer using a * binary string representation. This is left-filled with zeros if applicable. * * <pre> * 11001101 * </pre> * * @param out The output. * @param value The value. * @throws IOException Signals that an I/O exception has occurred. */ private static void writeByte(Writer out, int value) throws IOException { // This matches the functionality of: // data.write(String.format("%8s", Integer.toBinaryString(value & 0xff)).replace(' ', '0')) out.write(BIT_REP[value >>> 4]); out.write(BIT_REP[value & 0x0F]); } }
2,819
0
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/ApplicationException.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.examples.stress; /** * Thrown by the RNG utilities application. * * <p>It is expected that the exception is generated when the application cannot continue. * The exception may not have an inner cause, for example if application parameters are * incorrect. */ class ApplicationException extends RuntimeException { private static final long serialVersionUID = 1L; /** * Create a new instance. * * @param message The message. */ ApplicationException(String message) { super(message); } /** * Create a new instance. * * @param message The message. * @param cause The cause. */ ApplicationException(String message, Throwable cause) { super(message, cause); } }
2,820
0
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/StandardOptions.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.examples.stress; import org.apache.commons.rng.examples.stress.LogUtils.LogLevel; import picocli.CommandLine.Command; import picocli.CommandLine.Option; /** * Standard options for all commands. This sets the formatting for usage messages and * adds common parameters (help, version, verbosity). */ @Command(sortOptions = true, mixinStandardHelpOptions = true, versionProvider = ManifestVersionProvider.class, synopsisHeading = "%n", descriptionHeading = "%n", parameterListHeading = "%nParameters:%n", optionListHeading = "%nOptions:%n", commandListHeading = "%nCommands:%n") class StandardOptions { /** The log level. */ @Option(names = { "--logging" }, description = {"Specify the logging level (default: ${DEFAULT-VALUE}).", "Valid values: ${COMPLETION-CANDIDATES}"}) protected LogLevel logLevel = LogLevel.INFO; }
2,821
0
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/AlphaNumericComparator.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.examples.stress; import java.io.Serializable; import java.util.Comparator; /** * Provides number sensitive sorting for character sequences. * * <p>Extracts sub-sequences of either numeric ({@code [0, 9]}) or non-numeric characters * and compares them numerically or lexicographically. Leading zeros are ignored from * numbers. Negative numbers are not supported. * * <pre> * Traditional AlphaNumeric * z0200.html z2.html * z100.html z100.html * z2.html z0200.html * </pre> * * <p>This is based on ideas in the Alphanum algorithm by David Koelle.</p> * * <p>This implementation supports:</p> * * <ul> * <li>{@link CharSequence} comparison * <li>Direct use of input sequences for minimal memory consumption * <li>Numbers with leading zeros * </ul> * * <p>Any null sequences are ordered before non-null sequences.</p> * * <p>Note: The comparator is thread-safe so can be used in a parallel sort. * * @see <a href="http://www.DaveKoelle.com">Alphanum Algorithm</a> */ class AlphaNumericComparator implements Comparator<CharSequence>, Serializable { /** * An instance. */ public static final AlphaNumericComparator INSTANCE = new AlphaNumericComparator(); /** * The serial version ID. * Note: Comparators are recommended to be Serializable to allow serialization of * collections constructed with a Comparator. */ private static final long serialVersionUID = 1L; @Override public int compare(CharSequence seq1, CharSequence seq2) { // Null is less if (seq1 == null) { return -1; } if (seq2 == null) { return 1; } if (seq1.equals(seq2)) { return 0; } int pos1 = 0; int pos2 = 0; final int length1 = seq1.length(); final int length2 = seq2.length(); while (pos1 < length1 && pos2 < length2) { final int end1 = nextSubSequenceEnd(seq1, pos1, length1); final int end2 = nextSubSequenceEnd(seq2, pos2, length2); // If both sub-sequences contain numeric characters, sort them numerically int result = 0; if (isDigit(seq1.charAt(pos1)) && isDigit(seq2.charAt(pos2))) { result = compareNumerically(seq1, pos1, end1, seq2, pos2, end2); } else { result = compareLexicographically(seq1, pos1, end1, seq2, pos2, end2); } if (result != 0) { return result; } pos1 = end1; pos2 = end2; } return length1 - length2; } /** * Get the end position of the next sub-sequence of either digits or non-digit * characters starting from the start position. * * <p>The end position is exclusive such that the sub-sequence is the interval * {@code [start, end)}. * * @param seq the character sequence * @param start the start position * @param length the sequence length * @return the sub-sequence end position (exclusive) */ private static int nextSubSequenceEnd(CharSequence seq, int start, int length) { int pos = start; // Set the sub-sequence type (digits or non-digits) final boolean seqType = isDigit(seq.charAt(pos++)); while (pos < length && seqType == isDigit(seq.charAt(pos))) { // Extend the sub-sequence pos++; } return pos; } /** * Checks if the character is a digit. * * @param ch the character * @return true if a digit */ private static boolean isDigit(char ch) { return ch >= 48 && ch <= 57; } /** * Compares two sub-sequences numerically. Ignores leading zeros. Assumes all * characters are digits. * * @param seq1 the first sequence * @param start1 the start of the first sub-sequence * @param end1 the end of the first sub-sequence * @param seq2 the second sequence * @param start2 the start of the second sub-sequence * @param end2 the end of the second sub-sequence sequence * @return the value {@code 0} if the sub-sequences are equal; a value less than * {@code 0} if sub-sequence 1 is numerically less than sub-sequence 2; and a value * greater than {@code 0} if sub-sequence 1 is numerically greater than sub-sequence * 2. */ private static int compareNumerically(CharSequence seq1, int start1, int end1, CharSequence seq2, int start2, int end2) { // Ignore leading zeros in numbers int pos1 = advancePastLeadingZeros(seq1, start1, end1); int pos2 = advancePastLeadingZeros(seq2, start2, end2); // Simple comparison by length final int result = (end1 - pos1) - (end2 - pos2); // If equal, the first different number counts. if (result == 0) { while (pos1 < end1) { final char c1 = seq1.charAt(pos1++); final char c2 = seq2.charAt(pos2++); if (c1 != c2) { return c1 - c2; } } } return result; } /** * Advances past leading zeros in the sub-sequence. Returns the index of the start * character of the number. * * @param seq the sequence * @param start the start of the sub-sequence * @param end the end of the sub-sequence * @return the start index of the number */ private static int advancePastLeadingZeros(CharSequence seq, int start, int end) { int pos = start; // Ignore zeros only when there are further characters while (pos < end - 1 && seq.charAt(pos) == '0') { pos++; } return pos; } /** * Compares two sub-sequences lexicographically. This matches the compare function in * {@link String} using extracted sub-sequences. * * @param seq1 the first sequence * @param start1 the start of the first sub-sequence * @param end1 the end of the first sub-sequence * @param seq2 the second sequence * @param start2 the start of the second sub-sequence * @param end2 the end of the second sub-sequence sequence * @return the value {@code 0} if the sub-sequences are equal; a value less than * {@code 0} if sub-sequence 1 is lexicographically less than sub-sequence 2; and a * value greater than {@code 0} if sub-sequence 1 is lexicographically greater than * sub-sequence 2. * @see String#compareTo(String) */ private static int compareLexicographically(CharSequence seq1, int start1, int end1, CharSequence seq2, int start2, int end2) { final int len1 = end1 - start1; final int len2 = end2 - start2; final int limit = Math.min(len1, len2); for (int i = 0; i < limit; i++) { final char c1 = seq1.charAt(i + start1); final char c2 = seq2.charAt(i + start2); if (c1 != c2) { return c1 - c2; } } return len1 - len2; } }
2,822
0
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/ExamplesStressApplication.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.examples.stress; import picocli.CommandLine; import picocli.CommandLine.RunLast; /** * Executes testing utilities for the random number generators in the Commons RNG library. * * <p>The principle action is testing a generator by piping the values returned by its * {@link org.apache.commons.rng.UniformRandomProvider#nextInt() * UniformRandomProvider.nextInt()} method to a program that reads {@code int} values from * its standard input and writes an analysis report to standard output. The <a * href="http://www.phy.duke.edu/~rgb/General/dieharder.php"> "Dieharder"</a> test suite * is such a software.</p> * * <p>Example of command line, assuming that "examples-stress.jar" specifies this * class as the "main" class (see {@link #main(String[]) main} method):</p> * * <pre>{@code $ java -jar examples-stress.jar stress /usr/bin/dieharder -a -g 200 -Y 1 -k 2}</pre> * * <p>Other functionality includes:</p> * * <ul> * <li>Listing all the available generators * <li>Collating results from known stress test applications * <li>Outputting data from a random generator * <li>Showing the platform native byte order * <li>Testing data transfer to an application sub-process via its standard input * </ul> */ public final class ExamplesStressApplication { /** No public constructor. */ private ExamplesStressApplication() {} /** * Run the RNG examples stress command line application. * * @param args Application's arguments. */ public static void main(String[] args) { // Build the command line manually so we can configure options. final CommandLine cmd = new CommandLine(new ExamplesStressCommand()) .addSubcommand("bridge", new CommandLine(new BridgeTestCommand()) .setStopAtPositional(true)) .addSubcommand("endian", new EndianessCommand()) .addSubcommand("list", new ListCommand()) .addSubcommand("output", new CommandLine(new OutputCommand()) // Allow the input seed using hex (0x, 0X, #) // or octal (starting with 0) .registerConverter(Long.class, Long::decode)) .addSubcommand("results", new ResultsCommand()) .addSubcommand("stress", new CommandLine(new StressTestCommand()) .setStopAtPositional(true)) // Call last to apply to all sub-commands .setCaseInsensitiveEnumValuesAllowed(true); try { // Parse the command line and invokes the Callable program (RNGUtilities) cmd.parseWithHandler(new RunLast(), args); } catch (final CommandLine.ExecutionException ex) { final Throwable cause = ex.getCause(); if (cause != null) { // If this was an exception generated by the application then the full // stack trace is not needed depending on log level. This limits stack // trace output to unexpected errors in the common use case. if (cause instanceof ApplicationException && !LogUtils.isLoggable(LogUtils.LogLevel.DEBUG)) { LogUtils.error(cause.getMessage()); } else { LogUtils.error(cause, cause.getMessage()); } System.exit(1); } // No cause so re-throw. This may be a Picocli parsing error. throw ex; } } }
2,823
0
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/StressTestData.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.examples.stress; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.simple.RandomSource; /** * Encapsulate the data needed to create and test a random generator. This includes: * * <ul> * <li>An identifier for the random source * <li>The random source * <li>The constructor arguments * <li>The number of trials for each random source * </ul> */ class StressTestData { /** The identifier. */ private final String id; /** The random source. */ private final RandomSource randomSource; /** The arguments used to construct the random source. */ private final Object[] args; /** The number of trials. */ private final int trials; /** * Creates a new instance. * * @param randomSource The random source. * @param args The arguments used to construct the random source (can be {@code null}). */ StressTestData(RandomSource randomSource, Object[] args) { // The default ID is defined by the enum order. this(Integer.toString(randomSource.ordinal() + 1), randomSource, args, // Ignore by default (trials = 0) any source that has arguments args == null ? 1 : 0); } /** * Creates a new instance. * * @param id The identifier. * @param randomSource The random source. * @param args The arguments used to construct the random source (can be * {@code null}). * @param trials The number of trials. */ StressTestData(String id, RandomSource randomSource, Object[] args, int trials) { this.id = id; this.randomSource = randomSource; this.args = args; this.trials = trials; } /** * Create a new instance with the given ID prefix prepended to the current ID. * * @param idPrefix The ID prefix. * @return the stress test data */ StressTestData withIDPrefix(String idPrefix) { return new StressTestData(idPrefix + id, randomSource, args, trials); } /** * Create a new instance with the given number of trials. * * @param numberOfTrials The number of trials. * @return the stress test data */ StressTestData withTrials(int numberOfTrials) { return new StressTestData(id, randomSource, args, numberOfTrials); } /** * Creates the random generator. * * <p>It is recommended the seed is generated using {@link RandomSource#createSeed()}.</p> * * @param seed the seed (use {@code null} to automatically create a seed) * @return the uniform random provider */ UniformRandomProvider createRNG(byte[] seed) { return randomSource.create(seed, args); } /** * Gets the identifier. * * @return the id */ String getId() { return id; } /** * Gets the random source. * * @return the random source */ RandomSource getRandomSource() { return randomSource; } /** * Gets the arguments used to construct the random source. * * @return the arguments */ Object[] getArgs() { return args; } /** * Gets the number of trials. * * @return the number of trials */ int getTrials() { return trials; } }
2,824
0
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/EndianessCommand.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.examples.stress; import picocli.CommandLine.Command; import picocli.CommandLine.Mixin; import java.nio.ByteOrder; import java.util.concurrent.Callable; /** * Specification for the "endian" command. * * <p>This command prints the native byte order of the platform.</p> * * @see ByteOrder#nativeOrder() */ @Command(name = "endian", description = "Show the platform native byte order.") class EndianessCommand implements Callable<Void> { /** The standard options. */ @Mixin private StandardOptions reusableOptions; /** * Prints a template generators list to stdout. */ @Override public Void call() { // Log level will be relevant for any exception logging LogUtils.setLogLevel(reusableOptions.logLevel); LogUtils.info(ByteOrder.nativeOrder().toString()); return null; } }
2,825
0
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/StressTestDataList.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.examples.stress; import org.apache.commons.rng.core.source32.RandomIntSource; import org.apache.commons.rng.core.source64.RandomLongSource; import org.apache.commons.rng.simple.RandomSource; import org.apache.commons.rng.simple.internal.ProviderBuilder.RandomSourceInternal; import java.util.ArrayList; import java.util.EnumMap; import java.util.Iterator; import java.util.List; /** * Default list of generators defined by the {@link RandomSource}. Any source that * requires arguments will have a default set of arguments. */ class StressTestDataList implements Iterable<StressTestData> { /** * The example arguments for RandomSource values that require them. */ private static final EnumMap<RandomSource, Object[]> EXAMPLE_ARGUMENTS = new EnumMap<>(RandomSource.class); static { // Currently we cannot detect if the source requires arguments, // e.g. RandomSource.TWO_CMRES_SELECT. So example arguments must // be manually added here. EXAMPLE_ARGUMENTS.put(RandomSource.TWO_CMRES_SELECT, new Object[] {1, 2}); } /** List of generators. */ private final List<StressTestData> list = new ArrayList<>(); /** * Creates an empty list. */ private StressTestDataList() { // Do nothing } /** * Creates the list. The number of trials will be set if the source does not require arguments. * * @param idPrefix The id prefix prepended to each ID. * @param numberOfTrials The number of trials (ignored if {@code <= 0}). */ StressTestDataList(String idPrefix, int numberOfTrials) { // Auto-generate using the order of the RandomSource enum for (final RandomSource source : RandomSource.values()) { final Object[] args = EXAMPLE_ARGUMENTS.get(source); StressTestData data = new StressTestData(source, args).withIDPrefix(idPrefix); if (args == null && numberOfTrials > 0) { data = data.withTrials(numberOfTrials); } list.add(data); } } /** {@inheritDoc} */ @Override public Iterator<StressTestData> iterator() { return list.iterator(); } /** * Create a subset of the list containing only instances of {@link RandomIntSource}. * * @return the stress test data list */ public StressTestDataList subsetIntSource() { return subsetOf(RandomIntSource.class); } /** * Create a subset of the list containing only instances of {@link RandomLongSource}. * * @return the stress test data list */ public StressTestDataList subsetLongSource() { return subsetOf(RandomLongSource.class); } /** * Create a subset of the list containing only instances of the specified type. * * @param type The instance type. * @return the stress test data list */ private StressTestDataList subsetOf(Class<?> type) { final StressTestDataList subset = new StressTestDataList(); for (final StressTestData data : list) { // This makes a big assumption that the two enums have the same name RandomSourceInternal source; try { source = RandomSourceInternal.valueOf(data.getRandomSource().name()); } catch (IllegalArgumentException ex) { throw new ApplicationException("Unknown internal source: " + data.getRandomSource(), ex); } if (type.isAssignableFrom(source.getRng())) { subset.list.add(data); } } return subset; } /** * Create a subset of the list containing only instances of RandomSource within the * specified range of the enum. The first value in the enum corresponds to entry 1. * * @param min Minimum entry (inclusive) * @param max Maximum entry (inclusive) * @return the stress test data list */ public StressTestDataList subsetRandomSource(int min, int max) { final StressTestDataList subset = new StressTestDataList(); for (final StressTestData data : list) { final int entry = data.getRandomSource().ordinal() + 1; if (min <= entry && entry <= max) { subset.list.add(data); } } return subset; } }
2,826
0
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/RNGUtils.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.examples.stress; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.core.source32.IntProvider; import org.apache.commons.rng.core.source32.RandomIntSource; import org.apache.commons.rng.core.source64.RandomLongSource; import org.apache.commons.rng.core.util.NumberFactory; import org.apache.commons.rng.core.source64.LongProvider; import java.io.OutputStream; import java.nio.ByteOrder; import java.util.concurrent.ThreadLocalRandom; /** * Utility methods for a {@link UniformRandomProvider}. */ final class RNGUtils { /** Name prefix for bit-reversed RNGs. */ private static final String BYTE_REVERSED = "Byte-reversed "; /** Name prefix for bit-reversed RNGs. */ private static final String BIT_REVERSED = "Bit-reversed "; /** Name prefix for hash code mixed RNGs. */ private static final String HASH_CODE = "HashCode ^ "; /** Name prefix for ThreadLocalRandom xor mixed RNGs. */ private static final String TLR_MIXED = "ThreadLocalRandom ^ "; /** Name of xor operator for xor mixed RNGs. */ private static final String XOR = " ^ "; /** Message for an unrecognized source64 mode. */ private static final String UNRECOGNISED_SOURCE_64_MODE = "Unrecognized source64 mode: "; /** Message for an unrecognized native output type. */ private static final String UNRECOGNISED_NATIVE_TYPE = "Unrecognized native output type: "; /** The source64 mode for the default LongProvider caching implementation. */ private static final Source64Mode SOURCE_64_DEFAULT = Source64Mode.LO_HI; /** No public construction. */ private RNGUtils() {} /** * Gets the source64 mode for the default caching implementation in {@link LongProvider}. * * @return the source64 default mode */ static Source64Mode getSource64Default() { return SOURCE_64_DEFAULT; } /** * Wrap the random generator with a new instance that will reverse the byte order of * the native type. The input must be either a {@link RandomIntSource} or * {@link RandomLongSource}. * * @param rng The random generator. * @return the byte reversed random generator. * @throws ApplicationException If the input source native type is not recognized. * @see Integer#reverseBytes(int) * @see Long#reverseBytes(long) */ static UniformRandomProvider createReverseBytesProvider(final UniformRandomProvider rng) { if (rng instanceof RandomIntSource) { return new IntProvider() { @Override public int next() { return Integer.reverseBytes(rng.nextInt()); } @Override public String toString() { return BYTE_REVERSED + rng.toString(); } }; } if (rng instanceof RandomLongSource) { return new LongProvider() { @Override public long next() { return Long.reverseBytes(rng.nextLong()); } @Override public String toString() { return BYTE_REVERSED + rng.toString(); } }; } throw new ApplicationException(UNRECOGNISED_NATIVE_TYPE + rng); } /** * Wrap the random generator with a new instance that will reverse the bits of * the native type. The input must be either a {@link RandomIntSource} or * {@link RandomLongSource}. * * @param rng The random generator. * @return the bit reversed random generator. * @throws ApplicationException If the input source native type is not recognized. * @see Integer#reverse(int) * @see Long#reverse(long) */ static UniformRandomProvider createReverseBitsProvider(final UniformRandomProvider rng) { if (rng instanceof RandomIntSource) { return new IntProvider() { @Override public int next() { return Integer.reverse(rng.nextInt()); } @Override public String toString() { return BIT_REVERSED + rng.toString(); } }; } if (rng instanceof RandomLongSource) { return new LongProvider() { @Override public long next() { return Long.reverse(rng.nextLong()); } @Override public String toString() { return BIT_REVERSED + rng.toString(); } }; } throw new ApplicationException(UNRECOGNISED_NATIVE_TYPE + rng); } /** * Wrap the {@link RandomLongSource} with an {@link IntProvider} that will use the * specified part of {@link RandomLongSource#next()} to create the int value. * * @param <R> The type of the generator. * @param rng The random generator. * @param mode the mode * @return the int random generator. * @throws ApplicationException If the input source native type is not 64-bit. */ static <R extends RandomLongSource & UniformRandomProvider> UniformRandomProvider createIntProvider(final R rng, Source64Mode mode) { switch (mode) { case INT: return createIntProvider(rng); case LO_HI: return createLongLowerUpperBitsIntProvider(rng); case HI_LO: return createLongUpperLowerBitsIntProvider(rng); case HI: return createLongUpperBitsIntProvider(rng); case LO: return createLongLowerBitsIntProvider(rng); case LONG: default: throw new IllegalArgumentException("Unsupported mode " + mode); } } /** * Wrap the random generator with an {@link IntProvider} that will use * {@link UniformRandomProvider#nextInt()}. * An input {@link RandomIntSource} is returned unmodified. * * @param rng The random generator. * @return the int random generator. */ private static UniformRandomProvider createIntProvider(final UniformRandomProvider rng) { if (!(rng instanceof RandomIntSource)) { return new IntProvider() { @Override public int next() { return rng.nextInt(); } @Override public String toString() { return "Int bits " + rng.toString(); } }; } return rng; } /** * Wrap the random generator with an {@link IntProvider} that will use the lower then upper * 32-bits from {@link UniformRandomProvider#nextLong()}. * An input {@link RandomIntSource} is returned unmodified. * * @param rng The random generator. * @return the int random generator. */ private static UniformRandomProvider createLongLowerUpperBitsIntProvider(final RandomLongSource rng) { return new IntProvider() { private long source = -1; @Override public int next() { long next = source; if (next < 0) { // refill next = rng.next(); // store hi source = next >>> 32; // extract low return (int) next; } final int v = (int) next; // reset source = -1; return v; } @Override public String toString() { return "Long lower-upper bits " + rng.toString(); } }; } /** * Wrap the random generator with an {@link IntProvider} that will use the lower then upper * 32-bits from {@link UniformRandomProvider#nextLong()}. * An input {@link RandomIntSource} is returned unmodified. * * @param rng The random generator. * @return the int random generator. */ private static UniformRandomProvider createLongUpperLowerBitsIntProvider(final RandomLongSource rng) { return new IntProvider() { private long source = -1; @Override public int next() { long next = source; if (next < 0) { // refill next = rng.next(); // store low source = next & 0xffff_ffffL; // extract hi return (int) (next >>> 32); } final int v = (int) next; // reset source = -1; return v; } @Override public String toString() { return "Long upper-lower bits " + rng.toString(); } }; } /** * Wrap the random generator with an {@link IntProvider} that will use the upper * 32-bits of the {@code long} from {@link UniformRandomProvider#nextLong()}. * The input must be a {@link RandomLongSource}. * * @param rng The random generator. * @return the upper bits random generator. * @throws ApplicationException If the input source native type is not 64-bit. */ private static UniformRandomProvider createLongUpperBitsIntProvider(final RandomLongSource rng) { return new IntProvider() { @Override public int next() { return (int) (rng.next() >>> 32); } @Override public String toString() { return "Long upper-bits " + rng.toString(); } }; } /** * Wrap the random generator with an {@link IntProvider} that will use the lower * 32-bits of the {@code long} from {@link UniformRandomProvider#nextLong()}. * The input must be a {@link RandomLongSource}. * * @param rng The random generator. * @return the lower bits random generator. * @throws ApplicationException If the input source native type is not 64-bit. */ private static UniformRandomProvider createLongLowerBitsIntProvider(final RandomLongSource rng) { return new IntProvider() { @Override public int next() { return (int) rng.next(); } @Override public String toString() { return "Long lower-bits " + rng.toString(); } }; } /** * Wrap the random generator with a new instance that will combine the bits * using a {@code xor} operation with a generated hash code. The input must be either * a {@link RandomIntSource} or {@link RandomLongSource}. * * <pre> * {@code * System.identityHashCode(new Object()) ^ rng.nextInt() * } * </pre> * * Note: This generator will be slow. * * @param rng The random generator. * @return the combined random generator. * @throws ApplicationException If the input source native type is not recognized. * @see System#identityHashCode(Object) */ static UniformRandomProvider createHashCodeProvider(final UniformRandomProvider rng) { if (rng instanceof RandomIntSource) { return new IntProvider() { @Override public int next() { return System.identityHashCode(new Object()) ^ rng.nextInt(); } @Override public String toString() { return HASH_CODE + rng.toString(); } }; } if (rng instanceof RandomLongSource) { return new LongProvider() { @Override public long next() { final long mix = NumberFactory.makeLong(System.identityHashCode(new Object()), System.identityHashCode(new Object())); return mix ^ rng.nextLong(); } @Override public String toString() { return HASH_CODE + rng.toString(); } }; } throw new ApplicationException(UNRECOGNISED_NATIVE_TYPE + rng); } /** * Wrap the random generator with a new instance that will combine the bits * using a {@code xor} operation with the output from {@link ThreadLocalRandom}. * The input must be either a {@link RandomIntSource} or {@link RandomLongSource}. * * <pre> * {@code * ThreadLocalRandom.current().nextInt() ^ rng.nextInt() * } * </pre> * * @param rng The random generator. * @return the combined random generator. * @throws ApplicationException If the input source native type is not recognized. */ static UniformRandomProvider createThreadLocalRandomProvider(final UniformRandomProvider rng) { if (rng instanceof RandomIntSource) { return new IntProvider() { @Override public int next() { return ThreadLocalRandom.current().nextInt() ^ rng.nextInt(); } @Override public String toString() { return TLR_MIXED + rng.toString(); } }; } if (rng instanceof RandomLongSource) { return new LongProvider() { @Override public long next() { return ThreadLocalRandom.current().nextLong() ^ rng.nextLong(); } @Override public String toString() { return TLR_MIXED + rng.toString(); } }; } throw new ApplicationException(UNRECOGNISED_NATIVE_TYPE + rng); } /** * Combine the two random generators using a {@code xor} operations. * The input must be either a {@link RandomIntSource} or {@link RandomLongSource}. * The returned type will match the native output type of {@code rng1}. * * <pre> * {@code * rng1.nextInt() ^ rng2.nextInt() * } * </pre> * * @param rng1 The first random generator. * @param rng2 The second random generator. * @return the combined random generator. * @throws ApplicationException If the input source native type is not recognized. */ static UniformRandomProvider createXorProvider(final UniformRandomProvider rng1, final UniformRandomProvider rng2) { if (rng1 instanceof RandomIntSource) { return new IntProvider() { @Override public int next() { return rng1.nextInt() ^ rng2.nextInt(); } @Override public String toString() { return rng1.toString() + XOR + rng2.toString(); } }; } if (rng1 instanceof RandomLongSource) { return new LongProvider() { @Override public long next() { return rng1.nextLong() ^ rng2.nextLong(); } @Override public String toString() { return rng1.toString() + XOR + rng2.toString(); } }; } throw new ApplicationException(UNRECOGNISED_NATIVE_TYPE + rng1); } /** * Create a new instance to write batches of byte data from the specified RNG to the * specified output stream. * * <p>This will detect the native output type of the RNG and create an appropriate * data output for the raw bytes. The input must be either a {@link RandomIntSource} or * {@link RandomLongSource}.</p> * * <p>If the RNG is a {@link RandomLongSource} then the byte output can be 32-bit or 64-bit. * If 32-bit then the 64-bit output will be written as if 2 {@code int} values were generated * sequentially from the {@code long} (order depends on the source64 mode). This setting is * significant depending on the byte order. For example for a high-low source64 mode and * using the Java standard big-endian representation the output is the same as the raw 64-bit * output. If using little endian the output bytes will be written as:</p> * * <pre>{@code * 76543210 -> 4567 0123 * }</pre> * * <h2>Note</h2> * * <p>The output from an implementation of RandomLongSource from the RNG core package * may output the long bits as integers: in high-low order; in low-high order; using * only the low bits; using only the high bits; or other combinations. This method * allows testing the long output as if it were two int outputs, i.e. using the full * bit output of a long provider with a stress test application that targets 32-bit * random values (e.g. Test U01). * * <p>The results of stress testing can be used to determine if the provider * implementation can use the upper, lower or both parts of the long output for int * generation. In the case of the combined upper-lower output it is not expected that * the order low-high or high-low is important given the stress test will consume * thousands of numbers per test. The default 32-bit mode for a 64-bit source is high-low * for backwards compatibility. * * @param rng The random generator. * @param source64 The output mode for a 64-bit source * @param out Output stream. * @param byteSize Number of bytes values to write. * @param byteOrder Byte order. * @return the data output * @throws ApplicationException If the input source native type is not recognized; or if * the mode for a RandomLongSource is not one of: raw; hi-lo; or lo-hi. */ static RngDataOutput createDataOutput(final UniformRandomProvider rng, Source64Mode source64, OutputStream out, int byteSize, ByteOrder byteOrder) { if (rng instanceof RandomIntSource) { return RngDataOutput.ofInt(out, byteSize / 4, byteOrder); } if (rng instanceof RandomLongSource) { switch (source64) { case HI_LO: return RngDataOutput.ofLongAsHLInt(out, byteSize / 8, byteOrder); case LO_HI: return RngDataOutput.ofLongAsLHInt(out, byteSize / 8, byteOrder); case LONG: return RngDataOutput.ofLong(out, byteSize / 8, byteOrder); // Note other options should have already been converted to an IntProvider case INT: case LO: case HI: default: throw new ApplicationException(UNRECOGNISED_SOURCE_64_MODE + source64); } } throw new ApplicationException(UNRECOGNISED_NATIVE_TYPE + rng); } /** * Parses the argument into an object suitable for the RandomSource constructor. Supports: * * <ul> * <li>Integer * </ul> * * @param argument the argument * @return the object * @throws ApplicationException If the argument is not recognized */ static Object parseArgument(String argument) { try { // Currently just support TWO_CMRES_SELECT which uses integers. // Future RandomSource implementations may require other parsing, for example // recognising a long by the suffix 'L'. This functionality // could use Commons Lang NumberUtils.createNumber(String). return Integer.parseInt(argument); } catch (final NumberFormatException ex) { throw new ApplicationException("Failed to parse RandomSource argument: " + argument, ex); } } }
2,827
0
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/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. */ /** * This package contains an application for interfacing with external * software that perform stringent tests to check the uniformity of * the sequences being passed to them. */ package org.apache.commons.rng.examples.stress;
2,828
0
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/ProcessUtils.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.examples.stress; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Utility methods for a {@link Process}. */ final class ProcessUtils { /** The timeout to wait for the process exit value in milliseconds. */ private static final long DEFAULT_TIMEOUT_MILLIS = 1000L; /** No public construction. */ private ProcessUtils() {} /** * Check the executable exists and has execute permissions. * * @param executable The executable. * @throws ApplicationException If the executable is invalid. */ static void checkExecutable(File executable) { if (!executable.exists() || !executable.canExecute()) { throw new ApplicationException("Program is not executable: " + executable); } } /** * Check the output directory exists and has write permissions. * * @param fileOutputPrefix The file output prefix. * @throws ApplicationException If the output directory is invalid. */ static void checkOutputDirectory(File fileOutputPrefix) { final File reportDir = fileOutputPrefix.getAbsoluteFile().getParentFile(); if (!reportDir.exists() || !reportDir.isDirectory() || !reportDir.canWrite()) { throw new ApplicationException("Invalid output directory: " + reportDir); } } /** * Builds the command for the sub-process. * * @param executable The executable file. * @param executableArguments The executable arguments. * @return the command * @throws ApplicationException If the executable path cannot be resolved */ static List<String> buildSubProcessCommand(File executable, List<String> executableArguments) { final ArrayList<String> command = new ArrayList<>(); try { command.add(executable.getCanonicalPath()); } catch (final IOException ex) { // Not expected to happen as the file has been tested to exist throw new ApplicationException("Cannot resolve executable path: " + ex.getMessage(), ex); } command.addAll(executableArguments); return command; } /** * Get the exit value from the process, waiting at most for 1 second, otherwise kill the process * and return {@code null}. * * <p>This should be used when it is expected the process has completed.</p> * * @param process The process. * @return The exit value. * @see Process#destroy() */ static Integer getExitValue(Process process) { return getExitValue(process, DEFAULT_TIMEOUT_MILLIS); } /** * Get the exit value from the process, waiting at most for the given time, otherwise * kill the process and return {@code null}. * * <p>This should be used when it is expected the process has completed. If the timeout * expires an error message is logged before the process is killed.</p> * * @param process The process. * @param timeoutMillis The timeout (in milliseconds). * @return The exit value. * @see Process#destroy() */ static Integer getExitValue(Process process, long timeoutMillis) { final long startTime = System.currentTimeMillis(); long remaining = timeoutMillis; while (remaining > 0) { try { return process.exitValue(); } catch (final IllegalThreadStateException ex) { try { Thread.sleep(Math.min(remaining + 1, 100)); } catch (final InterruptedException e) { // Reset interrupted status and stop waiting Thread.currentThread().interrupt(); break; } } remaining = timeoutMillis - (System.currentTimeMillis() - startTime); } LogUtils.error("Failed to obtain exit value after %d ms, forcing termination", timeoutMillis); // Not finished so kill it process.destroy(); return null; } }
2,829
0
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples
Create_ds/commons-rng/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/LogUtils.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.examples.stress; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; /** * Simple utility for logging messages to the console. * * <p>This is not a replacement for a logging framework and may be replaced in the future. */ final class LogUtils { /** The logging level. */ private static LogLevel logLevel = LogLevel.INFO; /** * The log level. */ enum LogLevel { /** The error log level. */ ERROR(0), /** The information log level. */ INFO(1), /** The debug log level. */ DEBUG(2); /** The prefix for log messages. */ private final String prefix; /** The logging level. */ private final int level; /** * Create a new instance. * * @param level The level. */ LogLevel(int level) { // Just use the name prefix = "[" + name() + "] "; this.level = level; } /** * Gets the message prefix. * * @return the prefix */ String getPrefix() { return prefix; } /** * Gets the level. * * @return the level */ int getLevel() { return level; } } /** * No public construction. */ private LogUtils() {} /** * Sets the log level. * * @param logLevel The new log level. */ static void setLogLevel(LogLevel logLevel) { LogUtils.logLevel = logLevel; } /** * Checks if the given level is loggable. * * @param level The level. * @return true if loggable */ static boolean isLoggable(LogLevel level) { return level.getLevel() <= LogUtils.logLevel.getLevel(); } /** * Log a debug message to {@link System#out}. * * @param message The message. */ static void debug(String message) { if (isLoggable(LogLevel.DEBUG)) { println(System.out, LogLevel.DEBUG.getPrefix() + message); } } /** * Log a debug message to {@link System#out}. * * @param format The format. * @param args The arguments. */ static void debug(String format, Object... args) { if (isLoggable(LogLevel.DEBUG)) { printf(System.out, LogLevel.DEBUG.getPrefix() + format, args); } } /** * Log an info message to {@link System#out}. * * @param message The message. */ static void info(String message) { if (isLoggable(LogLevel.INFO)) { println(System.out, LogLevel.INFO.getPrefix() + message); } } /** * Log an info message to {@link System#out}. * * @param format The format. * @param args The arguments. */ static void info(String format, Object... args) { if (isLoggable(LogLevel.INFO)) { printf(System.out, LogLevel.INFO.getPrefix() + format, args); } } /** * Log an error message to {@link System#err}. * * @param message The message. */ static void error(String message) { if (isLoggable(LogLevel.ERROR)) { println(System.err, LogLevel.ERROR.getPrefix() + message); } } /** * Log an error message to {@link System#err}. * * @param format The format. * @param args The arguments. */ static void error(String format, Object... args) { if (isLoggable(LogLevel.ERROR)) { printf(System.err, LogLevel.ERROR.getPrefix() + format, args); } } /** * Log an error message to {@link System#err}. The stack trace of the thrown is added. * * @param thrown The thrown. * @param message The message. */ static void error(Throwable thrown, String message) { if (isLoggable(LogLevel.ERROR)) { final StringWriter sw = new StringWriter(); try (PrintWriter pw = createErrorPrintWriter(sw)) { pw.print(message); addStackTrace(pw, thrown); } println(System.err, sw.toString()); } } /** * Log an error message to {@link System#err}. The stack trace of the thrown is * added. * * @param thrown The thrown. * @param format The format. * @param args The arguments. */ static void error(Throwable thrown, String format, Object... args) { if (isLoggable(LogLevel.ERROR)) { final StringWriter sw = new StringWriter(); try (PrintWriter pw = createErrorPrintWriter(sw)) { pw.printf(format, args); addStackTrace(pw, thrown); } printf(System.err, sw.toString()); } } /** * Creates the error print writer. It will contain the prefix for error * messages. * * @param sw The string writer. * @return the print writer */ private static PrintWriter createErrorPrintWriter(StringWriter sw) { final PrintWriter pw = new PrintWriter(sw); pw.print(LogLevel.ERROR.getPrefix()); return pw; } /** * Adds the stack trace to the print writer. * * @param pw The print writer. * @param thrown The thrown. */ private static void addStackTrace(PrintWriter pw, Throwable thrown) { // Complete the current line pw.println(); thrown.printStackTrace(pw); } /** * Print a message to the provided {@link PrintStream}. * * @param out The output. * @param message The message. * @see PrintStream#println(String) */ private static void println(PrintStream out, String message) { out.println(message); } /** * Print a message to the provided {@link PrintStream}. * * @param out The output. * @param format The format. * @param args The arguments. * @see PrintStream#printf(String, Object...) */ private static void printf(PrintStream out, String format, Object... args) { // Ensure a new line is added out.printf(format + "%n", args); } }
2,830
0
Create_ds/commons-rng/commons-rng-examples/examples-jpms/jpms-lib/src/main
Create_ds/commons-rng/commons-rng-examples/examples-jpms/jpms-lib/src/main/java/module-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. */ /** * This module contains code for testing that the library * can be used as a Java 9 Java Platform Module System (JPMS) module. */ module org.apache.commons.rng.examples.jpms.lib { requires org.apache.commons.rng.api; requires org.apache.commons.rng.sampling; exports org.apache.commons.rng.examples.jpms.lib; }
2,831
0
Create_ds/commons-rng/commons-rng-examples/examples-jpms/jpms-lib/src/main/java/org/apache/commons/rng/examples/jpms
Create_ds/commons-rng/commons-rng-examples/examples-jpms/jpms-lib/src/main/java/org/apache/commons/rng/examples/jpms/lib/DiceGame.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.examples.jpms.lib; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.distribution.ContinuousSampler; import org.apache.commons.rng.sampling.distribution.GaussianSampler; import org.apache.commons.rng.sampling.distribution.ZigguratNormalizedGaussianSampler; /** * Example application. */ public class DiceGame { /** Underlying RNG. */ private final UniformRandomProvider rng; /** Sampler. */ private final ContinuousSampler sampler; /** Number of rounds in the game. */ private final int rounds; /** Number of players in the game. */ private final int players; /** * @param players Number of players. * @param rounds Number of rounds. * @param rng RNG. * @param mu Mean. * @param sigma Standard deviation. */ public DiceGame(int players, int rounds, UniformRandomProvider rng, double mu, double sigma) { this.rng = rng; this.rounds = rounds; this.players = players; sampler = GaussianSampler.of(ZigguratNormalizedGaussianSampler.of(rng), mu, sigma); } /** * Play a game. * * @return the scores of all the players. */ public int[] play() { final int[] scores = new int[players]; for (int i = 0; i < rounds; i++) { doRound(scores); } return scores; } /** * Play a round and update the scores. * * @param currentScores Scores of the players. */ private void doRound(int[] currentScores) { for (int i = 0; i < players; i++) { currentScores[i] += roll(); } } /** * @return the score of one round. */ private int roll() { int score = 0; final int n = numberOfDice(); for (int i = 0; i < n; i++) { score += singleRoll(); } return score; } /** * @return a number between 1 and 6. */ private int singleRoll() { return rng.nextInt(6); } /** * @return the number of dice to roll. */ private int numberOfDice() { final double n = Math.round(sampler.sample()); return n <= 0 ? 0 : (int) n; } }
2,832
0
Create_ds/commons-rng/commons-rng-examples/examples-jpms/jpms-lib/src/main/java/org/apache/commons/rng/examples/jpms
Create_ds/commons-rng/commons-rng-examples/examples-jpms/jpms-lib/src/main/java/org/apache/commons/rng/examples/jpms/lib/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. */ /** * This package contains code for testing that the library * can be used as a Java 9 Java Platform Module System (JPMS) module. */ package org.apache.commons.rng.examples.jpms.lib;
2,833
0
Create_ds/commons-rng/commons-rng-examples/examples-jpms/jpms-app/src/main
Create_ds/commons-rng/commons-rng-examples/examples-jpms/jpms-app/src/main/java/module-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. */ /** * This module contains an application for testing that the library * can be used as a Java 9 Java Platform Module System (JPMS) module. */ module org.apache.commons.rng.examples.jpms.app { requires org.apache.commons.rng.examples.jpms.lib; requires org.apache.commons.rng.simple; }
2,834
0
Create_ds/commons-rng/commons-rng-examples/examples-jpms/jpms-app/src/main/java/org/apache/commons/rng/examples/jpms
Create_ds/commons-rng/commons-rng-examples/examples-jpms/jpms-app/src/main/java/org/apache/commons/rng/examples/jpms/app/DiceGameApplication.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.examples.jpms.app; import java.util.Arrays; import java.util.Comparator; import java.lang.module.ModuleDescriptor; import org.apache.commons.rng.simple.RandomSource; import org.apache.commons.rng.examples.jpms.lib.DiceGame; /** * Test that "commons-rng-simple" can be used as a module in Java 9. */ public final class DiceGameApplication { /** Line separator. */ private static final String LINE_SEP = System.getProperty("line.separator"); /** Required functionality. */ private final DiceGame game; /** * Application. * * @param numPlayers Number of players. * @param numRounds Number of rounds per game. * @param identifier RNG algorithm identifier. * @param mu Mean rolls per round. * @param sigma Standard deviation of rolls per round. */ private DiceGameApplication(int numPlayers, int numRounds, RandomSource identifier, double mu, double sigma) { game = new DiceGame(numPlayers, numRounds, identifier.create(), mu, sigma); } // Allow System.out and multiple " ---" strings // CHECKSTYLE: stop RegexpCheck // CHECKSTYLE: stop MultipleStringLiteralsCheck /** * Application's entry point. * * @param args Arguments, in the following order * <ol> * <li>Number of games</li> * <li>Number of players</li> * <li>Number of rounds per game</li> * <li>RNG {@link RandomSource identifier}</li> * <li>Mean rolls per round</li> * <li>Standard deviation of rolls per round</li> * </ol> */ public static void main(String[] args) { final int numGames = Integer.parseInt(args[0]); final DiceGameApplication app = new DiceGameApplication(Integer.parseInt(args[1]), Integer.parseInt(args[2]), RandomSource.valueOf(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5])); app.displayModuleInfo(); for (int i = 1; i <= numGames; i++) { System.out.println("--- Game " + i + " ---"); System.out.println(display(app.game.play())); } } /** * Display the list of players in decreasing order of scores. * * @param scores Scores returned by {@link #play()}. * @return a text diplaying the result of the game. */ private static String display(int[] scores) { final int[][] a = new int[scores.length][2]; for (int i = 0; i < scores.length; i++) { a[i][0] = i; a[i][1] = scores[i]; } Arrays.sort(a, Comparator.comparingInt(x -> -x[1])); final StringBuilder result = new StringBuilder(512); for (int i = 0; i < scores.length; i++) { result.append("Player ").append(a[i][0] + 1) .append(" has ").append(a[i][1]) .append(" points").append(LINE_SEP); } return result.toString(); } /** * Display JPMS information. */ private void displayModuleInfo() { for (final Module mod : new Module[] {DiceGame.class.getModule(), DiceGameApplication.class.getModule()}) { System.out.println("--- " + mod + " ---"); final ModuleDescriptor desc = mod.getDescriptor(); for (final ModuleDescriptor.Requires r : desc.requires()) { System.out.println(mod.getName() + " requires " + r.name()); } System.out.println(); } } }
2,835
0
Create_ds/commons-rng/commons-rng-examples/examples-jpms/jpms-app/src/main/java/org/apache/commons/rng/examples/jpms
Create_ds/commons-rng/commons-rng-examples/examples-jpms/jpms-app/src/main/java/org/apache/commons/rng/examples/jpms/app/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. */ /** * This package contains an application for testing that the library * can be used as a Java 9 Java Platform Module System (JPMS) module. */ package org.apache.commons.rng.examples.jpms.app;
2,836
0
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple/RandomSourceTest.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.simple; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.time.Duration; import java.util.SplittableRandom; import java.util.stream.DoubleStream; import java.util.stream.IntStream; import java.util.stream.LongStream; import org.apache.commons.rng.RandomProviderState; import org.apache.commons.rng.RestorableUniformRandomProvider; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.core.source64.LongProvider; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Tests for {@link RandomSource}. */ class RandomSourceTest { @Test void testCreateInt() { final int n = 4; for (int i = 0; i < n; i++) { // Can fail, but unlikely given the range. Assertions.assertNotEquals(RandomSource.createInt(), RandomSource.createInt()); } } @Test void testCreateLong() { final int n = 6; for (int i = 0; i < n; i++) { // Can fail, but unlikely given the range. Assertions.assertNotEquals(RandomSource.createLong(), RandomSource.createLong()); } } @Test void testCreateIntArray() { final int n = 13; final int[] seed = RandomSource.createIntArray(n); Assertions.assertEquals(n, seed.length); for (int i = 1; i < n; i++) { // Can fail, but unlikely given the range. Assertions.assertNotEquals(seed[i - 1], seed[i]); } } @Test void testCreateLongArray() { final int n = 9; final long[] seed = RandomSource.createLongArray(n); Assertions.assertEquals(n, seed.length); for (int i = 1; i < n; i++) { // Can fail, but unlikely given the range. Assertions.assertNotEquals(seed[i - 1], seed[i]); } } @Test void testIsJumpable() { Assertions.assertFalse(RandomSource.JDK.isJumpable(), "JDK is not Jumpable"); Assertions.assertTrue(RandomSource.XOR_SHIFT_1024_S_PHI.isJumpable(), "XOR_SHIFT_1024_S_PHI is Jumpable"); Assertions.assertTrue(RandomSource.XO_SHI_RO_256_SS.isJumpable(), "XO_SHI_RO_256_SS is Jumpable"); } @Test void testIsLongJumpable() { Assertions.assertFalse(RandomSource.JDK.isLongJumpable(), "JDK is not LongJumpable"); Assertions.assertFalse(RandomSource.XOR_SHIFT_1024_S_PHI.isLongJumpable(), "XOR_SHIFT_1024_S_PHI is not LongJumpable"); Assertions.assertTrue(RandomSource.XO_SHI_RO_256_SS.isLongJumpable(), "XO_SHI_RO_256_SS is LongJumpable"); } @Test void testIsSplittable() { Assertions.assertFalse(RandomSource.JDK.isSplittable(), "JDK is not Splittable"); Assertions.assertTrue(RandomSource.L32_X64_MIX.isSplittable(), "L32_X64_MIX is Splittable"); Assertions.assertTrue(RandomSource.L64_X128_MIX.isSplittable(), "L64_X128_MIX is Splittable"); } /** * MSWS should not infinite loop if the input RNG fails to provide randomness to create a seed. * See RNG-175. */ @Test void testMSWSCreateSeed() { final LongProvider broken = new LongProvider() { @Override public long next() { return 0; } }; Assertions.assertTimeoutPreemptively(Duration.ofMillis(100), () -> { RandomSource.MSWS.createSeed(broken); }); } /** * Test the unrestorable method correctly delegates all methods. * This includes the methods with default implementations in UniformRandomProvider, i.e. * the default methods should not be used. */ @Test void testUnrestorable() { // The test class should override all default methods assertNoDefaultMethods(RestorableRNG.class); final UniformRandomProvider rng1 = new RestorableRNG(); final RestorableRNG r = new RestorableRNG(); final UniformRandomProvider rng2 = RandomSource.unrestorable(r); Assertions.assertNotSame(rng2, r); // The unrestorable instance should override all default methods assertNoDefaultMethods(rng2.getClass()); // Despite the newly created RNG not being a RestorableUniformRandomProvider, // the method still wraps it in a new object. This is the behaviour since version 1.0. // It allows the method to wrap objects that implement UniformRandomProvider (such // as sub-interfaces or concrete classes) to prevent access to any additional methods. Assertions.assertNotSame(rng2, RandomSource.unrestorable(rng2)); // Ensure that they generate the same values. RandomAssert.assertProduceSameSequence(rng1, rng2); // Cast must work. @SuppressWarnings("unused") final RestorableUniformRandomProvider restorable = (RestorableUniformRandomProvider) rng1; // Cast must fail. Assertions.assertThrows(ClassCastException.class, () -> { @SuppressWarnings("unused") final RestorableUniformRandomProvider dummy = (RestorableUniformRandomProvider) rng2; }); } /** * Assert the class has overridden all default public interface methods. * * @param cls the class */ private static void assertNoDefaultMethods(Class<?> cls) { for (final Method method : cls.getMethods()) { if ((method.getModifiers() & Modifier.PUBLIC) != 0) { Assertions.assertTrue(!method.isDefault(), () -> cls.getName() + " should override method: " + method.toGenericString()); } } } /** * Class to provide a complete implementation of the {@link UniformRandomProvider} interface. * This must return a different result than the default implementations in the interface. */ private static class RestorableRNG implements RestorableUniformRandomProvider { /** The source of randomness. */ private final SplittableRandom rng = new SplittableRandom(123); @Override public void nextBytes(byte[] bytes) { nextBytes(bytes, 0, bytes.length); } @Override public void nextBytes(byte[] bytes, int start, int len) { RestorableUniformRandomProvider.super.nextBytes(bytes, start, len); // Rotate for (int i = start + len; i-- > start;) { bytes[i] += 1; } } @Override public int nextInt() { return RestorableUniformRandomProvider.super.nextInt() + 1; } @Override public int nextInt(int n) { final int v = RestorableUniformRandomProvider.super.nextInt(n) + 1; return v == n ? 0 : v; } @Override public int nextInt(int origin, int bound) { final int v = RestorableUniformRandomProvider.super.nextInt(origin, bound) + 1; return v == bound ? origin : v; } @Override public long nextLong() { // Source of randomness for all derived methods return rng.nextLong(); } @Override public long nextLong(long n) { final long v = RestorableUniformRandomProvider.super.nextLong(n) + 1; return v == n ? 0 : v; } @Override public long nextLong(long origin, long bound) { final long v = RestorableUniformRandomProvider.super.nextLong(origin, bound) + 1; return v == bound ? origin : v; } @Override public boolean nextBoolean() { return !RestorableUniformRandomProvider.super.nextBoolean(); } @Override public float nextFloat() { final float v = 1 - RestorableUniformRandomProvider.super.nextFloat(); return v == 1 ? 0 : v; } @Override public float nextFloat(float bound) { final float v = Math.nextUp(RestorableUniformRandomProvider.super.nextFloat(bound)); return v == bound ? 0 : v; } @Override public float nextFloat(float origin, float bound) { final float v = Math.nextUp(RestorableUniformRandomProvider.super.nextFloat(origin, bound)); return v == bound ? 0 : v; } @Override public double nextDouble() { final double v = 1 - RestorableUniformRandomProvider.super.nextDouble(); return v == 1 ? 0 : v; } @Override public double nextDouble(double bound) { final double v = Math.nextUp(RestorableUniformRandomProvider.super.nextDouble(bound)); return v == bound ? 0 : v; } @Override public double nextDouble(double origin, double bound) { final double v = Math.nextUp(RestorableUniformRandomProvider.super.nextDouble(origin, bound)); return v == bound ? 0 : v; } // Stream methods must return different values than the default so we reimplement them @Override public IntStream ints() { return IntStream.generate(() -> nextInt() + 1).sequential(); } @Override public IntStream ints(int origin, int bound) { return IntStream.generate(() -> { final int v = nextInt(origin, bound) + 1; return v == bound ? origin : v; }).sequential(); } @Override public IntStream ints(long streamSize) { return ints().limit(streamSize); } @Override public IntStream ints(long streamSize, int origin, int bound) { return ints(origin, bound).limit(streamSize); } @Override public LongStream longs() { return LongStream.generate(() -> nextLong() + 1).sequential(); } @Override public LongStream longs(long origin, long bound) { return LongStream.generate(() -> { final long v = nextLong(origin, bound) + 1; return v == bound ? origin : v; }).sequential(); } @Override public LongStream longs(long streamSize) { return longs().limit(streamSize); } @Override public LongStream longs(long streamSize, long origin, long bound) { return longs(origin, bound).limit(streamSize); } @Override public DoubleStream doubles() { return DoubleStream.generate(() -> { final double v = Math.nextUp(nextDouble()); return v == 1 ? 0 : v; }).sequential(); } @Override public DoubleStream doubles(double origin, double bound) { return DoubleStream.generate(() -> { final double v = Math.nextUp(nextDouble(origin, bound)); return v == bound ? origin : v; }).sequential(); } @Override public DoubleStream doubles(long streamSize) { return doubles().limit(streamSize); } @Override public DoubleStream doubles(long streamSize, double origin, double bound) { return doubles(origin, bound).limit(streamSize); } @Override public RandomProviderState saveState() { // Do nothing return null; } @Override public void restoreState(RandomProviderState state) { // Do nothing } } }
2,837
0
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple/ProvidersCommonParametricTest.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.simple; import java.util.Arrays; import java.util.List; import java.util.ArrayList; import java.util.function.LongSupplier; import java.util.stream.Collectors; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.ObjectInputStream; import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.JumpableUniformRandomProvider; import org.apache.commons.rng.LongJumpableUniformRandomProvider; import org.apache.commons.rng.RandomProviderState; import org.apache.commons.rng.RestorableUniformRandomProvider; import org.apache.commons.rng.SplittableUniformRandomProvider; import org.apache.commons.rng.core.RandomProviderDefaultState; import org.apache.commons.rng.core.source64.LongProvider; import org.apache.commons.rng.core.source64.SplitMix64; /** * Tests which all generators must pass. */ class ProvidersCommonParametricTest { private static Iterable<ProvidersList.Data> getProvidersTestData() { return ProvidersList.list(); } // Seeding tests. @ParameterizedTest @MethodSource("getProvidersTestData") void testUnsupportedSeedType(ProvidersList.Data data) { final RandomSource originalSource = data.getSource(); final byte seed = 123; final Object[] originalArgs = data.getArgs(); Assertions.assertThrows(UnsupportedOperationException.class, () -> originalSource.create(seed, originalArgs)); } /** * Test the factory create method returns the same class as the instance create method. */ @ParameterizedTest @MethodSource("getProvidersTestData") void testFactoryCreateMethod(ProvidersList.Data data) { final RandomSource originalSource = data.getSource(); final Object originalSeed = data.getSeed(); final Object[] originalArgs = data.getArgs(); // Cannot test providers that require arguments Assumptions.assumeTrue(originalArgs == null); @SuppressWarnings("deprecation") final UniformRandomProvider rng = RandomSource.create(data.getSource()); final UniformRandomProvider generator = originalSource.create(originalSeed, originalArgs); Assertions.assertEquals(generator.getClass(), rng.getClass()); } /** * Test the factory create method returns the same class as the instance create method * and produces the same output. */ @ParameterizedTest @MethodSource("getProvidersTestData") void testFactoryCreateMethodWithSeed(ProvidersList.Data data) { final RandomSource originalSource = data.getSource(); final Object originalSeed = data.getSeed(); final Object[] originalArgs = data.getArgs(); final UniformRandomProvider generator = originalSource.create(originalSeed, originalArgs); @SuppressWarnings("deprecation") final UniformRandomProvider rng1 = RandomSource.create(originalSource, originalSeed, originalArgs); Assertions.assertEquals(rng1.getClass(), generator.getClass()); // Check the output final UniformRandomProvider rng2 = originalSource.create(originalSeed, originalArgs); for (int i = 0; i < 10; i++) { Assertions.assertEquals(rng2.nextLong(), rng1.nextLong()); } } /** * Test the create method throws an {@link IllegalArgumentException} if passed the wrong * arguments. */ @ParameterizedTest @MethodSource("getProvidersTestData") void testCreateMethodThrowsWithIncorrectArguments(ProvidersList.Data data) { final RandomSource originalSource = data.getSource(); final Object[] originalArgs = data.getArgs(); if (originalArgs == null) { // Try passing arguments to a provider that does not require them final int arg1 = 123; final double arg2 = 456.0; Assertions.assertThrows(IllegalArgumentException.class, () -> originalSource.create(arg1, arg2), () -> "Source does not require arguments: " + originalSource); } else { // Try no arguments for a provider that does require them Assertions.assertThrows(IllegalArgumentException.class, () -> originalSource.create(), () -> "Source requires arguments: " + originalSource); } } @ParameterizedTest @MethodSource("getProvidersTestData") void testAllSeedTypes(ProvidersList.Data data) { final RandomSource originalSource = data.getSource(); final Object originalSeed = data.getSeed(); final Object[] originalArgs = data.getArgs(); final Integer intSeed = -12131415; final Long longSeed = -1213141516171819L; final int[] intArraySeed = new int[] {0, 11, -22, 33, -44, 55, -66, 77, -88, 99}; final long[] longArraySeed = new long[] {11111L, -222222L, 3333333L, -44444444L}; final byte[] byteArraySeed = new byte[] {-128, -91, -45, -32, -1, 0, 11, 23, 54, 88, 127}; final Object[] seeds = new Object[] {null, intSeed, longSeed, intArraySeed, longArraySeed, byteArraySeed}; int nonNativeSeedCount = 0; int seedCount = 0; for (final Object s : seeds) { ++seedCount; if (originalSource.isNativeSeed(s)) { Assertions.assertNotNull(s, "Identified native seed is null"); Assertions.assertEquals(s.getClass(), originalSeed.getClass(), "Incorrect identification of native seed type"); } else { ++nonNativeSeedCount; } originalSource.create(s, originalArgs); } Assertions.assertEquals(6, seedCount); Assertions.assertEquals(5, nonNativeSeedCount); } @ParameterizedTest @MethodSource("getProvidersTestData") void testNullSeed(ProvidersList.Data data) { final RandomSource originalSource = data.getSource(); final Object[] originalArgs = data.getArgs(); // Note: This is the only test that explicitly calls RandomSource.create() with no other arguments. final UniformRandomProvider rng = originalArgs == null ? originalSource.create() : originalSource.create(null, originalArgs); checkNextIntegerInRange(rng, 10, 10000); } @ParameterizedTest @MethodSource("getProvidersTestData") void testEmptyIntArraySeed(ProvidersList.Data data) { final RandomSource originalSource = data.getSource(); final Object[] originalArgs = data.getArgs(); final int[] empty = new int[0]; Assumptions.assumeTrue(originalSource.isNativeSeed(empty)); // Exercise the default seeding procedure. final UniformRandomProvider rng = originalSource.create(empty, originalArgs); checkNextIntegerInRange(rng, 10, 20000); } @ParameterizedTest @MethodSource("getProvidersTestData") void testEmptyLongArraySeed(ProvidersList.Data data) { final RandomSource originalSource = data.getSource(); final Object[] originalArgs = data.getArgs(); final long[] empty = new long[0]; Assumptions.assumeTrue(originalSource.isNativeSeed(empty)); // Exercise the default seeding procedure. final UniformRandomProvider rng = originalSource.create(empty, originalArgs); checkNextIntegerInRange(rng, 10, 10000); } @ParameterizedTest @MethodSource("getProvidersTestData") void testZeroIntArraySeed(ProvidersList.Data data) { final RandomSource originalSource = data.getSource(); final Object[] originalArgs = data.getArgs(); // Exercise capacity to escape all "zero" state. final int[] zero = new int[2000]; // Large enough to fill the entire state with zeroes. final UniformRandomProvider rng = originalSource.create(zero, originalArgs); Assumptions.assumeTrue(createsNonZeroLongOutput(rng, 2000), () -> "RNG is non-functional with an all zero seed: " + originalSource); checkNextIntegerInRange(rng, 10, 10000); } @ParameterizedTest @MethodSource("getProvidersTestData") void testZeroLongArraySeed(ProvidersList.Data data) { final RandomSource originalSource = data.getSource(); final Object[] originalArgs = data.getArgs(); // Exercise capacity to escape all "zero" state. final long[] zero = new long[2000]; // Large enough to fill the entire state with zeroes. final UniformRandomProvider rng = originalSource.create(zero, originalArgs); Assumptions.assumeTrue(createsNonZeroLongOutput(rng, 2000), () -> "RNG is non-functional with an all zero seed: " + originalSource); checkNextIntegerInRange(rng, 10, 10000); } @ParameterizedTest @MethodSource("getProvidersTestData") void testRandomSourceCreateSeed(ProvidersList.Data data) { final RandomSource originalSource = data.getSource(); final Object[] originalArgs = data.getArgs(); final byte[] seed = originalSource.createSeed(); final UniformRandomProvider rng = originalSource.create(seed, originalArgs); checkNextIntegerInRange(rng, 10, 10000); } @ParameterizedTest @MethodSource("getProvidersTestData") void testRandomSourceCreateSeedFromRNG(ProvidersList.Data data) { final RandomSource originalSource = data.getSource(); final Object[] originalArgs = data.getArgs(); final byte[] seed = originalSource.createSeed(new SplitMix64(RandomSource.createLong())); final UniformRandomProvider rng = originalSource.create(seed, originalArgs); checkNextIntegerInRange(rng, 10, 10000); } @ParameterizedTest @MethodSource("getProvidersTestData") void testRandomSourceCreateSeedFromInvalidRNG(ProvidersList.Data data) { // Create a RNG that will fill a byte[] seed with all zeros. // The ensure non-zero range checks in the RandomSource should // create a good seed and a functional RNG. final LongProvider badRng = new LongProvider() { @Override public long next() { return 0; } }; final RandomSource originalSource = data.getSource(); final byte[] seed = originalSource.createSeed(badRng); // The seed generation should be repeatable Assertions.assertArrayEquals(seed, originalSource.createSeed(badRng)); // The RNG seed will create a functional generator final Object[] originalArgs = data.getArgs(); final UniformRandomProvider rng = originalSource.create(seed, originalArgs); checkNextIntegerInRange(rng, 10, 10000); } // State save and restore tests. @SuppressWarnings("unused") @ParameterizedTest @MethodSource("getProvidersTestData") void testUnrestorable(ProvidersList.Data data) { final RandomSource originalSource = data.getSource(); final Object originalSeed = data.getSeed(); final Object[] originalArgs = data.getArgs(); // Create two generators of the same type as the one being tested. final UniformRandomProvider rng1 = originalSource.create(originalSeed, originalArgs); final UniformRandomProvider rng2 = RandomSource.unrestorable(originalSource.create(originalSeed, originalArgs)); // Ensure that they generate the same values. RandomAssert.assertProduceSameSequence(rng1, rng2); // Cast must work. final RestorableUniformRandomProvider restorable = (RestorableUniformRandomProvider) rng1; // Cast must fail. Assertions.assertThrows(ClassCastException.class, () -> { final RestorableUniformRandomProvider dummy = (RestorableUniformRandomProvider) rng2; }); } @ParameterizedTest @MethodSource("getProvidersTestData") void testSerializingState(ProvidersList.Data data) throws IOException, ClassNotFoundException { final UniformRandomProvider generator = data.getSource().create(data.getSeed(), data.getArgs()); // Large "n" is not necessary here as we only test the serialization. final int n = 100; // Cast is OK: all instances created by this library inherit from "BaseProvider". final RestorableUniformRandomProvider restorable = (RestorableUniformRandomProvider) generator; // Save. final RandomProviderState stateOrig = restorable.saveState(); // Serialize. final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(((RandomProviderDefaultState) stateOrig).getState()); // Store some values. final List<Number> listOrig = makeList(n, generator); // Discard a few more. final List<Number> listDiscard = makeList(n, generator); Assertions.assertNotEquals(0, listDiscard.size()); Assertions.assertNotEquals(listOrig, listDiscard); // Retrieve from serialized stream. final ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); final ObjectInputStream ois = new ObjectInputStream(bis); final RandomProviderState stateNew = new RandomProviderDefaultState((byte[]) ois.readObject()); Assertions.assertNotSame(stateOrig, stateNew); // Reset. restorable.restoreState(stateNew); // Replay. final List<Number> listReplay = makeList(n, generator); Assertions.assertNotSame(listOrig, listReplay); // Check that the serialized data recreated the orginal state. Assertions.assertEquals(listOrig, listReplay); } @ParameterizedTest @MethodSource("getProvidersTestData") void testUnrestorableToString(ProvidersList.Data data) { final UniformRandomProvider generator = data.getSource().create(data.getSeed(), data.getArgs()); Assertions.assertEquals(generator.toString(), RandomSource.unrestorable(generator).toString()); } @ParameterizedTest @MethodSource("getProvidersTestData") void testSupportedInterfaces(ProvidersList.Data data) { final RandomSource originalSource = data.getSource(); final Object[] originalArgs = data.getArgs(); final UniformRandomProvider rng = originalSource.create(null, originalArgs); Assertions.assertEquals(rng instanceof JumpableUniformRandomProvider, originalSource.isJumpable(), "isJumpable"); Assertions.assertEquals(rng instanceof LongJumpableUniformRandomProvider, originalSource.isLongJumpable(), "isLongJumpable"); Assertions.assertEquals(rng instanceof SplittableUniformRandomProvider, originalSource.isSplittable(), "isSplittable"); } ///// Support methods below. // The methods // * makeList // * checkNextIntegerInRange // * checkNextInRange // have been copied from "src/test" in module "commons-rng-core". // TODO: check whether it is possible to have a single implementation. /** * Populates a list with random numbers. * * @param n Loop counter. * @param generator Random generator. * @return a list containing {@code 11 * n} random numbers. */ private static List<Number> makeList(int n, UniformRandomProvider generator) { final List<Number> list = new ArrayList<>(); for (int i = 0; i < n; i++) { // Append 11 values. list.add(generator.nextInt()); list.add(generator.nextInt(21)); list.add(generator.nextInt(436)); list.add(generator.nextLong()); list.add(generator.nextLong(157894)); list.add(generator.nextLong(5745833)); list.add(generator.nextFloat()); list.add(generator.nextFloat()); list.add(generator.nextDouble()); list.add(generator.nextDouble()); list.add(generator.nextBoolean() ? 1 : 0); } return list; } /** * Tests uniformity of the distribution produced by {@code nextInt(int)}. * * @param rng Generator. * @param max Upper bound. * @param sampleSize Number of random values generated. * @param generator Random generator. */ private static void checkNextIntegerInRange(final UniformRandomProvider rng, final int max, int sampleSize) { final LongSupplier nextMethod = () -> rng.nextInt(max); checkNextInRange(rng, max, sampleSize, nextMethod); } /** * Tests uniformity of the distribution produced by the given * {@code nextMethod}. * It performs a chi-square test of homogeneity of the observed * distribution with the expected uniform distribution. * Repeat tests are performed at the 1% level and the total number of failed * tests is tested at the 0.5% significance level. * * @param n Upper bound. * @param nextMethod method to call. * @param sampleSize Number of random values generated. * @param generator Random generator. */ private static void checkNextInRange(UniformRandomProvider generator, long n, int sampleSize, LongSupplier nextMethod) { final int numTests = 500; // Do not change (statistical test assumes that dof = 9). final int numBins = 10; // dof = numBins - 1 // Set up bins. final long[] binUpperBounds = new long[numBins]; final double step = n / (double) numBins; for (int k = 0; k < numBins; k++) { binUpperBounds[k] = (long) ((k + 1) * step); } // Rounding error occurs on the long value of 2305843009213693951L binUpperBounds[numBins - 1] = n; // Run the tests. int numFailures = 0; final double[] expected = new double[numBins]; long previousUpperBound = 0; for (int k = 0; k < numBins; k++) { final long range = binUpperBounds[k] - previousUpperBound; expected[k] = sampleSize * (range / (double) n); previousUpperBound = binUpperBounds[k]; } final int[] observed = new int[numBins]; // Chi-square critical value with 9 degrees of freedom // and 1% significance level. final double chi2CriticalValue = 21.665994333461924; // For storing chi2 larger than the critical value. final List<Double> failedStat = new ArrayList<>(); try { final int lastDecileIndex = numBins - 1; for (int i = 0; i < numTests; i++) { Arrays.fill(observed, 0); SAMPLE: for (int j = 0; j < sampleSize; j++) { final long value = nextMethod.getAsLong(); Assertions.assertTrue(value >= 0 && value < n, "Range"); for (int k = 0; k < lastDecileIndex; k++) { if (value < binUpperBounds[k]) { ++observed[k]; continue SAMPLE; } } ++observed[lastDecileIndex]; } // Compute chi-square. double chi2 = 0; for (int k = 0; k < numBins; k++) { final double diff = observed[k] - expected[k]; chi2 += diff * diff / expected[k]; } // Statistics check. if (chi2 > chi2CriticalValue) { failedStat.add(chi2); ++numFailures; } } } catch (final Exception e) { // Should never happen. throw new RuntimeException("Unexpected", e); } // The expected number of failed tests can be modelled as a Binomial distribution // B(n, p) with n=500, p=0.01 (500 tests with a 1% significance level). // The cumulative probability of the number of failed tests (X) is: // x P(X>x) // 10 0.0132 // 11 0.00521 // 12 0.00190 if (numFailures > 11) { // Test will fail with 0.5% probability Assertions.fail(String.format( "%s: Too many failures for n = %d, sample size = %d " + "(%d out of %d tests failed, chi2 > %.3f=%s)", generator, n, sampleSize, numFailures, numTests, chi2CriticalValue, failedStat.stream().map(d -> String.format("%.3f", d)) .collect(Collectors.joining(", ", "[", "]")))); } } /** * Return true if the generator creates non-zero output from * {@link UniformRandomProvider#nextLong()} within the given number of cycles. * * @param rng Random generator. * @param cycles Number of cycles. * @return true if non-zero output */ private static boolean createsNonZeroLongOutput(UniformRandomProvider rng, int cycles) { boolean nonZero = false; for (int i = 0; i < cycles; i++) { if (rng.nextLong() != 0) { nonZero = true; } } return nonZero; } }
2,838
0
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple/JDKRandomWrapperTest.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.simple; import java.util.Random; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.core.source64.LongProvider; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Tests for the {@link JDKRandomWrapper} class. */ class JDKRandomWrapperTest { /** * Test all the methods shared by Random and UniformRandomProvider are equivalent. */ @Test void testJDKRandomEquivalence() { // Initialize. final long seed = RandomSource.createLong(); final Random rng1 = new Random(seed); final UniformRandomProvider rng2 = new JDKRandomWrapper(new Random(seed)); checkSameSequence(rng1, rng2); } /** * Ensure that both generators produce the same sequences. * * @param rng1 RNG. * @param rng2 RNG. */ private static void checkSameSequence(Random rng1, UniformRandomProvider rng2) { for (int i = 0; i < 4; i++) { Assertions.assertEquals(rng1.nextInt(), rng2.nextInt()); } for (int i = 0; i < 7; i++) { Assertions.assertEquals(rng1.nextLong(), rng2.nextLong()); } for (int i = 0; i < 9; i++) { Assertions.assertEquals(rng1.nextFloat(), rng2.nextFloat()); } for (int i = 0; i < 12; i++) { Assertions.assertEquals(rng1.nextDouble(), rng2.nextDouble()); } for (int i = 0; i < 18; i++) { Assertions.assertEquals(rng1.nextBoolean(), rng2.nextBoolean()); } for (int i = 0; i < 19; i++) { final int max = i + 123456; Assertions.assertEquals(rng1.nextInt(max), rng2.nextInt(max)); } final int len = 233; final byte[] store1 = new byte[len]; final byte[] store2 = new byte[len]; rng1.nextBytes(store1); rng2.nextBytes(store2); for (int i = 0; i < len; i++) { Assertions.assertEquals(store1[i], store2[i]); } } /** * Test {@link UniformRandomProvider#nextLong(long)} matches that from the core * BaseProvider implementation. */ @Test void testNextLongInRange() { final long seed = RandomSource.createLong(); // This will use the RNG core BaseProvider implementation. // Use a LongProvider to directly use the Random::nextLong method // which is different from IntProvider::nextLong. final UniformRandomProvider rng1 = new LongProvider() { private final Random random = new Random(seed); @Override public long next() { return random.nextLong(); } }; final UniformRandomProvider rng2 = new JDKRandomWrapper(new Random(seed)); // Test cases // 1 : Smallest range // 256 : Integer power of 2 // 56757 : Integer range // 1L << 32 : Non-integer power of 2 // (1L << 62) + 1 : Worst case for rejection rate for the algorithm. // Reject probability is approximately 0.5 thus the test hits // all code paths. for (final long max : new long[] {1, 256, 56757, 1L << 32, (1L << 62) + 1}) { for (int i = 0; i < 10; i++) { Assertions.assertEquals(rng1.nextLong(max), rng2.nextLong(max)); } } } @Test void testNextLongInRangeThrows() { final UniformRandomProvider rng1 = new JDKRandomWrapper(new Random(5675767L)); Assertions.assertThrows(IllegalArgumentException.class, () -> rng1.nextLong(0)); } /** * Test the bytes created by {@link UniformRandomProvider#nextBytes(byte[], int, int)} matches * {@link Random#nextBytes(byte[])}. */ @Test void testNextByteInRange() { final long seed = RandomSource.createLong(); final Random rng1 = new Random(seed); final UniformRandomProvider rng2 = new JDKRandomWrapper(new Random(seed)); checkSameBytes(rng1, rng2, 1, 0, 1); checkSameBytes(rng1, rng2, 100, 0, 100); checkSameBytes(rng1, rng2, 100, 10, 90); checkSameBytes(rng1, rng2, 245, 67, 34); } /** * Ensure that the bytes produced in a sub-range of a byte array by * {@link UniformRandomProvider#nextBytes(byte[], int, int)} match the bytes created * by the JDK {@link Random#nextBytes(byte[])}. * * @param rng1 JDK Random. * @param rng2 RNG. * @param size Size of byte array. * @param start Index at which to start inserting the generated bytes. * @param len Number of bytes to insert. */ private static void checkSameBytes(Random rng1, UniformRandomProvider rng2, int size, int start, int length) { final byte[] store1 = new byte[length]; final byte[] store2 = new byte[size]; rng1.nextBytes(store1); rng2.nextBytes(store2, start, length); for (int i = 0; i < length; i++) { Assertions.assertEquals(store1[i], store2[i + start]); } } }
2,839
0
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple/JDKRandomBridgeTest.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.simple; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.ObjectInputStream; import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; import java.util.Random; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Tests for the {@link JDKRandomBridge} adaptor class. */ class JDKRandomBridgeTest { @Test void testJDKRandomEquivalence() { // Initialize. final long seed = RandomSource.createLong(); final Random rng1 = new Random(seed); final Random rng2 = new JDKRandomBridge(RandomSource.JDK, seed); checkSameSequence(rng1, rng2); // Reseed. final long newSeed = RandomSource.createLong(); Assertions.assertNotEquals(seed, newSeed); rng1.setSeed(newSeed); rng2.setSeed(newSeed); checkSameSequence(rng1, rng2); } @Test void testSerialization() throws IOException, ClassNotFoundException { // Initialize. final long seed = RandomSource.createLong(); final Random rng = new JDKRandomBridge(RandomSource.SPLIT_MIX_64, seed); // Serialize. final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(rng); // Retrieve from serialized stream. final ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); final ObjectInputStream ois = new ObjectInputStream(bis); final Random serialRng = (Random) (ois.readObject()); // Check that the serialized data recreated the original state. checkSameSequence(rng, serialRng); } /** * Ensure that both generators produce the same sequences. * * @param rng1 RNG. * @param rng2 RNG. */ private void checkSameSequence(Random rng1, Random rng2) { for (int i = 0; i < 4; i++) { Assertions.assertEquals(rng1.nextInt(), rng2.nextInt()); } for (int i = 0; i < 7; i++) { Assertions.assertEquals(rng1.nextLong(), rng2.nextLong()); } for (int i = 0; i < 9; i++) { Assertions.assertEquals(rng1.nextFloat(), rng2.nextFloat()); } for (int i = 0; i < 12; i++) { Assertions.assertEquals(rng1.nextDouble(), rng2.nextDouble()); } for (int i = 0; i < 17; i++) { Assertions.assertEquals(rng1.nextGaussian(), rng2.nextGaussian()); } for (int i = 0; i < 18; i++) { Assertions.assertEquals(rng1.nextBoolean(), rng2.nextBoolean()); } for (int i = 0; i < 19; i++) { final int max = i + 123456; Assertions.assertEquals(rng1.nextInt(max), rng2.nextInt(max)); } final int len = 233; final byte[] store1 = new byte[len]; final byte[] store2 = new byte[len]; rng1.nextBytes(store1); rng2.nextBytes(store2); for (int i = 0; i < len; i++) { Assertions.assertEquals(store1[i], store2[i]); } } }
2,840
0
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple/RandomAssert.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.simple; import org.junit.jupiter.api.Assertions; import org.apache.commons.rng.UniformRandomProvider; /** * Utility class for testing random generators. */ public final class RandomAssert { /** * Class contains only static methods. */ private RandomAssert() {} /** * Exercise all methods from the UniformRandomProvider interface, and * ensure that the two generators produce the same sequence. * * @param rng1 RNG. * @param rng2 RNG. */ public static void assertProduceSameSequence(UniformRandomProvider rng1, UniformRandomProvider rng2) { for (int i = 0; i < 54; i++) { Assertions.assertEquals(rng1.nextBoolean(), rng2.nextBoolean()); } for (int i = 0; i < 23; i++) { Assertions.assertEquals(rng1.nextInt(), rng2.nextInt()); } for (int i = 0; i < 4; i++) { final int min = 31 * i + 3; for (int j = 0; j < 5; j++) { final int max = 107 * i + 374 * j + 11; Assertions.assertEquals(rng1.nextInt(max), rng2.nextInt(max)); Assertions.assertEquals(rng1.nextInt(min, max), rng2.nextInt(min, max)); } } for (int i = 0; i < 23; i++) { Assertions.assertEquals(rng1.nextLong(), rng2.nextLong()); } for (int i = 0; i < 4; i++) { final int min = 31 * i + 3; for (int j = 0; j < 5; j++) { final long max = (Long.MAX_VALUE >> 2) + 107 * i + 374 * j + 11; Assertions.assertEquals(rng1.nextLong(max), rng2.nextLong(max)); Assertions.assertEquals(rng1.nextLong(min, max), rng2.nextLong(min, max)); } } for (int i = 0; i < 35; i++) { Assertions.assertEquals(rng1.nextFloat(), rng2.nextFloat()); Assertions.assertEquals(rng1.nextFloat(12.34f), rng2.nextFloat(12.34f)); Assertions.assertEquals(rng1.nextFloat(1.23f, 12.34f), rng2.nextFloat(1.23f, 12.34f)); } for (int i = 0; i < 27; i++) { Assertions.assertEquals(rng1.nextDouble(), rng2.nextDouble()); Assertions.assertEquals(rng1.nextDouble(12.34), rng2.nextDouble(12.34)); Assertions.assertEquals(rng1.nextDouble(1.23, 12.34), rng2.nextDouble(1.23, 12.34)); } final int size = 345; final byte[] a1 = new byte[size]; final byte[] a2 = new byte[size]; for (int i = 0; i < 3; i++) { rng1.nextBytes(a1); rng2.nextBytes(a2); Assertions.assertArrayEquals(a1, a2); } for (int i = 0; i < 5; i++) { final int offset = 200 + i; final int n = 23 + i; rng1.nextBytes(a1, offset, n); rng2.nextBytes(a2, offset, n); Assertions.assertArrayEquals(a1, a2); } // Streams Assertions.assertArrayEquals(rng1.ints().limit(4).toArray(), rng2.ints().limit(4).toArray()); Assertions.assertArrayEquals(rng1.ints(5).toArray(), rng2.ints(5).toArray()); Assertions.assertArrayEquals(rng1.ints(-3, 12).limit(4).toArray(), rng2.ints(-3, 12).limit(4).toArray()); Assertions.assertArrayEquals(rng1.ints(5, -13, 2).toArray(), rng2.ints(5, -13, 2).toArray()); Assertions.assertArrayEquals(rng1.longs().limit(4).toArray(), rng2.longs().limit(4).toArray()); Assertions.assertArrayEquals(rng1.longs(5).toArray(), rng2.longs(5).toArray()); Assertions.assertArrayEquals(rng1.longs(-3, 12).limit(4).toArray(), rng2.longs(-3, 12).limit(4).toArray()); Assertions.assertArrayEquals(rng1.longs(5, -13, 2).toArray(), rng2.longs(5, -13, 2).toArray()); Assertions.assertArrayEquals(rng1.doubles().limit(4).toArray(), rng2.doubles().limit(4).toArray()); Assertions.assertArrayEquals(rng1.doubles(5).toArray(), rng2.doubles(5).toArray()); Assertions.assertArrayEquals(rng1.doubles(-3, 12).limit(4).toArray(), rng2.doubles(-3, 12).limit(4).toArray()); Assertions.assertArrayEquals(rng1.doubles(5, -13, 2).toArray(), rng2.doubles(5, -13, 2).toArray()); } }
2,841
0
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple/ProvidersList.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.simple; import java.util.Arrays; import java.util.List; import java.util.ArrayList; import java.util.Collections; /** * The purpose of this class is to provide the list of all generators * implemented in the library. * The list must be updated with each new RNG implementation. * * @see #list() * @see #list32() * @see #list64() */ public final class ProvidersList { /** List of all RNGs implemented in the library. */ private static final List<Data> LIST = new ArrayList<>(); /** List of 32-bits based RNGs. */ private static final List<Data> LIST32 = new ArrayList<>(); /** List of 64-bits based RNGs. */ private static final List<Data> LIST64 = new ArrayList<>(); static { try { // "int"-based RNGs. add(LIST32, RandomSource.JDK, -122333444455555L); add(LIST32, RandomSource.MT, new int[] {-123, -234, -345}); add(LIST32, RandomSource.WELL_512_A, new int[] {-23, -34, -45}); add(LIST32, RandomSource.WELL_1024_A, new int[] {-1234, -2345, -3456}); add(LIST32, RandomSource.WELL_19937_A, new int[] {-2123, -3234, -4345}); add(LIST32, RandomSource.WELL_19937_C, new int[] {-123, -234, -345, -456}); add(LIST32, RandomSource.WELL_44497_A, new int[] {-12345, -23456, -34567}); add(LIST32, RandomSource.WELL_44497_B, new int[] {123, 234, 345}); add(LIST32, RandomSource.ISAAC, new int[] {123, -234, 345, -456}); add(LIST32, RandomSource.MWC_256, new int[] {12, -1234, -3456, 45678}); add(LIST32, RandomSource.KISS, new int[] {12, 1234, 23456, 345678}); add(LIST32, RandomSource.XO_RO_SHI_RO_64_S, new int[] {42, 12345}); add(LIST32, RandomSource.XO_RO_SHI_RO_64_SS, new int[] {78942, 134}); add(LIST32, RandomSource.XO_SHI_RO_128_PLUS, new int[] {565642, 1234, 4534}); add(LIST32, RandomSource.XO_SHI_RO_128_SS, new int[] {89, 1234, 6787}); add(LIST32, RandomSource.PCG_XSH_RR_32, new long[] {1738L, 1234L}); add(LIST32, RandomSource.PCG_XSH_RS_32, new long[] {259L, 2861L}); add(LIST32, RandomSource.PCG_MCG_XSH_RS_32, 9678L); add(LIST32, RandomSource.PCG_MCG_XSH_RR_32, 2578291L); // Ensure a high complexity increment is used for the Weyl sequence otherwise // it will not output random data. add(LIST32, RandomSource.MSWS, new long[] {687233648L, 678656564562300L, 0xb5ad4eceda1ce2a9L}); add(LIST32, RandomSource.SFC_32, new int[] {-23574234, 7654343}); add(LIST32, RandomSource.XO_SHI_RO_128_PP, new int[] {8796823, -3244890, -263842}); add(LIST32, RandomSource.PCG_XSH_RR_32_OS, 72346247L); add(LIST32, RandomSource.PCG_XSH_RS_32_OS, -5340832872354L); add(LIST32, RandomSource.L32_X64_MIX, new int[] {2134678128, -162788128}); // ... add more here. // "long"-based RNGs. add(LIST64, RandomSource.SPLIT_MIX_64, -988777666655555L); add(LIST64, RandomSource.XOR_SHIFT_1024_S, new long[] {123456L, 234567L, -345678L}); add(LIST64, RandomSource.XOR_SHIFT_1024_S_PHI, new long[] {-234567L, -345678L, 3456789L}); add(LIST64, RandomSource.TWO_CMRES, 55443322); add(LIST64, RandomSource.TWO_CMRES_SELECT, -987654321, 5, 8); add(LIST64, RandomSource.MT_64, new long[] {1234567L, 2345678L, -3456789L}); add(LIST64, RandomSource.XO_RO_SHI_RO_128_PLUS, new long[] {55646L, -456659L, 565656L}); add(LIST64, RandomSource.XO_RO_SHI_RO_128_SS, new long[] {45655L, 5454544L, 4564659L}); add(LIST64, RandomSource.XO_SHI_RO_256_PLUS, new long[] {11222L, -568989L, -456789L}); add(LIST64, RandomSource.XO_SHI_RO_256_SS, new long[] {98765L, -2345678L, -3456789L}); add(LIST64, RandomSource.XO_SHI_RO_512_PLUS, new long[] {89932L, -545669L, 4564689L}); add(LIST64, RandomSource.XO_SHI_RO_512_SS, new long[] {123L, -654654L, 45646789L}); add(LIST64, RandomSource.PCG_RXS_M_XS_64, new long[] {42088L, 69271L}); add(LIST64, RandomSource.SFC_64, new long[] {-2357423478979842L, 76543434515L}); add(LIST64, RandomSource.XO_RO_SHI_RO_128_PP, new long[] {789741321465L, -461321684612L, -12301654794L}); add(LIST64, RandomSource.XO_SHI_RO_256_PP, new long[] {2374243L, -8097397345383L, -223479293943L}); add(LIST64, RandomSource.XO_SHI_RO_512_PP, new long[] {-1210684761321465L, -485132198745L, 89942134798523L}); add(LIST64, RandomSource.XO_RO_SHI_RO_1024_PP, new long[] {236424345654L, 781544546164721L, -85235476312346L}); add(LIST64, RandomSource.XO_RO_SHI_RO_1024_S, new long[] {-1574314L, 7879874453221215L, -7894343883216L}); add(LIST64, RandomSource.XO_RO_SHI_RO_1024_SS, new long[] {-41514541234654321L, -12146412316546L, 7984134134L}); add(LIST64, RandomSource.PCG_RXS_M_XS_64_OS, -34657834534L); add(LIST64, RandomSource.L64_X128_SS, new long[] {-2379479823783L, -235642384324L, 123678172804389L}); add(LIST64, RandomSource.L64_X128_MIX, new long[] {-9723846672394L, 623748567398002L, -23678792345897934L}); add(LIST64, RandomSource.L64_X256_MIX, new long[] {236784568279L, 237894579279L, -2378945793L}); add(LIST64, RandomSource.L64_X1024_MIX, new long[] {279834579232345L, -2374689578237L, -2347895789327L}); add(LIST64, RandomSource.L128_X128_MIX, new long[] {236748567823789L, 237485792375L, 2374895789324L}); add(LIST64, RandomSource.L128_X256_MIX, new long[] {-829345782324L, -92304897238673245L, 28974785792345L}); add(LIST64, RandomSource.L128_X1024_MIX, new long[] {-6563745678920234L, 7348578274523L, 234523455234L}); // ... add more here. // Do not modify the remaining statements. // Complete list. LIST.addAll(LIST32); LIST.addAll(LIST64); } catch (final Exception e) { // CHECKSTYLE: stop Regexp System.err.println("Unexpected exception while creating the list of generators: " + e); e.printStackTrace(System.err); // CHECKSTYLE: resume Regexp throw new RuntimeException(e); } } /** * Class contains only static methods. */ private ProvidersList() {} /** * Helper to statisfy Junit requirement that each parameter set contains * the same number of objects. */ private static void add(List<Data> list, RandomSource source, Object... data) { final RandomSource rng = source; final Object seed = data.length > 0 ? data[0] : null; final Object[] args = data.length > 1 ? Arrays.copyOfRange(data, 1, data.length) : null; list.add(new Data(rng, seed, args)); } /** * Subclasses that are "parametric" tests can forward the call to * the "@Parameters"-annotated method to this method. * * @return the list of all generators. */ public static Iterable<Data> list() { return Collections.unmodifiableList(LIST); } /** * Subclasses that are "parametric" tests can forward the call to * the "@Parameters"-annotated method to this method. * * @return the list of 32-bits based generators. */ public static Iterable<Data> list32() { return Collections.unmodifiableList(LIST32); } /** * Subclasses that are "parametric" tests can forward the call to * the "@Parameters"-annotated method to this method. * * @return the list of 64-bits based generators. */ public static Iterable<Data> list64() { return Collections.unmodifiableList(LIST64); } /** * Helper. * Better not to mix Junit assumptions of the usage of "Object[]". */ public static class Data { /** RNG specifier. */ private final RandomSource source; /** Seed (constructor's first parameter). */ private final Object seed; /** Constructor's additional parameters. */ private final Object[] args; /** * @param source RNG specifier. * @param seed Seed (constructor's first parameter). * @param args Constructor's additional parameters. */ public Data(RandomSource source, Object seed, Object[] args) { this.source = source; this.seed = seed; this.args = args; } /** * Gets the RNG specifier. * * @return RNG specifier. */ public RandomSource getSource() { return source; } /** * Gets the seed (constructor's first parameter). * * @return Seed */ public Object getSeed() { return seed; } /** * Gets the constructor's additional parameters. * * @return Additional parameters. */ public Object[] getArgs() { return args == null ? null : Arrays.copyOf(args, args.length); } @Override public String toString() { return source.toString() + " seed=" + seed + " args=" + Arrays.toString(args); } } }
2,842
0
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple/ThreadLocalRandomSourceTest.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.simple; import org.apache.commons.rng.UniformRandomProvider; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.util.EnumSet; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * Tests for {@link ThreadLocalRandomSource}. */ class ThreadLocalRandomSourceTest { /** * A set of all the RandomSource options that requires arguments. This should be * ignored in certain tests since they are not supported. */ private static EnumSet<RandomSource> toIgnore; @BeforeAll public static void createToIgnoreSet() { toIgnore = EnumSet.of(RandomSource.TWO_CMRES_SELECT); } @Test void testCurrentThrowsForNullRandomSource() { Assertions.assertThrows(IllegalArgumentException.class, () -> ThreadLocalRandomSource.current(null)); } @Test void testCurrentThrowsForRandomSourceWithDataArguments() { Assertions.assertThrows(IllegalArgumentException.class, () -> ThreadLocalRandomSource.current(RandomSource.TWO_CMRES_SELECT)); } @Test void testCurrentForAllRandomSources() throws InterruptedException, ExecutionException, TimeoutException { final RandomSource[] sources = RandomSource.values(); final UniformRandomProvider[] rngs = new UniformRandomProvider[sources.length]; for (int i = 0; i < sources.length; i++) { final RandomSource source = sources[i]; if (toIgnore.contains(source)) { continue; } final UniformRandomProvider rng = getCurrent(source); Assertions.assertNotNull(rng, () -> "Failed to create source: " + source); rngs[i] = rng; } for (int i = 0; i < sources.length; i++) { final RandomSource source = sources[i]; if (toIgnore.contains(source)) { continue; } final UniformRandomProvider rng = getCurrent(source); Assertions.assertSame(rngs[i], rng, () -> "Failed to return same source: " + source); } // Build on a new thread final UniformRandomProvider[] rngs2 = new UniformRandomProvider[rngs.length]; final ExecutorService executor = Executors.newFixedThreadPool(1); final Future<?> future = executor.submit( new Runnable() { @Override public void run() { for (int i = 0; i < sources.length; i++) { if (toIgnore.contains(sources[i])) { continue; } rngs2[i] = getCurrent(sources[i]); } } }); // Shutdown and wait for task to end executor.shutdown(); future.get(30, TimeUnit.SECONDS); // The RNG from the new thread should be different for (int i = 0; i < sources.length; i++) { final RandomSource source = sources[i]; if (toIgnore.contains(source)) { continue; } Assertions.assertNotSame(rngs[i], rngs2[i], () -> "Failed to return different source: " + source); } } private static UniformRandomProvider getCurrent(RandomSource source) { try { return ThreadLocalRandomSource.current(source); } catch (final RuntimeException ex) { throw new RuntimeException("Failed to get current: " + source, ex); } } }
2,843
0
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple/internal/NativeSeedTypeTest.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.simple.internal; import java.math.BigDecimal; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Arrays; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.IntStream; import java.util.stream.LongStream; import org.apache.commons.rng.core.source64.SplitMix64; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.MethodSource; /** * Tests for the {@link NativeSeedType} factory seed conversions. * * <p>Note: All supported types are tested in the {@link NativeSeedTypeParametricTest}. */ class NativeSeedTypeTest { /** * Perform the reference int to long conversion. * This may change between release versions. * The reference implementation is to create a long using a SplitMix64 generator. * * @param v Value * @return the result */ private static long int2long(int v) { return new SplitMix64(v).nextLong(); } /** * Perform the reference long to int[] conversion. * This may change between release versions. * The reference implementation is to create a long[] using a SplitMix64 generator * and split each into an int, least significant bytes first. * * @param v Value * @param length Array length * @return the result */ private static int[] long2intArray(long v, int length) { class LoHiSplitMix64 extends SplitMix64 { /** Cache part of the most recently generated long value. * Store the upper 32-bits from nextLong() in the lower half * and all zero bits in the upper half when cached. * Set to -1 when empty and requires a refill. */ private long next = -1; LoHiSplitMix64(long seed) { super(seed); } @Override public int nextInt() { long l = next; if (l < 0) { l = nextLong(); // Reserve the upper 32-bits next = l >>> 32; // Return the lower 32-bits return (int) l; } // Clear cache and return the previous upper 32-bits next = -1; return (int) l; } } return IntStream.generate(new LoHiSplitMix64(v)::nextInt).limit(length).toArray(); } /** * Perform the reference long to long[] conversion. * This may change between release versions. * The reference implementation is to create a long[] using a SplitMix64 generator. * * @param v Value * @param length Array length * @return the result */ private static long[] long2longArray(long v, int length) { return LongStream.generate(new SplitMix64(v)::nextLong).limit(length).toArray(); } /** * Gets the lengths for the byte[] seeds to convert. * * @return the lengths */ static IntStream getByteLengths() { return IntStream.rangeClosed(0, Long.BYTES * 2); } /** * Gets the int seeds to convert. * * @return the int seeds */ static IntStream getIntSeeds() { return IntStream.of(0, -1, 1267831682, 236786348, -52364); } /** * Gets the long seeds to convert. * * @return the long seeds */ static LongStream getLongSeeds() { return LongStream.of(0, -1, 237848224324L, 6678328688668L, -2783792379423L); } /** * Test the conversion throws for an unsupported seed type. * The error message should contain the type, not the string representation of the seed. */ @ParameterizedTest @MethodSource void testConvertSeedToBytesUsingUnsupportedSeedThrows(Object seed) { final UnsupportedOperationException ex = Assertions.assertThrows( UnsupportedOperationException.class, () -> NativeSeedType.convertSeedToBytes(seed)); if (seed == null) { Assertions.assertTrue(ex.getMessage().contains("null")); } else { Assertions.assertTrue(ex.getMessage().contains(seed.getClass().getName())); } } /** * Return an array of unsupported seed objects. * * @return the seeds */ static Object[] testConvertSeedToBytesUsingUnsupportedSeedThrows() { return new Object[] { null, BigDecimal.ONE, "The quick brown fox jumped over the lazy dog", new Object() { @Override public String toString() { throw new IllegalStateException("error message should not call toString()"); } } }; } /** * Test the conversion passes through a byte[]. This hits the edge case of a seed * that can be converted that is not a native type. */ @Test void testConvertSeedToBytesUsingByteArray() { final byte[] seed = {42, 78, 99}; Assertions.assertSame(seed, NativeSeedType.convertSeedToBytes(seed)); } @ParameterizedTest @CsvSource({ "3, 1", "4, 1", "5, 1", "7, 2", "8, 2", "9, 2", "13, 2", "0, 0", }) void testConvertByteArrayToIntArray(int byteSize, int intSize) { final byte[] bytes = new byte[byteSize]; // Get the maximum number of ints to use all the bytes final int size = Conversions.intSizeFromByteSize(byteSize); // If the size is too big, fill the remaining bytes with non-zero values. // These should not be used during conversion. if (size > intSize) { Arrays.fill(bytes, intSize * Integer.BYTES, bytes.length, (byte) -1); } final int expected = Math.min(size, intSize); final int[] ints = (int[]) NativeSeedType.INT_ARRAY.convert(bytes, intSize); Assertions.assertEquals(expected, ints.length); // The seed should be zero, i.e. extra bytes have not been used for (final int i : ints) { Assertions.assertEquals(0, i); } } @ParameterizedTest @CsvSource({ "7, 1", "8, 1", "9, 1", "15, 2", "16, 2", "17, 2", "25, 2", "0, 0", }) void testConvertByteArrayToLongArray(int byteSize, int longSize) { final byte[] bytes = new byte[byteSize]; // Get the maximum number of longs to use all the bytes final long size = Conversions.longSizeFromByteSize(byteSize); // If the size is too big, fill the remaining bytes with non-zero values. // These should not be used during conversion. if (size > longSize) { Arrays.fill(bytes, longSize * Long.BYTES, bytes.length, (byte) -1); } final long expected = Math.min(size, longSize); final long[] longs = (long[]) NativeSeedType.LONG_ARRAY.convert(bytes, longSize); Assertions.assertEquals(expected, longs.length); // The seed should be zero, i.e. extra bytes have not been used for (final long i : longs) { Assertions.assertEquals(0, i); } } @ParameterizedTest @CsvSource({ "1, 1", "2, 1", "3, 1", "3, 2", "4, 2", "5, 2", "7, 2", "0, 0", }) void testConvertIntArrayToLongArray(int intSize, int longSize) { final int[] ints = new int[intSize]; // Get the maximum number of longs to use all the ints final long size = Conversions.longSizeFromIntSize(intSize); // If the size is too big, fill the remaining ints with non-zero values. // These should not be used during conversion. if (size > longSize) { Arrays.fill(ints, longSize * 2, ints.length, -1); } final long expected = Math.min(size, longSize); final long[] longs = (long[]) NativeSeedType.LONG_ARRAY.convert(ints, longSize); Assertions.assertEquals(expected, longs.length); // The seed should be zero, i.e. extra ints have not been used for (final long i : longs) { Assertions.assertEquals(0, i); } } @ParameterizedTest @CsvSource({ "0, 1", "1, 1", "2, 1", "0, 2", "1, 2", "2, 2", "3, 2", "0, 0", }) void testConvertLongArrayToIntArray(int longSize, int intSize) { final long[] longs = new long[longSize]; // Get the maximum number of ints to use all the longs final int size = longSize * 2; // If the size is too big, fill the remaining longs with non-zero values. // These should not be used during conversion. if (size > intSize) { Arrays.fill(longs, Conversions.longSizeFromIntSize(intSize), longs.length, -1); } final int expected = Math.min(size, intSize); final int[] ints = (int[]) NativeSeedType.INT_ARRAY.convert(longs, intSize); Assertions.assertEquals(expected, ints.length); // The seed should be zero, i.e. extra longs have not been used for (final int i : ints) { Assertions.assertEquals(0, i); } } // The following tests define the conversion contract for NativeSeedType. // // - Native seed types are passed through with no change // - long to int conversion uses hi ^ lo // - int to long conversion expands the bits. // Creating a long using a SplitMix64 is the reference implementation. // - long to long[] conversion seeds a RNG then expands. // Filling using a SplitMix64 is the reference implementation. // - long to int[] conversion seeds a RNG then expands. // Filling using a SplitMix64 is the reference implementation. // - Primitive expansion should produce equivalent output bits // for all larger output seed types, // i.e. int -> long == int -> int[0]+int[1] == int -> long[0] // - int[] to int conversion uses ^ of all the bits // - long[] to long conversion uses ^ of all the bits // - Array-to-array conversions are little-endian. // - Arrays are converted with no zero fill to expand the length. // - Array conversion may be full length (F), // or truncated (T) to the required bytes for the native type. // // Conversions are tested to perform an equivalent to the following operations. // // Int // int -> int // long -> int // int[] -> int // long[] -> F int[] -> int // byte[] -> F int[] -> int // // Long // int -> long // long -> long // int[] -> F long[] -> long // long[] -> long // byte[] -> F long[] -> int // // int[] // int -> int[] // long -> int[] // int[] -> int[] // long[] -> T int[] // byte[] -> T int[] // // int[] // int -> long[] // long -> long[] // int[] -> T long[] // long[] -> long[] // byte[] -> T long[] // // Notes: // 1. The actual implementation may be optimised to avoid redundant steps. // 2. Primitive type native seed use all bits from an array (F). // 3. Array type native seeds use only the initial n bytes from an array (T) required // to satisfy the native seed length n // 4. Expansion of primitive seeds to a different native type should be consistent. // Seeding an integer to create an int[] should match the byte output of // using the same integer (or long) to create a long[] of equivalent length @ParameterizedTest @MethodSource(value = {"getIntSeeds"}) void testPrimitiveSeedExpansion(int seed) { for (int i = 1; i < 3; i++) { final long l1 = (Long) NativeSeedType.LONG.convert(seed, i); final int[] ia1 = (int[]) NativeSeedType.INT_ARRAY.convert(seed, i * 2); final long[] la1 = (long[]) NativeSeedType.LONG_ARRAY.convert(seed, i); final int[] ia2 = (int[]) NativeSeedType.INT_ARRAY.convert(Long.valueOf(seed), i * 2); final long[] la2 = (long[]) NativeSeedType.LONG_ARRAY.convert(Long.valueOf(seed), i); Assertions.assertEquals(i, la1.length); Assertions.assertEquals(l1, la1[0], "int -> long != int -> long[0]"); Assertions.assertArrayEquals(ia1, ia2, "int -> int[] != long -> int[]"); Assertions.assertArrayEquals(la1, la2, "int -> long[] != long -> long[]"); final ByteBuffer bb = ByteBuffer.allocate(i * Long.BYTES).order(ByteOrder.LITTLE_ENDIAN); Arrays.stream(ia1).forEach(bb::putInt); bb.flip(); for (int j = 0; j < i; j++) { Assertions.assertEquals(bb.getLong(), la1[j]); } } } @ParameterizedTest @MethodSource(value = {"getIntSeeds"}) void testIntNativeSeedWithInt(int seed) { // Native type final Integer s = Integer.valueOf(seed); for (int i = 0; i < 3; i++) { Assertions.assertSame(s, NativeSeedType.INT.convert(s, i)); } } @ParameterizedTest @MethodSource(value = {"getIntSeeds"}) void testIntNativeSeedWithLong(long seed) { // Primitive conversion: Note: >>> takes precendence over ^ final Integer l = (int) (seed ^ seed >>> 32); for (int i = 0; i < 3; i++) { Assertions.assertEquals(l, (Integer) NativeSeedType.INT.convert(seed, i)); } } @ParameterizedTest @MethodSource(value = {"getByteLengths"}) void testIntNativeSeedWithArrays(int bytes) { final byte[] byteSeed = new byte[bytes]; ThreadLocalRandom.current().nextBytes(byteSeed); // Get the bytes as each array type final int longSize = Conversions.longSizeFromByteSize(bytes); final int intSize = Conversions.intSizeFromByteSize(bytes); final ByteBuffer bb = ByteBuffer.wrap( Arrays.copyOf(byteSeed, longSize * Long.BYTES)) .order(ByteOrder.LITTLE_ENDIAN); final long[] longSeed = new long[longSize]; for (int i = 0; i < longSeed.length; i++) { longSeed[i] = bb.getLong(); } bb.clear(); final int[] intSeed = new int[intSize]; int expected = 0; for (int i = 0; i < intSeed.length; i++) { intSeed[i] = bb.getInt(); expected ^= intSeed[i]; } // Length parameter is ignored and full bytes are always used for (int i = 0; i < 3; i++) { Assertions.assertEquals(expected, NativeSeedType.INT.convert(byteSeed, i)); Assertions.assertEquals(expected, NativeSeedType.INT.convert(intSeed, i)); Assertions.assertEquals(expected, NativeSeedType.INT.convert(longSeed, i)); } } @ParameterizedTest @MethodSource(value = {"getIntSeeds"}) void testLongNativeSeedWithInt(int seed) { // Primitive conversion. final Long l = int2long(seed); for (int i = 0; i < 3; i++) { Assertions.assertEquals(l, (Long) NativeSeedType.LONG.convert(seed, i)); } } @ParameterizedTest @MethodSource(value = {"getLongSeeds"}) void testLongNativeSeedWithLong(long seed) { // Native type final Long s = Long.valueOf(seed); for (int i = 0; i < 3; i++) { Assertions.assertSame(s, NativeSeedType.LONG.convert(s, i)); } } @ParameterizedTest @MethodSource(value = {"getByteLengths"}) void testLongNativeSeedWithArrays(int bytes) { final byte[] byteSeed = new byte[bytes]; ThreadLocalRandom.current().nextBytes(byteSeed); // Get the bytes as each array type final int longSize = Conversions.longSizeFromByteSize(bytes); final int intSize = Conversions.intSizeFromByteSize(bytes); final ByteBuffer bb = ByteBuffer.wrap( Arrays.copyOf(byteSeed, longSize * Long.BYTES)) .order(ByteOrder.LITTLE_ENDIAN); final long[] longSeed = new long[longSize]; long expected = 0; for (int i = 0; i < longSeed.length; i++) { longSeed[i] = bb.getLong(); expected ^= longSeed[i]; } bb.clear(); final int[] intSeed = new int[intSize]; for (int i = 0; i < intSeed.length; i++) { intSeed[i] = bb.getInt(); } // Length parameter is ignored and full bytes are always used for (int i = 0; i < 3; i++) { Assertions.assertEquals(expected, NativeSeedType.LONG.convert(byteSeed, i)); Assertions.assertEquals(expected, NativeSeedType.LONG.convert(intSeed, i)); Assertions.assertEquals(expected, NativeSeedType.LONG.convert(longSeed, i)); } } @ParameterizedTest @MethodSource(value = {"getIntSeeds"}) void testIntArrayNativeSeedWithInt(int seed) { // Full-length conversion for (int i = 0; i < 3; i++) { // Note: int seed is expanded using the same method as a long seed Assertions.assertArrayEquals(long2intArray(seed, i), (int[]) NativeSeedType.INT_ARRAY.convert(seed, i)); } } @ParameterizedTest @MethodSource(value = {"getLongSeeds"}) void testIntArrayNativeSeedWithLong(long seed) { // Full-length conversion for (int i = 0; i < 3; i++) { Assertions.assertArrayEquals(long2intArray(seed, i), (int[]) NativeSeedType.INT_ARRAY.convert(seed, i)); } } @ParameterizedTest @MethodSource(value = {"getByteLengths"}) void testIntArrayNativeSeedWithArrays(int bytes) { final byte[] byteSeed = new byte[bytes]; ThreadLocalRandom.current().nextBytes(byteSeed); // Get the bytes as each array type final int longSize = Conversions.longSizeFromByteSize(bytes); final int intSize = Conversions.intSizeFromByteSize(bytes); final ByteBuffer bb = ByteBuffer.wrap( Arrays.copyOf(byteSeed, longSize * Long.BYTES)) .order(ByteOrder.LITTLE_ENDIAN); final long[] longSeed = new long[longSize]; for (int i = 0; i < longSeed.length; i++) { longSeed[i] = bb.getLong(); } bb.clear(); final int[] intSeed = new int[intSize]; for (int i = 0; i < intSeed.length; i++) { intSeed[i] = bb.getInt(); } // Native type Assertions.assertSame(intSeed, NativeSeedType.INT_ARRAY.convert(intSeed, 0)); Assertions.assertSame(intSeed, NativeSeedType.INT_ARRAY.convert(intSeed, intSize)); Assertions.assertSame(intSeed, NativeSeedType.INT_ARRAY.convert(intSeed, intSize * 2)); // Full-length conversion Assertions.assertArrayEquals(intSeed, (int[]) NativeSeedType.INT_ARRAY.convert(byteSeed, intSize)); Assertions.assertArrayEquals(intSeed, (int[]) NativeSeedType.INT_ARRAY.convert(longSeed, intSize)); // Truncation Assertions.assertArrayEquals(new int[0], (int[]) NativeSeedType.INT_ARRAY.convert(byteSeed, 0)); Assertions.assertArrayEquals(new int[0], (int[]) NativeSeedType.INT_ARRAY.convert(longSeed, 0)); if (intSize != 0) { Assertions.assertArrayEquals(Arrays.copyOf(intSeed, 1), (int[]) NativeSeedType.INT_ARRAY.convert(byteSeed, 1)); Assertions.assertArrayEquals(Arrays.copyOf(intSeed, 1), (int[]) NativeSeedType.INT_ARRAY.convert(longSeed, 1)); } // No zero-fill (only use the bytes in the input seed) Assertions.assertArrayEquals(intSeed, (int[]) NativeSeedType.INT_ARRAY.convert(byteSeed, intSize * 2)); Assertions.assertArrayEquals(Arrays.copyOf(intSeed, longSize * 2), (int[]) NativeSeedType.INT_ARRAY.convert(longSeed, intSize * 2)); } @ParameterizedTest @MethodSource(value = {"getIntSeeds"}) void testLongArrayNativeSeedWithInt(int seed) { // Full-length conversion for (int i = 0; i < 3; i++) { // Note: int seed is expanded using the same method as a long seed Assertions.assertArrayEquals(long2longArray(seed, i), (long[]) NativeSeedType.LONG_ARRAY.convert(seed, i)); } } @ParameterizedTest @MethodSource(value = {"getLongSeeds"}) void testLongArrayNativeSeedWithLong(long seed) { // Full-length conversion for (int i = 0; i < 3; i++) { Assertions.assertArrayEquals(long2longArray(seed, i), (long[]) NativeSeedType.LONG_ARRAY.convert(seed, i)); } } @ParameterizedTest @MethodSource(value = {"getByteLengths"}) void testLongArrayNativeSeedWithArrays(int bytes) { final byte[] byteSeed = new byte[bytes]; ThreadLocalRandom.current().nextBytes(byteSeed); // Get the bytes as each array type final int longSize = Conversions.longSizeFromByteSize(bytes); final int intSize = Conversions.intSizeFromByteSize(bytes); final ByteBuffer bb = ByteBuffer.wrap( Arrays.copyOf(byteSeed, longSize * Long.BYTES)) .order(ByteOrder.LITTLE_ENDIAN); final long[] longSeed = new long[longSize]; for (int i = 0; i < longSeed.length; i++) { longSeed[i] = bb.getLong(); } bb.clear(); final int[] intSeed = new int[intSize]; for (int i = 0; i < intSeed.length; i++) { intSeed[i] = bb.getInt(); } // Native type Assertions.assertSame(longSeed, NativeSeedType.LONG_ARRAY.convert(longSeed, 0)); Assertions.assertSame(longSeed, NativeSeedType.LONG_ARRAY.convert(longSeed, longSize)); Assertions.assertSame(longSeed, NativeSeedType.LONG_ARRAY.convert(longSeed, longSize * 2)); // Full-length conversion Assertions.assertArrayEquals(longSeed, (long[]) NativeSeedType.LONG_ARRAY.convert(byteSeed, longSize)); Assertions.assertArrayEquals(longSeed, (long[]) NativeSeedType.LONG_ARRAY.convert(intSeed, longSize)); // Truncation Assertions.assertArrayEquals(new long[0], (long[]) NativeSeedType.LONG_ARRAY.convert(byteSeed, 0)); Assertions.assertArrayEquals(new long[0], (long[]) NativeSeedType.LONG_ARRAY.convert(intSeed, 0)); if (longSize != 0) { Assertions.assertArrayEquals(Arrays.copyOf(longSeed, 1), (long[]) NativeSeedType.LONG_ARRAY.convert(byteSeed, 1)); Assertions.assertArrayEquals(Arrays.copyOf(longSeed, 1), (long[]) NativeSeedType.LONG_ARRAY.convert(intSeed, 1)); } // No zero-fill (only use the bytes in the input seed) Assertions.assertArrayEquals(longSeed, (long[]) NativeSeedType.LONG_ARRAY.convert(byteSeed, longSize * 2)); Assertions.assertArrayEquals(longSeed, (long[]) NativeSeedType.LONG_ARRAY.convert(intSeed, longSize * 2)); } }
2,844
0
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple/internal/IntArray2LongArrayTest.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.simple.internal; import java.util.stream.IntStream; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; /** * Tests for the {@link IntArray2LongArray} converter. */ class IntArray2LongArrayTest { /** * Gets the lengths for the int[] seeds to convert. * * @return the lengths */ static IntStream getLengths() { return IntStream.rangeClosed(0, (Long.BYTES / Integer.BYTES) * 2); } /** * Gets the expected output length. * * @param ints Number of ints * @return the output length */ private static int getOutputLength(int ints) { return (int) Math.ceil((double) ints / 2); } @ParameterizedTest @MethodSource(value = {"getLengths"}) void testSeedSizeIsMultipleOfIntSize(int ints) { final int[] seed = new int[ints]; final long[] out = new IntArray2LongArray().convert(seed); Assertions.assertEquals(getOutputLength(ints), out.length); } }
2,845
0
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple/internal/MixFunctionsTest.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.simple.internal; import java.util.SplittableRandom; import org.apache.commons.rng.core.source64.SplitMix64; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; /** * Tests for {@link MixFunctions}. */ class MixFunctionsTest { @ParameterizedTest @ValueSource(longs = {0, -1, 1, 63812881278371L, -236812734617872L}) void testStafford13(long seed) { // Reference output is from a SplitMix64 generator final SplitMix64 rng = new SplitMix64(seed); long x = seed; for (int i = 0; i < 20; i++) { Assertions.assertEquals(rng.nextLong(), MixFunctions.stafford13(x += MixFunctions.GOLDEN_RATIO_64)); } } @Test void testMurmur3() { // Reference output from the c++ function fmix32(uint32_t) in smhasher. // https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp final int seedA = 0x012de1ba; final int[] valuesA = { 0x2f66c8b6, 0x256c0269, 0x054ef409, 0x402425ba, 0x78ebf590, 0x76bea1db, 0x8bf5dcbe, 0x104ecdd4, 0x43cfc87e, 0xa33c7643, 0x4d210f56, 0xfa12093d, }; int x = seedA; for (int z : valuesA) { Assertions.assertEquals(z, MixFunctions.murmur3(x += MixFunctions.GOLDEN_RATIO_32)); } // Values from a seed of zero final int[] values0 = { 0x92ca2f0e, 0x3cd6e3f3, 0x1b147dcc, 0x4c081dbf, 0x487981ab, 0xdb408c9d, 0x78bc1b8f, 0xd83072e5, 0x65cbdd54, 0x1f4b8cef, 0x91783bb0, 0x0231739b, }; x = 0; for (int z : values0) { Assertions.assertEquals(z, MixFunctions.murmur3(x += MixFunctions.GOLDEN_RATIO_32)); } } /** * Test the reverse of the Stafford 13 mix function. */ @Test void testUnmixStafford13() { final SplittableRandom rng = new SplittableRandom(); for (int i = 0; i < 100; i++) { final long x = rng.nextLong(); final long y = MixFunctions.stafford13(x); Assertions.assertEquals(x, unmixStafford13(y)); } } /** * Reverse the Stafford 13 mix function. * * <p>This can be used to generate specific seed values for a SplitMix-style RNG using * the Stafford 13 mix constants, for example in the SeedFactoryTest. It is left in * the test source code as a reference to allow computation of test seeds. * * @param x Argument * @return the result */ private static long unmixStafford13(long x) { // Multiplicative inverse: // https://lemire.me/blog/2017/09/18/computing-the-inverse-of-odd-integers/ // Invert 0xbf58476d1ce4e5b9L final long u1 = 0x96de1b173f119089L; // Invert 0x94d049bb133111ebL final long u2 = 0x319642b2d24d8ec3L; // Inversion of xor right-shift operations exploits the facts: // 1. A xor operation can be used to recover itself: // x ^ y = z // z ^ y = x // z ^ x = y // 2. During xor right-shift of size n the top n-bits are unchanged. // 3. Known values from the top bits can be used to recover the next set of n-bits. // Recovery is done by xoring with the shifted argument, then doubling the right shift. // This is iterated until all bits are recovered. With initial large shifts only one // doubling is required. x = x ^ (x >>> 31); x ^= x >>> 62; x *= u2; x = x ^ (x >>> 27); x ^= x >>> 54; x *= u1; x = x ^ (x >>> 30); x ^= x >>> 60; return x; } }
2,846
0
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple/internal/ArrayConverterEndianTest.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.simple.internal; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Arrays; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.IntStream; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; /** * Tests the endian conversion of all array converters. */ class ArrayConverterEndianTest { /** * Gets the lengths for the byte[] seeds. * * @return the lengths */ static IntStream getLengths() { return IntStream.rangeClosed(0, 16); } @ParameterizedTest @MethodSource(value = {"getLengths"}) void testLittleEndian(int bytes) { final byte[] seedBytes = new byte[bytes]; ThreadLocalRandom.current().nextBytes(seedBytes); // Reference implementation using a ByteBuffer final ByteBuffer bb = ByteBuffer.wrap( Arrays.copyOf(seedBytes, Conversions.longSizeFromByteSize(bytes) * Long.BYTES)) .order(ByteOrder.LITTLE_ENDIAN); // byte[] -> int[] final int[] expectedInt = new int[Conversions.intSizeFromByteSize(bytes)]; for (int i = 0; i < expectedInt.length; i++) { expectedInt[i] = bb.getInt(); } Assertions.assertArrayEquals(expectedInt, new ByteArray2IntArray().convert(seedBytes)); Assertions.assertArrayEquals(expectedInt, (int[]) NativeSeedType.INT_ARRAY.convert(seedBytes, expectedInt.length)); // byte[] -> long[] bb.clear(); final long[] expectedLong = new long[Conversions.longSizeFromByteSize(bytes)]; for (int i = 0; i < expectedLong.length; i++) { expectedLong[i] = bb.getLong(); } Assertions.assertArrayEquals(expectedLong, new ByteArray2LongArray().convert(seedBytes)); Assertions.assertArrayEquals(expectedLong, (long[]) NativeSeedType.LONG_ARRAY.convert(seedBytes, expectedLong.length)); // int[] -> long[] Assertions.assertArrayEquals(expectedLong, new IntArray2LongArray().convert(expectedInt)); Assertions.assertArrayEquals(expectedLong, (long[]) NativeSeedType.LONG_ARRAY.convert(expectedInt, expectedLong.length)); // long[] -> int[] Assertions.assertArrayEquals(expectedInt, (int[]) NativeSeedType.INT_ARRAY.convert(expectedLong, expectedInt.length)); } }
2,847
0
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple/internal/RandomSourceInternalParametricTest.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.simple.internal; import org.apache.commons.rng.core.source64.SplitMix64; import org.apache.commons.rng.simple.internal.ProviderBuilder.RandomSourceInternal; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import java.util.EnumMap; import java.util.function.Supplier; /** * Tests for the {@link ProviderBuilder.RandomSourceInternal} seed conversions. This test * ensures that all random sources can create a seed or convert any supported seed to the * correct type for the constructor. */ class RandomSourceInternalParametricTest { /** The supported seeds for conversion to a native seed type. */ private static final Object[] SUPPORTED_SEEDS = { Integer.valueOf(1), Long.valueOf(2), new int[] {3, 4, 5}, new long[] {6, 7, 8}, new byte[] {9, 10, 11}, }; /** Example unsupported seeds for conversion to a native seed type. */ private static final Object[] UNSUPPORTED_SEEDS = { null, Double.valueOf(Math.PI), }; /** The expected byte size of the seed for each RandomSource. */ private static final EnumMap<RandomSourceInternal, Integer> EXPECTED_SEED_BYTES = new EnumMap<>(RandomSourceInternal.class); static { final int intBytes = Integer.BYTES; final int longBytes = Long.BYTES; EXPECTED_SEED_BYTES.put(RandomSourceInternal.JDK, longBytes * 1); EXPECTED_SEED_BYTES.put(RandomSourceInternal.WELL_512_A, intBytes * 16); EXPECTED_SEED_BYTES.put(RandomSourceInternal.WELL_1024_A, intBytes * 32); EXPECTED_SEED_BYTES.put(RandomSourceInternal.WELL_19937_A, intBytes * 624); EXPECTED_SEED_BYTES.put(RandomSourceInternal.WELL_19937_C, intBytes * 624); EXPECTED_SEED_BYTES.put(RandomSourceInternal.WELL_44497_A, intBytes * 1391); EXPECTED_SEED_BYTES.put(RandomSourceInternal.WELL_44497_B, intBytes * 1391); EXPECTED_SEED_BYTES.put(RandomSourceInternal.MT, intBytes * 624); EXPECTED_SEED_BYTES.put(RandomSourceInternal.ISAAC, intBytes * 256); EXPECTED_SEED_BYTES.put(RandomSourceInternal.SPLIT_MIX_64, longBytes * 1); EXPECTED_SEED_BYTES.put(RandomSourceInternal.XOR_SHIFT_1024_S, longBytes * 16); EXPECTED_SEED_BYTES.put(RandomSourceInternal.TWO_CMRES, intBytes * 1); EXPECTED_SEED_BYTES.put(RandomSourceInternal.TWO_CMRES_SELECT, intBytes * 1); EXPECTED_SEED_BYTES.put(RandomSourceInternal.MT_64, longBytes * 312); EXPECTED_SEED_BYTES.put(RandomSourceInternal.MWC_256, intBytes * 257); EXPECTED_SEED_BYTES.put(RandomSourceInternal.KISS, intBytes * 4); EXPECTED_SEED_BYTES.put(RandomSourceInternal.XOR_SHIFT_1024_S_PHI, longBytes * 16); EXPECTED_SEED_BYTES.put(RandomSourceInternal.XO_RO_SHI_RO_64_S, intBytes * 2); EXPECTED_SEED_BYTES.put(RandomSourceInternal.XO_RO_SHI_RO_64_SS, intBytes * 2); EXPECTED_SEED_BYTES.put(RandomSourceInternal.XO_SHI_RO_128_PLUS, intBytes * 4); EXPECTED_SEED_BYTES.put(RandomSourceInternal.XO_SHI_RO_128_SS, intBytes * 4); EXPECTED_SEED_BYTES.put(RandomSourceInternal.XO_RO_SHI_RO_128_PLUS, longBytes * 2); EXPECTED_SEED_BYTES.put(RandomSourceInternal.XO_RO_SHI_RO_128_SS, longBytes * 2); EXPECTED_SEED_BYTES.put(RandomSourceInternal.XO_SHI_RO_256_PLUS, longBytes * 4); EXPECTED_SEED_BYTES.put(RandomSourceInternal.XO_SHI_RO_256_SS, longBytes * 4); EXPECTED_SEED_BYTES.put(RandomSourceInternal.XO_SHI_RO_512_PLUS, longBytes * 8); EXPECTED_SEED_BYTES.put(RandomSourceInternal.XO_SHI_RO_512_SS, longBytes * 8); EXPECTED_SEED_BYTES.put(RandomSourceInternal.PCG_XSH_RR_32, longBytes * 2); EXPECTED_SEED_BYTES.put(RandomSourceInternal.PCG_XSH_RS_32, longBytes * 2); EXPECTED_SEED_BYTES.put(RandomSourceInternal.PCG_RXS_M_XS_64, longBytes * 2); EXPECTED_SEED_BYTES.put(RandomSourceInternal.PCG_MCG_XSH_RR_32, longBytes * 1); EXPECTED_SEED_BYTES.put(RandomSourceInternal.PCG_MCG_XSH_RS_32, longBytes * 1); EXPECTED_SEED_BYTES.put(RandomSourceInternal.MSWS, longBytes * 3); EXPECTED_SEED_BYTES.put(RandomSourceInternal.SFC_32, intBytes * 3); EXPECTED_SEED_BYTES.put(RandomSourceInternal.SFC_64, longBytes * 3); EXPECTED_SEED_BYTES.put(RandomSourceInternal.JSF_32, intBytes * 1); EXPECTED_SEED_BYTES.put(RandomSourceInternal.JSF_64, longBytes * 1); EXPECTED_SEED_BYTES.put(RandomSourceInternal.XO_SHI_RO_128_PP, intBytes * 4); EXPECTED_SEED_BYTES.put(RandomSourceInternal.XO_RO_SHI_RO_128_PP, longBytes * 2); EXPECTED_SEED_BYTES.put(RandomSourceInternal.XO_SHI_RO_256_PP, longBytes * 4); EXPECTED_SEED_BYTES.put(RandomSourceInternal.XO_SHI_RO_512_PP, longBytes * 8); EXPECTED_SEED_BYTES.put(RandomSourceInternal.XO_RO_SHI_RO_1024_PP, longBytes * 16); EXPECTED_SEED_BYTES.put(RandomSourceInternal.XO_RO_SHI_RO_1024_S, longBytes * 16); EXPECTED_SEED_BYTES.put(RandomSourceInternal.XO_RO_SHI_RO_1024_SS, longBytes * 16); EXPECTED_SEED_BYTES.put(RandomSourceInternal.PCG_XSH_RR_32_OS, longBytes); EXPECTED_SEED_BYTES.put(RandomSourceInternal.PCG_XSH_RS_32_OS, longBytes); EXPECTED_SEED_BYTES.put(RandomSourceInternal.PCG_RXS_M_XS_64_OS, longBytes); EXPECTED_SEED_BYTES.put(RandomSourceInternal.L64_X128_SS, longBytes * 4); EXPECTED_SEED_BYTES.put(RandomSourceInternal.L64_X128_MIX, longBytes * 4); EXPECTED_SEED_BYTES.put(RandomSourceInternal.L64_X256_MIX, longBytes * 6); EXPECTED_SEED_BYTES.put(RandomSourceInternal.L64_X1024_MIX, longBytes * 18); EXPECTED_SEED_BYTES.put(RandomSourceInternal.L128_X128_MIX, longBytes * 6); EXPECTED_SEED_BYTES.put(RandomSourceInternal.L128_X256_MIX, longBytes * 8); EXPECTED_SEED_BYTES.put(RandomSourceInternal.L128_X1024_MIX, longBytes * 20); EXPECTED_SEED_BYTES.put(RandomSourceInternal.L32_X64_MIX, intBytes * 4); // ... add more here. // Verify the seed byte size is reflected in the enum javadoc for RandomSource. } /** * Get the class type of the native seed for the random source. * * @param randomSourceInternal Internal identifier for the random source. */ private static Class<?> getType(RandomSourceInternal randomSourceInternal) { // The first constructor argument is always the seed type return randomSourceInternal.getArgs()[0]; } /** * Test the seed can be created as the correct type. * * @param randomSourceInternal Internal identifier for the random source. */ @ParameterizedTest @EnumSource void testCreateSeed(RandomSourceInternal randomSourceInternal) { final Class<?> type = getType(randomSourceInternal); final Object seed = randomSourceInternal.createSeed(); Assertions.assertNotNull(seed); Assertions.assertEquals(type, seed.getClass(), "Seed was not the correct class"); Assertions.assertTrue(randomSourceInternal.isNativeSeed(seed), "Seed was not identified as the native type"); } /** * Test the seed can be converted to the correct type from any of the supported input types. * * @param randomSourceInternal Internal identifier for the random source. */ @ParameterizedTest @EnumSource void testConvertSupportedSeed(RandomSourceInternal randomSourceInternal) { final Class<?> type = getType(randomSourceInternal); for (final Object input : SUPPORTED_SEEDS) { final Object seed = randomSourceInternal.convertSeed(input); final Supplier<String> msg = () -> input.getClass() + " input seed was not converted"; Assertions.assertNotNull(seed, msg); Assertions.assertEquals(type, seed.getClass(), msg); Assertions.assertTrue(randomSourceInternal.isNativeSeed(seed), msg); } } /** * Test unsupported input seed types are rejected. * * @param randomSourceInternal Internal identifier for the random source. */ @ParameterizedTest @EnumSource void testCannotConvertUnsupportedSeed(RandomSourceInternal randomSourceInternal) { for (final Object input : UNSUPPORTED_SEEDS) { Assertions.assertThrows(UnsupportedOperationException.class, () -> randomSourceInternal.convertSeed(input), () -> input.getClass() + " input seed was not rejected as unsupported"); } } /** * Test the seed byte size is reported as the size of a int/long primitive for Int/Long * seed types and a multiple of it for int[]/long[] types. * * @param randomSourceInternal Internal identifier for the random source. */ @ParameterizedTest @EnumSource void testCreateSeedBytesSizeIsPositiveAndMultipleOf4Or8(RandomSourceInternal randomSourceInternal) { // This should be the full length seed final byte[] seed = randomSourceInternal.createSeedBytes(new SplitMix64(12345L)); final int size = seed.length; Assertions.assertNotEquals(0, size, "Seed is empty"); if (randomSourceInternal.isNativeSeed(Integer.valueOf(0))) { Assertions.assertEquals(4, size, "Expect 4 bytes for Integer"); } else if (randomSourceInternal.isNativeSeed(Long.valueOf(0))) { Assertions.assertEquals(8, size, "Expect 8 bytes for Long"); } else if (randomSourceInternal.isNativeSeed(new int[0])) { Assertions.assertEquals(0, size % 4, "Expect 4n bytes for int[]"); } else if (randomSourceInternal.isNativeSeed(new long[0])) { Assertions.assertEquals(0, size % 8, "Expect 8n bytes for long[]"); } else { Assertions.fail("Unknown native seed type"); } } /** * Test the seed byte size against the expected value. * * <p>The expected values are maintained in a table and must be manually updated * for new generators. This test forms an additional cross-reference check that the * seed size in RandomSourceInternal has been correctly set and the size should map to * the array size in the RandomSource javadoc (if applicable). * * @param randomSourceInternal Internal identifier for the random source. */ @ParameterizedTest @EnumSource void testCreateSeedBytes(RandomSourceInternal randomSourceInternal) { // This should be the full length seed final byte[] seed = randomSourceInternal.createSeedBytes(new SplitMix64(12345L)); final int size = seed.length; final Integer expected = EXPECTED_SEED_BYTES.get(randomSourceInternal); Assertions.assertNotNull(expected, () -> "Missing expected seed byte size: " + randomSourceInternal); Assertions.assertEquals(expected.intValue(), size, () -> randomSourceInternal.toString()); } }
2,848
0
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple/internal/LongArray2IntArrayTest.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.simple.internal; import java.util.stream.IntStream; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; /** * Tests for the {@link LongArray2IntArray} converter. */ class LongArray2IntArrayTest { /** * Gets the lengths for the output int[] seeds. * * @return the lengths */ static IntStream getLengths() { return IntStream.rangeClosed(0, 5); } /** * Gets the expected input length to produce the specified number of ints. * * @param ints Number of ints * @return the input length */ private static int getInputLength(int ints) { return (int) Math.ceil((double) ints / Integer.BYTES); } @ParameterizedTest @MethodSource(value = {"getLengths"}) void testIntSizeIsMultipleOfSeedSize(int ints) { final long[] seed = new long[getInputLength(ints)]; final int[] out = new LongArray2IntArray().convert(seed); Assertions.assertEquals(seed.length * 2, out.length); } }
2,849
0
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple/internal/Long2IntTest.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.simple.internal; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Tests for the {@link Long2Int} converter to ensure code coverage. */ class Long2IntTest { @Test void testConversion() { final Long2Int c = new Long2Int(); for (final long l : new long[] {2637678842234L, -62374682438234L, -1L, 0}) { Assertions.assertEquals(Conversions.long2Int(l), c.convert(l)); } } }
2,850
0
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple/internal/Long2LongArrayTest.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.simple.internal; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Tests for the {@link Long2LongArray} converter. */ class Long2LongArrayTest { @Test void testFixedLengthConversion() { final Long seed = 567L; final int length = 3; final long[] out = new Long2LongArray(length).convert(seed); Assertions.assertEquals(length, out.length); } }
2,851
0
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple/internal/SeedUtilsTest.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.simple.internal; import org.apache.commons.math3.stat.inference.ChiSquareTest; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.core.source64.SplitMix64; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.Arrays; /** * Tests for the {@link SeedUtils}. */ class SeedUtilsTest { /** * Test the int hex permutation has 8 unique hex digits per permutation. * A uniformity test is performed on to check each hex digits is used evenly at each * character position. */ @Test void testCreateIntHexPermutation() { final UniformRandomProvider rng = new SplitMix64(-567435247L); final long[][] samples = new long[8][16]; for (int i = 0; i < 1000; i++) { int sample = SeedUtils.createIntHexPermutation(rng); int observed = 0; for (int j = 0; j < 8; j++) { final int digit = sample & 0xf; Assertions.assertEquals(0, observed & (1 << digit), "Duplicate digit in sample"); observed |= 1 << digit; samples[j][digit]++; sample >>>= 4; } } final ChiSquareTest chiSquareTest = new ChiSquareTest(); final double[] expected = new double[16]; Arrays.fill(expected, 1.0 / 16); // Pass if we cannot reject null hypothesis that distributions are the same. for (int j = 0; j < 8; j++) { Assertions.assertFalse(chiSquareTest.chiSquareTest(expected, samples[j], 0.001), "Not uniform in digit " + j); } } /** * Test the long hex permutation has 8 unique hex digits per permutation in the upper and * lower 32-bits. * A uniformity test is performed on to check each hex digits is used evenly at each * character position. */ @Test void testCreateLongHexPermutation() { final UniformRandomProvider rng = new SplitMix64(34645768L); final long[][] samples = new long[16][16]; for (int i = 0; i < 1000; i++) { long sample = SeedUtils.createLongHexPermutation(rng); // Check lower 32-bits long observed = 0; for (int j = 0; j < 8; j++) { final int digit = (int) (sample & 0xfL); Assertions.assertEquals(0, observed & (1 << digit), "Duplicate digit in lower sample"); observed |= 1 << digit; samples[j][digit]++; sample >>>= 4; } // Check upper 32-bits observed = 0; for (int j = 8; j < 16; j++) { final int digit = (int) (sample & 0xfL); Assertions.assertEquals(0, observed & (1 << digit), "Duplicate digit in upper sample"); observed |= 1 << digit; samples[j][digit]++; sample >>>= 4; } } final ChiSquareTest chiSquareTest = new ChiSquareTest(); final double[] expected = new double[16]; Arrays.fill(expected, 1.0 / 16); // Pass if we cannot reject null hypothesis that distributions are the same. for (int j = 0; j < 16; j++) { Assertions.assertFalse(chiSquareTest.chiSquareTest(expected, samples[j], 0.001), "Not uniform in digit " + j); } } }
2,852
0
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple/internal/ByteArray2LongArrayTest.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.simple.internal; import java.util.stream.IntStream; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; /** * Tests for the {@link ByteArray2LongArray} converter. */ class ByteArray2LongArrayTest { /** * Gets the lengths for the byte[] seeds to convert. * * @return the lengths */ static IntStream getLengths() { return IntStream.rangeClosed(0, Long.BYTES * 2); } /** * Gets the expected output length. * * @param bytes Number of bytes * @return the output length */ private static int getOutputLength(int bytes) { return (int) Math.ceil((double) bytes / Long.BYTES); } @ParameterizedTest @MethodSource(value = {"getLengths"}) void testSeedSizeIsMultipleOfIntSize(int bytes) { final byte[] seed = new byte[bytes]; final long[] out = new ByteArray2LongArray().convert(seed); Assertions.assertEquals(getOutputLength(bytes), out.length); } }
2,853
0
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple/internal/ByteArray2IntArrayTest.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.simple.internal; import java.util.stream.IntStream; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; /** * Tests for the {@link ByteArray2IntArray} converter. */ class ByteArray2IntArrayTest { /** * Gets the lengths for the byte[] seeds to convert. * * @return the lengths */ static IntStream getLengths() { return IntStream.rangeClosed(0, Integer.BYTES * 2); } /** * Gets the expected output length. * * @param bytes Number of bytes * @return the output length */ private static int getOutputLength(int bytes) { return (int) Math.ceil((double) bytes / Integer.BYTES); } @ParameterizedTest @MethodSource(value = {"getLengths"}) void testSeedSizeIsMultipleOfIntSize(int bytes) { final byte[] seed = new byte[bytes]; final int[] out = new ByteArray2IntArray().convert(seed); Assertions.assertEquals(getOutputLength(bytes), out.length); } }
2,854
0
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple/internal/SeedConverterComposerTest.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.simple.internal; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Tests for the {@link SeedConverterComposer}. */ class SeedConverterComposerTest { @Test void testComposedCoversion() { final Int2Long int2Long = new Int2Long(); final Long2LongArray long2LongArray = new Long2LongArray(3); final SeedConverterComposer<Integer, Long, long[]> composer = new SeedConverterComposer<>(int2Long, long2LongArray); final Integer in = 123; final Object out = composer.convert(in); Assertions.assertTrue(out instanceof long[], "Bad type conversion"); Assertions.assertEquals(3, ((long[])out).length, "Incorrect long[] length"); } }
2,855
0
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple/internal/Long2IntArrayTest.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.simple.internal; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Tests for the {@link Long2IntArray} converter. */ class Long2IntArrayTest { @Test void testFixedLengthConversion() { for (int length = 0; length < 10; length++) { testFixedLengthConversion(length); } } private static void testFixedLengthConversion(int length) { final Long seed = 567L; final int[] out = new Long2IntArray(length).convert(seed); Assertions.assertEquals(length, out.length); // This very seed dependent but the algorithm // should only produce 0 about 1 in 2^32 times. for (int i = 0; i < length; i++) { Assertions.assertNotEquals(0, out[i]); } } }
2,856
0
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple/internal/NativeSeedTypeParametricTest.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.simple.internal; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.api.Test; import java.lang.reflect.Array; import java.util.Arrays; import java.util.Set; import java.util.function.Supplier; import java.util.stream.Collectors; /** * Tests for the {@link NativeSeedType} seed conversions. This test * ensures that a seed can be created or converted from any supported input seed to each * supported native seed type. */ class NativeSeedTypeParametricTest { /** This is a list of the class types that are supported native seeds. */ private static final Object[] SUPPORTED_NATIVE_TYPES = { Integer.class, Long.class, int[].class, long[].class }; /** Example supported seeds for conversion to a native seed type. */ private static final Object[] SUPPORTED_SEEDS = { Integer.valueOf(1), Long.valueOf(2), new int[] {3, 4, 5}, new long[] {6, 7, 8}, new byte[] {9, 10, 11}, }; /** Example unsupported seeds for conversion to a native seed type. */ private static final Object[] UNSUPPORTED_SEEDS = { null, Double.valueOf(Math.PI), }; /** * Check that there are enum values for all supported types. * This ensures the test is maintained to correspond to the enum. */ @Test void testNativeSeedTypeEnum() { Set<Class<?>> supported = Arrays.stream(SUPPORTED_NATIVE_TYPES) .map(o -> (Class<?>) o) .collect(Collectors.toSet()); Assertions.assertEquals(SUPPORTED_NATIVE_TYPES.length, supported.size(), "Class type of supported seeds should be unique"); final NativeSeedType[] values = NativeSeedType.values(); Assertions.assertEquals(SUPPORTED_NATIVE_TYPES.length, values.length, "Incorrect number of enum values for the supported native types"); // Remove each Arrays.stream(values).map(NativeSeedType::getType).forEach(supported::remove); Assertions.assertEquals(0, supported.size()); } /** * Test the seed can be created as the correct type. * * @param nativeSeedType Native seed type. */ @ParameterizedTest @EnumSource void testCreateSeed(NativeSeedType nativeSeedType) { final int size = 3; final Object seed = nativeSeedType.createSeed(size); Assertions.assertNotNull(seed); final Class<?> type = nativeSeedType.getType(); Assertions.assertEquals(type, seed.getClass(), "Seed was not the correct class"); if (type.isArray()) { Assertions.assertEquals(size, Array.getLength(seed), "Seed was not created the correct length"); } } /** * Test the seed can be checked as non-zero in a sub-range. This uses a bad range to * generate an expected exception. The non-zero requirement is not tested as random * seeding is very unlikely to create even a single 32-bit integer that is zero and * requires correction. This test at least verifies the (from, to) sub-range arguments * are used. * * @param nativeSeedType Native seed type. */ @ParameterizedTest @EnumSource void testCreateArraySeedWithNonZeroRangeThrows(NativeSeedType nativeSeedType) { Assumptions.assumeTrue(nativeSeedType.getType().isArray(), "Not an array type"); // Arguments: (size, from, to) // Since the seed is created randomly it is very likely non-zero. // Use a sub-range that will throw on the first array access; otherwise // if the array location is valid it will likely be non-zero and no further // checks are made. Assertions.assertThrows(IndexOutOfBoundsException.class, () -> nativeSeedType.createSeed(0, 0, 1)); Assertions.assertThrows(IndexOutOfBoundsException.class, () -> nativeSeedType.createSeed(1, -1, 1)); Assertions.assertThrows(IndexOutOfBoundsException.class, () -> nativeSeedType.createSeed(1, 1, 2)); Assertions.assertThrows(IndexOutOfBoundsException.class, () -> nativeSeedType.createSeed(1, 2, 3)); } /** * Test the seed can be created, converted to a byte[] and then back to the native type. * * @param nativeSeedType Native seed type. */ @ParameterizedTest @EnumSource void testConvertSeedToBytes(NativeSeedType nativeSeedType) { final int size = 3; final Object seed = nativeSeedType.createSeed(size); Assertions.assertNotNull(seed, "Null seed"); final byte[] bytes = NativeSeedType.convertSeedToBytes(seed); Assertions.assertNotNull(bytes, "Null byte[] seed"); final Object seed2 = nativeSeedType.convertSeed(bytes, size); if (nativeSeedType.getType().isArray()) { // This handles nested primitive arrays Assertions.assertArrayEquals(new Object[] {seed}, new Object[] {seed2}, "byte[] seed was not converted back"); } else { Assertions.assertEquals(seed, seed2, "byte[] seed was not converted back"); } } /** * Test the seed can be converted to the correct type from any of the supported input types. * * @param nativeSeedType The native seed type enum instance. */ @ParameterizedTest @EnumSource void testConvertSupportedSeed(NativeSeedType nativeSeedType) { // Size can be ignored during conversion and so it not asserted final int size = 3; for (final Object input : SUPPORTED_SEEDS) { final Object seed = nativeSeedType.convertSeed(input, size); final Supplier<String> msg = () -> input.getClass() + " input seed was not converted"; Assertions.assertNotNull(seed, msg); Assertions.assertEquals(nativeSeedType.getType(), seed.getClass(), msg); } } /** * Test unsupported input seed types are rejected. * * @param nativeSeedType The native seed type enum instance. */ @ParameterizedTest @EnumSource void testCannotConvertUnsupportedSeed(NativeSeedType nativeSeedType) { final int size = 3; for (final Object input : UNSUPPORTED_SEEDS) { Assertions.assertThrows(UnsupportedOperationException.class, () -> nativeSeedType.convertSeed(input, size)); } } }
2,857
0
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple/internal/SeedFactoryTest.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.simple.internal; import java.util.Map; import java.util.Arrays; import java.util.HashMap; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.core.source32.IntProvider; import org.apache.commons.rng.core.source64.LongProvider; import org.apache.commons.rng.core.source64.RandomLongSource; import org.apache.commons.rng.core.source64.SplitMix64; import org.apache.commons.rng.core.util.NumberFactory; /** * Tests for {@link SeedFactory}. */ class SeedFactoryTest { @Test void testCreateLong() { final Map<Long, Integer> values = new HashMap<>(); final int n = 100000; for (int i = 0; i < n; i++) { final long v = SeedFactory.createLong(); Integer count = values.get(v); if (count == null) { count = 0; } values.put(v, count + 1); } // Check that all seeds are different. assertDifferentValues(values); } @Test void testCreateLongArray() { final Map<Long, Integer> values = new HashMap<>(); final int n = 100000; final long[] array = SeedFactory.createLongArray(n); Assertions.assertEquals(n, array.length); for (long v : array) { Integer count = values.get(v); if (count == null) { count = 0; } values.put(v, count + 1); } // Check that all seeds are different. assertDifferentValues(values); } @Test void testCreateIntArray() { final Map<Long, Integer> values = new HashMap<>(); for (int i = 0; i < 50000; i++) { final int[] a = SeedFactory.createIntArray(2); final long v = NumberFactory.makeLong(a[0], a[1]); Integer count = values.get(v); if (count == null) { count = 0; } values.put(v, count + 1); } // Check that all pairs in are different. assertDifferentValues(values); } /** * Asserts that all the keys in given {@code map} have their * value equal to 1. * * @param map Map to counts. */ private static <T> void assertDifferentValues(Map<T, Integer> map) { final StringBuilder sb = new StringBuilder(); int duplicates = 0; for (Map.Entry<T, Integer> entry : map.entrySet()) { final int count = entry.getValue(); if (count <= 0) { throw new IllegalStateException(); } if (count > 1) { duplicates += count - 1; sb.append(entry.getKey() + ": " + count + "\n"); } } if (duplicates > 0) { Assertions.fail(duplicates + " duplicates\n" + sb); } } @Test void testCreateIntArrayWithZeroSize() { Assertions.assertArrayEquals(new int[0], SeedFactory.createIntArray(0)); } @Test void testCreateIntArrayWithCompleteBlockSize() { // Block size is 8 for int assertCreateIntArray(8); } @Test void testCreateIntArrayWithIncompleteBlockSize() { // Block size is 8 for int assertCreateIntArray(8 + 1); } /** * Checks that the int array values can be placed into 2 bins with * approximately equal number of counts. * The test uses the expectation from a fixed-step "random walk". * * @param n The size of the array. */ private static void assertCreateIntArray(int n) { final int[] array = SeedFactory.createIntArray(n); Assertions.assertEquals(n, array.length, "Incorrect array length"); // The bit count should be 50%. int bitCount = 0; for (final int i : array) { bitCount += Integer.bitCount(i); } final int numberOfBits = n * Integer.SIZE; assertMonobit(bitCount, numberOfBits); } @Test void testCreateLongArrayWithZeroSize() { Assertions.assertArrayEquals(new long[0], SeedFactory.createLongArray(0)); } @Test void testCreateLongArrayWithCompleteBlockSize() { // Block size is 4 for long assertCreateLongArray(4); } @Test void testCreateLongArrayWithIncompleteBlockSize() { // Block size is 4 for long assertCreateLongArray(4 + 1); } /** * Checks that the long array values can be placed into 2 bins with * approximately equal number of counts. * The test uses the expectation from a fixed-step "random walk". * * @param n The size of the array. */ private static void assertCreateLongArray(int n) { final long[] array = SeedFactory.createLongArray(n); Assertions.assertEquals(n, array.length, "Incorrect array length"); // The bit count should be 50%. int bitCount = 0; for (final long i : array) { bitCount += Long.bitCount(i); } final int numberOfBits = n * Long.SIZE; assertMonobit(bitCount, numberOfBits); } /** * Assert that the number of 1 bits is approximately 50%. This is based upon a * fixed-step "random walk" of +1/-1 from zero. * * <p>The test is equivalent to the NIST Monobit test with a fixed p-value of 0.0001. * The number of bits is recommended to be above 100.</p> * * @see <A * href="https://csrc.nist.gov/publications/detail/sp/800-22/rev-1a/final">Bassham, et * al (2010) NIST SP 800-22: A Statistical Test Suite for Random and Pseudorandom * Number Generators for Cryptographic Applications. Section 2.1.</a> * * @param bitCount The bit count. * @param numberOfBits Number of bits. */ private static void assertMonobit(int bitCount, int numberOfBits) { // Convert the bit count into a number of +1/-1 steps. final double sum = 2.0 * bitCount - numberOfBits; // The reference distribution is Normal with a standard deviation of sqrt(n). // Check the absolute position is not too far from the mean of 0 with a fixed // p-value of 0.0001 taken from a 2-tailed Normal distribution. Computation of // the p-value requires the complimentary error function. // The p-value is set to be equal to a 0.01 with 1 allowed re-run. // (Re-runs are not configured for this test.) final double absSum = Math.abs(sum); final double max = Math.sqrt(numberOfBits) * 3.891; Assertions.assertTrue(absSum <= max, () -> "Walked too far astray: " + absSum + " > " + max + " (test will fail randomly about 1 in 10,000 times)"); } @Test void testCreateByteArrayWithSizeZero() { assertCreateByteArray(new byte[0]); } @Test void testCreateByteArrayIgnoresNonZeroPositions() { final byte position = 123; int n = 3; for (int i = 0; i < n; i++) { final byte[] expected = new byte[n]; expected[i] = position; assertCreateByteArray(expected); } } /** * Assert that the SeedFactory uses the bytes exactly as generated by the * {@link UniformRandomProvider#nextBytes(byte[])} method (assuming they are not all zero). * * @param expected the expected */ private static void assertCreateByteArray(final byte[] expected) { final UniformRandomProvider rng = new IntProvider() { @Override public int next() { Assertions.fail("This method should not be used"); return 0; } @Override public void nextBytes(byte[] bytes) { System.arraycopy(expected, 0, bytes, 0, Math.min(expected.length, bytes.length)); } }; final byte[] seed = SeedFactory.createByteArray(rng, expected.length, 0, expected.length); Assertions.assertArrayEquals(expected, seed); } @Test void testCreateByteArrayWithAllZeroBytesUpdatesFromTo() { final UniformRandomProvider rng = new IntProvider() { @Override public int next() { // Deliberately produce zero return 0; } }; // Test the method only replaces the target sub-range. // Test all sub-ranges. final int size = 4; for (int start = 0; start < size; start++) { final int from = start; for (int end = start; end < size; end++) { final int to = end; final byte[] seed = SeedFactory.createByteArray(rng, 4, from, to); // Validate for (int i = 0; i < from; i++) { final int index = i; Assertions.assertEquals(0, seed[i], () -> String.format("[%d, %d) zero at position %d should not be modified", from, to, index)); } if (to > from) { byte allBits = 0; for (int i = from; i < to; i++) { allBits |= seed[i]; } Assertions.assertNotEquals(0, allBits, () -> String.format("[%d, %d) should not be all zero", from, to)); } for (int i = to; i < size; i++) { final int index = i; Assertions.assertEquals(0, seed[i], () -> String.format("[%d, %d) zero at position %d should not be modified", from, to, index)); } } } } @Test void testEnsureNonZeroIntArrayIgnoresEmptySeed() { final int[] seed = new int[0]; SeedFactory.ensureNonZero(seed, 0, 0); // Note: Nothing to assert. // This tests an ArrayIndexOutOfBoundsException does not occur. } @ParameterizedTest @CsvSource({ "0, 0, 1", "1, -1, 1", "1, 0, 2", "1, 1, 2", }) void testEnsureNonZeroIntArrayThrowsWithInvalidRange(int n, int from, int to) { final int[] seed = new int[n]; Assertions.assertThrows(IndexOutOfBoundsException.class, () -> SeedFactory.ensureNonZero(seed, from, to)); } @Test void testEnsureNonZeroIntArrayWithAllZeroBytesUpdatesFromTo() { // Test the method only replaces the target sub-range. // Test all sub-ranges. final int size = 4; final int[] seed = new int[size]; for (int start = 0; start < size; start++) { final int from = start; for (int end = start; end < size; end++) { final int to = end; Arrays.fill(seed, 0); SeedFactory.ensureNonZero(seed, from, to); // Validate for (int i = 0; i < from; i++) { final int index = i; Assertions.assertEquals(0, seed[i], () -> String.format("[%d, %d) zero at position %d should not be modified", from, to, index)); } if (to > from) { int allBits = 0; for (int i = from; i < to; i++) { allBits |= seed[i]; } Assertions.assertNotEquals(0, allBits, () -> String.format("[%d, %d) should not be all zero", from, to)); } for (int i = to; i < size; i++) { final int index = i; Assertions.assertEquals(0, seed[i], () -> String.format("[%d, %d) zero at position %d should not be modified", from, to, index)); } } } } @Test void testEnsureNonZeroLongArrayIgnoresEmptySeed() { final long[] seed = new long[0]; SeedFactory.ensureNonZero(seed, 0, 0); // Note: Nothing to assert. // This tests an ArrayIndexOutOfBoundsException does not occur. } @ParameterizedTest @CsvSource({ "0, 0, 1", "1, -1, 1", "1, 0, 2", "1, 1, 2", }) void testEnsureNonZeroLongArrayThrowsWithInvalidRange(int n, int from, int to) { final long[] seed = new long[n]; Assertions.assertThrows(IndexOutOfBoundsException.class, () -> SeedFactory.ensureNonZero(seed, from, to)); } @Test void testEnsureNonZeroLongArrayWithAllZeroBytesUpdatesFromTo() { // Test the method only replaces the target sub-range. // Test all sub-ranges. final int size = 4; final long[] seed = new long[size]; for (int start = 0; start < size; start++) { final int from = start; for (int end = start; end < size; end++) { final int to = end; Arrays.fill(seed, 0); SeedFactory.ensureNonZero(seed, from, to); // Validate for (int i = 0; i < from; i++) { final int index = i; Assertions.assertEquals(0, seed[i], () -> String.format("[%d, %d) zero at position %d should not be modified", from, to, index)); } if (to > from) { long allBits = 0; for (int i = from; i < to; i++) { allBits |= seed[i]; } Assertions.assertNotEquals(0, allBits, () -> String.format("[%d, %d) should not be all zero", from, to)); } for (int i = to; i < size; i++) { final int index = i; Assertions.assertEquals(0, seed[i], () -> String.format("[%d, %d) zero at position %d should not be modified", from, to, index)); } } } } @Test void testEnsureNonZeroByteArrayIgnoresEmptySeed() { final byte[] seed = new byte[0]; final UniformRandomProvider rng = new SplitMix64(123); SeedFactory.ensureNonZero(seed, 0, 0, rng); // Note: Nothing to assert. // This tests an ArrayIndexOutOfBoundsException does not occur. } @ParameterizedTest @CsvSource({ "0, 0, 1", "1, -1, 1", "1, 0, 2", "1, 1, 2", }) void testEnsureNonZeroByteArrayThrowsWithInvalidRange(int n, int from, int to) { final byte[] seed = new byte[n]; final UniformRandomProvider rng = new SplitMix64(123); Assertions.assertThrows(IndexOutOfBoundsException.class, () -> SeedFactory.ensureNonZero(seed, from, to, rng)); } /** * Test the fixed values returned for the zero byte array source of randomness * have specific properties. */ @Test void testZeroByteArraySourceOfRandomness() { Assertions.assertEquals(0, MixFunctions.stafford13(-MixFunctions.GOLDEN_RATIO_64 + MixFunctions.GOLDEN_RATIO_64)); Assertions.assertEquals(0, MixFunctions.stafford13((1463436497261722119L << 1) + MixFunctions.GOLDEN_RATIO_64) & (-1L >>> 56)); Assertions.assertEquals(0, MixFunctions.stafford13((4949471497809997598L << 1) + MixFunctions.GOLDEN_RATIO_64) & (-1L >>> 48)); // Note: // Finding a value x where MixFunctions.stafford13((x << 1) + MixFunctions.GOLDEN_RATIO_64) // is zero for the least significant 7 bytes used inversion of the mix function. // See the MixFunctionsTest for a routine to perform the unmixing. Assertions.assertEquals(0, MixFunctions.stafford13((953042962641938212L << 1) + MixFunctions.GOLDEN_RATIO_64) & (-1L >>> 8)); } @ParameterizedTest @ValueSource(longs = {0, -MixFunctions.GOLDEN_RATIO_64, 1463436497261722119L, 4949471497809997598L, 953042962641938212L}) void testEnsureNonZeroByteArrayWithAllZeroBytesUpdatesFromTo(long next) { // Use a fixed source of randomness to demonstrate the method is robust. // This should only be used when the sub-range is non-zero length. int[] calls = {0}; final UniformRandomProvider rng = new LongProvider() { @Override public long next() { calls[0]++; return next; } }; // Test the method only replaces the target sub-range. // Test all sub-ranges up to size. final int size = 2 * Long.BYTES; final byte[] seed = new byte[size]; for (int start = 0; start < size; start++) { final int from = start; for (int end = start; end < size; end++) { final int to = end; Arrays.fill(seed, (byte) 0); final int before = calls[0]; SeedFactory.ensureNonZero(seed, from, to, rng); // Validate for (int i = 0; i < from; i++) { final int index = i; Assertions.assertEquals(0, seed[i], () -> String.format("[%d, %d) zero at position %d should not be modified", from, to, index)); } if (to > from) { byte allBits = 0; for (int i = from; i < to; i++) { allBits |= seed[i]; } Assertions.assertNotEquals(0, allBits, () -> String.format("[%d, %d) should not be all zero", from, to)); // Check the source was used to seed the sequence Assertions.assertNotEquals(before, calls[0], () -> String.format("[%d, %d) should use the random source", from, to)); } else { // Check the source was not used Assertions.assertEquals(before, calls[0], () -> String.format("[%d, %d) should not use the random source", from, to)); } for (int i = to; i < size; i++) { final int index = i; Assertions.assertEquals(0, seed[i], () -> String.format("[%d, %d) zero at position %d should not be modified", from, to, index)); } } } } @Test void testEnsureNonZeroValue() { final long expected = 345; RandomLongSource source = new RandomLongSource() { @Override public long next() { return expected; } }; Assertions.assertEquals(expected, SeedFactory.ensureNonZero(source, 0), "Zero should be replaced using the random source"); for (final long nonZero : new long[] {Long.MIN_VALUE, -1, 1, 9876654321L, Long.MAX_VALUE}) { Assertions.assertEquals(nonZero, SeedFactory.ensureNonZero(source, nonZero), "Non-zero should be unmodified"); } } }
2,858
0
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple/internal/NoOpConverterTest.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.simple.internal; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Tests for the {@link NoOpConverter}. */ class NoOpConverterTest { @Test void testNoOpIntegerCoversion() { final NoOpConverter<Integer> converter = new NoOpConverter<>(); final Integer in = 123; Assertions.assertSame(in, converter.convert(in)); } @Test void testNoOpLongArrayCoversion() { final NoOpConverter<long[]> converter = new NoOpConverter<>(); final long[] in = {123L, 456L, Long.MAX_VALUE}; Assertions.assertSame(in, converter.convert(in)); } }
2,859
0
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/test/java/org/apache/commons/rng/simple/internal/ConversionsTest.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.simple.internal; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Arrays; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.IntStream; import java.util.stream.LongStream; import org.apache.commons.rng.core.source64.SplitMix64; import org.apache.commons.rng.core.util.NumberFactory; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; /** * Tests for {@link Conversions}. */ class ConversionsTest { /** * 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> */ private static final long GOLDEN_RATIO = 0x9e3779b97f4a7c15L; /** * Gets the lengths for the byte[] seeds to convert. * * @return the lengths */ static IntStream getByteLengths() { return IntStream.rangeClosed(0, Long.BYTES * 2); } /** * Gets the lengths for the int[] seeds to convert. * * @return the lengths */ static IntStream getIntLengths() { return IntStream.rangeClosed(0, (Long.BYTES / Integer.BYTES) * 2); } /** * Gets the lengths for the long[] seeds to convert. * * @return the lengths */ static IntStream getLongLengths() { return IntStream.rangeClosed(0, 2); } @ParameterizedTest @ValueSource(ints = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, Integer.MAX_VALUE}) void testIntSizeFromByteSize(int size) { Assertions.assertEquals((int) Math.ceil((double) size / Integer.BYTES), Conversions.intSizeFromByteSize(size)); } @ParameterizedTest @ValueSource(ints = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, Integer.MAX_VALUE}) void testLongSizeFromByteSize(int size) { Assertions.assertEquals((int) Math.ceil((double) size / Long.BYTES), Conversions.longSizeFromByteSize(size)); } @ParameterizedTest @ValueSource(ints = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, Integer.MAX_VALUE}) void testIntSizeFromLongSize(int size) { Assertions.assertEquals((int) Math.min(size * 2L, Integer.MAX_VALUE), Conversions.intSizeFromLongSize(size)); } @ParameterizedTest @ValueSource(ints = {0, 1, 2, 3, 4, 5, Integer.MAX_VALUE}) void testLongSizeFromIntSize(int size) { Assertions.assertEquals((int) Math.ceil((double) size / 2), Conversions.longSizeFromIntSize(size)); } @RepeatedTest(value = 5) void testInt2Long() { final int v = ThreadLocalRandom.current().nextInt(); Assertions.assertEquals(new SplitMix64(v).nextLong(), Conversions.int2Long(v)); } @RepeatedTest(value = 5) void testInt2IntArray() { final int v = ThreadLocalRandom.current().nextInt(); getIntLengths().forEach(len -> { Assertions.assertArrayEquals(Conversions.long2IntArray(v, len), Conversions.int2IntArray(v, len)); }); } @RepeatedTest(value = 5) void testInt2LongArray() { final int v = ThreadLocalRandom.current().nextInt(); getIntLengths().forEach(len -> { final long[] a = Conversions.int2LongArray(v, len); Assertions.assertArrayEquals(Conversions.long2LongArray(v, len), a); if (len != 0) { // Special case of expansion to length 1 // Expandion is done by mixing Assertions.assertEquals(Conversions.int2Long(v), a[0]); } }); } @RepeatedTest(value = 5) void testLong2Int() { final long v = ThreadLocalRandom.current().nextLong(); Assertions.assertEquals(NumberFactory.makeInt(v), Conversions.long2Int(v)); } @RepeatedTest(value = 5) void testLong2IntArray() { // Avoid seed == 0 - 0x9e3779b97f4a7c15L. See testLong2IntArrayLength2NotAllZero. long seed; do { seed = ThreadLocalRandom.current().nextLong(); } while (seed == -GOLDEN_RATIO); final long v = seed; getIntLengths().forEach(len -> { final int longs = Conversions.longSizeFromIntSize(len); // Little-endian conversion final ByteBuffer bb = ByteBuffer.allocate(longs * Long.BYTES).order(ByteOrder.LITTLE_ENDIAN); LongStream.generate(new SplitMix64(v)::nextLong).limit(longs).forEach(bb::putLong); bb.clear(); final int[] expected = new int[len]; for (int i = 0; i < len; i++) { expected[i] = bb.getInt(); } Assertions.assertArrayEquals(expected, Conversions.long2IntArray(v, len)); // Note: // long -> int[] position[0] != long -> int // Reduction is done by folding upper and lower using xor }); } /** * Test the long2IntArray conversion avoids an input that will generate a zero from the * SplitMix64-style RNG. This prevents creating an array of length 2 that is zero. * * <p>This special case avoids creating a small state Xor-based generator such as * XoRoShiRo64StarStar with a seed of all zeros. */ @Test void testLong2IntArrayLength2NotAllZero() { // The first output from the SplitMix64 is mix(seed + GOLDEN_RATIO). // Create the seed to ensure a zero output from the mix function. final long seed = -GOLDEN_RATIO; Assertions.assertEquals(0, new SplitMix64(seed).nextLong()); // Note: This cannot occur for int2IntArray as the SplitMix64 is seeded with the int. // This ignores the case of an output int[] of length 1 which could be zero. // An int -> int[1] conversion is nonsensical and should not be performed by the library. Assertions.assertNotEquals(0, new SplitMix64((int) seed).nextLong()); // The conversion should detect this case and a zero seed of length 2 should not happen. final int[] actual = Conversions.long2IntArray(seed, 2); Assertions.assertFalse(Arrays.equals(new int[2], actual)); // Longer arrays may be a partially zero as the generator state passes through // the zero-point. Assertions.assertArrayEquals( Arrays.copyOf(Conversions.long2IntArray(seed - GOLDEN_RATIO, 2), 4), Conversions.long2IntArray(seed - GOLDEN_RATIO, 4)); } @RepeatedTest(value = 5) void testLong2LongArray() { final long v = ThreadLocalRandom.current().nextLong(); getIntLengths().forEach(len -> { Assertions.assertArrayEquals(LongStream.generate(new SplitMix64(v)::nextLong).limit(len).toArray(), Conversions.long2LongArray(v, len)); }); } @ParameterizedTest @MethodSource(value = {"getIntLengths"}) void testIntArray2Int(int ints) { final int[] seed = ThreadLocalRandom.current().ints(ints).toArray(); // xor all the bytes int expected = 0; for (final int i : seed) { expected ^= i; } Assertions.assertEquals(expected, Conversions.intArray2Int(seed)); } @ParameterizedTest @MethodSource(value = {"getIntLengths"}) void testIntArray2Long(int ints) { final int[] seed = ThreadLocalRandom.current().ints(ints).toArray(); // int[] -> long[] -> long // Concatenate all ints in little-endian order to bytes final int outLength = Conversions.longSizeFromIntSize(ints); final int[] filledSeed = Arrays.copyOf(seed, outLength * 2); final ByteBuffer bb = ByteBuffer.allocate(filledSeed.length * Integer.BYTES) .order(ByteOrder.LITTLE_ENDIAN); Arrays.stream(filledSeed).forEach(bb::putInt); // xor all the bytes read as longs long expected = 0; bb.flip(); for (int i = outLength; i-- != 0;) { final long l = bb.getLong(); expected ^= l; } Assertions.assertEquals(expected, Conversions.intArray2Long(seed)); } @ParameterizedTest @MethodSource(value = {"getIntLengths"}) void testIntArray2LongComposed(int ints) { final int[] seed = ThreadLocalRandom.current().ints(ints).toArray(); final long expected = new LongArray2Long().convert(new IntArray2LongArray().convert(seed)); Assertions.assertEquals(expected, Conversions.intArray2Long(seed)); } @ParameterizedTest @MethodSource(value = {"getIntLengths"}) void testIntArray2LongArray(int ints) { final int[] seed = ThreadLocalRandom.current().ints(ints).toArray(); // Concatenate all bytes in little-endian order to bytes final int outLength = Conversions.longSizeFromIntSize(ints); final ByteBuffer bb = ByteBuffer.allocate(outLength * Long.BYTES) .order(ByteOrder.LITTLE_ENDIAN); Arrays.stream(seed).forEach(bb::putInt); bb.clear(); final long[] expected = new long[outLength]; for (int i = 0; i < outLength; i++) { expected[i] = bb.getLong(); } Assertions.assertArrayEquals(expected, Conversions.intArray2LongArray(seed, outLength)); // Zero fill Assertions.assertArrayEquals(Arrays.copyOf(expected, outLength * 2), Conversions.intArray2LongArray(seed, outLength * 2)); // Truncation for (int i = 0; i < outLength; i++) { Assertions.assertArrayEquals(Arrays.copyOf(expected, i), Conversions.intArray2LongArray(seed, i)); } } @ParameterizedTest @MethodSource(value = {"getLongLengths"}) void testLongArray2Int(long longs) { final long[] seed = ThreadLocalRandom.current().longs(longs).toArray(); // xor all the bytes long expected = 0; for (final long i : seed) { expected ^= i; } Assertions.assertEquals((int) (expected ^ expected >>> 32), Conversions.longArray2Int(seed)); } @ParameterizedTest @MethodSource(value = {"getLongLengths"}) void testLongArray2Long(long longs) { final long[] seed = ThreadLocalRandom.current().longs(longs).toArray(); // xor all the bytes long expected = 0; for (final long i : seed) { expected ^= i; } Assertions.assertEquals(expected, Conversions.longArray2Long(seed)); } @ParameterizedTest @MethodSource(value = {"getLongLengths"}) void testLongArray2IntArray(int longs) { final long[] seed = ThreadLocalRandom.current().longs(longs).toArray(); // Concatenate all bytes in little-endian order to bytes final int outLength = Conversions.intSizeFromLongSize(longs); final ByteBuffer bb = ByteBuffer.allocate(longs * Long.BYTES) .order(ByteOrder.LITTLE_ENDIAN); Arrays.stream(seed).forEach(bb::putLong); bb.clear(); final int[] expected = new int[outLength]; for (int i = 0; i < outLength; i++) { expected[i] = bb.getInt(); } Assertions.assertArrayEquals(expected, Conversions.longArray2IntArray(seed, outLength)); // Zero fill Assertions.assertArrayEquals(Arrays.copyOf(expected, outLength * 2), Conversions.longArray2IntArray(seed, outLength * 2)); // Truncation for (int i = 0; i < outLength; i++) { Assertions.assertArrayEquals(Arrays.copyOf(expected, i), Conversions.longArray2IntArray(seed, i)); } } @ParameterizedTest @MethodSource(value = {"getByteLengths"}) void testByteArray2Int(int bytes) { final byte[] seed = new byte[bytes]; ThreadLocalRandom.current().nextBytes(seed); // byte[] -> int[] -> int // Concatenate all bytes in little-endian order to bytes final int outLength = Conversions.intSizeFromByteSize(bytes); final byte[] filledSeed = Arrays.copyOf(seed, outLength * Integer.BYTES); final ByteBuffer bb = ByteBuffer.wrap(filledSeed) .order(ByteOrder.LITTLE_ENDIAN); // xor all the bytes read as ints int expected = 0; for (int i = outLength; i-- != 0;) { final long l = bb.getInt(); expected ^= l; } Assertions.assertEquals(expected, Conversions.byteArray2Int(seed)); } @ParameterizedTest @MethodSource(value = {"getByteLengths"}) void testByteArray2IntComposed(int bytes) { final byte[] seed = new byte[bytes]; ThreadLocalRandom.current().nextBytes(seed); final int expected = new IntArray2Int().convert(new ByteArray2IntArray().convert(seed)); Assertions.assertEquals(expected, Conversions.byteArray2Int(seed)); } @ParameterizedTest @MethodSource(value = {"getByteLengths"}) void testByteArray2IntArray(int bytes) { final byte[] seed = new byte[bytes]; ThreadLocalRandom.current().nextBytes(seed); // Concatenate all bytes in little-endian order to bytes final int outLength = Conversions.intSizeFromByteSize(bytes); final byte[] filledSeed = Arrays.copyOf(seed, outLength * Integer.BYTES); final ByteBuffer bb = ByteBuffer.wrap(filledSeed) .order(ByteOrder.LITTLE_ENDIAN); final int[] expected = new int[outLength]; for (int i = 0; i < outLength; i++) { expected[i] = bb.getInt(); } Assertions.assertArrayEquals(expected, Conversions.byteArray2IntArray(seed, outLength)); // Zero fill Assertions.assertArrayEquals(Arrays.copyOf(expected, outLength * 2), Conversions.byteArray2IntArray(seed, outLength * 2)); // Truncation for (int i = 0; i < outLength; i++) { Assertions.assertArrayEquals(Arrays.copyOf(expected, i), Conversions.byteArray2IntArray(seed, i)); } } @ParameterizedTest @MethodSource(value = {"getByteLengths"}) void testByteArray2Long(int bytes) { final byte[] seed = new byte[bytes]; ThreadLocalRandom.current().nextBytes(seed); // byte[] -> long[] -> long // Concatenate all bytes in little-endian order to bytes final int outLength = Conversions.longSizeFromByteSize(bytes); final byte[] filledSeed = Arrays.copyOf(seed, outLength * Long.BYTES); final ByteBuffer bb = ByteBuffer.wrap(filledSeed) .order(ByteOrder.LITTLE_ENDIAN); // xor all the bytes read as longs long expected = 0; for (int i = outLength; i-- != 0;) { final long l = bb.getLong(); expected ^= l; } Assertions.assertEquals(expected, Conversions.byteArray2Long(seed)); } @ParameterizedTest @MethodSource(value = {"getByteLengths"}) void testByteArray2LongComposed(int bytes) { final byte[] seed = new byte[bytes]; ThreadLocalRandom.current().nextBytes(seed); final long expected = new LongArray2Long().convert(new ByteArray2LongArray().convert(seed)); Assertions.assertEquals(expected, Conversions.byteArray2Long(seed)); } @ParameterizedTest @MethodSource(value = {"getByteLengths"}) void testByteArray2LongArray(int bytes) { final byte[] seed = new byte[bytes]; ThreadLocalRandom.current().nextBytes(seed); // Concatenate all bytes in little-endian order to bytes final int outLength = Conversions.longSizeFromByteSize(bytes); final byte[] filledSeed = Arrays.copyOf(seed, outLength * Long.BYTES); final ByteBuffer bb = ByteBuffer.wrap(filledSeed) .order(ByteOrder.LITTLE_ENDIAN); final long[] expected = new long[outLength]; for (int i = 0; i < outLength; i++) { expected[i] = bb.getLong(); } Assertions.assertArrayEquals(expected, Conversions.byteArray2LongArray(seed, outLength)); // Zero fill Assertions.assertArrayEquals(Arrays.copyOf(expected, outLength * 2), Conversions.byteArray2LongArray(seed, outLength * 2)); // Truncation for (int i = 0; i < outLength; i++) { Assertions.assertArrayEquals(Arrays.copyOf(expected, i), Conversions.byteArray2LongArray(seed, i)); } } }
2,860
0
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple/ThreadLocalRandomSource.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.simple; import java.util.EnumMap; import org.apache.commons.rng.UniformRandomProvider; /** * This class provides a thread-local {@link UniformRandomProvider}. * * <p>The {@link UniformRandomProvider} is created once-per-thread using the default * construction method {@link RandomSource#create()}. * * <p>Example:</p> * <pre><code> * import org.apache.commons.rng.simple.RandomSource; * import org.apache.commons.rng.simple.ThreadLocalRandomSource; * import org.apache.commons.rng.sampling.distribution.PoissonSampler; * * // Access a thread-safe random number generator * UniformRandomProvider rng = ThreadLocalRandomSource.current(RandomSource.SPLIT_MIX_64); * * // One-time Poisson sample * double mean = 12.3; * int counts = PoissonSampler.of(rng, mean).sample(); * </code></pre> * * <p>Note if the {@link RandomSource} requires additional arguments then it is not * supported. The same can be achieved using:</p> * * <pre><code> * import org.apache.commons.rng.simple.RandomSource; * import org.apache.commons.rng.sampling.distribution.PoissonSampler; * * // Provide a thread-safe random number generator with data arguments * private static ThreadLocal&lt;UniformRandomProvider&gt; rng = * new ThreadLocal&lt;UniformRandomProvider&gt;() { * &#64;Override * protected UniformRandomProvider initialValue() { * return RandomSource.TWO_CMRES_SELECT.create(null, 3, 4); * } * }; * * // One-time Poisson sample using a thread-safe random number generator * double mean = 12.3; * int counts = PoissonSampler.of(rng.get(), mean).sample(); * </code></pre> * * @since 1.3 */ public final class ThreadLocalRandomSource { /** * A map containing the {@link ThreadLocal} instance for each {@link RandomSource}. * * <p>This should only be modified to create new instances in a synchronized block. */ private static final EnumMap<RandomSource, ThreadLocal<UniformRandomProvider>> SOURCES = new EnumMap<>(RandomSource.class); /** No public construction. */ private ThreadLocalRandomSource() {} /** * Extend the {@link ThreadLocal} to allow creation of the desired {@link RandomSource}. */ private static class ThreadLocalRng extends ThreadLocal<UniformRandomProvider> { /** The source. */ private final RandomSource source; /** * Create a new instance. * * @param source the source */ ThreadLocalRng(RandomSource source) { this.source = source; } @Override protected UniformRandomProvider initialValue() { // Create with the default seed generation method return source.create(); } } /** * Returns the current thread's copy of the given {@code source}. If there is no * value for the current thread, it is first initialized to the value returned * by {@link RandomSource#create()}. * * <p>Note if the {@code source} requires additional arguments then it is not * supported. * * @param source the source * @return the current thread's value of the {@code source}. * @throws IllegalArgumentException if the source is null or the source requires arguments */ public static UniformRandomProvider current(RandomSource source) { ThreadLocal<UniformRandomProvider> rng = SOURCES.get(source); // Implement double-checked locking: // https://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Java if (rng == null) { // Do the checks on the source here since it is an edge case // and the EnumMap handles null (returning null). if (source == null) { throw new IllegalArgumentException("Random source is null"); } synchronized (SOURCES) { rng = SOURCES.computeIfAbsent(source, ThreadLocalRng::new); } } return rng.get(); } }
2,861
0
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple/JDKRandomBridge.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.simple; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.ObjectInputStream; import java.util.Random; import org.apache.commons.rng.RestorableUniformRandomProvider; import org.apache.commons.rng.core.RandomProviderDefaultState; /** * Subclass of {@link Random} that {@link #next(int) delegates} to a * {@link RestorableUniformRandomProvider} instance but will otherwise rely * on the base class for generating all the random types. * * <p>Legacy applications coded against the JDK's API could use this subclass * of {@link Random} in order to replace its linear congruential generator * by any {@link RandomSource}.</p> * * <p>Caveat: Use of this class is <em>not</em> recommended for new applications. * In particular, there is no guarantee that the serialized form of this class * will be compatible across (even <em>minor</em>) releases of the library.</p> * * @since 1.0 */ public final class JDKRandomBridge extends Random { /** Serializable version identifier. */ private static final long serialVersionUID = 20161107L; /** Source. */ private final RandomSource source; /** Delegate. */ private transient RestorableUniformRandomProvider delegate; /** Workaround JDK's "Random" bug: https://bugs.openjdk.java.net/browse/JDK-8154225. */ private final transient boolean isInitialized; /** * Creates a new instance. * * @param source Source of randomness. * @param seed Seed. Can be {@code null}. */ public JDKRandomBridge(RandomSource source, Object seed) { this.source = source; delegate = source.create(seed); isInitialized = true; } /** {@inheritDoc} */ @Override public synchronized void setSeed(long seed) { if (isInitialized) { delegate = source.create(seed); // Force the clearing of the "haveNextNextGaussian" flag // (cf. Javadoc of the base class); the value passed here // is irrelevant (since it will not be used). super.setSeed(0L); } } /** * Delegates the generation of 32 random bits to the * {@code RandomSource} argument provided at * {@link #JDKRandomBridge(RandomSource,Object) construction}. * The returned value is such that if the source of randomness is * {@link RandomSource#JDK}, all the generated values will be identical * to those produced by the same sequence of calls on a {@link Random} * instance initialized with the same seed. * * @param n Number of random bits which the requested value must contain. * @return the value represented by the {@code n} high-order bits of a * pseudo-random 32-bits integer. */ @Override protected int next(int n) { synchronized (this) { return delegate.nextInt() >>> (32 - n); } } /** * @param output Output stream. * @throws IOException if an error occurs. */ private void writeObject(ObjectOutputStream output) throws IOException { synchronized (this) { // Write non-transient fields. output.defaultWriteObject(); // Save current state and size. // Avoid the use of ObjectOutputStream.writeObject(Object) to save the state. // This allows deserialization to avoid security issues in using readObject(). final byte[] state = ((RandomProviderDefaultState) delegate.saveState()).getState(); final int size = state.length; output.writeInt(size); output.write(state); } } /** * @param input Input stream. * @throws IOException if an error occurs. * @throws ClassNotFoundException if an error occurs. */ private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { // Read non-transient fields. input.defaultReadObject(); // Recreate the "delegate" from serialized info. delegate = source.create(); // And restore its state. // Avoid the use of input.readObject() to deserialize by manually reading the byte[]. // Note: ObjectInputStream.readObject() will execute the readObject() method of the named // class in the stream which may contain potentially malicious code. final int size = input.readInt(); final byte[] state = new byte[size]; input.readFully(state); delegate.restoreState(new RandomProviderDefaultState(state)); } }
2,862
0
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple/JDKRandomWrapper.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.simple; import org.apache.commons.rng.UniformRandomProvider; import java.util.Random; /** * Wraps a {@link Random} instance to implement {@link UniformRandomProvider}. All methods from * the {@code Random} that match those in {@code UniformRandomProvider} are used directly. * * <p>This class can be used to wrap an instance of * {@link java.security.SecureRandom SecureRandom}. The {@code SecureRandom} class provides * cryptographic random number generation. The features available depend on the Java version * and platform. Consult the Java documentation for more details.</p> * * <p>Note: Use of {@code java.util.Random} is <em>not</em> recommended for applications. * There are many other pseudo-random number generators that are statistically superior and often * faster (see {@link RandomSource}).</p> * * @see java.security.SecureRandom * @see RandomSource * @since 1.3 */ public final class JDKRandomWrapper implements UniformRandomProvider { /** The JDK Random instance. */ private final Random rng; /** * Create a wrapper around a Random instance. * * @param rng JDK {@link Random} instance to which the random number * generation is delegated. */ public JDKRandomWrapper(Random rng) { this.rng = rng; } /** {@inheritDoc} */ @Override public void nextBytes(byte[] bytes) { rng.nextBytes(bytes); } /** {@inheritDoc} */ @Override public void nextBytes(byte[] bytes, int start, int len) { final byte[] reduced = new byte[len]; rng.nextBytes(reduced); System.arraycopy(reduced, 0, bytes, start, len); } /** {@inheritDoc} */ @Override public int nextInt() { return rng.nextInt(); } /** {@inheritDoc} */ @Override public int nextInt(int n) { return rng.nextInt(n); } /** {@inheritDoc} */ @Override public long nextLong() { return rng.nextLong(); } /** {@inheritDoc} */ @Override public long nextLong(long n) { // Code copied from "o.a.c.rng.core.BaseProvider". if (n <= 0) { throw new IllegalArgumentException("Must be strictly positive: " + n); } long bits; long val; do { bits = nextLong() >>> 1; val = bits % n; } while (bits - val + (n - 1) < 0); return val; } /** {@inheritDoc} */ @Override public boolean nextBoolean() { return rng.nextBoolean(); } /** {@inheritDoc} */ @Override public float nextFloat() { return rng.nextFloat(); } /** {@inheritDoc} */ @Override public double nextDouble() { return rng.nextDouble(); } }
2,863
0
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple/RandomSource.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.simple; import java.util.stream.DoubleStream; import java.util.stream.IntStream; import java.util.stream.LongStream; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.RestorableUniformRandomProvider; import org.apache.commons.rng.simple.internal.ProviderBuilder; import org.apache.commons.rng.simple.internal.SeedFactory; /** * This class provides the API for creating generators of random numbers. * * <p>Usage examples:</p> * <pre><code> * UniformRandomProvider rng = RandomSource.XO_RO_SHI_RO_128_PP.create(); * </code></pre> * or * <pre><code> * final int[] seed = new int[] { 196, 9, 0, 226 }; * UniformRandomProvider rng = RandomSource.XO_RO_SHI_RO_128_PP.create(seed); * </code></pre> * or * <pre><code> * final int[] seed = RandomSource.createIntArray(256); * UniformRandomProvider rng = RandomSource.XO_RO_SHI_RO_128_PP.create(seed); * </code></pre> * where the enum value is the identifier of the generator's concrete * implementation, and the argument to method {@code create} is the * (optional) seed. * * <p> * In the first form, a random seed will be {@link SeedFactory generated * automatically}; in the second form, a fixed seed is used; a random seed * is explicitly generated in the third form. * </p> * * <h2>Seeding</h2> * <p> * Seeding is the procedure by which a value (or set of values) is * used to <i>initialize</i> a generator instance. * The requirement that a given seed will always result in the same * internal state allows to create different instances of a generator * that will produce the same sequence of pseudo-random numbers. * </p> * * <p> * The type of data used as a seed depends on the concrete implementation * as some types may not provide enough information to fully initialize * the generator's internal state. * <br> * The reference algorithm's seeding procedure (if provided) operates * on a value of a (single) <i>native</i> type: * Each concrete implementation's constructor creates an instance using * the native type whose information contents is used to set the * internal state. * <br> * When the seed value passed by the caller is of the native type, it is * expected that the sequences produced will be identical to those * produced by other implementations of the same reference algorithm. * <br> * However, when the seed value passed by the caller is not of the native * type, a transformation is performed by this library and the resulting * native type value will <i>not</i> contain more information than the * original seed value. * If the algorithm's native type is "simpler" than the type passed by * the caller, then some (unused) information will even be lost. * <br> * The transformation from non-native to native seed type is arbitrary, * as long as it does not reduce the amount of information required by * the algorithm to initialize its state. * The consequence of the transformation is that sequences produced * by this library may <i>not</i> be the same as the sequences produced * by other implementations of the same algorithm! * </p> * * <p> * For each algorithm, the Javadoc mentions the "ideal" size of the seed, * meaning the number of {@code int} or {@code long} values that is neither * too large (i.e. some of the seed is useless) or too small (i.e. an * internal procedure will fill the state with redundant information * computed from the given seed). * </p> * * <p> * Note that some algorithms are inherently sensitive to having too low * diversity in their initial state. * For example, it is often a bad idea to use a seed that is mostly * composed of zeroes, or of repeated values. * </p> * * <p> * This class provides methods to generate random seeds (single values * or arrays of values, of {@code int} or {@code long} types) that can * be passed to the {@link RandomSource#create(Object,Object[]) * generator's factory method}. * </p> * <p> * Although the seed-generating methods defined in this class will likely * return different values each time they are called, there is no guarantee: * </p> * <ul> * <li> * In any sub-sequence, it is <a href="https://en.wikipedia.org/wiki/Birthday_problem"> * expected</a> that the same numbers can occur, with a probability getting * higher as the range of allowed values is smaller and the sequence becomes * longer. * </li> * <li> * It possible that the resulting "seed" will not be <i>good</i> (i.e. * it will not generate a sufficiently uniformly random sequence for the * intended purpose), even if the generator is good! * The only way to ensure that the selected seed will make the generator * produce a good sequence is to submit that sequence to a series of * stringent tests, as provided by tools such as * <a href="http://www.phy.duke.edu/~rgb/General/dieharder.php">dieharder</a> * or <a href="http://simul.iro.umontreal.ca/testu01/tu01.html">TestU01</a>. * </li> * </ul> * * <p> * <b>Note:</b> * Seeding is not equivalent to restoring the internal state of an * <i>already initialized</i> generator. * Indeed, generators can have a state that is more complex than the * seed, and seeding is thus a transformation (from seed to state). * Implementations do not provide the inverse transformation (from * state to seed), hence it is not generally possible to know the seed * that would initialize a new generator instance to the current state * of another instance. * Reseeding is also inefficient if the purpose is to continue the * same sequence where another instance left off, as it would require * to "replay" all the calls performed by that other instance (and it * would require to know the number of calls to the primary source of * randomness, which is also not usually accessible). * </p> * * <h2>Parallel applications</h2> * <p> * For parallel applications, some implementations have provision for producing * non-overlapping sequences by copying the generator and then advancing a large number * of steps in the generator sequence. Repeated jumps can create a series of * child generators that will output non-overlapping sequences over a specified number * of outputs. These implementations are identified using the {@link #isJumpable()} * and {@link #isLongJumpable()} methods. * </p> * <pre><code> * RandomSource source = RandomSource.XO_RO_SHI_RO_128_SS; // Known to be jumpable. * * JumpableUniformRandomProvider jumpable = (JumpableUniformRandomProvider) source.create(); * * // For use in parallel * UniformRandomProvider[] rngs = new UniformRandomProvider[10]; * for (int i = 0; i &lt; rngs.length; i++) { * rngs[i] = jumpable.jump(); * } * </code></pre> * <p> * For implementations that have no provision for producing non-overlapping * sequences, a possible workaround is that each thread uses * a generator of a different type (see {@link #TWO_CMRES_SELECT}). * </p> * * @since 1.0 */ public enum RandomSource { /** * Source of randomness is {@link org.apache.commons.rng.core.source32.JDKRandom}. * <ul> * <li>Native seed type: {@code Long}.</li> * </ul> */ JDK(ProviderBuilder.RandomSourceInternal.JDK), /** * Source of randomness is {@link org.apache.commons.rng.core.source32.Well512a}. * <ul> * <li>Native seed type: {@code int[]}.</li> * <li>Native seed size: 16.</li> * </ul> */ WELL_512_A(ProviderBuilder.RandomSourceInternal.WELL_512_A), /** * Source of randomness is {@link org.apache.commons.rng.core.source32.Well1024a}. * <ul> * <li>Native seed type: {@code int[]}.</li> * <li>Native seed size: 32.</li> * </ul> */ WELL_1024_A(ProviderBuilder.RandomSourceInternal.WELL_1024_A), /** * Source of randomness is {@link org.apache.commons.rng.core.source32.Well19937a}. * <ul> * <li>Native seed type: {@code int[]}.</li> * <li>Native seed size: 624.</li> * </ul> */ WELL_19937_A(ProviderBuilder.RandomSourceInternal.WELL_19937_A), /** * Source of randomness is {@link org.apache.commons.rng.core.source32.Well19937c}. * <ul> * <li>Native seed type: {@code int[]}.</li> * <li>Native seed size: 624.</li> * </ul> */ WELL_19937_C(ProviderBuilder.RandomSourceInternal.WELL_19937_C), /** * Source of randomness is {@link org.apache.commons.rng.core.source32.Well44497a}. * <ul> * <li>Native seed type: {@code int[]}.</li> * <li>Native seed size: 1391.</li> * </ul> */ WELL_44497_A(ProviderBuilder.RandomSourceInternal.WELL_44497_A), /** * Source of randomness is {@link org.apache.commons.rng.core.source32.Well44497b}. * <ul> * <li>Native seed type: {@code int[]}.</li> * <li>Native seed size: 1391.</li> * </ul> */ WELL_44497_B(ProviderBuilder.RandomSourceInternal.WELL_44497_B), /** * Source of randomness is {@link org.apache.commons.rng.core.source32.MersenneTwister}. * <ul> * <li>Native seed type: {@code int[]}.</li> * <li>Native seed size: 624.</li> * </ul> */ MT(ProviderBuilder.RandomSourceInternal.MT), /** * Source of randomness is {@link org.apache.commons.rng.core.source32.ISAACRandom}. * <ul> * <li>Native seed type: {@code int[]}.</li> * <li>Native seed size: 256.</li> * </ul> */ ISAAC(ProviderBuilder.RandomSourceInternal.ISAAC), /** * Source of randomness is {@link org.apache.commons.rng.core.source64.SplitMix64}. * <ul> * <li>Native seed type: {@code Long}.</li> * </ul> */ SPLIT_MIX_64(ProviderBuilder.RandomSourceInternal.SPLIT_MIX_64), /** * Source of randomness is {@link org.apache.commons.rng.core.source64.XorShift1024Star}. * <ul> * <li>Native seed type: {@code long[]}.</li> * <li>Native seed size: 16.</li> * </ul> * * @deprecated Since 1.3, where it is recommended to use {@code XOR_SHIFT_1024_S_PHI} * instead due to its slightly better (more uniform) output. {@code XOR_SHIFT_1024_S} * is still quite usable but both are variants of the same algorithm and maintain their * internal state identically. Their outputs are correlated and the two should not be * used together when independent sequences are assumed. */ @Deprecated XOR_SHIFT_1024_S(ProviderBuilder.RandomSourceInternal.XOR_SHIFT_1024_S), /** * Source of randomness is {@link org.apache.commons.rng.core.source64.TwoCmres}. * This generator is equivalent to {@link #TWO_CMRES_SELECT} with the choice of the * pair {@code (0, 1)} for the two subcycle generators. * <ul> * <li>Native seed type: {@code Integer}.</li> * </ul> */ TWO_CMRES(ProviderBuilder.RandomSourceInternal.TWO_CMRES), /** * Source of randomness is {@link org.apache.commons.rng.core.source64.TwoCmres}, * with explicit selection of the two subcycle generators. * The selection of the subcycle generator is by passing its index in the internal * table, a value between 0 (included) and 13 (included). * The two indices must be different. * Different choices of an ordered pair of indices create independent generators. * <ul> * <li>Native seed type: {@code Integer}.</li> * </ul> */ TWO_CMRES_SELECT(ProviderBuilder.RandomSourceInternal.TWO_CMRES_SELECT), /** * Source of randomness is {@link org.apache.commons.rng.core.source64.MersenneTwister64}. * <ul> * <li>Native seed type: {@code long[]}.</li> * <li>Native seed size: 312.</li> * </ul> */ MT_64(ProviderBuilder.RandomSourceInternal.MT_64), /** * Source of randomness is {@link org.apache.commons.rng.core.source32.MultiplyWithCarry256}. * <ul> * <li>Native seed type: {@code int[]}.</li> * <li>Native seed size: 257.</li> * </ul> */ MWC_256(ProviderBuilder.RandomSourceInternal.MWC_256), /** * Source of randomness is {@link org.apache.commons.rng.core.source32.KISSRandom}. * <ul> * <li>Native seed type: {@code int[]}.</li> * <li>Native seed size: 4.</li> * </ul> */ KISS(ProviderBuilder.RandomSourceInternal.KISS), /** * Source of randomness is {@link org.apache.commons.rng.core.source64.XorShift1024StarPhi}. * <ul> * <li>Native seed type: {@code long[]}.</li> * <li>Native seed size: 16.</li> * </ul> * @since 1.3 */ XOR_SHIFT_1024_S_PHI(ProviderBuilder.RandomSourceInternal.XOR_SHIFT_1024_S_PHI), /** * Source of randomness is {@link org.apache.commons.rng.core.source32.XoRoShiRo64Star}. * <ul> * <li>Native seed type: {@code int[]}.</li> * <li>Native seed size: 2.</li> * </ul> * @since 1.3 */ XO_RO_SHI_RO_64_S(ProviderBuilder.RandomSourceInternal.XO_RO_SHI_RO_64_S), /** * Source of randomness is {@link org.apache.commons.rng.core.source32.XoRoShiRo64StarStar}. * <ul> * <li>Native seed type: {@code int[]}.</li> * <li>Native seed size: 2.</li> * </ul> * @since 1.3 */ XO_RO_SHI_RO_64_SS(ProviderBuilder.RandomSourceInternal.XO_RO_SHI_RO_64_SS), /** * Source of randomness is {@link org.apache.commons.rng.core.source32.XoShiRo128Plus}. * <ul> * <li>Native seed type: {@code int[]}.</li> * <li>Native seed size: 4.</li> * </ul> * @since 1.3 */ XO_SHI_RO_128_PLUS(ProviderBuilder.RandomSourceInternal.XO_SHI_RO_128_PLUS), /** * Source of randomness is {@link org.apache.commons.rng.core.source32.XoShiRo128StarStar}. * <ul> * <li>Native seed type: {@code int[]}.</li> * <li>Native seed size: 4.</li> * </ul> * @since 1.3 */ XO_SHI_RO_128_SS(ProviderBuilder.RandomSourceInternal.XO_SHI_RO_128_SS), /** * Source of randomness is {@link org.apache.commons.rng.core.source64.XoRoShiRo128Plus}. * <ul> * <li>Native seed type: {@code long[]}.</li> * <li>Native seed size: 2.</li> * </ul> * @since 1.3 */ XO_RO_SHI_RO_128_PLUS(ProviderBuilder.RandomSourceInternal.XO_RO_SHI_RO_128_PLUS), /** * Source of randomness is {@link org.apache.commons.rng.core.source64.XoRoShiRo128StarStar}. * <ul> * <li>Native seed type: {@code long[]}.</li> * <li>Native seed size: 2.</li> * </ul> * @since 1.3 */ XO_RO_SHI_RO_128_SS(ProviderBuilder.RandomSourceInternal.XO_RO_SHI_RO_128_SS), /** * Source of randomness is {@link org.apache.commons.rng.core.source64.XoShiRo256Plus}. * <ul> * <li>Native seed type: {@code long[]}.</li> * <li>Native seed size: 4.</li> * </ul> * @since 1.3 */ XO_SHI_RO_256_PLUS(ProviderBuilder.RandomSourceInternal.XO_SHI_RO_256_PLUS), /** * Source of randomness is {@link org.apache.commons.rng.core.source64.XoShiRo256StarStar}. * <ul> * <li>Native seed type: {@code long[]}.</li> * <li>Native seed size: 4.</li> * </ul> * @since 1.3 */ XO_SHI_RO_256_SS(ProviderBuilder.RandomSourceInternal.XO_SHI_RO_256_SS), /** * Source of randomness is {@link org.apache.commons.rng.core.source64.XoShiRo512Plus}. * <ul> * <li>Native seed type: {@code long[]}.</li> * <li>Native seed size: 8.</li> * </ul> * @since 1.3 */ XO_SHI_RO_512_PLUS(ProviderBuilder.RandomSourceInternal.XO_SHI_RO_512_PLUS), /** * Source of randomness is {@link org.apache.commons.rng.core.source64.XoShiRo512StarStar}. * <ul> * <li>Native seed type: {@code long[]}.</li> * <li>Native seed size: 8.</li> * </ul> * @since 1.3 */ XO_SHI_RO_512_SS(ProviderBuilder.RandomSourceInternal.XO_SHI_RO_512_SS), /** * Source of randomness is {@link org.apache.commons.rng.core.source32.PcgXshRr32}. * <ul> * <li>Native seed type: {@code long[]}.</li> * <li>Native seed size: 2.</li> * </ul> * @since 1.3 */ PCG_XSH_RR_32(ProviderBuilder.RandomSourceInternal.PCG_XSH_RR_32), /** * Source of randomness is {@link org.apache.commons.rng.core.source32.PcgXshRs32}. * <ul> * <li>Native seed type: {@code long[]}.</li> * <li>Native seed size: 2.</li> * </ul> * @since 1.3 */ PCG_XSH_RS_32(ProviderBuilder.RandomSourceInternal.PCG_XSH_RS_32), /** * Source of randomness is {@link org.apache.commons.rng.core.source64.PcgRxsMXs64}. * <ul> * <li>Native seed type: {@code long[]}.</li> * <li>Native seed size: 2.</li> * </ul> * @since 1.3 */ PCG_RXS_M_XS_64(ProviderBuilder.RandomSourceInternal.PCG_RXS_M_XS_64), /** * Source of randomness is {@link org.apache.commons.rng.core.source32.PcgMcgXshRr32}. * <ul> * <li>Native seed type: {@code Long}.</li> * </ul> * @since 1.3 */ PCG_MCG_XSH_RR_32(ProviderBuilder.RandomSourceInternal.PCG_MCG_XSH_RR_32), /** * Source of randomness is {@link org.apache.commons.rng.core.source32.PcgMcgXshRs32}. * <ul> * <li>Native seed type: {@code Long}.</li> * </ul> * @since 1.3 */ PCG_MCG_XSH_RS_32(ProviderBuilder.RandomSourceInternal.PCG_MCG_XSH_RS_32), /** * Source of randomness is {@link org.apache.commons.rng.core.source32.MiddleSquareWeylSequence}. * <ul> * <li>Native seed type: {@code long[]}.</li> * <li>Native seed size: 3.</li> * </ul> * @since 1.3 */ MSWS(ProviderBuilder.RandomSourceInternal.MSWS), /** * Source of randomness is {@link org.apache.commons.rng.core.source32.DotyHumphreySmallFastCounting32}. * <ul> * <li>Native seed type: {@code int[]}.</li> * <li>Native seed size: 3.</li> * </ul> * @since 1.3 */ SFC_32(ProviderBuilder.RandomSourceInternal.SFC_32), /** * Source of randomness is {@link org.apache.commons.rng.core.source64.DotyHumphreySmallFastCounting64}. * <ul> * <li>Native seed type: {@code long[]}.</li> * <li>Native seed size: 3.</li> * </ul> * @since 1.3 */ SFC_64(ProviderBuilder.RandomSourceInternal.SFC_64), /** * Source of randomness is {@link org.apache.commons.rng.core.source32.JenkinsSmallFast32}. * <ul> * <li>Native seed type: {@code Integer}.</li> * </ul> * @since 1.3 */ JSF_32(ProviderBuilder.RandomSourceInternal.JSF_32), /** * Source of randomness is {@link org.apache.commons.rng.core.source64.JenkinsSmallFast64}. * <ul> * <li>Native seed type: {@code Long}.</li> * </ul> * @since 1.3 */ JSF_64(ProviderBuilder.RandomSourceInternal.JSF_64), /** * Source of randomness is {@link org.apache.commons.rng.core.source32.XoShiRo128PlusPlus}. * <ul> * <li>Native seed type: {@code int[]}.</li> * <li>Native seed size: 4.</li> * </ul> * @since 1.3 */ XO_SHI_RO_128_PP(ProviderBuilder.RandomSourceInternal.XO_SHI_RO_128_PP), /** * Source of randomness is {@link org.apache.commons.rng.core.source64.XoRoShiRo128PlusPlus}. * <ul> * <li>Native seed type: {@code long[]}.</li> * <li>Native seed size: 2.</li> * </ul> * @since 1.3 */ XO_RO_SHI_RO_128_PP(ProviderBuilder.RandomSourceInternal.XO_RO_SHI_RO_128_PP), /** * Source of randomness is {@link org.apache.commons.rng.core.source64.XoShiRo256PlusPlus}. * <ul> * <li>Native seed type: {@code long[]}.</li> * <li>Native seed size: 4.</li> * </ul> * @since 1.3 */ XO_SHI_RO_256_PP(ProviderBuilder.RandomSourceInternal.XO_SHI_RO_256_PP), /** * Source of randomness is {@link org.apache.commons.rng.core.source64.XoShiRo512PlusPlus}. * <ul> * <li>Native seed type: {@code long[]}.</li> * <li>Native seed size: 8.</li> * </ul> * @since 1.3 */ XO_SHI_RO_512_PP(ProviderBuilder.RandomSourceInternal.XO_SHI_RO_512_PP), /** * Source of randomness is {@link org.apache.commons.rng.core.source64.XoRoShiRo1024PlusPlus}. * <ul> * <li>Native seed type: {@code long[]}.</li> * <li>Native seed size: 16.</li> * </ul> * @since 1.3 */ XO_RO_SHI_RO_1024_PP(ProviderBuilder.RandomSourceInternal.XO_RO_SHI_RO_1024_PP), /** * Source of randomness is {@link org.apache.commons.rng.core.source64.XoRoShiRo1024Star}. * <ul> * <li>Native seed type: {@code long[]}.</li> * <li>Native seed size: 16.</li> * </ul> * @since 1.3 */ XO_RO_SHI_RO_1024_S(ProviderBuilder.RandomSourceInternal.XO_RO_SHI_RO_1024_S), /** * Source of randomness is {@link org.apache.commons.rng.core.source64.XoRoShiRo1024StarStar}. * <ul> * <li>Native seed type: {@code long[]}.</li> * <li>Native seed size: 16.</li> * </ul> * @since 1.3 */ XO_RO_SHI_RO_1024_SS(ProviderBuilder.RandomSourceInternal.XO_RO_SHI_RO_1024_SS), /** * Source of randomness is {@link org.apache.commons.rng.core.source32.PcgXshRr32}. * <ul> * <li>Native seed type: {@code Long}.</li> * </ul> * @since 1.4 */ PCG_XSH_RR_32_OS(ProviderBuilder.RandomSourceInternal.PCG_XSH_RR_32_OS), /** * Source of randomness is {@link org.apache.commons.rng.core.source32.PcgXshRs32}. * <ul> * <li>Native seed type: {@code Long}.</li> * </ul> * @since 1.4 */ PCG_XSH_RS_32_OS(ProviderBuilder.RandomSourceInternal.PCG_XSH_RS_32_OS), /** * Source of randomness is {@link org.apache.commons.rng.core.source64.PcgRxsMXs64}. * <ul> * <li>Native seed type: {@code Long}.</li> * </ul> * @since 1.4 */ PCG_RXS_M_XS_64_OS(ProviderBuilder.RandomSourceInternal.PCG_RXS_M_XS_64_OS), /** * Source of randomness is {@link org.apache.commons.rng.core.source64.L64X128StarStar}. * <ul> * <li>Native seed type: {@code long[]}.</li> * <li>Native seed size: 4.</li> * </ul> * @since 1.5 */ L64_X128_SS(ProviderBuilder.RandomSourceInternal.L64_X128_SS), /** * Source of randomness is {@link org.apache.commons.rng.core.source64.L64X128Mix}. * <ul> * <li>Native seed type: {@code long[]}.</li> * <li>Native seed size: 4.</li> * </ul> * @since 1.5 */ L64_X128_MIX(ProviderBuilder.RandomSourceInternal.L64_X128_MIX), /** * Source of randomness is {@link org.apache.commons.rng.core.source64.L64X256Mix}. * <ul> * <li>Native seed type: {@code long[]}.</li> * <li>Native seed size: 6.</li> * </ul> * @since 1.5 */ L64_X256_MIX(ProviderBuilder.RandomSourceInternal.L64_X256_MIX), /** * Source of randomness is {@link org.apache.commons.rng.core.source64.L64X1024Mix}. * <ul> * <li>Native seed type: {@code long[]}.</li> * <li>Native seed size: 18.</li> * </ul> * @since 1.5 */ L64_X1024_MIX(ProviderBuilder.RandomSourceInternal.L64_X1024_MIX), /** * Source of randomness is {@link org.apache.commons.rng.core.source64.L128X128Mix}. * <ul> * <li>Native seed type: {@code long[]}.</li> * <li>Native seed size: 6.</li> * </ul> * @since 1.5 */ L128_X128_MIX(ProviderBuilder.RandomSourceInternal.L128_X128_MIX), /** * Source of randomness is {@link org.apache.commons.rng.core.source64.L128X256Mix}. * <ul> * <li>Native seed type: {@code long[]}.</li> * <li>Native seed size: 8.</li> * </ul> * @since 1.5 */ L128_X256_MIX(ProviderBuilder.RandomSourceInternal.L128_X256_MIX), /** * Source of randomness is {@link org.apache.commons.rng.core.source64.L128X1024Mix}. * <ul> * <li>Native seed type: {@code long[]}.</li> * <li>Native seed size: 20.</li> * </ul> * @since 1.5 */ L128_X1024_MIX(ProviderBuilder.RandomSourceInternal.L128_X1024_MIX), /** * Source of randomness is {@link org.apache.commons.rng.core.source32.L32X64Mix}. * <ul> * <li>Native seed type: {@code int[]}.</li> * <li>Native seed size: 4.</li> * </ul> * @since 1.5 */ L32_X64_MIX(ProviderBuilder.RandomSourceInternal.L32_X64_MIX); /** Internal identifier. */ private final ProviderBuilder.RandomSourceInternal internalIdentifier; /** * @param id Internal identifier. */ RandomSource(ProviderBuilder.RandomSourceInternal id) { internalIdentifier = id; } /** * @return the internal identifier. */ ProviderBuilder.RandomSourceInternal getInternalIdentifier() { return internalIdentifier; } /** * Checks whether the type of given {@code seed} is the native type * of the implementation. * * @param seed Seed value. * @return {@code true} if the type of {@code seed} is the native * type for this RNG source. */ public boolean isNativeSeed(Object seed) { return internalIdentifier.isNativeSeed(seed); } /** * Creates a seed suitable for the implementing class represented by this random source. * * <p>The seed will be created as if passing a {@code null} seed to the method * {@link #create(Object, Object...)}. It will satisfy the seed size and any * other seed requirements for the implementing class. The seed is converted from the native * type to a byte representation.</p> * * <p>Usage example:</p> * <pre><code> * RandomSource source = ...; * byte[] seed = source.createSeed(); * UniformRandomProvider rng = source.create(seed); * </code></pre> * * @return the seed * @since 1.3 */ public byte[] createSeed() { return internalIdentifier.createSeedBytes(); } /** * Creates a seed suitable for the implementing class represented by this random source * using the supplied source of randomness. * * <p>The seed will satisfy the seed size and any other seed requirements for the * implementing class.</p> * * <p>Usage example:</p> * <pre><code> * RandomSource source = ...; * UniformRandomProvider seedRng = new JDKRandomWrapper(new SecureRandom()); * byte[] seed = source.createSeed(seedRng); * UniformRandomProvider rng = source.create(seed); * </code></pre> * * @param rng Source of randomness. * @return the seed * @since 1.3 */ public byte[] createSeed(UniformRandomProvider rng) { return internalIdentifier.createSeedBytes(rng); } /** * Checks whether the implementing class represented by this random source * supports the {@link org.apache.commons.rng.JumpableUniformRandomProvider * JumpableUniformRandomProvider} interface. If {@code true} the instance returned * by {@link #create(RandomSource)} may be cast to the interface; otherwise a class * cast exception will occur. * * <p>Usage example:</p> * <pre><code> * RandomSource source = ...; * if (source.isJumpable()) { * JumpableUniformRandomProvider rng = * (JumpableUniformRandomProvider) source.create(); * } * </code></pre> * * @return {@code true} if jumpable * @since 1.3 */ public boolean isJumpable() { return isAssignableTo(org.apache.commons.rng.JumpableUniformRandomProvider.class); } /** * Checks whether the implementing class represented by this random source * supports the {@link org.apache.commons.rng.LongJumpableUniformRandomProvider * LongJumpableUniformRandomProvider} interface. If {@code true} the instance returned * by {@link #create(RandomSource)} may be cast to the interface; otherwise a class * cast exception will occur. * * <p>Usage example:</p> * <pre><code> * RandomSource source = ...; * if (source.isJumpable()) { * LongJumpableUniformRandomProvider rng = * (LongJumpableUniformRandomProvider) source.create(); * } * </code></pre> * * @return {@code true} if long jumpable * @since 1.3 */ public boolean isLongJumpable() { return isAssignableTo(org.apache.commons.rng.LongJumpableUniformRandomProvider.class); } /** * Checks whether the implementing class represented by this random source * supports the {@link org.apache.commons.rng.SplittableUniformRandomProvider * SplittableUniformRandomProvider} interface. If {@code true} the instance returned * by {@link #create(RandomSource)} may be cast to the interface; otherwise a class * cast exception will occur. * * <p>Usage example:</p> * <pre><code> * RandomSource source = ...; * if (source.isSplittable()) { * SplittableUniformRandomProvider rng = * (SplittableUniformRandomProvider) source.create(); * } * </code></pre> * * @return {@code true} if splittable * @since 1.5 */ public boolean isSplittable() { return isAssignableTo(org.apache.commons.rng.SplittableUniformRandomProvider.class); } /** * Determines if the implementing class represented by this random source is either the same * as, or is a subclass or subinterface of, the class or interface represented * by the specified {@code Class} parameter. It returns true if so; otherwise it returns * false. * * @param type the {@code Class} object to be checked * @return the boolean value indicating whether the class of this random source * can be assigned to objects of the specified type */ private boolean isAssignableTo(Class<?> type) { return type.isAssignableFrom(internalIdentifier.getRng()); } /** * Creates a random number generator with a random seed. * * <p>Usage example:</p> * <pre><code> * UniformRandomProvider rng = RandomSource.XO_RO_SHI_RO_128_PP.create(); * </code></pre> * <p>or, if a {@link RestorableUniformRandomProvider "save/restore"} functionality is needed,</p> * <pre><code> * RestorableUniformRandomProvider rng = RandomSource.XO_RO_SHI_RO_128_PP.create(); * </code></pre> * * <p>This method will raise an exception if the generator requires arguments in addition * to a seed (e.g. {@link #TWO_CMRES_SELECT}).</p> * * @return the RNG. * @throws IllegalArgumentException if the generator requires arguments in addition * to a seed. * * @see #create(Object,Object[]) * @since 1.4 */ public RestorableUniformRandomProvider create() { return ProviderBuilder.create(getInternalIdentifier()); } /** * Creates a random number generator with the given {@code seed}. * * <p>Usage example:</p> * <pre><code> * UniformRandomProvider rng = RandomSource.XO_RO_SHI_RO_128_PP.create(0x123abcL); * UniformRandomProvider rng = RandomSource.TWO_CMRES_SELECT.create(26219, 6, 9); * // null seed with arguments * UniformRandomProvider rng = RandomSource.TWO_CMRES_SELECT.create((Object) null, 6, 9); * </code></pre> * * <p>Valid types for the {@code seed} are:</p> * <ul> * <li>{@code Integer} (or {@code int})</li> * <li>{@code Long} (or {@code long})</li> * <li>{@code int[]}</li> * <li>{@code long[]}</li> * <li>{@code byte[]}</li> * </ul> * * <p>Notes:</p> * <ul> * <li> * When the seed type passed as argument is more complex (i.e. more * bits can be independently chosen) than the generator's * {@link #isNativeSeed(Object) native type}, the conversion of a * set of different seeds will necessarily result in the same value * of the native seed type. * </li> * <li> * When the native seed type is an array, the same remark applies * when the array contains more bits than the state of the generator. * </li> * <li> * When the {@code seed} is {@code null}, a seed of the native type * will be generated. If the native type is an array, the generated * size is limited a maximum of 128. * </li> * </ul> * * <p>This method will raise an exception if the additional arguments for * the implementation's constructor are incorrect (e.g. {@link #TWO_CMRES_SELECT}). * This includes the case where arguments are supplied and the implementation * does not require additional arguments.</p> * * @param seed Seed value. It can be {@code null} (in which case a * random value will be used). * @param data Additional arguments to the implementation's constructor. * Please refer to the documentation of each specific implementation. * @return the RNG. * @throws IllegalArgumentException if the argument data required to initialize the * generator is incorrect. * @throws UnsupportedOperationException if the type of the {@code seed} * is invalid. * * @see #create() * @since 1.4 */ public RestorableUniformRandomProvider create(Object seed, Object... data) { return ProviderBuilder.create(getInternalIdentifier(), seed, data); } /** * Creates a random number generator with a random seed. * * <p>Usage example:</p> * <pre><code> * UniformRandomProvider rng = RandomSource.create(RandomSource.MT); * </code></pre> * <p>or, if a {@link RestorableUniformRandomProvider "save/restore"} functionality is needed,</p> * <pre><code> * RestorableUniformRandomProvider rng = RandomSource.create(RandomSource.MT); * </code></pre> * * <p>This method will raise an exception if the generator requires arguments in addition * to a seed (e.g. {@link #TWO_CMRES_SELECT}).</p> * * @param source RNG type. * @return the RNG. * @throws IllegalArgumentException if the generator requires arguments in addition * to a seed. * * @see #create(RandomSource,Object,Object[]) * @deprecated It is preferred to use the {@link RandomSource#create()} instance method. */ @Deprecated public static RestorableUniformRandomProvider create(RandomSource source) { return ProviderBuilder.create(source.getInternalIdentifier()); } /** * Creates a random number generator with the given {@code seed}. * * <p>Usage example:</p> * <pre><code> * UniformRandomProvider rng = RandomSource.create(RandomSource.XO_RO_SHI_RO_128_PP, 0x123abcL); * UniformRandomProvider rng = RandomSource.create(RandomSource.TWO_CMRES_SELECT, 26219, 6, 9); * </code></pre> * * <p>Valid types for the {@code seed} are:</p> * <ul> * <li>{@code Integer} (or {@code int})</li> * <li>{@code Long} (or {@code long})</li> * <li>{@code int[]}</li> * <li>{@code long[]}</li> * <li>{@code byte[]}</li> * </ul> * * <p>Notes:</p> * <ul> * <li> * When the seed type passed as argument is more complex (i.e. more * bits can be independently chosen) than the generator's * {@link #isNativeSeed(Object) native type}, the conversion of a * set of different seeds will necessarily result in the same value * of the native seed type. * </li> * <li> * When the native seed type is an array, the same remark applies * when the array contains more bits than the state of the generator. * </li> * <li> * When the {@code seed} is {@code null}, a seed of the native type * will be generated. If the native type is an array, the generated * size is limited a maximum of 128. * </li> * </ul> * * <p>This method will raise an exception if the additional arguments for * the implementation's constructor are incorrect (e.g. {@link #TWO_CMRES_SELECT}). * This includes the case where arguments are supplied and the implementation * does not require additional arguments.</p> * * @param source RNG type. * @param seed Seed value. It can be {@code null} (in which case a * random value will be used). * @param data Additional arguments to the implementation's constructor. * Please refer to the documentation of each specific implementation. * @return the RNG. * @throws IllegalArgumentException if the argument data required to initialize the * generator is incorrect. * @throws UnsupportedOperationException if the type of the {@code seed} * is invalid. * * @see #create(RandomSource) * @deprecated It is preferred to use the {@link RandomSource#create(Object, Object...)} instance method. */ @Deprecated public static RestorableUniformRandomProvider create(RandomSource source, Object seed, Object... data) { return ProviderBuilder.create(source.getInternalIdentifier(), seed, data); } /** * Creates a number for use as a seed. * * @return a random number. */ public static int createInt() { return SeedFactory.createInt(); } /** * Creates a number for use as a seed. * * @return a random number. */ public static long createLong() { return SeedFactory.createLong(); } /** * Creates an array of numbers for use as a seed. * * @param n Size of the array to create. * @return an array of {@code n} random numbers. */ public static int[] createIntArray(int n) { return SeedFactory.createIntArray(n); } /** * Creates an array of numbers for use as a seed. * * @param n Size of the array to create. * @return an array of {@code n} random numbers. */ public static long[] createLongArray(int n) { return SeedFactory.createLongArray(n); } /** * Wraps the given {@code delegate} generator in a new instance that * only provides access to the {@link UniformRandomProvider} methods. * * <p>This method can be used to prevent access to any methods of the {@code delegate} * that are not defined in the {@link UniformRandomProvider} interface. * For example this will prevent access to the "save/restore" functionality of * any {@link RestorableUniformRandomProvider} {@link #create() created} * by the {@link RandomSource} factory methods, or will prevent access to the jump * functionality of generators. * * <p>Since the method applies to more than the {@link RestorableUniformRandomProvider} * interface it is left to the caller to determine if any methods require hiding, * for example: * * <pre><code> * UniformRandomProvider rng = ...; * if (rng instanceof JumpableUniformRandomProvider) { * rng = RandomSource.unrestorable(rng); * } * </code></pre> * * @param delegate Generator to which calls will be delegated. * @return a new instance */ public static UniformRandomProvider unrestorable(final UniformRandomProvider delegate) { return new UniformRandomProvider() { @Override public void nextBytes(byte[] bytes) { delegate.nextBytes(bytes); } @Override public void nextBytes(byte[] bytes, int start, int len) { delegate.nextBytes(bytes, start, len); } @Override public int nextInt() { return delegate.nextInt(); } @Override public int nextInt(int n) { return delegate.nextInt(n); } @Override public int nextInt(int origin, int bound) { return delegate.nextInt(origin, bound); } @Override public long nextLong() { return delegate.nextLong(); } @Override public long nextLong(long n) { return delegate.nextLong(n); } @Override public long nextLong(long origin, long bound) { return delegate.nextLong(origin, bound); } @Override public boolean nextBoolean() { return delegate.nextBoolean(); } @Override public float nextFloat() { return delegate.nextFloat(); } @Override public float nextFloat(float bound) { return delegate.nextFloat(bound); } @Override public float nextFloat(float origin, float bound) { return delegate.nextFloat(origin, bound); } @Override public double nextDouble() { return delegate.nextDouble(); } @Override public double nextDouble(double bound) { return delegate.nextDouble(bound); } @Override public double nextDouble(double origin, double bound) { return delegate.nextDouble(origin, bound); } @Override public IntStream ints() { return delegate.ints(); } @Override public IntStream ints(int origin, int bound) { return delegate.ints(origin, bound); } @Override public IntStream ints(long streamSize) { return delegate.ints(streamSize); } @Override public IntStream ints(long streamSize, int origin, int bound) { return delegate.ints(streamSize, origin, bound); } @Override public LongStream longs() { return delegate.longs(); } @Override public LongStream longs(long origin, long bound) { return delegate.longs(origin, bound); } @Override public LongStream longs(long streamSize) { return delegate.longs(streamSize); } @Override public LongStream longs(long streamSize, long origin, long bound) { return delegate.longs(streamSize, origin, bound); } @Override public DoubleStream doubles() { return delegate.doubles(); } @Override public DoubleStream doubles(double origin, double bound) { return delegate.doubles(origin, bound); } @Override public DoubleStream doubles(long streamSize) { return delegate.doubles(streamSize); } @Override public DoubleStream doubles(long streamSize, double origin, double bound) { return delegate.doubles(streamSize, origin, bound); } @Override public String toString() { return delegate.toString(); } }; } }
2,864
0
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple/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. */ /** * This package provides * {@link org.apache.commons.rng.simple.RandomSource factory methods} * by which low-level classes implemented in module "commons-rng-core" * are instantiated. * <br> * Classes in package {@link org.apache.commons.rng.simple.internal} * should not be used directly. * <br> * The generators are <i>not</i> thread-safe: Parallel applications must * use different generator instances in different threads. * * <p> * In the case of pseudo-random generators, the source of randomness is * usually a set of numbers whose bits representation are scrambled in such * a way as to produce a random-looking sequence. * <br> * The main property of the sequence is that the numbers must be uniformly * distributed within their allowed range. * <br> * Classes in this package do not provide any further processing of the * number generation such as to match other types of distribution. * </p> * * <p> * Which source of randomness to choose may depend on which properties * are more important. * Considerations can include speed of generation, memory usage, period * size, equidistribution, correlation, etc. * <br> * For some of the generators, interesting properties (of the reference * implementations) are proven in scientific papers. * Some generators can also suffer from potential weaknesses. * </p> * * <p> * For simple sampling, any of the generators implemented in this library * may be sufficient. * <br> * For Monte-Carlo simulations that require generating high-dimensional * vectors), equidistribution and non-correlation are crucial. * The <i>Mersenne Twister</i> and <i>Well</i> generators have * equidistribution properties proven according to their bits pool size * which is directly related to their period (all of them have maximal * period, i.e. a generator with size {@code n} pool has a period * <code>2<sup>n</sup>-1</code>). * They also have equidistribution properties for 32 bits blocks up to * {@code s/32} dimension where {@code s} is their pool size. * <br> * For example, {@code Well19937c} is equidistributed up to dimension 623 * (i.e. 19937 divided by 32). * It means that a Monte-Carlo simulation generating vectors of {@code n} * (32-bits integer) variables at each iteration has some guarantee on the * properties of its components as long as {@code n < 623}. * Note that if the variables are of type {@code double}, the limit is * divided by two (since 64 bits are needed to create a {@code double}). * <br> * Reference to the relevant publications are listed in the specific * documentation of each class. * </p> * * <p> * Memory usage can vary a lot between providers. * The state of {@code MersenneTwister} is composed of 624 integers, * using about 2.5 kB. * The <i>Well</i> generators use 6 integer arrays, the length of each * being equal to the pool size; thus, for example, {@code Well44497b} * uses about 33 kB. * </p> */ package org.apache.commons.rng.simple;
2,865
0
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple/internal/IntArray2Int.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.simple.internal; /** * Creates a single value by "xor" of all the values in the input array. * * @since 1.0 */ public class IntArray2Int implements SeedConverter<int[], Integer> { /** {@inheritDoc} */ @Override public Integer convert(int[] seed) { return Conversions.intArray2Int(seed); } }
2,866
0
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple/internal/LongArray2Long.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.simple.internal; /** * Creates a single value by "xor" of all the values in the input array. * * @since 1.0 */ public class LongArray2Long implements SeedConverter<long[], Long> { /** {@inheritDoc} */ @Override public Long convert(long[] seed) { return Conversions.longArray2Long(seed); } }
2,867
0
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple/internal/MixFunctions.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.simple.internal; /** * Performs mixing of bits. * * @since 1.5 */ final class MixFunctions { /** * The fractional part of the golden ratio, phi, scaled to 64-bits and rounded to odd. * This can be used as an increment for a Weyl sequence. * * @see <a href="https://en.wikipedia.org/wiki/Golden_ratio">Golden ratio</a> */ static final long GOLDEN_RATIO_64 = 0x9e3779b97f4a7c15L; /** * The fractional part of the golden ratio, phi, scaled to 32-bits and rounded to odd. * This can be used as an increment for a Weyl sequence. * * @see <a href="https://en.wikipedia.org/wiki/Golden_ratio">Golden ratio</a> */ static final int GOLDEN_RATIO_32 = 0x9e3779b9; /** No instances. */ private MixFunctions() {} /** * Perform variant 13 of David Stafford's 64-bit mix function. * This is the mix function used in the * {@link org.apache.commons.rng.core.source64.SplitMix64 SplitMix64} RNG. * * <p>This is ranked first of the top 14 Stafford mixers. * * @param x the input value * @return the output value * @see <a href="http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html">Better * Bit Mixing - Improving on MurmurHash3&#39;s 64-bit Finalizer.</a> */ static long stafford13(long x) { x = (x ^ (x >>> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >>> 27)) * 0x94d049bb133111ebL; return x ^ (x >>> 31); } /** * Perform the finalising 32-bit mix function of Austin Appleby's MurmurHash3. * * @param x the input value * @return the output value * @see <a href="https://github.com/aappleby/smhasher">SMHasher</a> */ static int murmur3(int x) { x = (x ^ (x >>> 16)) * 0x85ebca6b; x = (x ^ (x >>> 13)) * 0xc2b2ae35; return x ^ (x >>> 16); } }
2,868
0
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple/internal/Long2Int.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.simple.internal; import org.apache.commons.rng.core.util.NumberFactory; /** * Converts a {@code Long} to an {@code Integer}. * * @since 1.0 */ public class Long2Int implements SeedConverter<Long, Integer> { /** {@inheritDoc} */ @SuppressWarnings("deprecation") @Override public Integer convert(Long seed) { return NumberFactory.makeInt(seed); } }
2,869
0
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple/internal/Long2LongArray.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.simple.internal; /** * Uses a {@code Long} value to seed a * {@link org.apache.commons.rng.core.source64.SplitMix64 SplitMix64} RNG and * create a {@code long[]} with the requested number of random * values. * * @since 1.0 */ public class Long2LongArray implements Seed2ArrayConverter<Long, long[]> { /** Size of the output array. */ private final int size; /** * @param size Size of the output array. */ public Long2LongArray(int size) { this.size = size; } /** {@inheritDoc} */ @Override public long[] convert(Long seed) { return convert(seed, size); } /** * {@inheritDoc} * * @since 1.3 */ @Override public long[] convert(Long seed, int outputSize) { return Conversions.long2LongArray(seed, outputSize); } }
2,870
0
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple/internal/NativeSeedType.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.simple.internal; import org.apache.commons.rng.core.util.NumberFactory; /** * The native seed type. Contains values for all native seed types and methods * to convert supported seed types to the native seed type. * * <p>Valid native seed types are:</p> * <ul> * <li>{@code Integer}</li> * <li>{@code Long}</li> * <li>{@code int[]}</li> * <li>{@code long[]}</li> * </ul> * * <p>Valid types for seed conversion are:</p> * <ul> * <li>{@code Integer} (or {@code int})</li> * <li>{@code Long} (or {@code long})</li> * <li>{@code int[]}</li> * <li>{@code long[]}</li> * <li>{@code byte[]}</li> * </ul> * * @since 1.3 */ public enum NativeSeedType { /** The seed type is {@code Integer}. */ INT(Integer.class, 4) { @Override public Integer createSeed(int size, int from, int to) { return SeedFactory.createInt(); } @Override protected Integer convert(Integer seed, int size) { return seed; } @Override protected Integer convert(Long seed, int size) { return Conversions.long2Int(seed); } @Override protected Integer convert(int[] seed, int size) { return Conversions.intArray2Int(seed); } @Override protected Integer convert(long[] seed, int size) { return Conversions.longArray2Int(seed); } @Override protected Integer convert(byte[] seed, int size) { return Conversions.byteArray2Int(seed); } }, /** The seed type is {@code Long}. */ LONG(Long.class, 8) { @Override public Long createSeed(int size, int from, int to) { return SeedFactory.createLong(); } @Override protected Long convert(Integer seed, int size) { return Conversions.int2Long(seed); } @Override protected Long convert(Long seed, int size) { return seed; } @Override protected Long convert(int[] seed, int size) { return Conversions.intArray2Long(seed); } @Override protected Long convert(long[] seed, int size) { return Conversions.longArray2Long(seed); } @Override protected Long convert(byte[] seed, int size) { return Conversions.byteArray2Long(seed); } }, /** The seed type is {@code int[]}. */ INT_ARRAY(int[].class, 4) { @Override public int[] createSeed(int size, int from, int to) { // Limit the number of calls to the synchronized method. The generator // will support self-seeding. return SeedFactory.createIntArray(Math.min(size, RANDOM_SEED_ARRAY_SIZE), from, to); } @Override protected int[] convert(Integer seed, int size) { return Conversions.int2IntArray(seed, size); } @Override protected int[] convert(Long seed, int size) { return Conversions.long2IntArray(seed, size); } @Override protected int[] convert(int[] seed, int size) { return seed; } @Override protected int[] convert(long[] seed, int size) { // Avoid zero filling seeds that are too short return Conversions.longArray2IntArray(seed, Math.min(size, Conversions.intSizeFromLongSize(seed.length))); } @Override protected int[] convert(byte[] seed, int size) { // Avoid zero filling seeds that are too short return Conversions.byteArray2IntArray(seed, Math.min(size, Conversions.intSizeFromByteSize(seed.length))); } }, /** The seed type is {@code long[]}. */ LONG_ARRAY(long[].class, 8) { @Override public long[] createSeed(int size, int from, int to) { // Limit the number of calls to the synchronized method. The generator // will support self-seeding. return SeedFactory.createLongArray(Math.min(size, RANDOM_SEED_ARRAY_SIZE), from, to); } @Override protected long[] convert(Integer seed, int size) { return Conversions.int2LongArray(seed, size); } @Override protected long[] convert(Long seed, int size) { return Conversions.long2LongArray(seed, size); } @Override protected long[] convert(int[] seed, int size) { // Avoid zero filling seeds that are too short return Conversions.intArray2LongArray(seed, Math.min(size, Conversions.longSizeFromIntSize(seed.length))); } @Override protected long[] convert(long[] seed, int size) { return seed; } @Override protected long[] convert(byte[] seed, int size) { // Avoid zero filling seeds that are too short return Conversions.byteArray2LongArray(seed, Math.min(size, Conversions.longSizeFromByteSize(seed.length))); } }; /** Error message for unrecognized seed types. */ private static final String UNRECOGNISED_SEED = "Unrecognized seed type: "; /** Maximum length of the seed array (for creating array seeds). */ private static final int RANDOM_SEED_ARRAY_SIZE = 128; /** Define the class type of the native seed. */ private final Class<?> type; /** * Define the number of bytes required to represent the native seed. If the type is * an array then this represents the size of a single value of the type. */ private final int bytes; /** * Instantiates a new native seed type. * * @param type Define the class type of the native seed. * @param bytes Define the number of bytes required to represent the native seed. */ NativeSeedType(Class<?> type, int bytes) { this.type = type; this.bytes = bytes; } /** * Gets the class type of the native seed. * * @return the type */ public Class<?> getType() { return type; } /** * Gets the number of bytes required to represent the native seed type. If the type is * an array then this represents the size of a single value of the type. * * @return the number of bytes */ public int getBytes() { return bytes; } /** * Creates the seed. The output seed type is determined by the native seed type. If the * output is an array the required size of the array can be specified. * * @param size The size of the seed (array types only). * @return the seed */ public Object createSeed(int size) { // Maintain behaviour since 1.3 to ensure position [0] of array seeds is non-zero. return createSeed(size, 0, Math.min(size, 1)); } /** * Creates the seed. The output seed type is determined by the native seed type. If * the output is an array the required size of the array can be specified and a * sub-range that must not be all-zero. * * @param size The size of the seed (array types only). * @param from The start of the not all-zero sub-range (inclusive; array types only). * @param to The end of the not all-zero sub-range (exclusive; array types only). * @return the seed * @throws IndexOutOfBoundsException if the sub-range is out of bounds * @since 1.5 */ public abstract Object createSeed(int size, int from, int to); /** * Converts the input seed from any of the supported seed types to the native seed type. * If the output is an array the required size of the array can be specified. * * @param seed Input seed. * @param size The size of the output seed (array types only). * @return the native seed. * @throws UnsupportedOperationException if the {@code seed} type is invalid. */ public Object convertSeed(Object seed, int size) { // Convert to native type. // Each method must be overridden by specific implementations. if (seed instanceof Integer) { return convert((Integer) seed, size); } else if (seed instanceof Long) { return convert((Long) seed, size); } else if (seed instanceof int[]) { return convert((int[]) seed, size); } else if (seed instanceof long[]) { return convert((long[]) seed, size); } else if (seed instanceof byte[]) { return convert((byte[]) seed, size); } throw new UnsupportedOperationException(unrecognizedSeedMessage(seed)); } /** * Convert the input {@code Integer} seed to the native seed type. * * @param seed Input seed. * @param size The size of the output seed (array types only). * @return the native seed. */ protected abstract Object convert(Integer seed, int size); /** * Convert the input {@code Long} seed to the native seed type. * * @param seed Input seed. * @param size The size of the output seed (array types only). * @return the native seed. */ protected abstract Object convert(Long seed, int size); /** * Convert the input {@code int[]} seed to the native seed type. * * @param seed Input seed. * @param size The size of the output seed (array types only). * @return the native seed. */ protected abstract Object convert(int[] seed, int size); /** * Convert the input {@code long[]} seed to the native seed type. * * @param seed Input seed. * @param size The size of the output seed (array types only). * @return the native seed. */ protected abstract Object convert(long[] seed, int size); /** * Convert the input {@code byte[]} seed to the native seed type. * * @param seed Input seed. * @param size The size of the output seed (array types only). * @return the native seed. */ protected abstract Object convert(byte[] seed, int size); /** * Converts the input seed from any of the supported seed types to bytes. * * @param seed Input seed. * @return the seed bytes. * @throws UnsupportedOperationException if the {@code seed} type is invalid. */ public static byte[] convertSeedToBytes(Object seed) { if (seed instanceof Integer) { return NumberFactory.makeByteArray((Integer) seed); } else if (seed instanceof Long) { return NumberFactory.makeByteArray((Long) seed); } else if (seed instanceof int[]) { return NumberFactory.makeByteArray((int[]) seed); } else if (seed instanceof long[]) { return NumberFactory.makeByteArray((long[]) seed); } else if (seed instanceof byte[]) { return (byte[]) seed; } throw new UnsupportedOperationException(unrecognizedSeedMessage(seed)); } /** * Create an unrecognized seed message. This will add the class type of the seed. * * @param seed the seed * @return the message */ private static String unrecognizedSeedMessage(Object seed) { return UNRECOGNISED_SEED + ((seed == null) ? "null" : seed.getClass().getName()); } }
2,871
0
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple/internal/ByteArray2LongArray.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.simple.internal; /** * Creates a {@code long[]} from a {@code byte[]}. * * @since 1.0 */ public class ByteArray2LongArray implements SeedConverter<byte[], long[]> { /** {@inheritDoc} */ @Override public long[] convert(byte[] seed) { // Full length conversion return Conversions.byteArray2LongArray(seed, Conversions.longSizeFromByteSize(seed.length)); } }
2,872
0
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple/internal/NoOpConverter.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.simple.internal; /** * Dummy converter that simply passes on its input. * It can be useful to avoid "unchecked" compiler warnings. * * @param <SEED> Seed type. * * @since 1.0 */ public class NoOpConverter<SEED> implements SeedConverter<SEED, SEED> { /** {@inheritDoc} */ @Override public SEED convert(SEED seed) { return seed; } }
2,873
0
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple/internal/IntArray2LongArray.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.simple.internal; /** * Creates a {@code long[]} from an {@code int[]}. * * <p>Note: From version 1.5 this conversion uses the int bytes to compose the long bytes * in little-endian order. * The output {@code long[]} can be converted back using {@link LongArray2IntArray}. * * @since 1.0 */ public class IntArray2LongArray implements SeedConverter<int[], long[]> { /** {@inheritDoc} */ @Override public long[] convert(int[] seed) { // Full length conversion return Conversions.intArray2LongArray(seed, Conversions.longSizeFromIntSize(seed.length)); } }
2,874
0
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple/internal/Long2IntArray.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.simple.internal; /** * Uses a {@code long} value to seed a * {@link org.apache.commons.rng.core.source64.SplitMix64 SplitMix64} RNG and * create a {@code int[]} with the requested number of random * values. * * @since 1.0 */ public class Long2IntArray implements Seed2ArrayConverter<Long, int[]> { /** Size of the output array. */ private final int size; /** * @param size Size of the output array. */ public Long2IntArray(int size) { this.size = size; } /** {@inheritDoc} */ @Override public int[] convert(Long seed) { return convert(seed, size); } /** * {@inheritDoc} * * @since 1.3 */ @Override public int[] convert(Long seed, int outputSize) { return Conversions.long2IntArray(seed, outputSize); } }
2,875
0
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple/internal/LongArray2IntArray.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.simple.internal; /** * Creates an {@code int[]} from a {@code long[]}. * * <p>Note: From version 1.5 this conversion uses the long bytes in little-endian order. * The output {@code int[]} can be converted back using {@link IntArray2LongArray}. * * @since 1.0 */ public class LongArray2IntArray implements SeedConverter<long[], int[]> { /** {@inheritDoc} */ @Override public int[] convert(long[] seed) { // Full length conversion return Conversions.longArray2IntArray(seed, Conversions.intSizeFromLongSize(seed.length)); } }
2,876
0
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple/internal/Int2Long.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.simple.internal; /** * Converts a {@code Integer} to an {@code Long}. * * @since 1.0 */ public class Int2Long implements SeedConverter<Integer, Long> { /** {@inheritDoc} */ @Override public Long convert(Integer seed) { return Conversions.int2Long(seed); } }
2,877
0
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple/internal/SeedConverter.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.simple.internal; /** * Seed converter. * * @param <IN> Input seed type. * @param <OUT> Output seed type. * * @since 1.0 */ public interface SeedConverter<IN, OUT> { /** * Converts seed from input type to output type. * * @param seed Original seed value. * @return the converted seed value. */ OUT convert(IN seed); }
2,878
0
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple/internal/ProviderBuilder.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.simple.internal; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.RestorableUniformRandomProvider; import org.apache.commons.rng.core.source32.JDKRandom; import org.apache.commons.rng.core.source32.Well512a; import org.apache.commons.rng.core.source32.Well1024a; import org.apache.commons.rng.core.source32.Well19937a; import org.apache.commons.rng.core.source32.Well19937c; import org.apache.commons.rng.core.source32.Well44497a; import org.apache.commons.rng.core.source32.Well44497b; import org.apache.commons.rng.core.source32.ISAACRandom; import org.apache.commons.rng.core.source32.IntProvider; import org.apache.commons.rng.core.source32.MersenneTwister; import org.apache.commons.rng.core.source32.MiddleSquareWeylSequence; import org.apache.commons.rng.core.source32.MultiplyWithCarry256; import org.apache.commons.rng.core.source32.KISSRandom; import org.apache.commons.rng.core.source32.XoRoShiRo64Star; import org.apache.commons.rng.core.source32.XoRoShiRo64StarStar; import org.apache.commons.rng.core.source32.XoShiRo128Plus; import org.apache.commons.rng.core.source32.XoShiRo128PlusPlus; import org.apache.commons.rng.core.source32.XoShiRo128StarStar; import org.apache.commons.rng.core.source32.PcgXshRr32; import org.apache.commons.rng.core.source32.PcgXshRs32; import org.apache.commons.rng.core.source32.PcgMcgXshRr32; import org.apache.commons.rng.core.source32.PcgMcgXshRs32; import org.apache.commons.rng.core.source32.DotyHumphreySmallFastCounting32; import org.apache.commons.rng.core.source32.JenkinsSmallFast32; import org.apache.commons.rng.core.source32.L32X64Mix; import org.apache.commons.rng.core.source64.SplitMix64; import org.apache.commons.rng.core.source64.XorShift1024Star; import org.apache.commons.rng.core.source64.XorShift1024StarPhi; import org.apache.commons.rng.core.source64.TwoCmres; import org.apache.commons.rng.core.source64.XoRoShiRo1024PlusPlus; import org.apache.commons.rng.core.source64.XoRoShiRo1024Star; import org.apache.commons.rng.core.source64.XoRoShiRo1024StarStar; import org.apache.commons.rng.core.source64.MersenneTwister64; import org.apache.commons.rng.core.source64.XoRoShiRo128Plus; import org.apache.commons.rng.core.source64.XoRoShiRo128PlusPlus; import org.apache.commons.rng.core.source64.XoRoShiRo128StarStar; import org.apache.commons.rng.core.source64.XoShiRo256Plus; import org.apache.commons.rng.core.source64.XoShiRo256PlusPlus; import org.apache.commons.rng.core.source64.XoShiRo256StarStar; import org.apache.commons.rng.core.source64.XoShiRo512Plus; import org.apache.commons.rng.core.source64.XoShiRo512PlusPlus; import org.apache.commons.rng.core.source64.XoShiRo512StarStar; import org.apache.commons.rng.core.source64.PcgRxsMXs64; import org.apache.commons.rng.core.source64.DotyHumphreySmallFastCounting64; import org.apache.commons.rng.core.source64.JenkinsSmallFast64; import org.apache.commons.rng.core.source64.L64X1024Mix; import org.apache.commons.rng.core.source64.L64X128Mix; import org.apache.commons.rng.core.source64.L64X128StarStar; import org.apache.commons.rng.core.source64.L64X256Mix; import org.apache.commons.rng.core.source64.L128X1024Mix; import org.apache.commons.rng.core.source64.L128X128Mix; import org.apache.commons.rng.core.source64.L128X256Mix; /** * RNG builder. * <p> * It uses reflection to find the factory method of the RNG implementation, * and performs seed type conversions. * </p> */ public final class ProviderBuilder { /** Error message. */ private static final String INTERNAL_ERROR_MSG = "Internal error: Please file a bug report"; /** * Class only contains static method. */ private ProviderBuilder() {} /** * Creates a RNG instance. * * @param source RNG specification. * @return a new RNG instance. * @throws IllegalArgumentException if argument data to initialize the * generator implemented by the given {@code source} is missing. * @since 1.3 */ public static RestorableUniformRandomProvider create(RandomSourceInternal source) { // Delegate to the random source allowing generator specific implementations. return source.create(); } /** * Creates a RNG instance. * * @param source RNG specification. * @param seed Seed value. It can be {@code null} (in which case a * random value will be used). * @param args Additional arguments to the implementation's constructor. * @return a new RNG instance. * @throws UnsupportedOperationException if the seed type is invalid. * @throws IllegalArgumentException if argument data to initialize the * generator implemented by the given {@code source} is invalid. */ public static RestorableUniformRandomProvider create(RandomSourceInternal source, Object seed, Object[] args) { // Delegate to the random source allowing generator specific implementations. // This method checks arguments for null and calls the appropriate internal method. if (args != null) { return source.create(seed, args); } return seed == null ? source.create() : source.create(seed); } /** * Identifiers of the generators. */ public enum RandomSourceInternal { /** Source of randomness is {@link JDKRandom}. */ JDK(JDKRandom.class, 1, NativeSeedType.LONG), /** Source of randomness is {@link Well512a}. */ WELL_512_A(Well512a.class, 16, 0, 16, NativeSeedType.INT_ARRAY), /** Source of randomness is {@link Well1024a}. */ WELL_1024_A(Well1024a.class, 32, 0, 32, NativeSeedType.INT_ARRAY), /** Source of randomness is {@link Well19937a}. */ WELL_19937_A(Well19937a.class, 624, 0, 623, NativeSeedType.INT_ARRAY), /** Source of randomness is {@link Well19937c}. */ WELL_19937_C(Well19937c.class, 624, 0, 623, NativeSeedType.INT_ARRAY), /** Source of randomness is {@link Well44497a}. */ WELL_44497_A(Well44497a.class, 1391, 0, 1390, NativeSeedType.INT_ARRAY), /** Source of randomness is {@link Well44497b}. */ WELL_44497_B(Well44497b.class, 1391, 0, 1390, NativeSeedType.INT_ARRAY), /** Source of randomness is {@link MersenneTwister}. */ MT(MersenneTwister.class, 624, NativeSeedType.INT_ARRAY), /** Source of randomness is {@link ISAACRandom}. */ ISAAC(ISAACRandom.class, 256, NativeSeedType.INT_ARRAY), /** Source of randomness is {@link SplitMix64}. */ SPLIT_MIX_64(SplitMix64.class, 1, NativeSeedType.LONG), /** Source of randomness is {@link XorShift1024Star}. */ XOR_SHIFT_1024_S(XorShift1024Star.class, 16, 0, 16, NativeSeedType.LONG_ARRAY), /** Source of randomness is {@link TwoCmres}. */ TWO_CMRES(TwoCmres.class, 1, NativeSeedType.INT), /** * Source of randomness is {@link TwoCmres} with explicit selection * of the two subcycle generators. */ TWO_CMRES_SELECT(TwoCmres.class, 1, NativeSeedType.INT, Integer.TYPE, Integer.TYPE), /** Source of randomness is {@link MersenneTwister64}. */ MT_64(MersenneTwister64.class, 312, NativeSeedType.LONG_ARRAY), /** Source of randomness is {@link MultiplyWithCarry256}. */ MWC_256(MultiplyWithCarry256.class, 257, 0, 257, NativeSeedType.INT_ARRAY), /** Source of randomness is {@link KISSRandom}. */ KISS(KISSRandom.class, // If zero in initial 3 positions the output is a simple LCG 4, 0, 3, NativeSeedType.INT_ARRAY), /** Source of randomness is {@link XorShift1024StarPhi}. */ XOR_SHIFT_1024_S_PHI(XorShift1024StarPhi.class, 16, 0, 16, NativeSeedType.LONG_ARRAY), /** Source of randomness is {@link XoRoShiRo64Star}. */ XO_RO_SHI_RO_64_S(XoRoShiRo64Star.class, 2, 0, 2, NativeSeedType.INT_ARRAY), /** Source of randomness is {@link XoRoShiRo64StarStar}. */ XO_RO_SHI_RO_64_SS(XoRoShiRo64StarStar.class, 2, 0, 2, NativeSeedType.INT_ARRAY), /** Source of randomness is {@link XoShiRo128Plus}. */ XO_SHI_RO_128_PLUS(XoShiRo128Plus.class, 4, 0, 4, NativeSeedType.INT_ARRAY), /** Source of randomness is {@link XoShiRo128StarStar}. */ XO_SHI_RO_128_SS(XoShiRo128StarStar.class, 4, 0, 4, NativeSeedType.INT_ARRAY), /** Source of randomness is {@link XoRoShiRo128Plus}. */ XO_RO_SHI_RO_128_PLUS(XoRoShiRo128Plus.class, 2, 0, 2, NativeSeedType.LONG_ARRAY), /** Source of randomness is {@link XoRoShiRo128StarStar}. */ XO_RO_SHI_RO_128_SS(XoRoShiRo128StarStar.class, 2, 0, 2, NativeSeedType.LONG_ARRAY), /** Source of randomness is {@link XoShiRo256Plus}. */ XO_SHI_RO_256_PLUS(XoShiRo256Plus.class, 4, 0, 4, NativeSeedType.LONG_ARRAY), /** Source of randomness is {@link XoShiRo256StarStar}. */ XO_SHI_RO_256_SS(XoShiRo256StarStar.class, 4, 0, 4, NativeSeedType.LONG_ARRAY), /** Source of randomness is {@link XoShiRo512Plus}. */ XO_SHI_RO_512_PLUS(XoShiRo512Plus.class, 8, 0, 8, NativeSeedType.LONG_ARRAY), /** Source of randomness is {@link XoShiRo512StarStar}. */ XO_SHI_RO_512_SS(XoShiRo512StarStar.class, 8, 0, 8, NativeSeedType.LONG_ARRAY), /** Source of randomness is {@link PcgXshRr32}. */ PCG_XSH_RR_32(PcgXshRr32.class, 2, NativeSeedType.LONG_ARRAY), /** Source of randomness is {@link PcgXshRs32}. */ PCG_XSH_RS_32(PcgXshRs32.class, 2, NativeSeedType.LONG_ARRAY), /** Source of randomness is {@link PcgRxsMXs64}. */ PCG_RXS_M_XS_64(PcgRxsMXs64.class, 2, NativeSeedType.LONG_ARRAY), /** Source of randomness is {@link PcgMcgXshRr32}. */ PCG_MCG_XSH_RR_32(PcgMcgXshRr32.class, 1, NativeSeedType.LONG), /** Source of randomness is {@link PcgMcgXshRs32}. */ PCG_MCG_XSH_RS_32(PcgMcgXshRs32.class, 1, NativeSeedType.LONG), /** Source of randomness is {@link MiddleSquareWeylSequence}. */ MSWS(MiddleSquareWeylSequence.class, // Many partially zero seeds can create low quality initial output. // The Weyl increment cascades bits into the random state so ideally it // has a high number of bit transitions. Minimally ensure it is non-zero. 3, 2, 3, NativeSeedType.LONG_ARRAY) { @Override protected Object createSeed() { return createMswsSeed(SeedFactory.createLong()); } @Override protected Object convertSeed(Object seed) { // Allow seeding with primitives to generate a good seed if (seed instanceof Integer) { return createMswsSeed((Integer) seed); } else if (seed instanceof Long) { return createMswsSeed((Long) seed); } // Other types (e.g. the native long[]) are handled by the default conversion return super.convertSeed(seed); } @Override protected byte[] createByteArraySeed(UniformRandomProvider source) { // The seed requires approximately 4-6 calls to nextInt(). // Wrap the input and switch to a default if the input is faulty. final UniformRandomProvider wrapped = new IntProvider() { /** The number of remaining calls to the source generator. */ private int calls = 100; /** Default generator, initialised when required. */ private UniformRandomProvider defaultGen; @Override public int next() { if (calls == 0) { // The input source is broken. // Seed a default if (defaultGen == null) { defaultGen = new SplitMix64(source.nextLong()); } return defaultGen.nextInt(); } calls--; return source.nextInt(); } @Override public long nextLong() { // No specific requirements so always use the source return source.nextLong(); } }; return NativeSeedType.convertSeedToBytes(createMswsSeed(wrapped)); } /** * Creates the full length seed array from the input seed. * * @param seed the seed * @return the seed array */ private long[] createMswsSeed(long seed) { return createMswsSeed(new SplitMix64(seed)); } /** * Creates the full length seed array from the input seed using the method * recommended for the generator. This is a high quality Weyl increment composed * of a hex character permutation. * * @param source Source of randomness. * @return the seed array */ private long[] createMswsSeed(UniformRandomProvider source) { final long increment = SeedUtils.createLongHexPermutation(source); // The initial state should not be low complexity but the Weyl // state can be any number. final long state = increment; final long weylState = source.nextLong(); return new long[] {state, weylState, increment}; } }, /** Source of randomness is {@link DotyHumphreySmallFastCounting32}. */ SFC_32(DotyHumphreySmallFastCounting32.class, 3, NativeSeedType.INT_ARRAY), /** Source of randomness is {@link DotyHumphreySmallFastCounting64}. */ SFC_64(DotyHumphreySmallFastCounting64.class, 3, NativeSeedType.LONG_ARRAY), /** Source of randomness is {@link JenkinsSmallFast32}. */ JSF_32(JenkinsSmallFast32.class, 1, NativeSeedType.INT), /** Source of randomness is {@link JenkinsSmallFast64}. */ JSF_64(JenkinsSmallFast64.class, 1, NativeSeedType.LONG), /** Source of randomness is {@link XoShiRo128PlusPlus}. */ XO_SHI_RO_128_PP(XoShiRo128PlusPlus.class, 4, 0, 4, NativeSeedType.INT_ARRAY), /** Source of randomness is {@link XoRoShiRo128PlusPlus}. */ XO_RO_SHI_RO_128_PP(XoRoShiRo128PlusPlus.class, 2, 0, 2, NativeSeedType.LONG_ARRAY), /** Source of randomness is {@link XoShiRo256PlusPlus}. */ XO_SHI_RO_256_PP(XoShiRo256PlusPlus.class, 4, 0, 4, NativeSeedType.LONG_ARRAY), /** Source of randomness is {@link XoShiRo512PlusPlus}. */ XO_SHI_RO_512_PP(XoShiRo512PlusPlus.class, 8, 0, 8, NativeSeedType.LONG_ARRAY), /** Source of randomness is {@link XoRoShiRo1024PlusPlus}. */ XO_RO_SHI_RO_1024_PP(XoRoShiRo1024PlusPlus.class, 16, 0, 16, NativeSeedType.LONG_ARRAY), /** Source of randomness is {@link XoRoShiRo1024Star}. */ XO_RO_SHI_RO_1024_S(XoRoShiRo1024Star.class, 16, 0, 16, NativeSeedType.LONG_ARRAY), /** Source of randomness is {@link XoRoShiRo1024StarStar}. */ XO_RO_SHI_RO_1024_SS(XoRoShiRo1024StarStar.class, 16, 0, 16, NativeSeedType.LONG_ARRAY), /** Source of randomness is {@link PcgXshRr32}. */ PCG_XSH_RR_32_OS(PcgXshRr32.class, 1, NativeSeedType.LONG), /** Source of randomness is {@link PcgXshRs32}. */ PCG_XSH_RS_32_OS(PcgXshRs32.class, 1, NativeSeedType.LONG), /** Source of randomness is {@link PcgRxsMXs64}. */ PCG_RXS_M_XS_64_OS(PcgRxsMXs64.class, 1, NativeSeedType.LONG), /** Source of randomness is {@link L64X128StarStar}. */ L64_X128_SS(L64X128StarStar.class, 4, 2, 4, NativeSeedType.LONG_ARRAY), /** Source of randomness is {@link L64X128Mix}. */ L64_X128_MIX(L64X128Mix.class, 4, 2, 4, NativeSeedType.LONG_ARRAY), /** Source of randomness is {@link L64X256Mix}. */ L64_X256_MIX(L64X256Mix.class, 6, 2, 6, NativeSeedType.LONG_ARRAY), /** Source of randomness is {@link L64X1024Mix}. */ L64_X1024_MIX(L64X1024Mix.class, 18, 2, 18, NativeSeedType.LONG_ARRAY), /** Source of randomness is {@link L128X128Mix}. */ L128_X128_MIX(L128X128Mix.class, 6, 4, 6, NativeSeedType.LONG_ARRAY), /** Source of randomness is {@link L128X256Mix}. */ L128_X256_MIX(L128X256Mix.class, 8, 4, 8, NativeSeedType.LONG_ARRAY), /** Source of randomness is {@link L128X1024Mix}. */ L128_X1024_MIX(L128X1024Mix.class, 20, 4, 20, NativeSeedType.LONG_ARRAY), /** Source of randomness is {@link L32X64Mix}. */ L32_X64_MIX(L32X64Mix.class, 4, 2, 4, NativeSeedType.INT_ARRAY); /** Source type. */ private final Class<? extends UniformRandomProvider> rng; /** Native seed size. Used for array seeds. */ private final int nativeSeedSize; /** Start of the not all-zero sub-range for array seeds (inclusive). */ private final int notAllZeroFrom; /** End of the not all-zero sub-range for array seeds (exclusive). */ private final int notAllZeroTo; /** Define the parameter types of the data needed to build the generator. */ private final Class<?>[] args; /** Native seed type. Used to create a seed or convert input seeds. */ private final NativeSeedType nativeSeedType; /** * The constructor. * This is discovered using the constructor parameter types and stored for re-use. */ private transient Constructor<?> rngConstructor; /** * Create a new instance. * * <p>Used when the seed array has no requirement for a not all-zero sub-range. * * @param rng Source type. * @param nativeSeedSize Native seed size (array types only). * @param nativeSeedType Native seed type. * @param args Additional data needed to create a generator instance. */ RandomSourceInternal(Class<? extends UniformRandomProvider> rng, int nativeSeedSize, NativeSeedType nativeSeedType, Class<?>... args) { this(rng, nativeSeedSize, 0, 0, nativeSeedType, args); } /** * Create a new instance. * * <p>Note: The sub-range of an array seed that is not all-zero can be specified. * If the native seed array is used to represent a number of bits * that is not an exact multiple of the number of bytes in the seed, then a * safe approach is to specify the sub-range using a smaller size than the * full length seed. For example a {@link Well19937a} generator uses 19937 * bits and has a seed bit length of 19968. A safe range is [0, 19937 / 32). * * @param rng Source type. * @param nativeSeedSize Native seed size (array types only). * @param notAllZeroFrom The start of the not all-zero sub-range (inclusive). * @param notAllZeroTo The end of the not all-zero sub-range (exclusive). * @param nativeSeedType Native seed type. * @param args Additional data needed to create a generator instance. */ RandomSourceInternal(Class<? extends UniformRandomProvider> rng, int nativeSeedSize, int notAllZeroFrom, int notAllZeroTo, NativeSeedType nativeSeedType, Class<?>... args) { this.rng = rng; this.nativeSeedSize = nativeSeedSize; this.notAllZeroFrom = notAllZeroFrom; this.notAllZeroTo = notAllZeroTo; this.nativeSeedType = nativeSeedType; // Build the complete list of class types for the constructor this.args = (Class<?>[]) Array.newInstance(args.getClass().getComponentType(), 1 + args.length); this.args[0] = nativeSeedType.getType(); System.arraycopy(args, 0, this.args, 1, args.length); } /** * Gets the implementing class of the random source. * * @return the random source class. */ public Class<?> getRng() { return rng; } /** * Gets the class of the native seed. * * @return the seed class. */ Class<?> getSeed() { return args[0]; } /** * Gets the parameter types of the data needed to build the generator. * * @return the data needed to build the generator. */ Class<?>[] getArgs() { return args; } /** * Checks whether the type of given {@code seed} is the native type * of the implementation. * * @param <SEED> Seed type. * * @param seed Seed value. * @return {@code true} if the seed can be passed to the builder * for this RNG type. */ public <SEED> boolean isNativeSeed(SEED seed) { return seed != null && getSeed().equals(seed.getClass()); } /** * Creates a RNG instance. * * <p>This method can be over-ridden to allow fast construction of a generator * with low seeding cost that has no additional constructor arguments.</p> * * @return a new RNG instance. */ RestorableUniformRandomProvider create() { // Create a seed. final Object nativeSeed = createSeed(); // Instantiate. return create(getConstructor(), new Object[] {nativeSeed}); } /** * Creates a RNG instance. It is assumed the seed is not {@code null}. * * <p>This method can be over-ridden to allow fast construction of a generator * with low seed conversion cost that has no additional constructor arguments.</p> * * @param seed Seed value. It must not be {@code null}. * @return a new RNG instance. * @throws UnsupportedOperationException if the seed type is invalid. */ RestorableUniformRandomProvider create(Object seed) { // Convert seed to native type. final Object nativeSeed = convertSeed(seed); // Instantiate. return create(getConstructor(), new Object[] {nativeSeed}); } /** * Creates a RNG instance. This constructs a RNG using reflection and will error * if the constructor arguments do not match those required by the RNG's constructor. * * @param seed Seed value. It can be {@code null} (in which case a suitable * seed will be generated). * @param constructorArgs Additional arguments to the implementation's constructor. * It must not be {@code null}. * @return a new RNG instance. * @throws UnsupportedOperationException if the seed type is invalid. */ RestorableUniformRandomProvider create(Object seed, Object[] constructorArgs) { final Object nativeSeed = createNativeSeed(seed); // Build a single array with all the arguments to be passed // (in the right order) to the constructor. Object[] all = new Object[constructorArgs.length + 1]; all[0] = nativeSeed; System.arraycopy(constructorArgs, 0, all, 1, constructorArgs.length); // Instantiate. return create(getConstructor(), all); } /** * Creates a native seed. * * <p>The default implementation creates a seed of the native type and, for array seeds, * ensures not all bits are zero.</p> * * <p>This method should be over-ridden to satisfy seed requirements for the generator.</p> * * @return the native seed * @since 1.3 */ protected Object createSeed() { // Ensure the seed is not all-zero in the sub-range return nativeSeedType.createSeed(nativeSeedSize, notAllZeroFrom, notAllZeroTo); } /** * Creates a {@code byte[]} seed using the provided source of randomness. * * <p>The default implementation creates a full-length seed and ensures not all bits * are zero.</p> * * <p>This method should be over-ridden to satisfy seed requirements for the generator.</p> * * @param source Source of randomness. * @return the byte[] seed * @since 1.3 */ protected byte[] createByteArraySeed(UniformRandomProvider source) { // Ensure the seed is not all-zero in the sub-range. // Note: Convert the native seed array size/positions to byte size/positions. final int bytes = nativeSeedType.getBytes(); return SeedFactory.createByteArray(source, bytes * nativeSeedSize, bytes * notAllZeroFrom, bytes * notAllZeroTo); } /** * Converts a seed from any of the supported seed types to a native seed. * * <p>The default implementation delegates to the native seed type conversion.</p> * * <p>This method should be over-ridden to satisfy seed requirements for the generator.</p> * * @param seed Input seed (must not be null). * @return the native seed * @throws UnsupportedOperationException if the {@code seed} type is invalid. * @since 1.3 */ protected Object convertSeed(Object seed) { return nativeSeedType.convertSeed(seed, nativeSeedSize); } /** * Creates a native seed from any of the supported seed types. * * @param seed Input seed (may be null). * @return the native seed. * @throws UnsupportedOperationException if the {@code seed} type cannot be converted. */ private Object createNativeSeed(Object seed) { return seed == null ? createSeed() : convertSeed(seed); } /** * Creates a seed suitable for the implementing class represented by this random source. * * <p>It will satisfy the seed size and any other seed requirements for the * implementing class. The seed is converted from the native type to bytes.</p> * * @return the seed bytes * @since 1.3 */ public final byte[] createSeedBytes() { // Custom implementations can override createSeed final Object seed = createSeed(); return NativeSeedType.convertSeedToBytes(seed); } /** * Creates a seed suitable for the implementing class represented by this random source * using the supplied source of randomness. * * <p>It will satisfy the seed size and any other seed requirements for the * implementing class. The seed is converted from the native type to bytes.</p> * * @param source Source of randomness. * @return the seed bytes * @since 1.3 */ public final byte[] createSeedBytes(UniformRandomProvider source) { // Custom implementations can override createByteArraySeed return createByteArraySeed(source); } /** * Gets the constructor. * * @return the RNG constructor. */ private Constructor<?> getConstructor() { // The constructor never changes so it is stored for re-use. Constructor<?> constructor = rngConstructor; if (constructor == null) { // If null this is either the first attempt to find it or // look-up previously failed and this method will throw // upon each invocation. constructor = createConstructor(); rngConstructor = constructor; } return constructor; } /** * Creates a constructor. * * @return a RNG constructor. */ private Constructor<?> createConstructor() { try { return getRng().getConstructor(getArgs()); } catch (NoSuchMethodException e) { // Info in "RandomSourceInternal" is inconsistent with the // constructor of the implementation. throw new IllegalStateException(INTERNAL_ERROR_MSG, e); } } /** * Creates a RNG. * * @param rng RNG specification. * @param args Arguments to the implementation's constructor. * @return a new RNG instance. */ private static RestorableUniformRandomProvider create(Constructor<?> rng, Object[] args) { try { return (RestorableUniformRandomProvider) rng.newInstance(args); } catch (InvocationTargetException | InstantiationException | IllegalAccessException e) { throw new IllegalStateException(INTERNAL_ERROR_MSG, e); } } } }
2,879
0
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple/internal/Conversions.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.simple.internal; /** * Performs seed conversions. * * <p>Note: Legacy converters from version 1.0 use instances of * the {@link SeedConverter} interface. Instances are no longer * required as no state is used during conversion and converters * can use static methods. * * @since 1.5 */ final class Conversions { /** * 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> */ private static final long GOLDEN_RATIO = MixFunctions.GOLDEN_RATIO_64; /** No instances. */ private Conversions() {} /** * Compute the size of an {@code int} array required to hold the specified number of bytes. * Allows space for any remaining bytes that do not fit exactly in a 4 byte integer. * <pre> * n = ceil(size / 4) * </pre> * * @param size the size in bytes (assumed to be positive) * @return the size in ints */ static int intSizeFromByteSize(int size) { return (size + 3) >>> 2; } /** * Compute the size of an {@code long} array required to hold the specified number of bytes. * Allows space for any remaining bytes that do not fit exactly in an 8 byte long. * <pre> * n = ceil(size / 8) * </pre> * * @param size the size in bytes (assumed to be positive) * @return the size in longs */ static int longSizeFromByteSize(int size) { return (size + 7) >>> 3; } /** * Compute the size of an {@code int} array required to hold the specified number of longs. * Prevents overflow to a negative number when doubling the size. * <pre> * n = min(size * 2, 2^31 - 1) * </pre> * * @param size the size in longs (assumed to be positive) * @return the size in ints */ static int intSizeFromLongSize(int size) { // Avoid overflow when doubling the length. // If n is negative the signed shift creates a mask with all bits set; // otherwise it is zero and n is unchanged after the or operation. // The final mask clears the sign bit in the event n did overflow. final int n = size << 1; return (n | (n >> 31)) & Integer.MAX_VALUE; } /** * Compute the size of an {@code long} array required to hold the specified number of ints. * Allows space for an odd int. * <pre> * n = ceil(size / 2) * </pre> * * @param size the size in ints (assumed to be positive) * @return the size in longs */ static int longSizeFromIntSize(int size) { return (size + 1) >>> 1; } /** * Creates a {@code long} value from an {@code int}. The conversion * is made as if seeding a SplitMix64 RNG and calling nextLong(). * * @param input Input * @return a {@code long}. */ static long int2Long(int input) { return MixFunctions.stafford13(input + GOLDEN_RATIO); } /** * Creates an {@code int[]} value from an {@code int}. The conversion * is made as if seeding a SplitMix64 RNG and calling nextLong() to * generate the sequence and filling the ints * in little-endian order (least significant byte first). * * @param input Input * @param length Array length * @return an {@code int[]}. */ static int[] int2IntArray(int input, int length) { return long2IntArray(input, length); } /** * Creates a {@code long[]} value from an {@code int}. The conversion * is made as if seeding a SplitMix64 RNG and calling nextLong() to * generate the sequence. * * @param input Input * @param length Array length * @return a {@code long[]}. */ static long[] int2LongArray(int input, int length) { return long2LongArray(input, length); } /** * Creates an {@code int} value from a {@code long}. The conversion * is made by xoring the upper and lower bits. * * @param input Input * @return an {@code int}. */ static int long2Int(long input) { return (int) input ^ (int) (input >>> 32); } /** * Creates an {@code int[]} value from a {@code long}. The conversion * is made as if seeding a SplitMix64 RNG and calling nextLong() to * generate the sequence and filling the ints * in little-endian order (least significant byte first). * * <p>A special case is made to avoid an array filled with zeros for * the initial 2 positions. It is still possible to create a zero in * position 0. However any RNG with an int[] native type is expected to * require at least 2 int values. * * @param input Input * @param length Array length * @return an {@code int[]}. */ static int[] long2IntArray(long input, int length) { // Special case to avoid creating a zero-filled array of length 2. long v = input == -GOLDEN_RATIO ? ~input : input; final int[] output = new int[length]; // Process pairs final int n = length & ~0x1; for (int i = 0; i < n; i += 2) { final long x = MixFunctions.stafford13(v += GOLDEN_RATIO); output[i] = (int) x; output[i + 1] = (int) (x >>> 32); } // Final value if (n < length) { output[n] = (int) MixFunctions.stafford13(v + GOLDEN_RATIO); } return output; } /** * Creates a {@code long[]} value from a {@code long}. The conversion * is made as if seeding a SplitMix64 RNG and calling nextLong() to * generate the sequence. * * @param input Input * @param length Array length * @return a {@code long}. */ static long[] long2LongArray(long input, int length) { long v = input; final long[] output = new long[length]; for (int i = 0; i < length; i++) { output[i] = MixFunctions.stafford13(v += GOLDEN_RATIO); } return output; } /** * Creates an {@code int} value from a sequence of ints. The conversion * is made by combining all the longs with a xor operation. * * @param input Input bytes * @return an {@code int}. */ static int intArray2Int(int[] input) { int output = 0; for (final int i : input) { output ^= i; } return output; } /** * Creates a {@code long} value from a sequence of ints. The conversion * is made as if converting to a {@code long[]} array by filling the longs * in little-endian order (least significant byte first), then combining * all the longs with a xor operation. * * @param input Input bytes * @return a {@code long}. */ static long intArray2Long(int[] input) { long output = 0; final int n = input.length; // xor in the bits to a long in little-endian order for (int i = 0; i < n; i++) { // i = int index // i >> 1 = long index // i & 0x1 = int number in the long [0, 1] // (i & 0x1) << 5 = little-endian byte shift to the long {0, 32} output ^= (input[i] & 0xffffffffL) << ((i & 0x1) << 5); } return output; } /** * Creates a {@code long[]} value from a sequence of ints. The longs are * filled in little-endian order (least significant byte first). * * @param input Input ints * @param length Output array length * @return a {@code long[]}. */ static long[] intArray2LongArray(int[] input, int length) { final long[] output = new long[length]; // Overflow-safe minimum using long final int n = (int) Math.min(input.length, length * 2L); // Little-endian fill for (int i = 0; i < n; i++) { // i = int index // i >> 1 = long index // i & 0x1 = int number in the long [0, 1] // (i & 0x1) << 5 = little-endian byte shift to the long {0, 32} output[i >> 1] |= (input[i] & 0xffffffffL) << ((i & 0x1) << 5); } return output; } /** * Creates an {@code int} value from a sequence of longs. The conversion * is made as if combining all the longs with a xor operation, then folding * the long high and low parts using a xor operation. * * @param input Input longs * @return an {@code int}. */ static int longArray2Int(long[] input) { return Conversions.long2Int(longArray2Long(input)); } /** * Creates a {@code long} value from a sequence of longs. The conversion * is made by combining all the longs with a xor operation. * * @param input Input longs * @return a {@code long}. */ static long longArray2Long(long[] input) { long output = 0; for (final long i : input) { output ^= i; } return output; } /** * Creates a {@code int[]} value from a sequence of longs. The ints are * filled in little-endian order (least significant byte first). * * @param input Input longs * @param length Output array length * @return an {@code int[]}. */ static int[] longArray2IntArray(long[] input, int length) { final int[] output = new int[length]; // Overflow-safe minimum using long final int n = (int) Math.min(input.length * 2L, length); // Little-endian fill // Alternate low/high 32-bits from each long for (int i = 0; i < n; i++) { // i = int index // i >> 1 = long index // i & 0x1 = int number in the long [0, 1] // (i & 0x1) << 5 = little-endian long shift to the int {0, 32} output[i] = (int)((input[i >> 1]) >>> ((i & 0x1) << 5)); } return output; } /** * Creates an {@code int} value from a sequence of bytes. The conversion * is made as if converting to a {@code int[]} array by filling the ints * in little-endian order (least significant byte first), then combining * all the ints with a xor operation. * * @param input Input bytes * @return an {@code int}. */ static int byteArray2Int(byte[] input) { int output = 0; final int n = input.length; // xor in the bits to an int in little-endian order for (int i = 0; i < n; i++) { // i = byte index // i >> 2 = integer index // i & 0x3 = byte number in the integer [0, 3] // (i & 0x3) << 3 = little-endian byte shift to the integer {0, 8, 16, 24} output ^= (input[i] & 0xff) << ((i & 0x3) << 3); } return output; } /** * Creates an {@code int[]} value from a sequence of bytes. The ints are * filled in little-endian order (least significant byte first). * * @param input Input bytes * @param length Output array length * @return a {@code int[]}. */ static int[] byteArray2IntArray(byte[] input, int length) { final int[] output = new int[length]; // Overflow-safe minimum using long final int n = (int) Math.min(input.length, length * (long) Integer.BYTES); // Little-endian fill for (int i = 0; i < n; i++) { // i = byte index // i >> 2 = integer index // i & 0x3 = byte number in the integer [0, 3] // (i & 0x3) << 3 = little-endian byte shift to the integer {0, 8, 16, 24} output[i >> 2] |= (input[i] & 0xff) << ((i & 0x3) << 3); } return output; } /** * Creates a {@code long} value from a sequence of bytes. The conversion * is made as if converting to a {@code long[]} array by filling the longs * in little-endian order (least significant byte first), then combining * all the longs with a xor operation. * * @param input Input bytes * @return a {@code long}. */ static long byteArray2Long(byte[] input) { long output = 0; final int n = input.length; // xor in the bits to a long in little-endian order for (int i = 0; i < n; i++) { // i = byte index // i >> 3 = long index // i & 0x7 = byte number in the long [0, 7] // (i & 0x7) << 3 = little-endian byte shift to the long {0, 8, 16, 24, 32, 36, 40, 48, 56} output ^= (input[i] & 0xffL) << ((i & 0x7) << 3); } return output; } /** * Creates a {@code long[]} value from a sequence of bytes. The longs are * filled in little-endian order (least significant byte first). * * @param input Input bytes * @param length Output array length * @return a {@code long[]}. */ static long[] byteArray2LongArray(byte[] input, int length) { final long[] output = new long[length]; // Overflow-safe minimum using long final int n = (int) Math.min(input.length, length * (long) Long.BYTES); // Little-endian fill for (int i = 0; i < n; i++) { // i = byte index // i >> 3 = long index // i & 0x7 = byte number in the long [0, 7] // (i & 0x7) << 3 = little-endian byte shift to the long {0, 8, 16, 24, 32, 36, 40, 48, 56} output[i >> 3] |= (input[i] & 0xffL) << ((i & 0x7) << 3); } return output; } }
2,880
0
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple/internal/SeedUtils.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.simple.internal; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.core.util.NumberFactory; /** * Utility for creating seeds. */ final class SeedUtils { /** The modulus {@code 256 % 9}. */ private static final int MOD_09 = 256 % 9; /** The modulus {@code 256 % 10}. */ private static final int MOD_10 = 256 % 10; /** The modulus {@code 256 % 11}. */ private static final int MOD_11 = 256 % 11; /** The modulus {@code 256 % 12}. */ private static final int MOD_12 = 256 % 12; /** The modulus {@code 256 % 13}. */ private static final int MOD_13 = 256 % 13; /** The modulus {@code 256 % 14}. */ private static final int MOD_14 = 256 % 14; /** The modulus {@code 256 % 15}. */ private static final int MOD_15 = 256 % 15; /** The 16 hex digits in an array. */ private static final byte[] HEX_DIGIT_ARRAY = {0xf, 0xe, 0xd, 0xc, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0}; /** * Provider of unsigned 8-bit integers. */ private static class UnsignedByteProvider { /** Mask to extract the lowest 2 bits from an integer. */ private static final int MASK_2_BITS = 0x3; /** Mask to extract the lowest 8 bits from an integer. */ private static final int MASK_8_BITS = 0xff; /** Source of randomness. */ private final UniformRandomProvider rng; /** The current 32-bits of randomness. */ private int bits; /** The counter tracking the bits to extract. */ private int counter; /** * @param rng Source of randomness. */ UnsignedByteProvider(UniformRandomProvider rng) { this.rng = rng; } /** * Return the next unsigned byte. * * @return Value in the range[0,255] */ int nextUnsignedByte() { // Every 4 bytes generate a new 32-bit value final int count = counter & MASK_2_BITS; counter++; if (count == 0) { bits = rng.nextInt(); // Consume the first byte return bits & MASK_8_BITS; } // Consume a remaining byte (occurs 3 times) bits >>>= 8; return bits & MASK_8_BITS; } } /** * Class contains only static methods. */ private SeedUtils() {} /** * Creates an {@code int} containing a permutation of 8 hex digits chosen from 16. * * @param rng Source of randomness. * @return hex digit permutation. */ static int createIntHexPermutation(UniformRandomProvider rng) { final UnsignedByteProvider provider = new UnsignedByteProvider(rng); return createUpperBitsHexPermutation(provider); } /** * Creates a {@code long} containing a permutation of 8 hex digits chosen from 16 in * the upper and lower 32-bits. * * @param rng Source of randomness. * @return hex digit permutation. */ static long createLongHexPermutation(UniformRandomProvider rng) { final UnsignedByteProvider provider = new UnsignedByteProvider(rng); // Extract upper bits and combine with a second sample return NumberFactory.makeLong(createUpperBitsHexPermutation(provider), createUpperBitsHexPermutation(provider)); } /** * Creates a {@code int} containing a permutation of 8 hex digits chosen from 16. * * @param provider Source of randomness. * @return hex digit permutation. */ private static int createUpperBitsHexPermutation(UnsignedByteProvider provider) { // Compute a Fisher-Yates shuffle in-place on the 16 hex digits. // Each digit is chosen uniformly from the remaining digits. // The value is swapped with the current digit. // The following is an optimised sampling algorithm that generates // a uniform deviate in the range [0,n) from an unsigned byte. // The expected number of samples is 256/n. // This has a bias when n does not divide into 256. So samples must // be rejected at a rate of (256 % n) / 256: // n 256 % n Rejection rate // 9 4 0.015625 // 10 6 0.0234375 // 11 3 0.01171875 // 12 4 0.015625 // 13 9 0.03515625 // 14 4 0.015625 // 15 1 0.00390625 // 16 0 0 // The probability of no rejections is 1 - (1-p15) * (1-p14) ... = 0.115 final byte[] digits = HEX_DIGIT_ARRAY.clone(); // The first digit has no bias. Get an index using a mask to avoid modulus. int bits = copyToOutput(digits, 0, 15, provider.nextUnsignedByte() & 0xf); // All remaining digits have a bias so use the rejection algorithm to find // an appropriate uniform deviate in the range [0,n) bits = copyToOutput(digits, bits, 14, nextUnsignedByteInRange(provider, MOD_15, 15)); bits = copyToOutput(digits, bits, 13, nextUnsignedByteInRange(provider, MOD_14, 14)); bits = copyToOutput(digits, bits, 12, nextUnsignedByteInRange(provider, MOD_13, 13)); bits = copyToOutput(digits, bits, 11, nextUnsignedByteInRange(provider, MOD_12, 12)); bits = copyToOutput(digits, bits, 10, nextUnsignedByteInRange(provider, MOD_11, 11)); bits = copyToOutput(digits, bits, 9, nextUnsignedByteInRange(provider, MOD_10, 10)); bits = copyToOutput(digits, bits, 8, nextUnsignedByteInRange(provider, MOD_09, 9)); return bits; } /** * Get the next unsigned byte in the range {@code [0,n)} rejecting any over-represented * sample value using the pre-computed modulus. * * <p>This algorithm is as per Lemire (2019) adapted for 8-bit arithmetic.</p> * * @param provider Provider of bytes. * @param threshold Modulus threshold {@code 256 % n}. * @param n Upper range (exclusive) * @return Value. * @see <a href="https://arxiv.org/abs/1805.10941"> * Lemire (2019): Fast Random Integer Generation in an Interval</a> */ private static int nextUnsignedByteInRange(UnsignedByteProvider provider, int threshold, int n) { // Rejection method using multiply by a fraction: // n * [0, 2^8 - 1) // ------------ // 2^8 // The result is mapped back to an integer and will be in the range [0, n) int m; do { // Compute product of n * [0, 2^8 - 1) m = n * provider.nextUnsignedByte(); // Test the sample uniformity. } while ((m & 0xff) < threshold); // Final divide by 2^8 return m >>> 8; } /** * Copy the lower hex digit to the output bits. Swap the upper hex digit into * the lower position. This is equivalent to a swap step of a Fisher-Yates shuffle on * an array but the output of the shuffle are written to the bits. * * @param digits Digits. * @param bits Bits. * @param upper Upper index. * @param lower Lower index. * @return Updated bits. */ private static int copyToOutput(byte[] digits, int bits, int upper, int lower) { // Move the existing bits up and append the next hex digit. // This is equivalent to swapping lower to upper. final int newbits = bits << 4 | digits[lower] & 0xf; // Swap upper to lower. digits[lower] = digits[upper]; return newbits; } }
2,881
0
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple/internal/SeedConverterComposer.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.simple.internal; /** * Composes two {@link SeedConverter converters}. * * @param <IN> Input seed type. * @param <TRANS> Transitional seed type. * @param <OUT> Output seed type. * * @since 1.0 */ public class SeedConverterComposer<IN, TRANS, OUT> implements SeedConverter<IN, OUT> { /** First conversion. */ private final SeedConverter<IN, TRANS> first; /** Second conversion. */ private final SeedConverter<TRANS, OUT> second; /** * @param first First conversion. * @param second second conversion. */ public SeedConverterComposer(SeedConverter<IN, TRANS> first, SeedConverter<TRANS, OUT> second) { this.first = first; this.second = second; } /** {@inheritDoc} */ @Override public OUT convert(IN seed) { final TRANS trans = first.convert(seed); return second.convert(trans); } }
2,882
0
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple/internal/Seed2ArrayConverter.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.simple.internal; /** * Seed converter to create an output array type. * * @param <IN> Input seed type. * @param <OUT> Output seed type. * @since 1.3 */ public interface Seed2ArrayConverter<IN, OUT> extends SeedConverter<IN, OUT> { /** * Converts seed from input type to output type. The output type is expected to be an array. * * @param seed Original seed value. * @param outputSize Output size. * @return the converted seed value. */ OUT convert(IN seed, int outputSize); }
2,883
0
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple/internal/ByteArray2IntArray.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.simple.internal; /** * Creates a {@code int[]} from a {@code byte[]}. * * @since 1.0 */ public class ByteArray2IntArray implements SeedConverter<byte[], int[]> { /** {@inheritDoc} */ @Override public int[] convert(byte[] seed) { // Full length conversion return Conversions.byteArray2IntArray(seed, Conversions.intSizeFromByteSize(seed.length)); } }
2,884
0
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple/internal/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. */ /** * Utilities for seed conversion. */ package org.apache.commons.rng.simple.internal;
2,885
0
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple
Create_ds/commons-rng/commons-rng-simple/src/main/java/org/apache/commons/rng/simple/internal/SeedFactory.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.simple.internal; import java.security.SecureRandom; import java.util.concurrent.locks.ReentrantLock; import org.apache.commons.rng.core.util.NumberFactory; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.core.source64.RandomLongSource; import org.apache.commons.rng.core.source64.SplitMix64; import org.apache.commons.rng.core.source64.XoRoShiRo1024PlusPlus; /** * Utilities related to seeding. * * <p> * This class provides methods to generate random seeds (single values * or arrays of values, of {@code int} or {@code long} types) that can * be passed to the {@link org.apache.commons.rng.simple.RandomSource * methods that create a generator instance}. * <br> * Although the seed-generating methods defined in this class will likely * return different values for all calls, there is no guarantee that the * produced seed will result always in a "good" sequence of numbers (even * if the generator initialized with that seed is good). * <br> * There is <i>no guarantee</i> that sequences will not overlap. * </p> * * @since 1.0 */ public final class SeedFactory { /** Size of the state array of "XoRoShiRo1024PlusPlus". */ private static final int XO_RO_SHI_RO_1024_STATE_SIZE = 16; /** Size of block to fill in an {@code int[]} seed per synchronized operation. */ private static final int INT_ARRAY_BLOCK_SIZE = 8; /** Size of block to fill in a {@code long[]} seed per synchronized operation. */ private static final int LONG_ARRAY_BLOCK_SIZE = 4; /** * The lock to own when using the seed generator. This lock is unfair and there is no * particular access order for waiting threads. * * <p>This is used as an alternative to {@code synchronized} statements to guard access * to the seed generator.</p> */ private static final ReentrantLock LOCK = new ReentrantLock(false); /** Generator with a long period. */ private static final UniformRandomProvider SEED_GENERATOR; static { // Use a secure RNG so that different instances (e.g. in multiple JVM // instances started in rapid succession) will have different seeds. final SecureRandom seedGen = new SecureRandom(); final byte[] bytes = new byte[8 * XO_RO_SHI_RO_1024_STATE_SIZE]; seedGen.nextBytes(bytes); final long[] seed = NumberFactory.makeLongArray(bytes); // The XoRoShiRo1024PlusPlus generator cannot recover from an all zero seed and // will produce low quality initial output if initialized with some zeros. // Ensure it is non zero at all array positions using a SplitMix64 // generator (this is insensitive to a zero seed so can use the first seed value). final SplitMix64 rng = new SplitMix64(seed[0]); for (int i = 0; i < seed.length; i++) { seed[i] = ensureNonZero(rng, seed[i]); } SEED_GENERATOR = new XoRoShiRo1024PlusPlus(seed); } /** * Class contains only static methods. */ private SeedFactory() {} /** * Creates an {@code int} number for use as a seed. * * @return a random number. */ public static int createInt() { LOCK.lock(); try { return SEED_GENERATOR.nextInt(); } finally { LOCK.unlock(); } } /** * Creates a {@code long} number for use as a seed. * * @return a random number. */ public static long createLong() { LOCK.lock(); try { return SEED_GENERATOR.nextLong(); } finally { LOCK.unlock(); } } /** * Creates an array of {@code int} numbers for use as a seed. * * @param n Size of the array to create. * @return an array of {@code n} random numbers. */ public static int[] createIntArray(int n) { // Behaviour from v1.3 is to ensure the first position is non-zero return createIntArray(n, 0, Math.min(n, 1)); } /** * Creates an array of {@code int} numbers for use as a seed. * Optionally ensure a sub-range of the array is not all-zero. * * <p>This method is package-private for use by {@link NativeSeedType}. * * @param n Size of the array to create. * @param from The start of the not all-zero sub-range (inclusive). * @param to The end of the not all-zero sub-range (exclusive). * @return an array of {@code n} random numbers. * @throws IndexOutOfBoundsException if the sub-range is invalid * @since 1.5 */ static int[] createIntArray(int n, int from, int to) { final int[] seed = new int[n]; // Compute the size that can be filled with complete blocks final int blockSize = INT_ARRAY_BLOCK_SIZE * (n / INT_ARRAY_BLOCK_SIZE); int i = 0; while (i < blockSize) { final int end = i + INT_ARRAY_BLOCK_SIZE; fillIntArray(seed, i, end); i = end; } // Final fill only if required if (i != n) { fillIntArray(seed, i, n); } ensureNonZero(seed, from, to); return seed; } /** * Creates an array of {@code long} numbers for use as a seed. * * @param n Size of the array to create. * @return an array of {@code n} random numbers. */ public static long[] createLongArray(int n) { // Behaviour from v1.3 is to ensure the first position is non-zero return createLongArray(n, 0, Math.min(n, 1)); } /** * Creates an array of {@code long} numbers for use as a seed. * Optionally ensure a sub-range of the array is not all-zero. * * <p>This method is package-private for use by {@link NativeSeedType}. * * @param n Size of the array to create. * @param from The start of the not all-zero sub-range (inclusive). * @param to The end of the not all-zero sub-range (exclusive). * @return an array of {@code n} random numbers. * @throws IndexOutOfBoundsException if the sub-range is invalid * @since 1.5 */ static long[] createLongArray(int n, int from, int to) { final long[] seed = new long[n]; // Compute the size that can be filled with complete blocks final int blockSize = LONG_ARRAY_BLOCK_SIZE * (n / LONG_ARRAY_BLOCK_SIZE); int i = 0; while (i < blockSize) { final int end = i + LONG_ARRAY_BLOCK_SIZE; fillLongArray(seed, i, end); i = end; } // Final fill only if required if (i != n) { fillLongArray(seed, i, n); } ensureNonZero(seed, from, to); return seed; } /** * Fill the array between {@code start} inclusive and {@code end} exclusive from the * seed generator. The lock is used to guard access to the generator. * * @param array Array data. * @param start Start (inclusive). * @param end End (exclusive). */ private static void fillIntArray(int[] array, int start, int end) { LOCK.lock(); try { for (int i = start; i < end; i++) { array[i] = SEED_GENERATOR.nextInt(); } } finally { LOCK.unlock(); } } /** * Fill the array between {@code start} inclusive and {@code end} exclusive from the * seed generator. The lock is used to guard access to the generator. * * @param array Array data. * @param start Start (inclusive). * @param end End (exclusive). */ private static void fillLongArray(long[] array, int start, int end) { LOCK.lock(); try { for (int i = start; i < end; i++) { array[i] = SEED_GENERATOR.nextLong(); } } finally { LOCK.unlock(); } } /** * Creates an array of {@code byte} numbers for use as a seed using the supplied source of * randomness. A sub-range can be specified that must not contain all zeros. * * @param source Source of randomness. * @param n Size of the array to create. * @param from The start of the not all-zero sub-range (inclusive). * @param to The end of the not all-zero sub-range (exclusive). * @return an array of {@code n} random numbers. */ static byte[] createByteArray(UniformRandomProvider source, int n, int from, int to) { final byte[] seed = new byte[n]; source.nextBytes(seed); ensureNonZero(seed, from, to, source); return seed; } /** * Ensure the seed is not all-zero within the specified sub-range. * * <p>This method will check the sub-range and if all are zero it will fill the range * with a random sequence seeded from the default source of random int values. The * fill ensures position {@code from} has a non-zero value; and the entire sub-range * has a maximum of one zero. The method ensures any length sub-range contains * non-zero bits. The output seed is suitable for generators that cannot be seeded * with all zeros in the specified sub-range.</p> * * @param seed Seed array (modified in place). * @param from The start of the not all-zero sub-range (inclusive). * @param to The end of the not all-zero sub-range (exclusive). * @throws IndexOutOfBoundsException if the sub-range is invalid * @see #createInt() */ static void ensureNonZero(int[] seed, int from, int to) { if (from >= to) { return; } // No check on the range so an IndexOutOfBoundsException will occur if invalid for (int i = from; i < to; i++) { if (seed[i] != 0) { return; } } // Fill with non-zero values using a SplitMix-style PRNG. // The range is at least 1. // To ensure the first value is not zero requires the input to the mix function // to be non-zero. This is ensured if the start is even since the increment is odd. int x = createInt() << 1; for (int i = from; i < to; i++) { seed[i] = MixFunctions.murmur3(x += MixFunctions.GOLDEN_RATIO_32); } } /** * Ensure the seed is not all-zero within the specified sub-range. * * <p>This method will check the sub-range and if all are zero it will fill the range * with a random sequence seeded from the default source of random long values. The * fill ensures position {@code from} has a non-zero value; and the entire sub-range * has a maximum of one zero. The method ensures any length sub-range contains * non-zero bits. The output seed is suitable for generators that cannot be seeded * with all zeros in the specified sub-range.</p> * * @param seed Seed array (modified in place). * @param from The start of the not all-zero sub-range (inclusive). * @param to The end of the not all-zero sub-range (exclusive). * @throws IndexOutOfBoundsException if the sub-range is invalid * @see #createLong() */ static void ensureNonZero(long[] seed, int from, int to) { if (from >= to) { return; } // No check on the range so an IndexOutOfBoundsException will occur if invalid for (int i = from; i < to; i++) { if (seed[i] != 0) { return; } } // Fill with non-zero values using a SplitMix-style PRNG. // The range is at least 1. // To ensure the first value is not zero requires the input to the mix function // to be non-zero. This is ensured if the start is even since the increment is odd. long x = createLong() << 1; for (int i = from; i < to; i++) { seed[i] = MixFunctions.stafford13(x += MixFunctions.GOLDEN_RATIO_64); } } /** * Ensure the seed is not all-zero within the specified sub-range. * * <p>This method will check the sub-range and if all are zero it will fill the range * with a random sequence seeded from the provided source of randomness. If the range * length is above 8 then the first 8 bytes in the range are ensured to not all be * zero. If the range length is below 8 then the first byte in the range is ensured to * be non-zero. The method ensures any length sub-range contains non-zero bits. The * output seed is suitable for generators that cannot be seeded with all zeros in the * specified sub-range.</p> * * @param seed Seed array (modified in place). * @param from The start of the not all-zero sub-range (inclusive). * @param to The end of the not all-zero sub-range (exclusive). * @param source Source of randomness. * @throws IndexOutOfBoundsException if the sub-range is invalid */ static void ensureNonZero(byte[] seed, int from, int to, UniformRandomProvider source) { if (from >= to) { return; } // No check on the range so an IndexOutOfBoundsException will occur if invalid for (int i = from; i < to; i++) { if (seed[i] != 0) { return; } } // Defend against a faulty source of randomness (which supplied all zero bytes) // by filling with non-zero values using a SplitMix-style PRNG seeded from the source. // The range is at least 1. // To ensure the first value is not zero requires the input to the mix function // to be non-zero. This is ensured if the start is even since the increment is odd. long x = source.nextLong() << 1; // Process in blocks of 8. // Get the length without the final 3 bits set for a multiple of 8. final int len = (to - from) & ~0x7; final int end = from + len; int i = from; while (i < end) { long v = MixFunctions.stafford13(x += MixFunctions.GOLDEN_RATIO_64); for (int j = 0; j < 8; j++) { seed[i++] = (byte) v; v >>>= 8; } } if (i < to) { // The final bytes. long v = MixFunctions.stafford13(x + MixFunctions.GOLDEN_RATIO_64); // Note the special case where no blocks have been processed requires these // bytes to be non-zero, i.e. (to - from) < 8. In this case the value 'v' will // be non-zero due to the initialisation of 'x' as even. // Rotate the value so the least significant byte is non-zero. The rotation // in bits is rounded down to the nearest 8-bit block to ensure a byte rotation. if (len == 0) { v = Long.rotateRight(v, Long.numberOfTrailingZeros(v) & ~0x7); } while (i < to) { seed[i++] = (byte) v; v >>>= 8; } } } /** * Ensure the value is non-zero. * * <p>This method will replace a zero with a non-zero random number from the random source.</p> * * @param source Source of randomness. * @param value Value. * @return {@code value} if non-zero; else a new random number */ static long ensureNonZero(RandomLongSource source, long value) { long result = value; while (result == 0) { result = source.next(); } return result; } }
2,886
0
Create_ds/commons-rng/commons-rng-client-api/src/test/java/org/apache/commons
Create_ds/commons-rng/commons-rng-client-api/src/test/java/org/apache/commons/rng/SplittableUniformRandomProviderStreamTest.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; import java.util.Spliterator; import org.junit.jupiter.api.Assertions; /** * Tests for default stream method implementations in {@link UniformRandomProvider}. */ class SplittableUniformRandomProviderStreamTest extends BaseRandomProviderStreamTest { /** * Dummy class for checking the behavior of the SplittableUniformRandomProvider. */ private static class DummyGenerator implements SplittableUniformRandomProvider { /** An instance. */ static final DummyGenerator INSTANCE = new DummyGenerator(); @Override public long nextLong() { throw new UnsupportedOperationException("The nextLong method should not be invoked"); } @Override public SplittableUniformRandomProvider split(UniformRandomProvider source) { throw new UnsupportedOperationException("The split method should not be invoked"); } } @Override UniformRandomProvider create() { return DummyGenerator.INSTANCE; } @Override UniformRandomProvider createInts(int[] values) { return new DummyGenerator() { private int i; @Override public int nextInt() { return values[i++]; } }; } @Override UniformRandomProvider createInts(int[] values, int origin, int bound) { return new DummyGenerator() { private int i; @Override public int nextInt(int o, int b) { Assertions.assertEquals(origin, o, "origin"); Assertions.assertEquals(bound, b, "bound"); return values[i++]; } }; } @Override UniformRandomProvider createLongs(long[] values) { return new DummyGenerator() { private int i; @Override public long nextLong() { return values[i++]; } }; } @Override UniformRandomProvider createLongs(long[] values, long origin, long bound) { return new DummyGenerator() { private int i; @Override public long nextLong(long o, long b) { Assertions.assertEquals(origin, o, "origin"); Assertions.assertEquals(bound, b, "bound"); return values[i++]; } }; } @Override UniformRandomProvider createDoubles(double[] values) { return new DummyGenerator() { private int i; @Override public double nextDouble() { return values[i++]; } }; } @Override UniformRandomProvider createDoubles(double[] values, double origin, double bound) { return new DummyGenerator() { private int i; @Override public double nextDouble(double o, double b) { Assertions.assertEquals(origin, o, "origin"); Assertions.assertEquals(bound, b, "bound"); return values[i++]; } }; } @Override int getCharacteristics() { // Since this is splittable it supports sized and sub-sized. // Add non-null although this may not be relevant for primitive streams. return Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.NONNULL | Spliterator.IMMUTABLE; } }
2,887
0
Create_ds/commons-rng/commons-rng-client-api/src/test/java/org/apache/commons
Create_ds/commons-rng/commons-rng-client-api/src/test/java/org/apache/commons/rng/UniformRandomProviderTest.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; import java.math.BigDecimal; import java.math.MathContext; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.SplittableRandom; import java.util.concurrent.ThreadLocalRandom; import java.util.function.LongSupplier; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; /** * Tests for default method implementations in {@link UniformRandomProvider}. * * <p>This class verifies all exception conditions for the range methods. * Single value generation methods are asserted using a test of uniformity * from multiple samples. * * <p>Stream methods are tested {@link UniformRandomProviderStreamTest}. */ class UniformRandomProviderTest { /** Sample size for statistical uniformity tests. */ private static final int SAMPLE_SIZE = 1000; /** Sample size for statistical uniformity tests as a BigDecimal. */ private static final BigDecimal SAMPLE_SIZE_BD = BigDecimal.valueOf(SAMPLE_SIZE); /** Relative error used to verify the sum of expected frequencies matches the sample size. */ private static final double RELATIVE_ERROR = Math.ulp(1.0) * 2; /** * Dummy class for checking the behavior of the UniformRandomProvider. */ private static class DummyGenerator implements UniformRandomProvider { /** An instance. */ static final DummyGenerator INSTANCE = new DummyGenerator(); @Override public long nextLong() { throw new UnsupportedOperationException("The nextLong method should not be invoked"); } } static int[] invalidNextIntBound() { return new int[] {0, -1, Integer.MIN_VALUE}; } static Stream<Arguments> invalidNextIntOriginBound() { return Stream.of( Arguments.of(1, 1), Arguments.of(2, 1), Arguments.of(-1, -1), Arguments.of(-1, -2) ); } static long[] invalidNextLongBound() { return new long[] {0, -1, Long.MIN_VALUE}; } static Stream<Arguments> invalidNextLongOriginBound() { return Stream.of( Arguments.of(1L, 1L), Arguments.of(2L, 1L), Arguments.of(-1L, -1L), Arguments.of(-1L, -2L) ); } static float[] invalidNextFloatBound() { return new float[] {0, -1, -Float.MAX_VALUE, Float.NaN, Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY}; } static Stream<Arguments> invalidNextFloatOriginBound() { return Stream.of( Arguments.of(1f, 1f), Arguments.of(2f, 1f), Arguments.of(-1f, -1f), Arguments.of(-1f, -2f), Arguments.of(Float.NEGATIVE_INFINITY, 0f), Arguments.of(0f, Float.POSITIVE_INFINITY), Arguments.of(0f, Float.NaN), Arguments.of(Float.NaN, 1f) ); } static double[] invalidNextDoubleBound() { return new double[] {0, -1, -Double.MAX_VALUE, Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY}; } static Stream<Arguments> invalidNextDoubleOriginBound() { return Stream.of( Arguments.of(1, 1), Arguments.of(2, 1), Arguments.of(-1, -1), Arguments.of(-1, -2), Arguments.of(Double.NEGATIVE_INFINITY, 0), Arguments.of(0, Double.POSITIVE_INFINITY), Arguments.of(0, Double.NaN), Arguments.of(Double.NaN, 1) ); } /** * Creates a functional random generator by implementing the * {@link UniformRandomProvider#nextLong} method with a high quality source of randomness. * * @param seed Seed for the generator. * @return the random generator */ private static UniformRandomProvider createRNG(long seed) { // The algorithm for SplittableRandom with the default increment passes: // - Test U01 BigCrush // - PractRand with at least 2^42 bytes (4 TiB) of output return new SplittableRandom(seed)::nextLong; } @Test void testNextBytesThrows() { final UniformRandomProvider rng = DummyGenerator.INSTANCE; Assertions.assertThrows(NullPointerException.class, () -> rng.nextBytes(null)); Assertions.assertThrows(NullPointerException.class, () -> rng.nextBytes(null, 0, 1)); // Invalid range final int length = 10; final byte[] bytes = new byte[length]; Assertions.assertThrows(IndexOutOfBoundsException.class, () -> rng.nextBytes(bytes, -1, 1), "start < 0"); Assertions.assertThrows(IndexOutOfBoundsException.class, () -> rng.nextBytes(bytes, length, 1), "start >= length"); Assertions.assertThrows(IndexOutOfBoundsException.class, () -> rng.nextBytes(bytes, 0, -1), "len < 0"); Assertions.assertThrows(IndexOutOfBoundsException.class, () -> rng.nextBytes(bytes, 5, 10), "start + len > length"); Assertions.assertThrows(IndexOutOfBoundsException.class, () -> rng.nextBytes(bytes, 5, Integer.MAX_VALUE), "start + len > length, taking into account integer overflow"); } @ParameterizedTest @MethodSource(value = {"invalidNextIntBound"}) void testNextIntBoundThrows(int bound) { final UniformRandomProvider rng = DummyGenerator.INSTANCE; Assertions.assertThrows(IllegalArgumentException.class, () -> rng.nextInt(bound)); } @ParameterizedTest @MethodSource(value = {"invalidNextIntOriginBound"}) void testNextIntOriginBoundThrows(int origin, int bound) { final UniformRandomProvider rng = DummyGenerator.INSTANCE; Assertions.assertThrows(IllegalArgumentException.class, () -> rng.nextInt(origin, bound)); } @ParameterizedTest @MethodSource(value = {"invalidNextLongBound"}) void testNextLongBoundThrows(long bound) { final UniformRandomProvider rng = DummyGenerator.INSTANCE; Assertions.assertThrows(IllegalArgumentException.class, () -> rng.nextLong(bound)); } @ParameterizedTest @MethodSource(value = {"invalidNextLongOriginBound"}) void testNextLongOriginBoundThrows(long origin, long bound) { final UniformRandomProvider rng = DummyGenerator.INSTANCE; Assertions.assertThrows(IllegalArgumentException.class, () -> rng.nextLong(origin, bound)); } @ParameterizedTest @MethodSource(value = {"invalidNextFloatBound"}) void testNextFloatBoundThrows(float bound) { final UniformRandomProvider rng = DummyGenerator.INSTANCE; Assertions.assertThrows(IllegalArgumentException.class, () -> rng.nextFloat(bound)); } @ParameterizedTest @MethodSource(value = {"invalidNextFloatOriginBound"}) void testNextFloatOriginBoundThrows(float origin, float bound) { final UniformRandomProvider rng = DummyGenerator.INSTANCE; Assertions.assertThrows(IllegalArgumentException.class, () -> rng.nextFloat(origin, bound)); } @ParameterizedTest @MethodSource(value = {"invalidNextDoubleBound"}) void testNextDoubleBoundThrows(double bound) { final UniformRandomProvider rng = DummyGenerator.INSTANCE; Assertions.assertThrows(IllegalArgumentException.class, () -> rng.nextDouble(bound)); } @ParameterizedTest @MethodSource(value = {"invalidNextDoubleOriginBound"}) void testNextDoubleOriginBoundThrows(double origin, double bound) { final UniformRandomProvider rng = DummyGenerator.INSTANCE; Assertions.assertThrows(IllegalArgumentException.class, () -> rng.nextDouble(origin, bound)); } @Test void testNextFloatExtremes() { final UniformRandomProvider rng = new DummyGenerator() { private int i; private final int[] values = {0, -1, 1 << 8}; @Override public int nextInt() { return values[i++]; } }; Assertions.assertEquals(0, rng.nextFloat(), "Expected zero bits to return 0"); Assertions.assertEquals(Math.nextDown(1f), rng.nextFloat(), "Expected all bits to return ~1"); // Assumes the value is created from the high 24 bits of nextInt Assertions.assertEquals(1f - Math.nextDown(1f), rng.nextFloat(), "Expected 1 bit (shifted) to return ~0"); } @ParameterizedTest @ValueSource(floats = {Float.MIN_NORMAL, Float.MIN_NORMAL / 2}) void testNextFloatBoundRounding(float bound) { // This method will be used final UniformRandomProvider rng = new DummyGenerator() { @Override public float nextFloat() { return Math.nextDown(1.0f); } }; Assertions.assertEquals(bound, rng.nextFloat() * bound, "Expected result to be rounded up"); Assertions.assertEquals(Math.nextDown(bound), rng.nextFloat(bound), "Result was not correctly rounded down"); } @Test void testNextFloatOriginBoundInfiniteRange() { // This method will be used final UniformRandomProvider rng = new DummyGenerator() { private int i; private final float[] values = {0, 0.25f, 0.5f, 0.75f, 1}; @Override public float nextFloat() { return values[i++]; } }; final float x = Float.MAX_VALUE; Assertions.assertEquals(-x, rng.nextFloat(-x, x)); Assertions.assertEquals(-x / 2, rng.nextFloat(-x, x), Math.ulp(x / 2)); Assertions.assertEquals(0, rng.nextFloat(-x, x)); Assertions.assertEquals(x / 2, rng.nextFloat(-x, x), Math.ulp(x / 2)); Assertions.assertEquals(Math.nextDown(x), rng.nextFloat(-x, x)); } @Test void testNextFloatOriginBoundRounding() { // This method will be used final float v = Math.nextDown(1.0f); final UniformRandomProvider rng = new DummyGenerator() { @Override public float nextFloat() { return v; } }; float origin; float bound; // Simple case origin = 3.5f; bound = 4.5f; Assertions.assertEquals(bound, origin + v * (bound - origin), "Expected result to be rounded up"); Assertions.assertEquals(Math.nextDown(bound), rng.nextFloat(origin, bound), "Result was not correctly rounded down"); // Alternate formula: // requires sub-normal result for 'origin * v' to force rounding origin = -Float.MIN_NORMAL / 2; bound = Float.MIN_NORMAL / 2; Assertions.assertEquals(bound, origin * (1 - v) + v * bound, "Expected result to be rounded up"); Assertions.assertEquals(Math.nextDown(bound), rng.nextFloat(origin, bound), "Result was not correctly rounded down"); } @Test void testNextDoubleExtremes() { final UniformRandomProvider rng = new DummyGenerator() { private int i; private final long[] values = {0, -1, 1L << 11}; @Override public long nextLong() { return values[i++]; } }; Assertions.assertEquals(0, rng.nextDouble(), "Expected zero bits to return 0"); Assertions.assertEquals(Math.nextDown(1.0), rng.nextDouble(), "Expected all bits to return ~1"); // Assumes the value is created from the high 53 bits of nextInt Assertions.assertEquals(1.0 - Math.nextDown(1.0), rng.nextDouble(), "Expected 1 bit (shifted) to return ~0"); } @ParameterizedTest @ValueSource(doubles = {Double.MIN_NORMAL, Double.MIN_NORMAL / 2}) void testNextDoubleBoundRounding(double bound) { // This method will be used final UniformRandomProvider rng = new DummyGenerator() { @Override public double nextDouble() { return Math.nextDown(1.0); } }; Assertions.assertEquals(bound, rng.nextDouble() * bound, "Expected result to be rounded up"); Assertions.assertEquals(Math.nextDown(bound), rng.nextDouble(bound), "Result was not correctly rounded down"); } @Test void testNextDoubleOriginBoundInfiniteRange() { // This method will be used final UniformRandomProvider rng = new DummyGenerator() { private int i; private final double[] values = {0, 0.25, 0.5, 0.75, 1}; @Override public double nextDouble() { return values[i++]; } }; final double x = Double.MAX_VALUE; Assertions.assertEquals(-x, rng.nextDouble(-x, x)); Assertions.assertEquals(-x / 2, rng.nextDouble(-x, x), Math.ulp(x / 2)); Assertions.assertEquals(0, rng.nextDouble(-x, x)); Assertions.assertEquals(x / 2, rng.nextDouble(-x, x), Math.ulp(x / 2)); Assertions.assertEquals(Math.nextDown(x), rng.nextDouble(-x, x)); } @Test void testNextDoubleOriginBoundRounding() { // This method will be used final double v = Math.nextDown(1.0); final UniformRandomProvider rng = new DummyGenerator() { @Override public double nextDouble() { return v; } }; double origin; double bound; // Simple case origin = 3.5; bound = 4.5; Assertions.assertEquals(bound, origin + v * (bound - origin), "Expected result to be rounded up"); Assertions.assertEquals(Math.nextDown(bound), rng.nextDouble(origin, bound), "Result was not correctly rounded down"); // Alternate formula: // requires sub-normal result for 'origin * v' to force rounding origin = -Double.MIN_NORMAL / 2; bound = Double.MIN_NORMAL / 2; Assertions.assertEquals(bound, origin * (1 - v) + v * bound, "Expected result to be rounded up"); Assertions.assertEquals(Math.nextDown(bound), rng.nextDouble(origin, bound), "Result was not correctly rounded down"); } @Test void testNextBooleanIsIntSignBit() { final int size = 10; final int[] values = ThreadLocalRandom.current().ints(size).toArray(); final UniformRandomProvider rng = new DummyGenerator() { private int i; @Override public int nextInt() { return values[i++]; } }; for (int i = 0; i < size; i++) { Assertions.assertEquals(values[i] < 0, rng.nextBoolean()); } } // Statistical tests for uniform distribution // Monobit tests @ParameterizedTest @ValueSource(longs = {263784628482L, -2563472, -2367482842368L}) void testNextIntMonobit(long seed) { final UniformRandomProvider rng = createRNG(seed); int bitCount = 0; final int n = 100; for (int i = 0; i < n; i++) { bitCount += Integer.bitCount(rng.nextInt()); } final int numberOfBits = n * Integer.SIZE; assertMonobit(bitCount, numberOfBits); } @ParameterizedTest @ValueSource(longs = {263784628L, 253674, -23568426834L}) void testNextDoubleMonobit(long seed) { final UniformRandomProvider rng = createRNG(seed); int bitCount = 0; final int n = 100; for (int i = 0; i < n; i++) { bitCount += Long.bitCount((long) (rng.nextDouble() * (1L << 53))); } final int numberOfBits = n * 53; assertMonobit(bitCount, numberOfBits); } @ParameterizedTest @ValueSource(longs = {265342L, -234232, -672384648284L}) void testNextBooleanMonobit(long seed) { final UniformRandomProvider rng = createRNG(seed); int bitCount = 0; final int n = 1000; for (int i = 0; i < n; i++) { if (rng.nextBoolean()) { bitCount++; } } final int numberOfBits = n; assertMonobit(bitCount, numberOfBits); } @ParameterizedTest @ValueSource(longs = {-1526731, 263846, 4545}) void testNextFloatMonobit(long seed) { final UniformRandomProvider rng = createRNG(seed); int bitCount = 0; final int n = 100; for (int i = 0; i < n; i++) { bitCount += Integer.bitCount((int) (rng.nextFloat() * (1 << 24))); } final int numberOfBits = n * 24; assertMonobit(bitCount, numberOfBits); } @ParameterizedTest @CsvSource({ "-2638468223894, 16", "235647674, 17", "-928738475, 23", }) void testNextBytesMonobit(long seed, int range) { final UniformRandomProvider rng = createRNG(seed); final byte[] bytes = new byte[range]; int bitCount = 0; final int n = 100; for (int i = 0; i < n; i++) { rng.nextBytes(bytes); for (final byte b1 : bytes) { bitCount += Integer.bitCount(b1 & 0xff); } } final int numberOfBits = n * Byte.SIZE * range; assertMonobit(bitCount, numberOfBits); } /** * Assert that the number of 1 bits is approximately 50%. This is based upon a * fixed-step "random walk" of +1/-1 from zero. * * <p>The test is equivalent to the NIST Monobit test with a fixed p-value of * 0.01. The number of bits is recommended to be above 100.</p> * * @see <A * href="https://csrc.nist.gov/publications/detail/sp/800-22/rev-1a/final">Bassham, * et al (2010) NIST SP 800-22: A Statistical Test Suite for Random and * Pseudorandom Number Generators for Cryptographic Applications. Section * 2.1.</a> * * @param bitCount The bit count. * @param numberOfBits Number of bits. */ private static void assertMonobit(int bitCount, int numberOfBits) { // Convert the bit count into a number of +1/-1 steps. final double sum = 2.0 * bitCount - numberOfBits; // The reference distribution is Normal with a standard deviation of sqrt(n). // Check the absolute position is not too far from the mean of 0 with a fixed // p-value of 0.01 taken from a 2-tailed Normal distribution. Computation of // the p-value requires the complimentary error function. final double absSum = Math.abs(sum); final double max = Math.sqrt(numberOfBits) * 2.5758293035489004; Assertions.assertTrue(absSum <= max, () -> "Walked too far astray: " + absSum + " > " + max + " (test will fail randomly about 1 in 100 times)"); } // Uniformity tests @ParameterizedTest @CsvSource({ "263746283, 23, 0, 23", "-126536861889, 16, 0, 16", "617868181124, 1234, 567, 89", "-56788, 512, 0, 233", "6787535424, 512, 233, 279", }) void testNextBytesUniform(long seed, int length, int start, int size) { final UniformRandomProvider rng = createRNG(seed); final byte[] buffer = new byte[length]; final Runnable nextMethod = start == 0 && size == length ? () -> rng.nextBytes(buffer) : () -> rng.nextBytes(buffer, start, size); final int last = start + size; Assertions.assertTrue(isUniformNextBytes(buffer, start, last, nextMethod), "Expected uniform bytes"); // The parts of the buffer where no values are put should be zero. for (int i = 0; i < start; i++) { Assertions.assertEquals(0, buffer[i], () -> "Filled < start: " + start); } for (int i = last; i < length; i++) { Assertions.assertEquals(0, buffer[i], () -> "Filled >= last: " + last); } } /** * Checks that the generator values can be placed into 256 bins with * approximately equal number of counts. * Test allows to select only part of the buffer for performing the * statistics. * * @param buffer Buffer to be filled. * @param first First element (included) of {@code buffer} range for * which statistics must be taken into account. * @param last Last element (excluded) of {@code buffer} range for * which statistics must be taken into account. * @param nextMethod Method that fills the given {@code buffer}. * @return {@code true} if the distribution is uniform. */ private static boolean isUniformNextBytes(byte[] buffer, int first, int last, Runnable nextMethod) { final int sampleSize = 10000; // Number of possible values (do not change). final int byteRange = 256; // Chi-square critical value with 255 degrees of freedom // and 1% significance level. final double chi2CriticalValue = 310.45738821990585; // Bins. final long[] observed = new long[byteRange]; final double expected = (double) sampleSize * (last - first) / byteRange; for (int k = 0; k < sampleSize; k++) { nextMethod.run(); for (int i = first; i < last; i++) { // Convert byte to an index in [0, 255] ++observed[buffer[i] & 0xff]; } } // Compute chi-square. double chi2 = 0; for (int k = 0; k < byteRange; k++) { final double diff = observed[k] - expected; chi2 += diff * diff / expected; } // Statistics check. return chi2 <= chi2CriticalValue; } // Add range tests @ParameterizedTest @CsvSource({ // No lower bound "2673846826, 0, 10", "-23658268, 0, 12", "263478624, 0, 31", "1278332, 0, 32", "99734765, 0, 2016128993", "-63485384, 0, 1834691456", "3876457638, 0, 869657561", "-126784782, 0, 1570504788", "2637846, 0, 2147483647", // Small range "2634682, 567576, 567586", "-56757798989, -1000, -100", "-97324785, -54656, 12", "23423235, -526783468, 257", // Large range "-2634682, -1073741824, 1073741824", "6786868132, -1263842626, 1237846372", "-263846723, -368268, 2147483647", "7352352, -2147483648, 61523457", }) void testNextIntUniform(long seed, int origin, int bound) { final UniformRandomProvider rng = createRNG(seed); final LongSupplier nextMethod = origin == 0 ? () -> rng.nextInt(bound) : () -> rng.nextInt(origin, bound); checkNextInRange("nextInt", origin, bound, nextMethod); } @ParameterizedTest @CsvSource({ // No lower bound "2673846826, 0, 11", "-23658268, 0, 19", "263478624, 0, 31", "1278332, 0, 32", "99734765, 0, 2326378468282368421", "-63485384, 0, 4872347624242243222", "3876457638, 0, 6263784682638866843", "-126784782, 0, 7256684297832668332", "2637846, 0, 9223372036854775807", // Small range "2634682, 567576, 567586", "-56757798989, -1000, -100", "-97324785, -54656, 12", "23423235, -526783468, 257", // Large range "-2634682, -4611686018427387904, 4611686018427387904", "6786868132, -4962836478223688590, 6723648246224929947", "-263846723, -368268, 9223372036854775807", "7352352, -9223372036854775808, 61523457", }) void testNextLongUniform(long seed, long origin, long bound) { final UniformRandomProvider rng = createRNG(seed); final LongSupplier nextMethod = origin == 0 ? () -> rng.nextLong(bound) : () -> rng.nextLong(origin, bound); checkNextInRange("nextLong", origin, bound, nextMethod); } @ParameterizedTest @CsvSource({ // Note: If the range limits are integers above 2^24 (16777216) it is not possible // to represent all the values with a float. This has no effect on sampling into bins // but should be avoided when generating integers for use in production code. // No lower bound. "2673846826, 0, 11", "-23658268, 0, 19", "263478624, 0, 31", "1278332, 0, 32", "99734765, 0, 1234", "-63485384, 0, 578", "3876457638, 0, 10000", "-126784782, 0, 2983423", "2637846, 0, 16777216", // Range "2634682, 567576, 567586", "-56757798989, -1000, -100", "-97324785, -54656, 12", "23423235, -526783468, 257", "-2634682, -688689797, -516827", "6786868132, -67, 67", "-263846723, -5678, 42", "7352352, 678687, 61523457", }) void testNextFloatUniform(long seed, float origin, float bound) { Assertions.assertEquals((long) origin, origin, "origin"); Assertions.assertEquals((long) bound, bound, "bound"); final UniformRandomProvider rng = createRNG(seed); // Note casting as long will round towards zero. // If the upper bound is negative then this can create a domain error so use floor. final LongSupplier nextMethod = origin == 0 ? () -> (long) rng.nextFloat(bound) : () -> (long) Math.floor(rng.nextFloat(origin, bound)); checkNextInRange("nextFloat", (long) origin, (long) bound, nextMethod); } @ParameterizedTest @CsvSource({ // Note: If the range limits are integers above 2^53 (9007199254740992) it is not possible // to represent all the values with a double. This has no effect on sampling into bins // but should be avoided when generating integers for use in production code. // No lower bound. "2673846826, 0, 11", "-23658268, 0, 19", "263478624, 0, 31", "1278332, 0, 32", "99734765, 0, 1234", "-63485384, 0, 578", "3876457638, 0, 10000", "-126784782, 0, 2983423", "2637846, 0, 9007199254740992", // Range "2634682, 567576, 567586", "-56757798989, -1000, -100", "-97324785, -54656, 12", "23423235, -526783468, 257", "-2634682, -688689797, -516827", "6786868132, -67, 67", "-263846723, -5678, 42", "7352352, 678687, 61523457", }) void testNextDoubleUniform(long seed, double origin, double bound) { Assertions.assertEquals((long) origin, origin, "origin"); Assertions.assertEquals((long) bound, bound, "bound"); final UniformRandomProvider rng = createRNG(seed); // Note casting as long will round towards zero. // If the upper bound is negative then this can create a domain error so use floor. final LongSupplier nextMethod = origin == 0 ? () -> (long) rng.nextDouble(bound) : () -> (long) Math.floor(rng.nextDouble(origin, bound)); checkNextInRange("nextDouble", (long) origin, (long) bound, nextMethod); } /** * Tests uniformity of the distribution produced by the given * {@code nextMethod}. * It performs a chi-square test of homogeneity of the observed * distribution with the expected uniform distribution. * Repeat tests are performed at the 1% level and the total number of failed * tests is tested at the 0.5% significance level. * * @param method Generator method. * @param origin Lower bound (inclusive). * @param bound Upper bound (exclusive). * @param nextMethod method to call. */ private static void checkNextInRange(String method, long origin, long bound, LongSupplier nextMethod) { // Do not change // (statistical test assumes that 500 repeats are made with dof = 9). final int numTests = 500; final int numBins = 10; // dof = numBins - 1 // Set up bins. final long[] binUpperBounds = new long[numBins]; // Range may be above a positive long: step = (bound - origin) / bins final BigDecimal range = BigDecimal.valueOf(bound) .subtract(BigDecimal.valueOf(origin)); final double step = range.divide(BigDecimal.TEN).doubleValue(); for (int k = 1; k < numBins; k++) { binUpperBounds[k - 1] = origin + (long) (k * step); } // Final bound binUpperBounds[numBins - 1] = bound; // Create expected frequencies final double[] expected = new double[numBins]; long previousUpperBound = origin; final double scale = SAMPLE_SIZE_BD.divide(range, MathContext.DECIMAL128).doubleValue(); double sum = 0; for (int k = 0; k < numBins; k++) { final long binWidth = binUpperBounds[k] - previousUpperBound; expected[k] = scale * binWidth; sum += expected[k]; previousUpperBound = binUpperBounds[k]; } Assertions.assertEquals(SAMPLE_SIZE, sum, SAMPLE_SIZE * RELATIVE_ERROR, "Invalid expected frequencies"); final int[] observed = new int[numBins]; // Chi-square critical value with 9 degrees of freedom // and 1% significance level. final double chi2CriticalValue = 21.665994333461924; // For storing chi2 larger than the critical value. final List<Double> failedStat = new ArrayList<>(); try { final int lastDecileIndex = numBins - 1; for (int i = 0; i < numTests; i++) { Arrays.fill(observed, 0); SAMPLE: for (int j = 0; j < SAMPLE_SIZE; j++) { final long value = nextMethod.getAsLong(); if (value < origin) { Assertions.fail(String.format("Sample %d not within bound [%d, %d)", value, origin, bound)); } for (int k = 0; k < lastDecileIndex; k++) { if (value < binUpperBounds[k]) { ++observed[k]; continue SAMPLE; } } if (value >= bound) { Assertions.fail(String.format("Sample %d not within bound [%d, %d)", value, origin, bound)); } ++observed[lastDecileIndex]; } // Compute chi-square. double chi2 = 0; for (int k = 0; k < numBins; k++) { final double diff = observed[k] - expected[k]; chi2 += diff * diff / expected[k]; } // Statistics check. if (chi2 > chi2CriticalValue) { failedStat.add(chi2); } } } catch (final Exception e) { // Should never happen. throw new RuntimeException("Unexpected", e); } // The expected number of failed tests can be modelled as a Binomial distribution // B(n, p) with n=500, p=0.01 (500 tests with a 1% significance level). // The cumulative probability of the number of failed tests (X) is: // x P(X>x) // 10 0.0132 // 11 0.00521 // 12 0.00190 if (failedStat.size() > 11) { // Test will fail with 0.5% probability Assertions.fail(String.format( "%s: Too many failures for n = %d, sample size = %d " + "(%d out of %d tests failed, chi2 > %.3f=%s)", method, bound, SAMPLE_SIZE, failedStat.size(), numTests, chi2CriticalValue, failedStat.stream().map(d -> String.format("%.3f", d)) .collect(Collectors.joining(", ", "[", "]")))); } } }
2,888
0
Create_ds/commons-rng/commons-rng-client-api/src/test/java/org/apache/commons
Create_ds/commons-rng/commons-rng-client-api/src/test/java/org/apache/commons/rng/UniformRandomProviderStreamTest.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; import java.util.Spliterator; import org.junit.jupiter.api.Assertions; /** * Tests for default stream method implementations in {@link UniformRandomProvider}. */ class UniformRandomProviderStreamTest extends BaseRandomProviderStreamTest { /** * Dummy class for checking the behavior of the UniformRandomProvider. */ private static class DummyGenerator implements UniformRandomProvider { /** An instance. */ static final DummyGenerator INSTANCE = new DummyGenerator(); @Override public long nextLong() { throw new UnsupportedOperationException("The nextLong method should not be invoked"); } } @Override UniformRandomProvider create() { return DummyGenerator.INSTANCE; } @Override UniformRandomProvider createInts(int[] values) { return new DummyGenerator() { private int i; @Override public int nextInt() { return values[i++]; } }; } @Override UniformRandomProvider createInts(int[] values, int origin, int bound) { return new DummyGenerator() { private int i; @Override public int nextInt(int o, int b) { Assertions.assertEquals(origin, o, "origin"); Assertions.assertEquals(bound, b, "bound"); return values[i++]; } }; } @Override UniformRandomProvider createLongs(long[] values) { return new DummyGenerator() { private int i; @Override public long nextLong() { return values[i++]; } }; } @Override UniformRandomProvider createLongs(long[] values, long origin, long bound) { return new DummyGenerator() { private int i; @Override public long nextLong(long o, long b) { Assertions.assertEquals(origin, o, "origin"); Assertions.assertEquals(bound, b, "bound"); return values[i++]; } }; } @Override UniformRandomProvider createDoubles(double[] values) { return new DummyGenerator() { private int i; @Override public double nextDouble() { return values[i++]; } }; } @Override UniformRandomProvider createDoubles(double[] values, double origin, double bound) { return new DummyGenerator() { private int i; @Override public double nextDouble(double o, double b) { Assertions.assertEquals(origin, o, "origin"); Assertions.assertEquals(bound, b, "bound"); return values[i++]; } }; } @Override int getCharacteristics() { // The current stream produced by the generate method only returns immutable return Spliterator.IMMUTABLE; } }
2,889
0
Create_ds/commons-rng/commons-rng-client-api/src/test/java/org/apache/commons
Create_ds/commons-rng/commons-rng-client-api/src/test/java/org/apache/commons/rng/BaseRandomProviderStreamTest.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; import java.util.Spliterator; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.DoubleStream; import java.util.stream.IntStream; import java.util.stream.LongStream; import java.util.stream.Stream; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; /** * Tests for default stream method implementations in {@link UniformRandomProvider} and derived * interfaces. * * <p>This class exists to test that {@link UniformRandomProvider} and any derived interface that * overloads the base implementation function identically for the stream based methods. Stream * methods are asserted to call the corresponding single value generation method in the interface. */ abstract class BaseRandomProviderStreamTest { private static final long STREAM_SIZE_ONE = 1; static Stream<Arguments> invalidNextIntOriginBound() { return UniformRandomProviderTest.invalidNextIntOriginBound(); } static Stream<Arguments> invalidNextLongOriginBound() { return UniformRandomProviderTest.invalidNextLongOriginBound(); } static Stream<Arguments> invalidNextDoubleOriginBound() { return UniformRandomProviderTest.invalidNextDoubleOriginBound(); } static long[] streamSizes() { return new long[] {0, 1, 13}; } /** * Creates the provider used to test the stream methods. * The instance will be used to verify the following conditions: * <ul> * <li>Invalid stream sizes * <li>Unspecified stream size has an iterator that initially reports Long.MAX_VALUE * <li>Invalid bounds for the bounded stream methods * </ul> * * @return the uniform random provider */ abstract UniformRandomProvider create(); /** * Creates the provider using the specified {@code values} for the * {@link UniformRandomProvider#nextInt()} method. All other primitive * generation methods should raise an exception to ensure the * {@link UniformRandomProvider#ints()} method calls the correct generation * method. * * @param values Values to return from the generation method. * @return the uniform random provider */ abstract UniformRandomProvider createInts(int[] values); /** * Creates the provider using the specified {@code values} for the * {@link UniformRandomProvider#nextInt(int, int)} method. All other primitive * generation methods should raise an exception to ensure the * {@link UniformRandomProvider#ints(int, int)} method calls the correct * generation method. * * @param values Values to return from the generation method. * @param origin Origin for the generation method. Can be asserted to match the argument passed to the method. * @param bound Bound for the generation method. Can be asserted to match the argument passed to the method. * @return the uniform random provider */ abstract UniformRandomProvider createInts(int[] values, int origin, int bound); /** * Creates the provider using the specified {@code values} for the * {@link UniformRandomProvider#nextLong()} method. * All other primitive generation methods should raise an exception to * ensure the {@link UniformRandomProvider#longs()} method calls the correct * generation method. * * @param values Values to return from the generation method. * @return the uniform random provider */ abstract UniformRandomProvider createLongs(long[] values); /** * Creates the provider using the specified {@code values} for the * {@link UniformRandomProvider#nextLong(long, long)} method. * All other primitive generation methods should raise an exception to * ensure the {@link UniformRandomProvider#longs(long, long)} method calls the correct * generation method. * * @param values Values to return from the generation method. * @param origin Origin for the generation method. Can be asserted to match the argument passed to the method. * @param bound Bound for the generation method. Can be asserted to match the argument passed to the method. * @return the uniform random provider */ abstract UniformRandomProvider createLongs(long[] values, long origin, long bound); /** * Creates the provider using the specified {@code values} for the * {@link UniformRandomProvider#nextDouble()} method. * All other primitive generation methods should raise an exception to * ensure the {@link UniformRandomProvider#doubles()} method calls the correct * generation method. * * @param values Values to return from the generation method. * @return the uniform random provider */ abstract UniformRandomProvider createDoubles(double[] values); /** * Creates the provider using the specified {@code values} for the * {@link UniformRandomProvider#nextDouble(double, double)} method. * All other primitive generation methods should raise an exception to * ensure the {@link UniformRandomProvider#doubles(double, double)} method calls the correct * generation method. * * @param values Values to return from the generation method. * @param origin Origin for the generation method. Can be asserted to match the argument passed to the method. * @param bound Bound for the generation method. Can be asserted to match the argument passed to the method. * @return the uniform random provider */ abstract UniformRandomProvider createDoubles(double[] values, double origin, double bound); /** * Gets the expected stream characteristics for the initial stream created with unlimited size. * * @return the characteristics */ abstract int getCharacteristics(); @ParameterizedTest @ValueSource(longs = {-1, -2, Long.MIN_VALUE}) void testInvalidStreamSizeThrows(long size) { final UniformRandomProvider rng = create(); Assertions.assertThrows(IllegalArgumentException.class, () -> rng.ints(size), "ints()"); Assertions.assertThrows(IllegalArgumentException.class, () -> rng.ints(size, 1, 42), "ints(lower, upper)"); Assertions.assertThrows(IllegalArgumentException.class, () -> rng.longs(size), "longs()"); Assertions.assertThrows(IllegalArgumentException.class, () -> rng.longs(size, 3L, 33L), "longs(lower, upper)"); Assertions.assertThrows(IllegalArgumentException.class, () -> rng.doubles(size), "doubles()"); Assertions.assertThrows(IllegalArgumentException.class, () -> rng.doubles(size, 1.5, 2.75), "doubles(lower, upper)"); } @Test void testUnlimitedStreamSize() { final UniformRandomProvider rng = create(); assertUnlimitedSpliterator(rng.ints().spliterator(), "ints()"); assertUnlimitedSpliterator(rng.ints(1, 42).spliterator(), "ints(lower, upper)"); assertUnlimitedSpliterator(rng.longs().spliterator(), "longs()"); assertUnlimitedSpliterator(rng.longs(1627384682623L, 32676823622343L).spliterator(), "longs(lower, upper)"); assertUnlimitedSpliterator(rng.doubles().spliterator(), "doubles()"); assertUnlimitedSpliterator(rng.doubles(1.5, 2.75).spliterator(), "doubles(lower, upper)"); } /** * Assert the spliterator has an unlimited expected size and the characteristics specified * by {@link #getCharacteristics()}. * * @param spliterator Spliterator. * @param msg Error message. */ private void assertUnlimitedSpliterator(Spliterator<?> spliterator, String msg) { assertSpliterator(spliterator, Long.MAX_VALUE, getCharacteristics(), msg); } /** * Assert the spliterator has the expected size and characteristics. * * @param spliterator Spliterator. * @param expectedSize Expected size. * @param characteristics Expected characteristics. * @param msg Error message. * @see Spliterator#hasCharacteristics(int) */ static void assertSpliterator(Spliterator<?> spliterator, long expectedSize, int characteristics, String msg) { Assertions.assertEquals(expectedSize, spliterator.estimateSize(), msg); Assertions.assertTrue(spliterator.hasCharacteristics(characteristics), () -> String.format("%s: characteristics = %s, expected %s", msg, Integer.toBinaryString(spliterator.characteristics()), Integer.toBinaryString(characteristics) )); } // Test stream methods throw immediately for invalid range arguments. @ParameterizedTest @MethodSource(value = {"invalidNextIntOriginBound"}) void testIntsOriginBoundThrows(int origin, int bound) { final UniformRandomProvider rng = create(); Assertions.assertThrows(IllegalArgumentException.class, () -> rng.ints(origin, bound)); Assertions.assertThrows(IllegalArgumentException.class, () -> rng.ints(STREAM_SIZE_ONE, origin, bound)); } @ParameterizedTest @MethodSource(value = {"invalidNextLongOriginBound"}) void testLongsOriginBoundThrows(long origin, long bound) { final UniformRandomProvider rng = create(); Assertions.assertThrows(IllegalArgumentException.class, () -> rng.longs(origin, bound)); Assertions.assertThrows(IllegalArgumentException.class, () -> rng.longs(STREAM_SIZE_ONE, origin, bound)); } @ParameterizedTest @MethodSource(value = {"invalidNextDoubleOriginBound"}) void testDoublesOriginBoundThrows(double origin, double bound) { final UniformRandomProvider rng = create(); Assertions.assertThrows(IllegalArgumentException.class, () -> rng.doubles(origin, bound)); Assertions.assertThrows(IllegalArgumentException.class, () -> rng.doubles(STREAM_SIZE_ONE, origin, bound)); } // Test stream methods call the correct generation method in the UniformRandomProvider. // If range arguments are supplied they are asserted to be passed through. // Streams are asserted to be sequential. @ParameterizedTest @MethodSource(value = {"streamSizes"}) void testInts(long streamSize) { final int[] values = ThreadLocalRandom.current().ints(streamSize).toArray(); final UniformRandomProvider rng = createInts(values); final IntStream stream = rng.ints(); Assertions.assertFalse(stream.isParallel()); Assertions.assertArrayEquals(values, stream.limit(streamSize).toArray()); } @ParameterizedTest @MethodSource(value = {"streamSizes"}) void testIntsOriginBound(long streamSize) { final int origin = 13; final int bound = 42; final int[] values = ThreadLocalRandom.current().ints(streamSize, origin, bound).toArray(); final UniformRandomProvider rng = createInts(values, origin, bound); final IntStream stream = rng.ints(origin, bound); Assertions.assertFalse(stream.isParallel()); Assertions.assertArrayEquals(values, stream.limit(streamSize).toArray()); } @ParameterizedTest @MethodSource(value = {"streamSizes"}) void testIntsWithSize(long streamSize) { final int[] values = ThreadLocalRandom.current().ints(streamSize).toArray(); final UniformRandomProvider rng = createInts(values); final IntStream stream = rng.ints(streamSize); Assertions.assertFalse(stream.isParallel()); Assertions.assertArrayEquals(values, stream.toArray()); } @ParameterizedTest @MethodSource(value = {"streamSizes"}) void testIntsOriginBoundWithSize(long streamSize) { final int origin = 13; final int bound = 42; final int[] values = ThreadLocalRandom.current().ints(streamSize, origin, bound).toArray(); final UniformRandomProvider rng = createInts(values, origin, bound); final IntStream stream = rng.ints(streamSize, origin, bound); Assertions.assertFalse(stream.isParallel()); Assertions.assertArrayEquals(values, stream.toArray()); } @ParameterizedTest @MethodSource(value = {"streamSizes"}) void testLongs(long streamSize) { final long[] values = ThreadLocalRandom.current().longs(streamSize).toArray(); final UniformRandomProvider rng = createLongs(values); final LongStream stream = rng.longs(); Assertions.assertFalse(stream.isParallel()); Assertions.assertArrayEquals(values, stream.limit(streamSize).toArray()); } @ParameterizedTest @MethodSource(value = {"streamSizes"}) void testLongsOriginBound(long streamSize) { final long origin = 26278368423L; final long bound = 422637723236L; final long[] values = ThreadLocalRandom.current().longs(streamSize, origin, bound).toArray(); final UniformRandomProvider rng = createLongs(values, origin, bound); final LongStream stream = rng.longs(origin, bound); Assertions.assertFalse(stream.isParallel()); Assertions.assertArrayEquals(values, stream.limit(streamSize).toArray()); } @ParameterizedTest @MethodSource(value = {"streamSizes"}) void testLongsWithSize(long streamSize) { final long[] values = ThreadLocalRandom.current().longs(streamSize).toArray(); final UniformRandomProvider rng = createLongs(values); final LongStream stream = rng.longs(streamSize); Assertions.assertFalse(stream.isParallel()); Assertions.assertArrayEquals(values, stream.toArray()); } @ParameterizedTest @MethodSource(value = {"streamSizes"}) void testLongsOriginBoundWithSize(long streamSize) { final long origin = 26278368423L; final long bound = 422637723236L; final long[] values = ThreadLocalRandom.current().longs(streamSize, origin, bound).toArray(); final UniformRandomProvider rng = createLongs(values, origin, bound); final LongStream stream = rng.longs(streamSize, origin, bound); Assertions.assertFalse(stream.isParallel()); Assertions.assertArrayEquals(values, stream.toArray()); } @ParameterizedTest @MethodSource(value = {"streamSizes"}) void testDoubles(long streamSize) { final double[] values = ThreadLocalRandom.current().doubles(streamSize).toArray(); final UniformRandomProvider rng = createDoubles(values); final DoubleStream stream = rng.doubles(); Assertions.assertFalse(stream.isParallel()); Assertions.assertArrayEquals(values, stream.limit(streamSize).toArray()); } @ParameterizedTest @MethodSource(value = {"streamSizes"}) void testDoublesOriginBound(long streamSize) { final double origin = 1.23; final double bound = 4.56; final double[] values = ThreadLocalRandom.current().doubles(streamSize, origin, bound).toArray(); final UniformRandomProvider rng = createDoubles(values, origin, bound); final DoubleStream stream = rng.doubles(origin, bound); Assertions.assertFalse(stream.isParallel()); Assertions.assertArrayEquals(values, stream.limit(streamSize).toArray()); } @ParameterizedTest @MethodSource(value = {"streamSizes"}) void testDoublesWithSize(long streamSize) { final double[] values = ThreadLocalRandom.current().doubles(streamSize).toArray(); final UniformRandomProvider rng = createDoubles(values); final DoubleStream stream = rng.doubles(streamSize); Assertions.assertFalse(stream.isParallel()); Assertions.assertArrayEquals(values, stream.toArray()); } @ParameterizedTest @MethodSource(value = {"streamSizes"}) void testDoublesOriginBoundWithSize(long streamSize) { final double origin = 1.23; final double bound = 4.56; final double[] values = ThreadLocalRandom.current().doubles(streamSize, origin, bound).toArray(); final UniformRandomProvider rng = createDoubles(values, origin, bound); final DoubleStream stream = rng.doubles(streamSize, origin, bound); Assertions.assertFalse(stream.isParallel()); Assertions.assertArrayEquals(values, stream.toArray()); } }
2,890
0
Create_ds/commons-rng/commons-rng-client-api/src/test/java/org/apache/commons
Create_ds/commons-rng/commons-rng-client-api/src/test/java/org/apache/commons/rng/LongJumpableUniformRandomProviderTest.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; import java.util.HashSet; import java.util.Set; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Stream; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; /** * Tests for default method implementations in * {@link LongJumpableUniformRandomProvider}. * * <p>Streams methods are asserted to call the corresponding jump method in the * interface. */ class LongJumpableUniformRandomProviderTest { /** * Class for checking the behavior of the LongJumpableUniformRandomProvider. * This generator returns a fixed value. The value is incremented by jumping. */ private static class JumpableGenerator implements LongJumpableUniformRandomProvider { /** The increment to the value after a jump. */ private static final long JUMP_INCREMENT = 1; /** The increment to the value after a long jump. */ private static final long LONG_JUMP_INCREMENT = 1000; /** The value for nextLong(). */ private long value; JumpableGenerator(long seed) { this.value = seed; } @Override public long nextLong() { return value; } @Override public UniformRandomProvider jump() { final UniformRandomProvider copy = new JumpableGenerator(value); value += JUMP_INCREMENT; return copy; } @Override public JumpableUniformRandomProvider longJump() { final JumpableUniformRandomProvider copy = new JumpableGenerator(value); value += LONG_JUMP_INCREMENT; return copy; } } /** * Return a stream of jump arguments, each of the arguments consisting of the size of * the stream and the seed value for the jumpable generator. * * @return the stream of arguments */ static Stream<Arguments> jumpArguments() { return Stream.of( // size, seed Arguments.of(0, 0L), Arguments.of(1, 62317845757L), Arguments.of(5, -12683127894356L) ); } @ParameterizedTest @ValueSource(longs = {-1, -2, Long.MIN_VALUE}) void testInvalidStreamSizeThrows(long size) { final LongJumpableUniformRandomProvider rng = new JumpableGenerator(0); Assertions.assertThrows(IllegalArgumentException.class, () -> rng.jumps(size), "jumps"); Assertions.assertThrows(IllegalArgumentException.class, () -> rng.longJumps(size), "longJumps"); } @ParameterizedTest @MethodSource(value = {"jumpArguments"}) void testJumps(int size, long seed) { assertJumps(size, seed, LongJumpableUniformRandomProvider::jump, (rng, n) -> rng.jumps().limit(n)); } @ParameterizedTest @MethodSource(value = {"jumpArguments"}) void testJumpsWithSize(int size, long seed) { assertJumps(size, seed, JumpableUniformRandomProvider::jump, JumpableUniformRandomProvider::jumps); } @ParameterizedTest @MethodSource(value = {"jumpArguments"}) void testLongJumps(int size, long seed) { assertJumps(size, seed, LongJumpableUniformRandomProvider::longJump, (rng, n) -> rng.longJumps().limit(n)); } @ParameterizedTest @MethodSource(value = {"jumpArguments"}) void testLongJumpsWithSize(int size, long seed) { assertJumps(size, seed, LongJumpableUniformRandomProvider::longJump, LongJumpableUniformRandomProvider::longJumps); } /** * Assert that successive calls to the generator jump function will create a series of * generators that matches the stream function. * * @param size Number of jumps. * @param seed Seed for the generator. * @param jumpFunction Jump function to create a copy and advance the generator. * @param streamFunction Stream function to create a series of generators spaced * using the jump function. */ private static void assertJumps(int size, long seed, Function<? super LongJumpableUniformRandomProvider, ? extends UniformRandomProvider> jumpFunction, BiFunction<? super LongJumpableUniformRandomProvider, Long, Stream<? extends UniformRandomProvider>> streamFunction) { // Manually jump final JumpableGenerator jumpingRNG = new JumpableGenerator(seed); final long[] expected = new long[size]; for (int i = 0; i < size; i++) { final UniformRandomProvider copy = jumpFunction.apply(jumpingRNG); Assertions.assertNotSame(jumpingRNG, copy, "Jump function should return a copy"); expected[i] = copy.nextLong(); } // Stream (must be sequential) final JumpableGenerator streamingRNG = new JumpableGenerator(seed); final Stream<? extends UniformRandomProvider> stream = streamFunction.apply(streamingRNG, Long.valueOf(size)); Assertions.assertFalse(stream.isParallel(), "Jumping requires a non-parallel stream"); // Stream should create unique generators final Set<UniformRandomProvider> set = new HashSet<>(); final long[] actual = stream.map(x -> addAndReturn(set, x)) .mapToLong(UniformRandomProvider::nextLong) .toArray(); Assertions.assertEquals(size, set.size(), "Stream should have unique generators"); Assertions.assertFalse(set.contains(streamingRNG), "Stream contains the source of the stream as a generator"); Assertions.assertArrayEquals(expected, actual, "Stream function did not match the jump function"); } /** * Add the generator to the set and return the generator. This is a convenience * method used to check generator objects in a stream are unique and not the same as * the generator that created the stream. * * @param set Set * @param x Generator * @return the generator */ private static UniformRandomProvider addAndReturn(Set<UniformRandomProvider> set, UniformRandomProvider x) { set.add(x); return x; } }
2,891
0
Create_ds/commons-rng/commons-rng-client-api/src/test/java/org/apache/commons
Create_ds/commons-rng/commons-rng-client-api/src/test/java/org/apache/commons/rng/SplittableUniformRandomProviderTest.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; import java.util.Arrays; import java.util.HashSet; import java.util.Spliterator; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; import java.util.function.DoubleConsumer; import java.util.function.IntConsumer; import java.util.function.LongConsumer; import java.util.stream.LongStream; import java.util.stream.Stream; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; /** * Tests for split method implementations in * {@link SplittableUniformRandomProvider}. * * <p>This class verifies all exception conditions for the split methods and the * arguments to the methods to stream RNGs. Exception conditions and sequential * (default) output from the primitive stream methods are tested in * {@link SplittableUniformRandomProviderStreamTest}. * * <p>Parallel streams (RNGs and primitives) are tested using a splittable * generator that outputs a unique sequence using an atomic counter that is * thread-safe. */ class SplittableUniformRandomProviderTest { private static final long STREAM_SIZE_ONE = 1; /** The expected characteristics for the spliterator from the splittable stream. */ private static final int SPLITERATOR_CHARACTERISTICS = Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.NONNULL | Spliterator.IMMUTABLE; /** * Dummy class for checking the behavior of the SplittableUniformRandomProvider. * All generation and split methods throw an exception. This can be used to test * exception conditions for arguments to default stream functions. */ private static class DummyGenerator implements SplittableUniformRandomProvider { /** An instance. */ static final DummyGenerator INSTANCE = new DummyGenerator(); @Override public long nextLong() { throw new UnsupportedOperationException("The nextLong method should not be invoked"); } @Override public SplittableUniformRandomProvider split(UniformRandomProvider source) { throw new UnsupportedOperationException("The split(source) method should not be invoked"); } } /** * Class for outputting a unique sequence from the nextLong() method even under * recursive splitting. Splitting creates a new instance. */ private static class SequenceGenerator implements SplittableUniformRandomProvider { /** The value for nextLong. */ private final AtomicLong value; /** * @param seed Sequence seed value. */ SequenceGenerator(long seed) { value = new AtomicLong(seed); } /** * @param value The value for nextLong. */ SequenceGenerator(AtomicLong value) { this.value = value; } @Override public long nextLong() { return value.getAndIncrement(); } @Override public SplittableUniformRandomProvider split(UniformRandomProvider source) { // Ignore the source (use of the source is optional) return new SequenceGenerator(value); } } /** * Class for outputting a fixed value from the nextLong() method even under * recursive splitting. Splitting creates a new instance seeded with the nextLong value * from the source of randomness. This can be used to distinguish self-seeding from * seeding with an alternative source. */ private class FixedGenerator implements SplittableUniformRandomProvider { /** The value for nextLong. */ private final long value; /** * @param value Fixed value. */ FixedGenerator(long value) { this.value = value; } @Override public long nextLong() { return value; } @Override public SplittableUniformRandomProvider split(UniformRandomProvider source) { return new FixedGenerator(source.nextLong()); } } /** * Class to track recursive splitting and iterating over a fixed set of values. * Splitting without a source of randomness returns the same instance; with a * source of randomness will throw an exception. All generation methods throw an * exception. * * <p>An atomic counter is maintained to allow concurrent return of unique * values from a fixed array. The values are expected to be maintained in child * classes. Any generation methods that are overridden for tests should * be thread-safe, e.g. returning {@code values[count.getAndIncrement()]}. * * <p>A count of the number of splits is maintained. This is not used for assertions * to avoid test failures that may occur when streams are split differently, or not * at all, by the current JVM. The count can be used to debug splitting behavior * on JVM implementations. */ private static class CountingGenerator extends DummyGenerator { /** The split count. Incrementded when the generator is split. */ protected final AtomicInteger splitCount = new AtomicInteger(); /** The count of returned values. */ protected final AtomicInteger count = new AtomicInteger(); @Override public SplittableUniformRandomProvider split() { splitCount.getAndIncrement(); return this; } } /** * Class to return the same instance when splitting without a source of randomness; * with a source of randomness will throw an exception. All generation methods * throw an exception. Any generation methods that are overridden for tests should * be thread-safe. */ private abstract static class SingleInstanceGenerator extends DummyGenerator { @Override public SplittableUniformRandomProvider split() { return this; } } /** * Thread and stream sizes used to test parallel streams. * * @return the arguments */ static Stream<Arguments> threadAndStreamSizes() { return Stream.of( Arguments.of(1, 16), Arguments.of(2, 16), Arguments.of(4, 16), Arguments.of(8, 16), Arguments.of(4, 2), Arguments.of(8, 4) ); } /** * Execute the task in a ForkJoinPool with the specified level of parallelism. Any * parallel stream executing in the task should be limited to the specified level of * parallelism. * * <p><b>Note</b> * * <p>This is a JDK undocumented feature of streams to use the enclosing ForkJoinPool * in-place of {@link ForkJoinPool#commonPool()}; this behaviour may be subject to * change. * * <p>Here the intention is to force the parallel stream to execute with a varying * number of threads. Note that debugging using the {@link CountingGenerator} * indicates that the number of splits is not influenced by the enclosing pool * parallelism but rather the number of stream elements and possibly the * <em>standard</em> number of available processors. Further testing on Linux using * {@code numactl -C 1} to limit the number of processors returns 1 for * {@link ForkJoinPool#getCommonPoolParallelism()} and * {@link Runtime#availableProcessors()} with no change in the number of splits * performed by parallel streams. This indicates the splitting of parallel streams may * not respect the limits imposed on the executing JVM. However this does mean that * tests using this method do test the splitting of the stream, irrespective of * configured parallelism when executed on a machine that has multiple CPU cores, i.e. * the <em>potential</em> for parallelism. * * <p>It is unknown if the parallel streams will split when executed on a true single-core * JVM such as that provided by a continuous integration build environment running for * example in a virtual machine. * * @param <T> Return type of the task. * @param parallelism Level of parallelism. * @param task Task. * @return the task result * @throws InterruptedException the interrupted exception * @throws ExecutionException the execution exception */ private static <T> T execute(int parallelism, Callable<T> task) throws InterruptedException, ExecutionException { final ForkJoinPool threadPool = new ForkJoinPool(parallelism); try { return threadPool.submit(task).get(); } finally { threadPool.shutdown(); } } /** * Helper method to raise an assertion error inside an action passed to a Spliterator * when the action should not be invoked. * * @see Spliterator#tryAdvance(Consumer) * @see Spliterator#forEachRemaining(Consumer) */ private static void failSpliteratorShouldBeEmpty() { Assertions.fail("Spliterator should not have any remaining elements"); } @Test void testDefaultSplit() { // Create the split result so we can check the return value final SplittableUniformRandomProvider expected = new DummyGenerator(); // Implement split(UniformRandomProvider) final SplittableUniformRandomProvider rng = new DummyGenerator() { @Override public SplittableUniformRandomProvider split(UniformRandomProvider source) { Assertions.assertSame(this, source, "default split should use itself as the source"); return expected; } }; // Test the default split() Assertions.assertSame(expected, rng.split()); } // Tests for splitting the stream of splittable RNGs @ParameterizedTest @ValueSource(longs = {-1, -2, Long.MIN_VALUE}) void testSplitsInvalidStreamSizeThrows(long size) { final SplittableUniformRandomProvider rng = DummyGenerator.INSTANCE; Assertions.assertThrows(IllegalArgumentException.class, () -> rng.splits(size), "splits(size)"); final SplittableUniformRandomProvider source = new SequenceGenerator(42); Assertions.assertThrows(IllegalArgumentException.class, () -> rng.splits(size, source), "splits(size, source)"); } @Test void testSplitsUnlimitedStreamSize() { final SplittableUniformRandomProvider rng = DummyGenerator.INSTANCE; assertUnlimitedSpliterator(rng.splits().spliterator(), "splits()"); final SplittableUniformRandomProvider source = new SequenceGenerator(42); assertUnlimitedSpliterator(rng.splits(source).spliterator(), "splits(source)"); } /** * Assert the spliterator has an unlimited expected size and the characteristics for a sized * non-null immutable stream. * * @param spliterator Spliterator. * @param msg Error message. */ private static void assertUnlimitedSpliterator(Spliterator<?> spliterator, String msg) { BaseRandomProviderStreamTest.assertSpliterator(spliterator, Long.MAX_VALUE, SPLITERATOR_CHARACTERISTICS, msg); } @Test void testSplitsNullSourceThrows() { final SplittableUniformRandomProvider rng = DummyGenerator.INSTANCE; final SplittableUniformRandomProvider source = null; Assertions.assertThrows(NullPointerException.class, () -> rng.splits(source)); Assertions.assertThrows(NullPointerException.class, () -> rng.splits(STREAM_SIZE_ONE, source)); } /** * Test the splits method. The test asserts that a parallel stream of RNGs output a * sequence using a specialised sequence generator that maintains the sequence output * under recursive splitting. */ @ParameterizedTest @MethodSource(value = {"threadAndStreamSizes"}) void testSplitsParallel(int threads, long streamSize) throws InterruptedException, ExecutionException { final long start = Integer.toUnsignedLong(ThreadLocalRandom.current().nextInt()); final long[] actual = execute(threads, (Callable<long[]>) () -> { // The splits method will use itself as the source and the output should be the sequence final SplittableUniformRandomProvider rng = new SequenceGenerator(start); final SplittableUniformRandomProvider[] rngs = rng.splits(streamSize).parallel().toArray(SplittableUniformRandomProvider[]::new); // Check the instance is a new object of the same type. // These will be hashed using the system identity hash code. final HashSet<SplittableUniformRandomProvider> observed = new HashSet<>(); observed.add(rng); Arrays.stream(rngs).forEach(r -> { Assertions.assertTrue(observed.add(r), "Instance should be unique"); Assertions.assertEquals(SequenceGenerator.class, r.getClass()); }); // Get output from the unique RNGs: these return from the same atomic sequence return Arrays.stream(rngs).mapToLong(UniformRandomProvider::nextLong).toArray(); }); // Required to reorder the sequence to ascending Arrays.sort(actual); final long[] expected = LongStream.range(start, start + streamSize).toArray(); Assertions.assertArrayEquals(expected, actual); } /** * Test the splits method. The test asserts that a parallel stream of RNGs output a * sequence using a specialised sequence generator that maintains the sequence output * under recursive splitting. The sequence is used to seed a fixed generator. The stream * instances are verified to be the correct class type. */ @ParameterizedTest @MethodSource(value = {"threadAndStreamSizes"}) void testSplitsParallelWithSource(int threads, long streamSize) throws InterruptedException, ExecutionException { final long start = Integer.toUnsignedLong(ThreadLocalRandom.current().nextInt()); final long[] actual = execute(threads, (Callable<long[]>) () -> { // This generator defines the instances created. // It should not be split without a source. // Seed with something not the start value. final SplittableUniformRandomProvider rng = new FixedGenerator(~start) { @Override public SplittableUniformRandomProvider split() { throw new UnsupportedOperationException("The split method should not be invoked"); } }; // The splits method will use this to seed each instance. // This generator is split within the spliterator. final SplittableUniformRandomProvider source = new SequenceGenerator(start); final SplittableUniformRandomProvider[] rngs = rng.splits(streamSize, source).parallel().toArray(SplittableUniformRandomProvider[]::new); // Check the instance is a new object of the same type. // These will be hashed using the system identity hash code. final HashSet<SplittableUniformRandomProvider> observed = new HashSet<>(); observed.add(rng); Arrays.stream(rngs).forEach(r -> { Assertions.assertTrue(observed.add(r), "Instance should be unique"); Assertions.assertEquals(FixedGenerator.class, r.getClass()); }); // Get output from the unique RNGs: these return from the same atomic sequence return Arrays.stream(rngs).mapToLong(UniformRandomProvider::nextLong).toArray(); }); // Required to reorder the sequence to ascending Arrays.sort(actual); final long[] expected = LongStream.range(start, start + streamSize).toArray(); Assertions.assertArrayEquals(expected, actual); } @Test void testSplitsSpliterator() { final int start = 42; final SplittableUniformRandomProvider rng = new SequenceGenerator(start); // Split a large spliterator into four smaller ones; // each is used to test different functionality final long size = 41; Spliterator<SplittableUniformRandomProvider> s1 = rng.splits(size).spliterator(); Assertions.assertEquals(size, s1.estimateSize()); final Spliterator<SplittableUniformRandomProvider> s2 = s1.trySplit(); final Spliterator<SplittableUniformRandomProvider> s3 = s1.trySplit(); final Spliterator<SplittableUniformRandomProvider> s4 = s2.trySplit(); Assertions.assertEquals(size, s1.estimateSize() + s2.estimateSize() + s3.estimateSize() + s4.estimateSize()); // s1. Test cannot split indefinitely while (s1.estimateSize() > 1) { final long currentSize = s1.estimateSize(); final Spliterator<SplittableUniformRandomProvider> other = s1.trySplit(); Assertions.assertEquals(currentSize, s1.estimateSize() + other.estimateSize()); s1 = other; } Assertions.assertNull(s1.trySplit(), "Cannot split when size <= 1"); // The expected value is incremented for each generation call final long[] expected = {start}; // s2. Test advance for (long newSize = s2.estimateSize(); newSize-- > 0;) { Assertions.assertTrue(s2.tryAdvance(r -> Assertions.assertEquals(expected[0]++, r.nextLong()))); Assertions.assertEquals(newSize, s2.estimateSize(), "s2 size estimate"); } Assertions.assertFalse(s2.tryAdvance(r -> failSpliteratorShouldBeEmpty())); s2.forEachRemaining(r -> failSpliteratorShouldBeEmpty()); // s3. Test forEachRemaining s3.forEachRemaining(r -> Assertions.assertEquals(expected[0]++, r.nextLong())); Assertions.assertEquals(0, s3.estimateSize()); s3.forEachRemaining(r -> failSpliteratorShouldBeEmpty()); // s4. Test tryAdvance and forEachRemaining when the action throws an exception final IllegalStateException ex = new IllegalStateException(); final Consumer<SplittableUniformRandomProvider> badAction = r -> { throw ex; }; final long currentSize = s4.estimateSize(); Assertions.assertTrue(currentSize > 1, "Spliterator requires more elements to test advance"); Assertions.assertSame(ex, Assertions.assertThrows(IllegalStateException.class, () -> s4.tryAdvance(badAction))); Assertions.assertEquals(currentSize - 1, s4.estimateSize(), "Spliterator should be advanced even when action throws"); Assertions.assertSame(ex, Assertions.assertThrows(IllegalStateException.class, () -> s4.forEachRemaining(badAction))); Assertions.assertEquals(0, s4.estimateSize(), "Spliterator should be finished even when action throws"); s4.forEachRemaining(r -> failSpliteratorShouldBeEmpty()); } // Tests for splitting the primitive streams to test support for parallel execution @ParameterizedTest @MethodSource(value = {"threadAndStreamSizes"}) void testIntsParallelWithSize(int threads, long streamSize) throws InterruptedException, ExecutionException { final int[] values = ThreadLocalRandom.current().ints(streamSize).toArray(); final CountingGenerator rng = new CountingGenerator() { @Override public int nextInt() { return values[count.getAndIncrement()]; } }; final int[] actual = execute(threads, (Callable<int[]>) () -> rng.ints(streamSize).parallel().toArray() ); Arrays.sort(values); Arrays.sort(actual); Assertions.assertArrayEquals(values, actual); } @ParameterizedTest @MethodSource(value = {"threadAndStreamSizes"}) void testIntsParallelOriginBoundWithSize(int threads, long streamSize) throws InterruptedException, ExecutionException { final int origin = 13; final int bound = 42; final int[] values = ThreadLocalRandom.current().ints(streamSize, origin, bound).toArray(); final CountingGenerator rng = new CountingGenerator() { @Override public int nextInt(int o, int b) { Assertions.assertEquals(origin, o, "origin"); Assertions.assertEquals(bound, b, "bound"); return values[count.getAndIncrement()]; } }; final int[] actual = execute(threads, (Callable<int[]>) () -> rng.ints(streamSize, origin, bound).parallel().toArray() ); Arrays.sort(values); Arrays.sort(actual); Assertions.assertArrayEquals(values, actual); } @Test void testIntsSpliterator() { final int start = 42; final SplittableUniformRandomProvider rng = new SingleInstanceGenerator() { private final AtomicInteger value = new AtomicInteger(start); @Override public int nextInt() { return value.getAndIncrement(); } }; // Split a large spliterator into four smaller ones; // each is used to test different functionality final long size = 41; Spliterator.OfInt s1 = rng.ints(size).spliterator(); Assertions.assertEquals(size, s1.estimateSize()); final Spliterator.OfInt s2 = s1.trySplit(); final Spliterator.OfInt s3 = s1.trySplit(); final Spliterator.OfInt s4 = s2.trySplit(); Assertions.assertEquals(size, s1.estimateSize() + s2.estimateSize() + s3.estimateSize() + s4.estimateSize()); // s1. Test cannot split indefinitely while (s1.estimateSize() > 1) { final long currentSize = s1.estimateSize(); final Spliterator.OfInt other = s1.trySplit(); Assertions.assertEquals(currentSize, s1.estimateSize() + other.estimateSize()); s1 = other; } Assertions.assertNull(s1.trySplit(), "Cannot split when size <= 1"); // The expected value is incremented for each generation call final int[] expected = {start}; // s2. Test advance for (long newSize = s2.estimateSize(); newSize-- > 0;) { Assertions.assertTrue(s2.tryAdvance((IntConsumer) i -> Assertions.assertEquals(expected[0]++, i))); Assertions.assertEquals(newSize, s2.estimateSize(), "s2 size estimate"); } Assertions.assertFalse(s2.tryAdvance((IntConsumer) i -> failSpliteratorShouldBeEmpty())); s2.forEachRemaining((IntConsumer) i -> failSpliteratorShouldBeEmpty()); // s3. Test forEachRemaining s3.forEachRemaining((IntConsumer) i -> Assertions.assertEquals(expected[0]++, i)); Assertions.assertEquals(0, s3.estimateSize()); s3.forEachRemaining((IntConsumer) i -> failSpliteratorShouldBeEmpty()); // s4. Test tryAdvance and forEachRemaining when the action throws an exception final IllegalStateException ex = new IllegalStateException(); final IntConsumer badAction = i -> { throw ex; }; final long currentSize = s4.estimateSize(); Assertions.assertTrue(currentSize > 1, "Spliterator requires more elements to test advance"); Assertions.assertSame(ex, Assertions.assertThrows(IllegalStateException.class, () -> s4.tryAdvance(badAction))); Assertions.assertEquals(currentSize - 1, s4.estimateSize(), "Spliterator should be advanced even when action throws"); Assertions.assertSame(ex, Assertions.assertThrows(IllegalStateException.class, () -> s4.forEachRemaining(badAction))); Assertions.assertEquals(0, s4.estimateSize(), "Spliterator should be finished even when action throws"); s4.forEachRemaining((IntConsumer) i -> failSpliteratorShouldBeEmpty()); } @ParameterizedTest @MethodSource(value = {"threadAndStreamSizes"}) void testLongsParallelWithSize(int threads, long streamSize) throws InterruptedException, ExecutionException { final long[] values = ThreadLocalRandom.current().longs(streamSize).toArray(); final CountingGenerator rng = new CountingGenerator() { @Override public long nextLong() { return values[count.getAndIncrement()]; } }; final long[] actual = execute(threads, (Callable<long[]>) () -> rng.longs(streamSize).parallel().toArray() ); Arrays.sort(values); Arrays.sort(actual); Assertions.assertArrayEquals(values, actual); } @ParameterizedTest @MethodSource(value = {"threadAndStreamSizes"}) void testLongsParallelOriginBoundWithSize(int threads, long streamSize) throws InterruptedException, ExecutionException { final long origin = 195267376168313L; final long bound = 421268681268318L; final long[] values = ThreadLocalRandom.current().longs(streamSize, origin, bound).toArray(); final CountingGenerator rng = new CountingGenerator() { @Override public long nextLong(long o, long b) { Assertions.assertEquals(origin, o, "origin"); Assertions.assertEquals(bound, b, "bound"); return values[count.getAndIncrement()]; } }; final long[] actual = execute(threads, (Callable<long[]>) () -> rng.longs(streamSize, origin, bound).parallel().toArray() ); Arrays.sort(values); Arrays.sort(actual); Assertions.assertArrayEquals(values, actual); } @Test void testLongsSpliterator() { final long start = 42; final SplittableUniformRandomProvider rng = new SingleInstanceGenerator() { private final AtomicLong value = new AtomicLong(start); @Override public long nextLong() { return value.getAndIncrement(); } }; // Split a large spliterator into four smaller ones; // each is used to test different functionality final long size = 41; Spliterator.OfLong s1 = rng.longs(size).spliterator(); Assertions.assertEquals(size, s1.estimateSize()); final Spliterator.OfLong s2 = s1.trySplit(); final Spliterator.OfLong s3 = s1.trySplit(); final Spliterator.OfLong s4 = s2.trySplit(); Assertions.assertEquals(size, s1.estimateSize() + s2.estimateSize() + s3.estimateSize() + s4.estimateSize()); // s1. Test cannot split indefinitely while (s1.estimateSize() > 1) { final long currentSize = s1.estimateSize(); final Spliterator.OfLong other = s1.trySplit(); Assertions.assertEquals(currentSize, s1.estimateSize() + other.estimateSize()); s1 = other; } Assertions.assertNull(s1.trySplit(), "Cannot split when size <= 1"); // The expected value is incremented for each generation call final long[] expected = {start}; // s2. Test advance for (long newSize = s2.estimateSize(); newSize-- > 0;) { Assertions.assertTrue(s2.tryAdvance((LongConsumer) i -> Assertions.assertEquals(expected[0]++, i))); Assertions.assertEquals(newSize, s2.estimateSize(), "s2 size estimate"); } Assertions.assertFalse(s2.tryAdvance((LongConsumer) i -> failSpliteratorShouldBeEmpty())); s2.forEachRemaining((LongConsumer) i -> failSpliteratorShouldBeEmpty()); // s3. Test forEachRemaining s3.forEachRemaining((LongConsumer) i -> Assertions.assertEquals(expected[0]++, i)); Assertions.assertEquals(0, s3.estimateSize()); s3.forEachRemaining((LongConsumer) i -> failSpliteratorShouldBeEmpty()); // s4. Test tryAdvance and forEachRemaining when the action throws an exception final IllegalStateException ex = new IllegalStateException(); final LongConsumer badAction = i -> { throw ex; }; final long currentSize = s4.estimateSize(); Assertions.assertTrue(currentSize > 1, "Spliterator requires more elements to test advance"); Assertions.assertSame(ex, Assertions.assertThrows(IllegalStateException.class, () -> s4.tryAdvance(badAction))); Assertions.assertEquals(currentSize - 1, s4.estimateSize(), "Spliterator should be advanced even when action throws"); Assertions.assertSame(ex, Assertions.assertThrows(IllegalStateException.class, () -> s4.forEachRemaining(badAction))); Assertions.assertEquals(0, s4.estimateSize(), "Spliterator should be finished even when action throws"); s4.forEachRemaining((LongConsumer) i -> failSpliteratorShouldBeEmpty()); } @ParameterizedTest @MethodSource(value = {"threadAndStreamSizes"}) void testDoublesParallelWithSize(int threads, long streamSize) throws InterruptedException, ExecutionException { final double[] values = ThreadLocalRandom.current().doubles(streamSize).toArray(); final CountingGenerator rng = new CountingGenerator() { @Override public double nextDouble() { return values[count.getAndIncrement()]; } }; final double[] actual = execute(threads, (Callable<double[]>) () -> rng.doubles(streamSize).parallel().toArray() ); Arrays.sort(values); Arrays.sort(actual); Assertions.assertArrayEquals(values, actual); } @ParameterizedTest @MethodSource(value = {"threadAndStreamSizes"}) void testDoublesParallelOriginBoundWithSize(int threads, long streamSize) throws InterruptedException, ExecutionException { final double origin = 0.123; final double bound = 0.789; final double[] values = ThreadLocalRandom.current().doubles(streamSize, origin, bound).toArray(); final CountingGenerator rng = new CountingGenerator() { @Override public double nextDouble(double o, double b) { Assertions.assertEquals(origin, o, "origin"); Assertions.assertEquals(bound, b, "bound"); return values[count.getAndIncrement()]; } }; final double[] actual = execute(threads, (Callable<double[]>) () -> rng.doubles(streamSize, origin, bound).parallel().toArray() ); Arrays.sort(values); Arrays.sort(actual); Assertions.assertArrayEquals(values, actual); } @Test void testDoublesSpliterator() { // Due to lack of an AtomicDouble this uses an AtomicInteger. Any int value can be // represented as a double and the increment operator functions without loss of // precision (the same is not true if using an AtomicLong with >53 bits of precision). final int start = 42; final SplittableUniformRandomProvider rng = new SingleInstanceGenerator() { private final AtomicInteger value = new AtomicInteger(start); @Override public double nextDouble() { return value.getAndIncrement(); } }; // Split a large spliterator into four smaller ones; // each is used to test different functionality final long size = 41; Spliterator.OfDouble s1 = rng.doubles(size).spliterator(); Assertions.assertEquals(size, s1.estimateSize()); final Spliterator.OfDouble s2 = s1.trySplit(); final Spliterator.OfDouble s3 = s1.trySplit(); final Spliterator.OfDouble s4 = s2.trySplit(); Assertions.assertEquals(size, s1.estimateSize() + s2.estimateSize() + s3.estimateSize() + s4.estimateSize()); // s1. Test cannot split indefinitely while (s1.estimateSize() > 1) { final double currentSize = s1.estimateSize(); final Spliterator.OfDouble other = s1.trySplit(); Assertions.assertEquals(currentSize, s1.estimateSize() + other.estimateSize()); s1 = other; } Assertions.assertNull(s1.trySplit(), "Cannot split when size <= 1"); // The expected value is incremented for each generation call final double[] expected = {start}; // s2. Test advance for (double newSize = s2.estimateSize(); newSize-- > 0;) { Assertions.assertTrue(s2.tryAdvance((DoubleConsumer) i -> Assertions.assertEquals(expected[0]++, i))); Assertions.assertEquals(newSize, s2.estimateSize(), "s2 size estimate"); } Assertions.assertFalse(s2.tryAdvance((DoubleConsumer) i -> failSpliteratorShouldBeEmpty())); s2.forEachRemaining((DoubleConsumer) i -> failSpliteratorShouldBeEmpty()); // s3. Test forEachRemaining s3.forEachRemaining((DoubleConsumer) i -> Assertions.assertEquals(expected[0]++, i)); Assertions.assertEquals(0, s3.estimateSize()); s3.forEachRemaining((DoubleConsumer) i -> failSpliteratorShouldBeEmpty()); // s4. Test tryAdvance and forEachRemaining when the action throws an exception final IllegalStateException ex = new IllegalStateException(); final DoubleConsumer badAction = i -> { throw ex; }; final double currentSize = s4.estimateSize(); Assertions.assertTrue(currentSize > 1, "Spliterator requires more elements to test advance"); Assertions.assertSame(ex, Assertions.assertThrows(IllegalStateException.class, () -> s4.tryAdvance(badAction))); Assertions.assertEquals(currentSize - 1, s4.estimateSize(), "Spliterator should be advanced even when action throws"); Assertions.assertSame(ex, Assertions.assertThrows(IllegalStateException.class, () -> s4.forEachRemaining(badAction))); Assertions.assertEquals(0, s4.estimateSize(), "Spliterator should be finished even when action throws"); s4.forEachRemaining((DoubleConsumer) i -> failSpliteratorShouldBeEmpty()); } }
2,892
0
Create_ds/commons-rng/commons-rng-client-api/src/main/java/org/apache/commons
Create_ds/commons-rng/commons-rng-client-api/src/main/java/org/apache/commons/rng/LongJumpableUniformRandomProvider.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; import java.util.stream.Stream; /** * Applies to generators that can be advanced a very large number of * steps of the output sequence in a single operation. * * @since 1.3 */ public interface LongJumpableUniformRandomProvider extends JumpableUniformRandomProvider { /** * Creates a copy of the JumpableUniformRandomProvider and then advances the * state of the current instance. The copy is returned. * * <p>The current state will be advanced in a single operation by the equivalent of a * number of sequential calls to a method that updates the state of the provider. The * size of the long jump is implementation dependent.</p> * * <p>Repeat invocations of this method will create a series of generators * that are uniformly spaced at intervals of the output sequence. Each generator provides * non-overlapping output for the length of the long jump for use in parallel computations.</p> * * <p>The returned copy may be jumped {@code m / n} times before overlap with the current * instance where {@code m} is the long jump length and {@code n} * is the jump length of the {@link #jump()} method. * * @return A copy of the current state. */ JumpableUniformRandomProvider longJump(); /** * Returns an effectively unlimited stream of new random generators, each of which * implements the {@link JumpableUniformRandomProvider} interface. * * @return a stream of random generators. * @since 1.5 */ default Stream<JumpableUniformRandomProvider> longJumps() { return Stream.generate(this::longJump).sequential(); } /** * Returns a stream producing the given {@code streamSize} number of new random * generators, each of which implements the {@link JumpableUniformRandomProvider} * interface. * * @param streamSize Number of objects to generate. * @return a stream of random generators; the stream is limited to the given * {@code streamSize}. * @throws IllegalArgumentException if {@code streamSize} is negative. * @since 1.5 */ default Stream<JumpableUniformRandomProvider> longJumps(long streamSize) { UniformRandomProviderSupport.validateStreamSize(streamSize); return longJumps().limit(streamSize); } }
2,893
0
Create_ds/commons-rng/commons-rng-client-api/src/main/java/org/apache/commons
Create_ds/commons-rng/commons-rng-client-api/src/main/java/org/apache/commons/rng/UniformRandomProvider.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; import java.util.stream.DoubleStream; import java.util.stream.IntStream; import java.util.stream.LongStream; /** * Applies to generators of random number sequences that follow a uniform * distribution. * * @since 1.0 */ public interface UniformRandomProvider { /** * Generates {@code byte} values and places them into a user-supplied array. * * <p>The number of random bytes produced is equal to the length of the byte array. * * @param bytes Byte array in which to put the random bytes. * Cannot be {@code null}. */ default void nextBytes(byte[] bytes) { UniformRandomProviderSupport.nextBytes(this, bytes, 0, bytes.length); } /** * Generates {@code byte} values and places them into a user-supplied array. * * <p>The array is filled with bytes extracted from random integers. * This implies that the number of random bytes generated may be larger than * the length of the byte array. * * @param bytes Array in which to put the generated bytes. * Cannot be {@code null}. * @param start Index at which to start inserting the generated bytes. * @param len Number of bytes to insert. * @throws IndexOutOfBoundsException if {@code start < 0} or * {@code start >= bytes.length}. * @throws IndexOutOfBoundsException if {@code len < 0} or * {@code len > bytes.length - start}. */ default void nextBytes(byte[] bytes, int start, int len) { UniformRandomProviderSupport.validateFromIndexSize(start, len, bytes.length); UniformRandomProviderSupport.nextBytes(this, bytes, start, len); } /** * Generates an {@code int} value. * * @return the next random value. */ default int nextInt() { return (int) (nextLong() >>> 32); } /** * Generates an {@code int} value between 0 (inclusive) and the * specified value (exclusive). * * @param n Bound on the random number to be returned. Must be positive. * @return a random {@code int} value between 0 (inclusive) and {@code n} * (exclusive). * @throws IllegalArgumentException if {@code n} is not above zero. */ default int nextInt(int n) { UniformRandomProviderSupport.validateUpperBound(n); return UniformRandomProviderSupport.nextInt(this, n); } /** * Generates an {@code int} value between the specified {@code origin} (inclusive) and * the specified {@code bound} (exclusive). * * @param origin Lower bound on the random number to be returned. * @param bound Upper bound (exclusive) on the random number to be returned. * @return a random {@code int} value between {@code origin} (inclusive) and * {@code bound} (exclusive). * @throws IllegalArgumentException if {@code origin} is greater than or equal to * {@code bound}. * @since 1.5 */ default int nextInt(int origin, int bound) { UniformRandomProviderSupport.validateRange(origin, bound); return UniformRandomProviderSupport.nextInt(this, origin, bound); } /** * Generates a {@code long} value. * * @return the next random value. */ long nextLong(); /** * Generates a {@code long} value between 0 (inclusive) and the specified * value (exclusive). * * @param n Bound on the random number to be returned. Must be positive. * @return a random {@code long} value between 0 (inclusive) and {@code n} * (exclusive). * @throws IllegalArgumentException if {@code n} is not greater than 0. */ default long nextLong(long n) { UniformRandomProviderSupport.validateUpperBound(n); return UniformRandomProviderSupport.nextLong(this, n); } /** * Generates a {@code long} value between the specified {@code origin} (inclusive) and * the specified {@code bound} (exclusive). * * @param origin Lower bound on the random number to be returned. * @param bound Upper bound (exclusive) on the random number to be returned. * @return a random {@code long} value between {@code origin} (inclusive) and * {@code bound} (exclusive). * @throws IllegalArgumentException if {@code origin} is greater than or equal to * {@code bound}. * @since 1.5 */ default long nextLong(long origin, long bound) { UniformRandomProviderSupport.validateRange(origin, bound); return UniformRandomProviderSupport.nextLong(this, origin, bound); } /** * Generates a {@code boolean} value. * * @return the next random value. */ default boolean nextBoolean() { return nextInt() < 0; } /** * Generates a {@code float} value between 0 (inclusive) and 1 (exclusive). * * @return the next random value between 0 (inclusive) and 1 (exclusive). */ default float nextFloat() { return (nextInt() >>> 8) * 0x1.0p-24f; } /** * Generates a {@code float} value between 0 (inclusive) and the * specified {@code bound} (exclusive). * * @param bound Upper bound (exclusive) on the random number to be returned. * @return a random {@code float} value between 0 (inclusive) and {@code bound} * (exclusive). * @throws IllegalArgumentException if {@code bound} is not both finite and greater than 0. * @since 1.5 */ default float nextFloat(float bound) { UniformRandomProviderSupport.validateUpperBound(bound); return UniformRandomProviderSupport.nextFloat(this, bound); } /** * Generates a {@code float} value between the specified {@code origin} (inclusive) * and the specified {@code bound} (exclusive). * * @param origin Lower bound on the random number to be returned. * @param bound Upper bound (exclusive) on the random number to be returned. * @return a random {@code float} value between {@code origin} (inclusive) and * {@code bound} (exclusive). * @throws IllegalArgumentException if {@code origin} is not finite, or {@code bound} * is not finite, or {@code origin} is greater than or equal to {@code bound}. * @since 1.5 */ default float nextFloat(float origin, float bound) { UniformRandomProviderSupport.validateRange(origin, bound); return UniformRandomProviderSupport.nextFloat(this, origin, bound); } /** * Generates a {@code double} value between 0 (inclusive) and 1 (exclusive). * * @return the next random value between 0 (inclusive) and 1 (exclusive). */ default double nextDouble() { return (nextLong() >>> 11) * 0x1.0p-53; } /** * Generates a {@code double} value between 0 (inclusive) and the * specified {@code bound} (exclusive). * * @param bound Upper bound (exclusive) on the random number to be returned. * @return a random {@code double} value between 0 (inclusive) and {@code bound} * (exclusive). * @throws IllegalArgumentException if {@code bound} is not both finite and greater than 0. * @since 1.5 */ default double nextDouble(double bound) { UniformRandomProviderSupport.validateUpperBound(bound); return UniformRandomProviderSupport.nextDouble(this, bound); } /** * Generates a {@code double} value between the specified {@code origin} (inclusive) * and the specified {@code bound} (exclusive). * * @param origin Lower bound on the random number to be returned. * @param bound Upper bound (exclusive) on the random number to be returned. * @return a random {@code double} value between {@code origin} (inclusive) and * {@code bound} (exclusive). * @throws IllegalArgumentException if {@code origin} is not finite, or {@code bound} * is not finite, or {@code origin} is greater than or equal to {@code bound}. * @since 1.5 */ default double nextDouble(double origin, double bound) { UniformRandomProviderSupport.validateRange(origin, bound); return UniformRandomProviderSupport.nextDouble(this, origin, bound); } /** * Returns an effectively unlimited stream of {@code int} values. * * @return a stream of random {@code int} values. * @since 1.5 */ default IntStream ints() { return IntStream.generate(this::nextInt).sequential(); } /** * Returns an effectively unlimited stream of {@code int} values between the specified * {@code origin} (inclusive) and the specified {@code bound} (exclusive). * * @param origin Lower bound on the random number to be returned. * @param bound Upper bound (exclusive) on the random number to be returned. * @return a stream of random values between the specified {@code origin} (inclusive) * and the specified {@code bound} (exclusive). * @throws IllegalArgumentException if {@code origin} is greater than or equal to * {@code bound}. * @since 1.5 */ default IntStream ints(int origin, int bound) { UniformRandomProviderSupport.validateRange(origin, bound); return IntStream.generate(() -> nextInt(origin, bound)).sequential(); } /** * Returns a stream producing the given {@code streamSize} number of {@code int} * values. * * @param streamSize Number of values to generate. * @return a stream of random {@code int} values; the stream is limited to the given * {@code streamSize}. * @throws IllegalArgumentException if {@code streamSize} is negative. * @since 1.5 */ default IntStream ints(long streamSize) { UniformRandomProviderSupport.validateStreamSize(streamSize); return ints().limit(streamSize); } /** * Returns a stream producing the given {@code streamSize} number of {@code int} * values between the specified {@code origin} (inclusive) and the specified * {@code bound} (exclusive). * * @param streamSize Number of values to generate. * @param origin Lower bound on the random number to be returned. * @param bound Upper bound (exclusive) on the random number to be returned. * @return a stream of random values between the specified {@code origin} (inclusive) * and the specified {@code bound} (exclusive); the stream is limited to the given * {@code streamSize}. * @throws IllegalArgumentException if {@code streamSize} is negative, or if * {@code origin} is greater than or equal to {@code bound}. * @since 1.5 */ default IntStream ints(long streamSize, int origin, int bound) { UniformRandomProviderSupport.validateStreamSize(streamSize); UniformRandomProviderSupport.validateRange(origin, bound); return ints(origin, bound).limit(streamSize); } /** * Returns an effectively unlimited stream of {@code long} values. * * @return a stream of random {@code long} values. * @since 1.5 */ default LongStream longs() { return LongStream.generate(this::nextLong).sequential(); } /** * Returns an effectively unlimited stream of {@code long} values between the * specified {@code origin} (inclusive) and the specified {@code bound} (exclusive). * * @param origin Lower bound on the random number to be returned. * @param bound Upper bound (exclusive) on the random number to be returned. * @return a stream of random values between the specified {@code origin} (inclusive) * and the specified {@code bound} (exclusive). * @throws IllegalArgumentException if {@code origin} is greater than or equal to * {@code bound}. * @since 1.5 */ default LongStream longs(long origin, long bound) { UniformRandomProviderSupport.validateRange(origin, bound); return LongStream.generate(() -> nextLong(origin, bound)).sequential(); } /** * Returns a stream producing the given {@code streamSize} number of {@code long} * values. * * @param streamSize Number of values to generate. * @return a stream of random {@code long} values; the stream is limited to the given * {@code streamSize}. * @throws IllegalArgumentException if {@code streamSize} is negative. * @since 1.5 */ default LongStream longs(long streamSize) { UniformRandomProviderSupport.validateStreamSize(streamSize); return longs().limit(streamSize); } /** * Returns a stream producing the given {@code streamSize} number of {@code long} * values between the specified {@code origin} (inclusive) and the specified * {@code bound} (exclusive). * * @param streamSize Number of values to generate. * @param origin Lower bound on the random number to be returned. * @param bound Upper bound (exclusive) on the random number to be returned. * @return a stream of random values between the specified {@code origin} (inclusive) * and the specified {@code bound} (exclusive); the stream is limited to the given * {@code streamSize}. * @throws IllegalArgumentException if {@code streamSize} is negative, or if * {@code origin} is greater than or equal to {@code bound}. * @since 1.5 */ default LongStream longs(long streamSize, long origin, long bound) { UniformRandomProviderSupport.validateStreamSize(streamSize); UniformRandomProviderSupport.validateRange(origin, bound); return longs(origin, bound).limit(streamSize); } /** * Returns an effectively unlimited stream of {@code double} values between 0 * (inclusive) and 1 (exclusive). * * @return a stream of random values between 0 (inclusive) and 1 (exclusive). * @since 1.5 */ default DoubleStream doubles() { return DoubleStream.generate(this::nextDouble).sequential(); } /** * Returns an effectively unlimited stream of {@code double} values between the * specified {@code origin} (inclusive) and the specified {@code bound} (exclusive). * * @param origin Lower bound on the random number to be returned. * @param bound Upper bound (exclusive) on the random number to be returned. * @return a stream of random values between the specified {@code origin} (inclusive) * and the specified {@code bound} (exclusive). * @throws IllegalArgumentException if {@code origin} is not finite, or {@code bound} * is not finite, or {@code origin} is greater than or equal to {@code bound}. * @since 1.5 */ default DoubleStream doubles(double origin, double bound) { UniformRandomProviderSupport.validateRange(origin, bound); return DoubleStream.generate(() -> nextDouble(origin, bound)).sequential(); } /** * Returns a stream producing the given {@code streamSize} number of {@code double} * values between 0 (inclusive) and 1 (exclusive). * * @param streamSize Number of values to generate. * @return a stream of random values between 0 (inclusive) and 1 (exclusive); * the stream is limited to the given {@code streamSize}. * @throws IllegalArgumentException if {@code streamSize} is negative. * @since 1.5 */ default DoubleStream doubles(long streamSize) { UniformRandomProviderSupport.validateStreamSize(streamSize); return doubles().limit(streamSize); } /** * Returns a stream producing the given {@code streamSize} number of {@code double} * values between the specified {@code origin} (inclusive) and the specified * {@code bound} (exclusive). * * @param streamSize Number of values to generate. * @param origin Lower bound on the random number to be returned. * @param bound Upper bound (exclusive) on the random number to be returned. * @return a stream of random values between the specified {@code origin} (inclusive) * and the specified {@code bound} (exclusive); the stream is limited to the given * {@code streamSize}. * @throws IllegalArgumentException if {@code streamSize} is negative, or if * {@code origin} is not finite, or {@code bound} is not finite, or {@code origin} is * greater than or equal to {@code bound}. * @since 1.5 */ default DoubleStream doubles(long streamSize, double origin, double bound) { UniformRandomProviderSupport.validateStreamSize(streamSize); UniformRandomProviderSupport.validateRange(origin, bound); return doubles(origin, bound).limit(streamSize); } }
2,894
0
Create_ds/commons-rng/commons-rng-client-api/src/main/java/org/apache/commons
Create_ds/commons-rng/commons-rng-client-api/src/main/java/org/apache/commons/rng/RestorableUniformRandomProvider.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; /** * Applies to generators whose internal state can be saved and restored. * * @since 1.0 */ public interface RestorableUniformRandomProvider extends UniformRandomProvider { /** * Saves the state of a generator. * * @return the current state of this instance. It is a value that can * subsequently be passed to the {@link #restoreState(RandomProviderState) * restore} method. * @throws UnsupportedOperationException if the underlying source of * randomness does not support this functionality. */ RandomProviderState saveState(); /** * Restores the state of a generator. * * @param state State which this instance will be set to. * This parameter would usually have been obtained by a call to * {@link #saveState() saveState} performed either on the same * object as this one, or an object of the exact same class. * @throws UnsupportedOperationException if the underlying source of * randomness does not support this functionality. * @throws IllegalArgumentException if it was detected that the * {@code state} argument is incompatible with this instance. */ void restoreState(RandomProviderState state); }
2,895
0
Create_ds/commons-rng/commons-rng-client-api/src/main/java/org/apache/commons
Create_ds/commons-rng/commons-rng-client-api/src/main/java/org/apache/commons/rng/JumpableUniformRandomProvider.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; import java.util.stream.Stream; /** * Applies to generators that can be advanced a large number of * steps of the output sequence in a single operation. * * @since 1.3 */ public interface JumpableUniformRandomProvider extends UniformRandomProvider { /** * Creates a copy of the UniformRandomProvider and then advances the * state of the current instance. The copy is returned. * * <p>The current state will be advanced in a single operation by the equivalent of a * number of sequential calls to a method that updates the state of the provider. The * size of the jump is implementation dependent.</p> * * <p>Repeat invocations of this method will create a series of generators * that are uniformly spaced at intervals of the output sequence. Each generator provides * non-overlapping output for the length of the jump for use in parallel computations.</p> * * @return A copy of the current state. */ UniformRandomProvider jump(); /** * Returns an effectively unlimited stream of new random generators, each of which * implements the {@link UniformRandomProvider} interface. * * @return a stream of random generators. * @since 1.5 */ default Stream<UniformRandomProvider> jumps() { return Stream.generate(this::jump).sequential(); } /** * Returns a stream producing the given {@code streamSize} number of new random * generators, each of which implements the {@link UniformRandomProvider} * interface. * * @param streamSize Number of objects to generate. * @return a stream of random generators; the stream is limited to the given * {@code streamSize}. * @throws IllegalArgumentException if {@code streamSize} is negative. * @since 1.5 */ default Stream<UniformRandomProvider> jumps(long streamSize) { UniformRandomProviderSupport.validateStreamSize(streamSize); return jumps().limit(streamSize); } }
2,896
0
Create_ds/commons-rng/commons-rng-client-api/src/main/java/org/apache/commons
Create_ds/commons-rng/commons-rng-client-api/src/main/java/org/apache/commons/rng/RandomProviderState.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; /** * Marker interface for objects that represents the state of a random * generator. * * @since 1.0 */ public interface RandomProviderState {}
2,897
0
Create_ds/commons-rng/commons-rng-client-api/src/main/java/org/apache/commons
Create_ds/commons-rng/commons-rng-client-api/src/main/java/org/apache/commons/rng/UniformRandomProviderSupport.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; import java.util.Objects; import java.util.Spliterator; import java.util.function.Consumer; import java.util.function.DoubleConsumer; import java.util.function.IntConsumer; import java.util.function.LongConsumer; import java.util.function.ToDoubleFunction; import java.util.function.ToIntFunction; import java.util.function.ToLongFunction; /** * Support for {@link UniformRandomProvider} default methods. * * @since 1.5 */ final class UniformRandomProviderSupport { /** Message for an invalid stream size. */ private static final String INVALID_STREAM_SIZE = "Invalid stream size: "; /** Message for an invalid upper bound (must be positive, finite and above zero). */ private static final String INVALID_UPPER_BOUND = "Upper bound must be above zero: "; /** Message format for an invalid range for lower inclusive and upper exclusive. */ private static final String INVALID_RANGE = "Invalid range: [%s, %s)"; /** 2^32. */ private static final long POW_32 = 1L << 32; /** Message when the consumer action is null. */ private static final String NULL_ACTION = "action must not be null"; /** No instances. */ private UniformRandomProviderSupport() {} /** * Validate the stream size. * * @param size Stream size. * @throws IllegalArgumentException if {@code size} is negative. */ static void validateStreamSize(long size) { if (size < 0) { throw new IllegalArgumentException(INVALID_STREAM_SIZE + size); } } /** * Validate the upper bound. * * @param bound Upper bound (exclusive) on the random number to be returned. * @throws IllegalArgumentException if {@code bound} is equal to or less than zero. */ static void validateUpperBound(int bound) { if (bound <= 0) { throw new IllegalArgumentException(INVALID_UPPER_BOUND + bound); } } /** * Validate the upper bound. * * @param bound Upper bound (exclusive) on the random number to be returned. * @throws IllegalArgumentException if {@code bound} is equal to or less than zero. */ static void validateUpperBound(long bound) { if (bound <= 0) { throw new IllegalArgumentException(INVALID_UPPER_BOUND + bound); } } /** * Validate the upper bound. * * @param bound Upper bound (exclusive) on the random number to be returned. * @throws IllegalArgumentException if {@code bound} is equal to or less than zero, or * is not finite */ static void validateUpperBound(float bound) { // Negation of logic will detect NaN if (!(bound > 0 && bound <= Float.MAX_VALUE)) { throw new IllegalArgumentException(INVALID_UPPER_BOUND + bound); } } /** * Validate the upper bound. * * @param bound Upper bound (exclusive) on the random number to be returned. * @throws IllegalArgumentException if {@code bound} is equal to or less than zero, or * is not finite */ static void validateUpperBound(double bound) { // Negation of logic will detect NaN if (!(bound > 0 && bound <= Double.MAX_VALUE)) { throw new IllegalArgumentException(INVALID_UPPER_BOUND + bound); } } /** * Validate the range between the specified {@code origin} (inclusive) and the * specified {@code bound} (exclusive). * * @param origin Lower bound on the random number to be returned. * @param bound Upper bound (exclusive) on the random number to be returned. * @throws IllegalArgumentException if {@code origin} is greater than or equal to * {@code bound}. */ static void validateRange(int origin, int bound) { if (origin >= bound) { throw new IllegalArgumentException(String.format(INVALID_RANGE, origin, bound)); } } /** * Validate the range between the specified {@code origin} (inclusive) and the * specified {@code bound} (exclusive). * * @param origin Lower bound on the random number to be returned. * @param bound Upper bound (exclusive) on the random number to be returned. * @throws IllegalArgumentException if {@code origin} is greater than or equal to * {@code bound}. */ static void validateRange(long origin, long bound) { if (origin >= bound) { throw new IllegalArgumentException(String.format(INVALID_RANGE, origin, bound)); } } /** * Validate the range between the specified {@code origin} (inclusive) and the * specified {@code bound} (exclusive). * * @param origin Lower bound on the random number to be returned. * @param bound Upper bound (exclusive) on the random number to be returned. * @throws IllegalArgumentException if {@code origin} is not finite, or {@code bound} * is not finite, or {@code origin} is greater than or equal to {@code bound}. */ static void validateRange(double origin, double bound) { if (origin >= bound || !Double.isFinite(origin) || !Double.isFinite(bound)) { throw new IllegalArgumentException(String.format(INVALID_RANGE, origin, bound)); } } /** * 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> * * <p>Note: This is not an exact implementation of the functionality of * {@code Objects.checkFromIndexSize}. The following changes have been made: * <ul> * <li>The method signature has been changed to avoid the return of {@code fromIndex}; * this value is not used within this package. * <li>No checks are made for {@code length < 0} as this is assumed to be derived from * an array length. * </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 * @throws IndexOutOfBoundsException if the sub-range is out of bounds */ static void validateFromIndexSize(int fromIndex, int size, int length) { // check for any negatives (assume 'length' is positive array length), // or overflow safe length check given the values are all positive // remaining = length - fromIndex if ((fromIndex | size) < 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)); } } /** * Generates random bytes and places them into a user-supplied array. * * <p>The array is filled with bytes extracted from random {@code long} values. This * implies that the number of random bytes generated may be larger than the length of * the byte array. * * @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 nextBytes(UniformRandomProvider source, byte[] bytes, int start, int len) { // Index of first insertion plus multiple of 8 part of length // (i.e. length with 3 least significant bits unset). final int indexLoopLimit = start + (len & 0x7ffffff8); // Start filling in the byte array, 8 bytes at a time. int index = start; while (index < indexLoopLimit) { final long random = source.nextLong(); bytes[index++] = (byte) random; bytes[index++] = (byte) (random >>> 8); bytes[index++] = (byte) (random >>> 16); bytes[index++] = (byte) (random >>> 24); bytes[index++] = (byte) (random >>> 32); bytes[index++] = (byte) (random >>> 40); bytes[index++] = (byte) (random >>> 48); bytes[index++] = (byte) (random >>> 56); } // Index of last insertion + 1 final int indexLimit = start + len; // Fill in the remaining bytes. if (index < indexLimit) { long random = source.nextLong(); for (;;) { bytes[index++] = (byte) random; if (index == indexLimit) { break; } random >>>= 8; } } } /** * Generates an {@code int} value between 0 (inclusive) and the specified value * (exclusive). * * @param source Source of randomness. * @param n Bound on the random number to be returned. Must be strictly positive. * @return a random {@code int} value between 0 (inclusive) and {@code n} (exclusive). */ static int nextInt(UniformRandomProvider source, int n) { // Lemire (2019): Fast Random Integer Generation in an Interval // https://arxiv.org/abs/1805.10941 long m = (source.nextInt() & 0xffffffffL) * n; long l = m & 0xffffffffL; if (l < n) { // 2^32 % n final long t = POW_32 % n; while (l < t) { m = (source.nextInt() & 0xffffffffL) * n; l = m & 0xffffffffL; } } return (int) (m >>> 32); } /** * Generates an {@code int} value between the specified {@code origin} (inclusive) and * the specified {@code bound} (exclusive). * * @param source Source of randomness. * @param origin Lower bound on the random number to be returned. * @param bound Upper bound (exclusive) on the random number to be returned. Must be * above {@code origin}. * @return a random {@code int} value between {@code origin} (inclusive) and * {@code bound} (exclusive). */ static int nextInt(UniformRandomProvider source, int origin, int bound) { final int n = bound - origin; if (n > 0) { return nextInt(source, n) + origin; } // Range too large to fit in a positive integer. // Use simple rejection. int v = source.nextInt(); while (v < origin || v >= bound) { v = source.nextInt(); } return v; } /** * Generates an {@code long} value between 0 (inclusive) and the specified value * (exclusive). * * @param source Source of randomness. * @param n Bound on the random number to be returned. Must be strictly positive. * @return a random {@code long} value between 0 (inclusive) and {@code n} * (exclusive). */ static long nextLong(UniformRandomProvider source, long n) { long bits; long val; do { bits = source.nextLong() >>> 1; val = bits % n; } while (bits - val + (n - 1) < 0); return val; } /** * Generates a {@code long} value between the specified {@code origin} (inclusive) and * the specified {@code bound} (exclusive). * * @param source Source of randomness. * @param origin Lower bound on the random number to be returned. * @param bound Upper bound (exclusive) on the random number to be returned. Must be * above {@code origin}. * @return a random {@code long} value between {@code origin} (inclusive) and * {@code bound} (exclusive). */ static long nextLong(UniformRandomProvider source, long origin, long bound) { final long n = bound - origin; if (n > 0) { return nextLong(source, n) + origin; } // Range too large to fit in a positive integer. // Use simple rejection. long v = source.nextLong(); while (v < origin || v >= bound) { v = source.nextLong(); } return v; } /** * Generates a {@code float} value between 0 (inclusive) and the specified value * (exclusive). * * @param source Source of randomness. * @param bound Bound on the random number to be returned. Must be strictly positive. * @return a random {@code float} value between 0 (inclusive) and {@code bound} * (exclusive). */ static float nextFloat(UniformRandomProvider source, float bound) { float v = source.nextFloat() * bound; if (v >= bound) { // Correct rounding v = Math.nextDown(bound); } return v; } /** * Generates a {@code float} value between the specified {@code origin} (inclusive) * and the specified {@code bound} (exclusive). * * @param source Source of randomness. * @param origin Lower bound on the random number to be returned. Must be finite. * @param bound Upper bound (exclusive) on the random number to be returned. Must be * above {@code origin} and finite. * @return a random {@code float} value between {@code origin} (inclusive) and * {@code bound} (exclusive). */ static float nextFloat(UniformRandomProvider source, float origin, float bound) { float v = source.nextFloat(); // This expression allows (bound - origin) to be infinite // origin + (bound - origin) * v // == origin - origin * v + bound * v v = (1f - v) * origin + v * bound; if (v >= bound) { // Correct rounding v = Math.nextDown(bound); } return v; } /** * Generates a {@code double} value between 0 (inclusive) and the specified value * (exclusive). * * @param source Source of randomness. * @param bound Bound on the random number to be returned. Must be strictly positive. * @return a random {@code double} value between 0 (inclusive) and {@code bound} * (exclusive). */ static double nextDouble(UniformRandomProvider source, double bound) { double v = source.nextDouble() * bound; if (v >= bound) { // Correct rounding v = Math.nextDown(bound); } return v; } /** * Generates a {@code double} value between the specified {@code origin} (inclusive) * and the specified {@code bound} (exclusive). * * @param source Source of randomness. * @param origin Lower bound on the random number to be returned. Must be finite. * @param bound Upper bound (exclusive) on the random number to be returned. Must be * above {@code origin} and finite. * @return a random {@code double} value between {@code origin} (inclusive) and * {@code bound} (exclusive). */ static double nextDouble(UniformRandomProvider source, double origin, double bound) { double v = source.nextDouble(); // This expression allows (bound - origin) to be infinite // origin + (bound - origin) * v // == origin - origin * v + bound * v v = (1f - v) * origin + v * bound; if (v >= bound) { // Correct rounding v = Math.nextDown(bound); } return v; } // Spliterator support /** * Base class for spliterators for streams of values. Contains the range current position and * end position. Splitting is expected to divide the range in half and create instances * that span the two ranges. */ private static class ProviderSpliterator { /** The current position in the range. */ protected long position; /** The upper limit of the range. */ protected final long end; /** * @param start Start position of the stream (inclusive). * @param end Upper limit of the stream (exclusive). */ ProviderSpliterator(long start, long end) { position = start; this.end = end; } // Methods required by all Spliterators // See Spliterator.estimateSize() public long estimateSize() { return end - position; } // See Spliterator.characteristics() public int characteristics() { return Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.NONNULL | Spliterator.IMMUTABLE; } } /** * Spliterator for streams of SplittableUniformRandomProvider. */ static class ProviderSplitsSpliterator extends ProviderSpliterator implements Spliterator<SplittableUniformRandomProvider> { /** Source of randomness used to initialise the new instances. */ private final SplittableUniformRandomProvider source; /** Generator to split to create new instances. */ private final SplittableUniformRandomProvider rng; /** * @param start Start position of the stream (inclusive). * @param end Upper limit of the stream (exclusive). * @param source Source of randomness used to initialise the new instances. * @param rng Generator to split to create new instances. */ ProviderSplitsSpliterator(long start, long end, SplittableUniformRandomProvider source, SplittableUniformRandomProvider rng) { super(start, end); this.source = source; this.rng = rng; } @Override public Spliterator<SplittableUniformRandomProvider> trySplit() { final long start = position; final long middle = (start + end) >>> 1; if (middle <= start) { return null; } position = middle; return new ProviderSplitsSpliterator(start, middle, source.split(), rng); } @Override public boolean tryAdvance(Consumer<? super SplittableUniformRandomProvider> action) { Objects.requireNonNull(action, NULL_ACTION); final long pos = position; if (pos < end) { // Advance before exceptions from the action are relayed to the caller position = pos + 1; action.accept(rng.split(source)); return true; } return false; } @Override public void forEachRemaining(Consumer<? super SplittableUniformRandomProvider> action) { Objects.requireNonNull(action, NULL_ACTION); long pos = position; final long last = end; if (pos < last) { // Ensure forEachRemaining is called only once position = last; final SplittableUniformRandomProvider s = source; final SplittableUniformRandomProvider r = rng; do { action.accept(r.split(s)); } while (++pos < last); } } } /** * Spliterator for streams of int values that may be recursively split. */ static class ProviderIntsSpliterator extends ProviderSpliterator implements Spliterator.OfInt { /** Source of randomness. */ private final SplittableUniformRandomProvider source; /** Value generator function. */ private final ToIntFunction<SplittableUniformRandomProvider> gen; /** * @param start Start position of the stream (inclusive). * @param end Upper limit of the stream (exclusive). * @param source Source of randomness. * @param gen Value generator function. */ ProviderIntsSpliterator(long start, long end, SplittableUniformRandomProvider source, ToIntFunction<SplittableUniformRandomProvider> gen) { super(start, end); this.source = source; this.gen = gen; } @Override public Spliterator.OfInt trySplit() { final long start = position; final long middle = (start + end) >>> 1; if (middle <= start) { return null; } position = middle; return new ProviderIntsSpliterator(start, middle, source.split(), gen); } @Override public boolean tryAdvance(IntConsumer action) { Objects.requireNonNull(action, NULL_ACTION); final long pos = position; if (pos < end) { // Advance before exceptions from the action are relayed to the caller position = pos + 1; action.accept(gen.applyAsInt(source)); return true; } return false; } @Override public void forEachRemaining(IntConsumer action) { Objects.requireNonNull(action, NULL_ACTION); long pos = position; final long last = end; if (pos < last) { // Ensure forEachRemaining is called only once position = last; final SplittableUniformRandomProvider s = source; final ToIntFunction<SplittableUniformRandomProvider> g = gen; do { action.accept(g.applyAsInt(s)); } while (++pos < last); } } } /** * Spliterator for streams of long values that may be recursively split. */ static class ProviderLongsSpliterator extends ProviderSpliterator implements Spliterator.OfLong { /** Source of randomness. */ private final SplittableUniformRandomProvider source; /** Value generator function. */ private final ToLongFunction<SplittableUniformRandomProvider> gen; /** * @param start Start position of the stream (inclusive). * @param end Upper limit of the stream (exclusive). * @param source Source of randomness. * @param gen Value generator function. */ ProviderLongsSpliterator(long start, long end, SplittableUniformRandomProvider source, ToLongFunction<SplittableUniformRandomProvider> gen) { super(start, end); this.source = source; this.gen = gen; } @Override public Spliterator.OfLong trySplit() { final long start = position; final long middle = (start + end) >>> 1; if (middle <= start) { return null; } position = middle; return new ProviderLongsSpliterator(start, middle, source.split(), gen); } @Override public boolean tryAdvance(LongConsumer action) { Objects.requireNonNull(action, NULL_ACTION); final long pos = position; if (pos < end) { // Advance before exceptions from the action are relayed to the caller position = pos + 1; action.accept(gen.applyAsLong(source)); return true; } return false; } @Override public void forEachRemaining(LongConsumer action) { Objects.requireNonNull(action, NULL_ACTION); long pos = position; final long last = end; if (pos < last) { // Ensure forEachRemaining is called only once position = last; final SplittableUniformRandomProvider s = source; final ToLongFunction<SplittableUniformRandomProvider> g = gen; do { action.accept(g.applyAsLong(s)); } while (++pos < last); } } } /** * Spliterator for streams of double values that may be recursively split. */ static class ProviderDoublesSpliterator extends ProviderSpliterator implements Spliterator.OfDouble { /** Source of randomness. */ private final SplittableUniformRandomProvider source; /** Value generator function. */ private final ToDoubleFunction<SplittableUniformRandomProvider> gen; /** * @param start Start position of the stream (inclusive). * @param end Upper limit of the stream (exclusive). * @param source Source of randomness. * @param gen Value generator function. */ ProviderDoublesSpliterator(long start, long end, SplittableUniformRandomProvider source, ToDoubleFunction<SplittableUniformRandomProvider> gen) { super(start, end); this.source = source; this.gen = gen; } @Override public Spliterator.OfDouble trySplit() { final long start = position; final long middle = (start + end) >>> 1; if (middle <= start) { return null; } position = middle; return new ProviderDoublesSpliterator(start, middle, source.split(), gen); } @Override public boolean tryAdvance(DoubleConsumer action) { Objects.requireNonNull(action, NULL_ACTION); final long pos = position; if (pos < end) { // Advance before exceptions from the action are relayed to the caller position = pos + 1; action.accept(gen.applyAsDouble(source)); return true; } return false; } @Override public void forEachRemaining(DoubleConsumer action) { Objects.requireNonNull(action, NULL_ACTION); long pos = position; final long last = end; if (pos < last) { // Ensure forEachRemaining is called only once position = last; final SplittableUniformRandomProvider s = source; final ToDoubleFunction<SplittableUniformRandomProvider> g = gen; do { action.accept(g.applyAsDouble(s)); } while (++pos < last); } } } }
2,898
0
Create_ds/commons-rng/commons-rng-client-api/src/main/java/org/apache/commons
Create_ds/commons-rng/commons-rng-client-api/src/main/java/org/apache/commons/rng/SplittableUniformRandomProvider.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; import java.util.Objects; import java.util.stream.DoubleStream; import java.util.stream.IntStream; import java.util.stream.LongStream; import java.util.stream.Stream; import java.util.stream.StreamSupport; /** * Applies to generators that can be split into two objects (the original and a new instance) * each of which implements the same interface (and can be recursively split indefinitely). * It is assumed that the two generators resulting from a split can be used concurrently on * different threads. * * <p>Ideally all generators produced by recursive splitting from the original object are * statistically independent and individually uniform. In this case it would be expected that * the set of values collectively generated from a group of split generators would have the * same statistical properties as the same number of values produced from a single generator * object. * * @since 1.5 */ public interface SplittableUniformRandomProvider extends UniformRandomProvider { /** * Creates a new random generator, split off from this one, that implements * the {@link SplittableUniformRandomProvider} interface. * * <p>The current generator may be used a source of randomness to initialise the new instance. * In this case repeat invocations of this method will return objects with a different * initial state that are expected to be statistically independent. * * @return A new instance. */ default SplittableUniformRandomProvider split() { return split(this); } /** * Creates a new random generator, split off from this one, that implements * the {@link SplittableUniformRandomProvider} interface. * * @param source A source of randomness used to initialise the new instance. * @return A new instance. * @throws NullPointerException if {@code source} is null */ SplittableUniformRandomProvider split(UniformRandomProvider source); /** * Returns an effectively unlimited stream of new random generators, each of which * implements the {@link SplittableUniformRandomProvider} interface. * * <p>The current generator may be used a source of randomness to initialise the new instances. * * @return a stream of random generators. */ default Stream<SplittableUniformRandomProvider> splits() { return splits(Long.MAX_VALUE, this); } /** * Returns an effectively unlimited stream of new random generators, each of which * implements the {@link SplittableUniformRandomProvider} interface. * * @param source A source of randomness used to initialise the new instances; this may * be split to provide a source of randomness across a parallel stream. * @return a stream of random generators. * @throws NullPointerException if {@code source} is null */ default Stream<SplittableUniformRandomProvider> splits(SplittableUniformRandomProvider source) { return this.splits(Long.MAX_VALUE, source); } /** * Returns a stream producing the given {@code streamSize} number of new random * generators, each of which implements the {@link SplittableUniformRandomProvider} * interface. * * <p>The current generator may be used a source of randomness to initialise the new instances. * * @param streamSize Number of objects to generate. * @return a stream of random generators; the stream is limited to the given * {@code streamSize}. * @throws IllegalArgumentException if {@code streamSize} is negative. */ default Stream<SplittableUniformRandomProvider> splits(long streamSize) { return splits(streamSize, this); } /** * Returns a stream producing the given {@code streamSize} number of new random * generators, each of which implements the {@link SplittableUniformRandomProvider} * interface. * * @param streamSize Number of objects to generate. * @param source A source of randomness used to initialise the new instances; this may * be split to provide a source of randomness across a parallel stream. * @return a stream of random generators; the stream is limited to the given * {@code streamSize}. * @throws IllegalArgumentException if {@code streamSize} is negative. * @throws NullPointerException if {@code source} is null */ default Stream<SplittableUniformRandomProvider> splits(long streamSize, SplittableUniformRandomProvider source) { UniformRandomProviderSupport.validateStreamSize(streamSize); Objects.requireNonNull(source, "source"); return StreamSupport.stream( new UniformRandomProviderSupport.ProviderSplitsSpliterator(0, streamSize, source, this), false); } @Override default IntStream ints() { return ints(Long.MAX_VALUE); } @Override default IntStream ints(int origin, int bound) { return ints(Long.MAX_VALUE, origin, bound); } @Override default IntStream ints(long streamSize) { UniformRandomProviderSupport.validateStreamSize(streamSize); return StreamSupport.intStream( new UniformRandomProviderSupport.ProviderIntsSpliterator( 0, streamSize, this, UniformRandomProvider::nextInt), false); } @Override default IntStream ints(long streamSize, int origin, int bound) { UniformRandomProviderSupport.validateStreamSize(streamSize); UniformRandomProviderSupport.validateRange(origin, bound); return StreamSupport.intStream( new UniformRandomProviderSupport.ProviderIntsSpliterator( 0, streamSize, this, rng -> rng.nextInt(origin, bound)), false); } @Override default LongStream longs() { return longs(Long.MAX_VALUE); } @Override default LongStream longs(long origin, long bound) { return longs(Long.MAX_VALUE, origin, bound); } @Override default LongStream longs(long streamSize) { UniformRandomProviderSupport.validateStreamSize(streamSize); return StreamSupport.longStream( new UniformRandomProviderSupport.ProviderLongsSpliterator( 0, streamSize, this, UniformRandomProvider::nextLong), false); } @Override default LongStream longs(long streamSize, long origin, long bound) { UniformRandomProviderSupport.validateStreamSize(streamSize); UniformRandomProviderSupport.validateRange(origin, bound); return StreamSupport.longStream( new UniformRandomProviderSupport.ProviderLongsSpliterator( 0, streamSize, this, rng -> rng.nextLong(origin, bound)), false); } @Override default DoubleStream doubles() { return doubles(Long.MAX_VALUE); } @Override default DoubleStream doubles(double origin, double bound) { return doubles(Long.MAX_VALUE, origin, bound); } @Override default DoubleStream doubles(long streamSize) { UniformRandomProviderSupport.validateStreamSize(streamSize); return StreamSupport.doubleStream( new UniformRandomProviderSupport.ProviderDoublesSpliterator( 0, streamSize, this, UniformRandomProvider::nextDouble), false); } @Override default DoubleStream doubles(long streamSize, double origin, double bound) { UniformRandomProviderSupport.validateStreamSize(streamSize); UniformRandomProviderSupport.validateRange(origin, bound); return StreamSupport.doubleStream( new UniformRandomProviderSupport.ProviderDoublesSpliterator( 0, streamSize, this, rng -> rng.nextDouble(origin, bound)), false); } }
2,899