http://git-wip-us.apache.org/repos/asf/commons-rng/blob/2fdb5227/commons-rng-examples/examples-stress/src/main/c/stdin2testu01.c ---------------------------------------------------------------------- diff --git a/commons-rng-examples/examples-stress/src/main/c/stdin2testu01.c b/commons-rng-examples/examples-stress/src/main/c/stdin2testu01.c new file mode 100644 index 0000000..d1a4a6a --- /dev/null +++ b/commons-rng-examples/examples-stress/src/main/c/stdin2testu01.c @@ -0,0 +1,127 @@ +/* + * 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. + */ + +/* + * Utility for simple interfacing with the "TestU01" library: + * http://simul.iro.umontreal.ca/testu01/tu01.html + * + * It reads from its standard input an infinite sequence of 32-bits + * integers and runs one of the test suites "SmallCrush", "Crush" or + * "BigCrush". + * "TestU01" writes its report to standard output. + */ + +#include <stdint.h> +#include <unistd.h> +#include <string.h> + +#include <testu01/unif01.h> +#include <testu01/bbattery.h> +#include <testu01/util.h> + +#define TU_S "SmallCrush" +#define TU_C "Crush" +#define TU_B "BigCrush" +#define BUFFER_LENGTH 256 + +typedef struct { + unsigned long buffer[BUFFER_LENGTH]; + uint32_t index; +} StdinReader_state; + +unsigned long nextInt(void *par, + void *sta) { + StdinReader_state *state = (StdinReader_state *) sta; + if (state->index >= BUFFER_LENGTH) { + /* Refill. */ + fread(state->buffer, sizeof(unsigned long), BUFFER_LENGTH, stdin); + state->index = 0; + } + + uint32_t random = state->buffer[state->index]; + ++state->index; /* Next request. */ + + return random; +} + +double nextDouble(void *par, + void *sta) { + return nextInt(par, sta) / 4294967296.0; +} + + +static void dummy(void *sta) { + printf("N/A"); + + return; +} + +unif01_Gen *createStdinReader(void) { + unif01_Gen *gen; + StdinReader_state *state; + size_t len; + char name[60]; + + state = util_Malloc(sizeof(StdinReader_state)); + + gen = util_Malloc(sizeof(unif01_Gen)); + gen->state = state; + gen->param = NULL; + gen->Write = dummy; + gen->GetU01 = nextDouble; + gen->GetBits = nextInt; + + strcpy(name, "stdin"); + len = strlen(name); + gen->name = util_Calloc(len + 1, sizeof (char)); + strncpy(gen->name, name, len); + + // Read binary input. + freopen(NULL, "rb", stdin); + state->index = BUFFER_LENGTH; + + return gen; +} + +void deleteStdinReader(unif01_Gen *gen) { + gen->state = util_Free(gen->state); + gen->name = util_Free(gen->name); + util_Free(gen); +} + +int main(int argc, + char **argv) { + unif01_Gen *gen = createStdinReader(); + char *spec = argv[1]; + + if (argc < 2) { + printf("[ERROR] Specify test suite: '%s', '%s' or '%s'\n", TU_S, TU_C, TU_B); + exit(1); + } else if (strcmp(spec, TU_S) == 0) { + bbattery_SmallCrush(gen); + } else if (strcmp(spec, TU_C) == 0) { + bbattery_Crush(gen); + } else if (strcmp(spec, TU_B) == 0) { + bbattery_BigCrush(gen); + } else { + printf("[ERROR] Unknown specification: '%s'\n", spec); + exit(1); + } + + deleteStdinReader(gen); + return 0; +}
http://git-wip-us.apache.org/repos/asf/commons-rng/blob/2fdb5227/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/GeneratorsList.java ---------------------------------------------------------------------- diff --git a/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/GeneratorsList.java b/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/GeneratorsList.java new file mode 100644 index 0000000..037f60b --- /dev/null +++ b/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/GeneratorsList.java @@ -0,0 +1,59 @@ +/* + * 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.util.List; +import java.util.ArrayList; +import java.util.Iterator; + +import org.apache.commons.rng.UniformRandomProvider; +import org.apache.commons.rng.simple.RandomSource; + +/** + * List of generators. + */ +public class GeneratorsList implements Iterable<UniformRandomProvider> { + /** List. */ + private final List<UniformRandomProvider> list = new ArrayList<UniformRandomProvider>(); + + /** + * Creates list. + */ + public GeneratorsList() { + list.add(RandomSource.create(RandomSource.JDK)); + list.add(RandomSource.create(RandomSource.MT)); + list.add(RandomSource.create(RandomSource.WELL_512_A)); + list.add(RandomSource.create(RandomSource.WELL_1024_A)); + list.add(RandomSource.create(RandomSource.WELL_19937_A)); + list.add(RandomSource.create(RandomSource.WELL_19937_C)); + list.add(RandomSource.create(RandomSource.WELL_44497_A)); + list.add(RandomSource.create(RandomSource.WELL_44497_B)); + list.add(RandomSource.create(RandomSource.ISAAC)); + list.add(RandomSource.create(RandomSource.MT_64)); + list.add(RandomSource.create(RandomSource.SPLIT_MIX_64)); + list.add(RandomSource.create(RandomSource.XOR_SHIFT_1024_S)); + list.add(RandomSource.create(RandomSource.TWO_CMRES)); + list.add(RandomSource.create(RandomSource.MWC_256)); + list.add(RandomSource.create(RandomSource.KISS)); + } + + /** {@inheritDoc} */ + @Override + public Iterator<UniformRandomProvider> iterator() { + return list.iterator(); + } +} http://git-wip-us.apache.org/repos/asf/commons-rng/blob/2fdb5227/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/RandomStressTester.java ---------------------------------------------------------------------- diff --git a/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/RandomStressTester.java b/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/RandomStressTester.java new file mode 100644 index 0000000..1cad0dd --- /dev/null +++ b/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/RandomStressTester.java @@ -0,0 +1,292 @@ +/* + * 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.util.List; +import java.util.ArrayList; +import java.util.Arrays; +import java.io.IOException; +import java.io.File; +import java.io.PrintWriter; +import java.io.FileWriter; +import java.io.DataOutputStream; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import org.apache.commons.rng.UniformRandomProvider; + +/** + * Class that can be used for testing a 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. + * + * The <a href="http://www.phy.duke.edu/~rgb/General/dieharder.php"> + * "dieharder"</a> test suite is such a software. + * + * Example of command line, assuming that "examples.jar" specifies this + * class as the "main" class (see {@link #main(String[]) main} method): + * <pre><code> + * $ java -jar examples.jar \ + * report/dh_ \ + * 4 \ + * org.apache.commons.rng.examples.stress.GeneratorsList \ + * /usr/bin/dieharder -a -g 200 -Y 1 -k 2 + * </code></pre> + */ +public class RandomStressTester { + /** Comment prefix. */ + private static final String C = "# "; + /** New line. */ + private static final String N = "\n"; + /** Command line. */ + private final List<String> cmdLine; + /** Output prefix. */ + private final String fileOutputPrefix; + + /** + * Creates the application. + * + * @param cmd Command line. + * @param outputPrefix Output prefix for file reports. + */ + private RandomStressTester(List<String> cmd, + String outputPrefix) { + final File exec = new File(cmd.get(0)); + if (!exec.exists() || + !exec.canExecute()) { + throw new IllegalArgumentException("Program is not executable: " + exec); + } + + cmdLine = new ArrayList<String>(cmd); + fileOutputPrefix = outputPrefix; + + final File reportDir = new File(fileOutputPrefix).getParentFile(); + if (!reportDir.exists() || + !reportDir.isDirectory() || + !reportDir.canWrite()) { + throw new IllegalArgumentException("Invalid output directory: " + reportDir); + } + } + + /** + * Program's entry point. + * + * @param args Application's arguments. + * The order is as follows: + * <ol> + * <li>Output prefix: Filename prefix where the output of the analysis will + * written to. The appended suffix is the index of the instance within the + * list of generators to be tested.</li> + * <li>Number of threads to use concurrently: One thread will process one of + * the generators to be tested.</li> + * <li>Name of a class that implements {@code Iterable<UniformRandomProvider>} + * (and defines a default constructor): Each generator of the list will be + * tested by one instance of the analyzer program</li> + * <li>Path to the executable: this is the analyzer software that reads 32-bits + * integers from stdin.</li> + * <li>All remaining arguments are passed to the executable.</li> + * </ol> + */ + public static void main(String[] args) { + final String output = args[0]; + final int numThreads = Integer.parseInt(args[1]); + + final Iterable<UniformRandomProvider> rngList = createGeneratorsList(args[2]); + + final List<String> cmdLine = new ArrayList<String>(); + cmdLine.addAll(Arrays.asList(Arrays.copyOfRange(args, 3, args.length))); + + final RandomStressTester app = new RandomStressTester(cmdLine, output); + + try { + app.run(rngList, numThreads); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + /** + * Creates the tasks and starts the processes. + * + * @param generators List of generators to be analyzed. + * @param numConcurrentTasks Number of concurrent tasks. + * Twice as many threads will be started: one thread for the RNG and one + * for the analyzer. + * @throws IOException if an error occurs when writing to the disk. + */ + private void run(Iterable<UniformRandomProvider> generators, + int numConcurrentTasks) + throws IOException { + // Parallel execution. + final ExecutorService service = Executors.newFixedThreadPool(numConcurrentTasks); + + // Placeholder (output will be "null"). + final List<Future<?>> execOutput = new ArrayList<Future<?>>(); + + // Run tasks. + int count = 0; + for (UniformRandomProvider rng : generators) { + final File output = new File(fileOutputPrefix + (++count)); + final Runnable r = new Task(rng, output); + execOutput.add(service.submit(r)); + } + + // Wait for completion (ignoring return value). + try { + for (Future<?> f : execOutput) { + try { + f.get(); + } catch (ExecutionException e) { + System.err.println(e.getCause().getMessage()); + } + } + } catch (InterruptedException ignored) {} + + // Terminate all threads. + service.shutdown(); + } + + /** + * Creates the list of generators to be tested. + * + * @param name Name of the class that contains the generators to be + * analyzed. + * @return the list of generators. + * @throws IllegalStateException if an error occurs during instantiation. + */ + private static Iterable<UniformRandomProvider> createGeneratorsList(String name) { + try { + return (Iterable<UniformRandomProvider>) Class.forName(name).newInstance(); + } catch (ClassNotFoundException| + InstantiationException| + IllegalAccessException e) { + throw new RuntimeException(e); + } + } + + /** + * Pipes random numbers to the standard input of an analyzer. + */ + private class Task implements Runnable { + /** Directory for reports of the tester processes. */ + private final File output; + /** RNG to be tested. */ + private final UniformRandomProvider rng; + + /** + * Creates the task. + * + * @param random RNG to be tested. + * @param report Report file. + */ + Task(UniformRandomProvider random, + File report) { + rng = random; + output = report; + } + + /** {@inheritDoc} */ + @Override + public void run() { + try { + // Write header. + printHeader(output, rng); + + // Start test suite. + final ProcessBuilder builder = new ProcessBuilder(cmdLine); + builder.redirectOutput(ProcessBuilder.Redirect.appendTo(output)); + final Process testingProcess = builder.start(); + final DataOutputStream sink = new DataOutputStream(testingProcess.getOutputStream()); + + final long startTime = System.nanoTime(); + + try { + while (true) { + sink.writeInt(rng.nextInt()); + } + } catch (IOException e) { + // Hopefully getting here when the analyzing software terminates. + } + + final long endTime = System.nanoTime(); + + // Write footer. + printFooter(output, endTime - startTime); + + } catch (IOException e) { + throw new RuntimeException("Failed to start task: " + e.getMessage()); + } + } + } + + /** + * @param output File. + * @param rng Generator being tested. + * @param cmdLine + * @throws IOException if there was a problem opening or writing to + * the {@code output} file. + */ + private void printHeader(File output, + UniformRandomProvider rng) + throws IOException { + final StringBuilder sb = new StringBuilder(); + sb.append(C).append(N); + sb.append(C).append("RNG: ").append(rng.toString()).append(N); + sb.append(C).append(N); + sb.append(C).append("Java: ").append(System.getProperty("java.version")).append(N); + sb.append(C).append("Runtime: ").append(System.getProperty("java.runtime.version", "?")).append(N); + sb.append(C).append("JVM: ").append(System.getProperty("java.vm.name")) + .append(" ").append(System.getProperty("java.vm.version")).append(N); + sb.append(C).append("OS: ").append(System.getProperty("os.name")) + .append(" ").append(System.getProperty("os.version")) + .append(" ").append(System.getProperty("os.arch")).append(N); + sb.append(C).append(N); + + sb.append(C).append("Analyzer: "); + for (String s : cmdLine) { + sb.append(s).append(" "); + } + sb.append(N); + sb.append(C).append(N); + + final PrintWriter w = new PrintWriter(new FileWriter(output, true)); + w.print(sb.toString()); + w.close(); + } + + /** + * @param output File. + * @param nanoTime Duration of the run. + * @throws IOException if there was a problem opening or writing to + * the {@code output} file. + */ + private void printFooter(File output, + long nanoTime) + throws IOException { + final PrintWriter w = new PrintWriter(new FileWriter(output, true)); + w.println(C); + + final double duration = ((double) nanoTime) * 1e-9 / 60; + w.println(C + "Test duration: " + duration + " minutes"); + + w.println(C); + w.close(); + } +} http://git-wip-us.apache.org/repos/asf/commons-rng/blob/2fdb5227/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/package-info.java ---------------------------------------------------------------------- diff --git a/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/package-info.java b/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/package-info.java new file mode 100644 index 0000000..5b59e08 --- /dev/null +++ b/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/package-info.java @@ -0,0 +1,28 @@ +/* + * 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. + */ + +/** + * <h3>Stress test application</h3> + * + * <p> + * 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. + * </p> + */ + +package org.apache.commons.rng.examples.stress; http://git-wip-us.apache.org/repos/asf/commons-rng/blob/2fdb5227/commons-rng-examples/pom.xml ---------------------------------------------------------------------- diff --git a/commons-rng-examples/pom.xml b/commons-rng-examples/pom.xml index 07a04be..276aac7 100644 --- a/commons-rng-examples/pom.xml +++ b/commons-rng-examples/pom.xml @@ -29,6 +29,7 @@ <groupId>org.apache.commons</groupId> <artifactId>commons-rng-examples</artifactId> <version>1.1-SNAPSHOT</version> + <packaging>pom</packaging> <name>Apache Commons RNG Examples</name> <description>Examples of use of the random numbers generator implemented in the "commons-rng-simple" module. @@ -47,18 +48,25 @@ <rng.parent.dir>${basedir}/..</rng.parent.dir> </properties> - <dependencies> - <dependency> - <groupId>org.apache.commons</groupId> - <artifactId>commons-rng-simple</artifactId> - <version>1.1-SNAPSHOT</version> - </dependency> + <dependencyManagement> + <dependencies> + <dependency> + <groupId>org.apache.commons</groupId> + <artifactId>commons-rng-simple</artifactId> + <version>1.1-SNAPSHOT</version> + </dependency> - <dependency> - <groupId>org.apache.commons</groupId> - <artifactId>commons-rng-sampling</artifactId> - <version>1.1-SNAPSHOT</version> - </dependency> - </dependencies> + <dependency> + <groupId>org.apache.commons</groupId> + <artifactId>commons-rng-sampling</artifactId> + <version>1.1-SNAPSHOT</version> + </dependency> + </dependencies> + </dependencyManagement> + <modules> + <module>examples-stress</module> + <module>examples-sampling</module> + <module>examples-quadrature</module> + </modules> </project> http://git-wip-us.apache.org/repos/asf/commons-rng/blob/2fdb5227/commons-rng-examples/src/main/c/stdin2testu01.c ---------------------------------------------------------------------- diff --git a/commons-rng-examples/src/main/c/stdin2testu01.c b/commons-rng-examples/src/main/c/stdin2testu01.c deleted file mode 100644 index d1a4a6a..0000000 --- a/commons-rng-examples/src/main/c/stdin2testu01.c +++ /dev/null @@ -1,127 +0,0 @@ -/* - * 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. - */ - -/* - * Utility for simple interfacing with the "TestU01" library: - * http://simul.iro.umontreal.ca/testu01/tu01.html - * - * It reads from its standard input an infinite sequence of 32-bits - * integers and runs one of the test suites "SmallCrush", "Crush" or - * "BigCrush". - * "TestU01" writes its report to standard output. - */ - -#include <stdint.h> -#include <unistd.h> -#include <string.h> - -#include <testu01/unif01.h> -#include <testu01/bbattery.h> -#include <testu01/util.h> - -#define TU_S "SmallCrush" -#define TU_C "Crush" -#define TU_B "BigCrush" -#define BUFFER_LENGTH 256 - -typedef struct { - unsigned long buffer[BUFFER_LENGTH]; - uint32_t index; -} StdinReader_state; - -unsigned long nextInt(void *par, - void *sta) { - StdinReader_state *state = (StdinReader_state *) sta; - if (state->index >= BUFFER_LENGTH) { - /* Refill. */ - fread(state->buffer, sizeof(unsigned long), BUFFER_LENGTH, stdin); - state->index = 0; - } - - uint32_t random = state->buffer[state->index]; - ++state->index; /* Next request. */ - - return random; -} - -double nextDouble(void *par, - void *sta) { - return nextInt(par, sta) / 4294967296.0; -} - - -static void dummy(void *sta) { - printf("N/A"); - - return; -} - -unif01_Gen *createStdinReader(void) { - unif01_Gen *gen; - StdinReader_state *state; - size_t len; - char name[60]; - - state = util_Malloc(sizeof(StdinReader_state)); - - gen = util_Malloc(sizeof(unif01_Gen)); - gen->state = state; - gen->param = NULL; - gen->Write = dummy; - gen->GetU01 = nextDouble; - gen->GetBits = nextInt; - - strcpy(name, "stdin"); - len = strlen(name); - gen->name = util_Calloc(len + 1, sizeof (char)); - strncpy(gen->name, name, len); - - // Read binary input. - freopen(NULL, "rb", stdin); - state->index = BUFFER_LENGTH; - - return gen; -} - -void deleteStdinReader(unif01_Gen *gen) { - gen->state = util_Free(gen->state); - gen->name = util_Free(gen->name); - util_Free(gen); -} - -int main(int argc, - char **argv) { - unif01_Gen *gen = createStdinReader(); - char *spec = argv[1]; - - if (argc < 2) { - printf("[ERROR] Specify test suite: '%s', '%s' or '%s'\n", TU_S, TU_C, TU_B); - exit(1); - } else if (strcmp(spec, TU_S) == 0) { - bbattery_SmallCrush(gen); - } else if (strcmp(spec, TU_C) == 0) { - bbattery_Crush(gen); - } else if (strcmp(spec, TU_B) == 0) { - bbattery_BigCrush(gen); - } else { - printf("[ERROR] Unknown specification: '%s'\n", spec); - exit(1); - } - - deleteStdinReader(gen); - return 0; -} http://git-wip-us.apache.org/repos/asf/commons-rng/blob/2fdb5227/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/integration/ComputePi.java ---------------------------------------------------------------------- diff --git a/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/integration/ComputePi.java b/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/integration/ComputePi.java deleted file mode 100644 index 7218e8a..0000000 --- a/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/integration/ComputePi.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * 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.integration; - -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 { - /** Domain dimension. */ - private static final int DIMENSION = 2; - - /** - * @param source RNG algorithm. - */ - public ComputePi(RandomSource source) { - super(source, 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 != 2) { - throw new IllegalStateException("Missing arguments"); - } - - final long numPoints = Long.parseLong(args[0]); - final RandomSource randomSource = RandomSource.valueOf(args[1]); - - final ComputePi piApp = new ComputePi(randomSource); - final double piMC = piApp.compute(numPoints); - - //CHECKSTYLE: stop all - System.out.println("After generating " + (DIMENSION * numPoints) + - " random numbers, the error on ð is " + 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; - } -} http://git-wip-us.apache.org/repos/asf/commons-rng/blob/2fdb5227/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/integration/MonteCarloIntegration.java ---------------------------------------------------------------------- diff --git a/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/integration/MonteCarloIntegration.java b/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/integration/MonteCarloIntegration.java deleted file mode 100644 index 7631b2e..0000000 --- a/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/integration/MonteCarloIntegration.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * 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.integration; - -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.rng.simple.RandomSource; - -/** - * <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 source RNG algorithm. - * @param dimension Integration domain dimension. - */ - public MonteCarloIntegration(RandomSource source, - int dimension) { - this.rng = RandomSource.create(source); - this.dimension = dimension; - } - - /** - * Run the Monte-Carlo integration. - * - * @param n Number of random points to generate. - * @return the integral. - */ - public double integrate(long n) { - double result = 0; - long inside = 0; - long total = 0; - while (total < n) { - if (isInside(generateU01())) { - ++inside; - } - - ++total; - result = inside / (double) total; - } - - return result; - } - - /** - * 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; - } -} http://git-wip-us.apache.org/repos/asf/commons-rng/blob/2fdb5227/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/integration/package-info.java ---------------------------------------------------------------------- diff --git a/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/integration/package-info.java b/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/integration/package-info.java deleted file mode 100644 index 8fced09..0000000 --- a/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/integration/package-info.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * 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. - */ - -/** - * <h3>Monte-Carlo integration</h3> - * - * <p> - * This package contains a simple application that uses many - * uniformly-distributed random numbers. - * </p> - */ - -package org.apache.commons.rng.examples.integration; http://git-wip-us.apache.org/repos/asf/commons-rng/blob/2fdb5227/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/package-info.java ---------------------------------------------------------------------- diff --git a/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/package-info.java b/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/package-info.java deleted file mode 100644 index a88e369..0000000 --- a/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/package-info.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * 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. - */ - -/** - * <h3>Usage examples</h3> - * - * <p> - * This package contains examples of use of the Commons RNG library. - * </p> - */ - -package org.apache.commons.rng.examples; http://git-wip-us.apache.org/repos/asf/commons-rng/blob/2fdb5227/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/sampling/ProbabilityDensityApproximation.java ---------------------------------------------------------------------- diff --git a/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/sampling/ProbabilityDensityApproximation.java b/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/sampling/ProbabilityDensityApproximation.java deleted file mode 100644 index 3fa5ace..0000000 --- a/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/sampling/ProbabilityDensityApproximation.java +++ /dev/null @@ -1,200 +0,0 @@ -/* - * 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 java.io.PrintWriter; -import java.io.IOException; -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.rng.simple.RandomSource; -import org.apache.commons.rng.sampling.distribution.ZigguratNormalizedGaussianSampler; -import org.apache.commons.rng.sampling.distribution.MarsagliaNormalizedGaussianSampler; -import org.apache.commons.rng.sampling.distribution.BoxMullerNormalizedGaussianSampler; -import org.apache.commons.rng.sampling.distribution.ChengBetaSampler; -import org.apache.commons.rng.sampling.distribution.AhrensDieterExponentialSampler; -import org.apache.commons.rng.sampling.distribution.AhrensDieterMarsagliaTsangGammaSampler; -import org.apache.commons.rng.sampling.distribution.InverseTransformParetoSampler; -import org.apache.commons.rng.sampling.distribution.LogNormalSampler; -import org.apache.commons.rng.sampling.distribution.ContinuousUniformSampler; -import org.apache.commons.rng.sampling.distribution.GaussianSampler; -import org.apache.commons.rng.sampling.distribution.ContinuousSampler; - -/** - * Approximation of the probability density by the histogram of the sampler output. - */ -public class ProbabilityDensityApproximation { - /** Number of (equal-width) bins in the histogram. */ - private final int numBins; - /** Number of samples to be generated. */ - private final long numSamples; - - /** - * Application. - * - * @param numBins Number of "equal-width" bins. - * @param numSamples Number of samples. - */ - private ProbabilityDensityApproximation(int numBins, - long numSamples) { - this.numBins = numBins; - this.numSamples = numSamples; - } - - /** - * @param sampler Sampler. - * @param min Right abscissa of the first bin: every sample smaller - * than that value will increment an additional bin (of infinite width) - * placed before the first "equal-width" bin. - * @param Left abscissa of the last bin: every sample larger than or - * equal to that value will increment an additional bin (of infinite - * width) placed after the last "equal-width" bin. - * @param output Filename. - */ - private void createDensity(ContinuousSampler sampler, - double min, - double max, - String outputFile) - throws IOException { - final double binSize = (max - min) / numBins; - final long[] histogram = new long[numBins]; - - long n = 0; - long belowMin = 0; - long aboveMax = 0; - while (++n < numSamples) { - final double r = sampler.sample(); - - if (r < min) { - ++belowMin; - continue; - } - - if (r >= max) { - ++aboveMax; - continue; - } - - final int binIndex = (int) ((r - min) / binSize); - ++histogram[binIndex]; - } - - final double binHalfSize = 0.5 * binSize; - final double norm = 1 / (binSize * numSamples); - - final PrintWriter out = new PrintWriter(outputFile); - out.println("# Sampler: " + sampler); - out.println("# Number of bins: " + numBins); - out.println("# Min: " + min + " (fraction of samples below: " + (belowMin / (double) numSamples) + ")"); - out.println("# Max: " + max + " (fraction of samples above: " + (aboveMax / (double) numSamples) + ")"); - out.println("# Bin width: " + binSize); - out.println("# Histogram normalization factor: " + norm); - out.println("#"); - out.println("# " + (min - binHalfSize) + " " + (belowMin * norm)); - for (int i = 0; i < numBins; i++) { - out.println((min + (i + 1) * binSize - binHalfSize) + " " + (histogram[i] * norm)); - } - out.println("# " + (max + binHalfSize) + " " + (aboveMax * norm)); - out.close(); - } - - /** - * Program entry point. - * - * @param args Argument. They must be provided, in the following order: - * <ol> - * <li>Number of "equal-width" bins.</li> - * <li>Number of samples.</li> - * </ol> - * @throws IOException if failure occurred while writing to files. - */ - public static void main(String[] args) - throws IOException { - final int numBins = Integer.valueOf(args[0]); - final long numSamples = Long.valueOf(args[1]); - final ProbabilityDensityApproximation app = new ProbabilityDensityApproximation(numBins, numSamples); - - final UniformRandomProvider rng = RandomSource.create(RandomSource.XOR_SHIFT_1024_S); - - final double gaussMean = 1; - final double gaussSigma = 2; - final double gaussMin = -9; - final double gaussMax = 11; - app.createDensity(new GaussianSampler(new ZigguratNormalizedGaussianSampler(rng), - gaussMean, gaussSigma), - gaussMin, gaussMax, "gauss.ziggurat.txt"); - app.createDensity(new GaussianSampler(new MarsagliaNormalizedGaussianSampler(rng), - gaussMean, gaussSigma), - gaussMin, gaussMax, "gauss.marsaglia.txt"); - app.createDensity(new GaussianSampler(new BoxMullerNormalizedGaussianSampler(rng), - gaussMean, gaussSigma), - gaussMin, gaussMax, "gauss.boxmuller.txt"); - - final double alphaBeta = 4.3; - final double betaBeta = 2.1; - final double betaMin = 0; - final double betaMax = 1; - app.createDensity(new ChengBetaSampler(rng, alphaBeta, betaBeta), - betaMin, betaMax, "beta.case1.txt"); - final double alphaBetaAlt = 0.5678; - final double betaBetaAlt = 0.1234; - app.createDensity(new ChengBetaSampler(rng, alphaBetaAlt, betaBetaAlt), - betaMin, betaMax, "beta.case2.txt"); - - final double meanExp = 3.45; - final double expMin = 0; - final double expMax = 60; - app.createDensity(new AhrensDieterExponentialSampler(rng, meanExp), - expMin, expMax, "exp.txt"); - - final double thetaGammaSmallerThanOne = 0.1234; - final double alphaGamma = 3.456; - final double gammaMin = 0; - final double gammaMax1 = 40; - app.createDensity(new AhrensDieterMarsagliaTsangGammaSampler(rng, alphaGamma, thetaGammaSmallerThanOne), - gammaMin, gammaMax1, "gamma.case1.txt"); - final double thetaGammaLargerThanOne = 2.345; - final double gammaMax2 = 70; - app.createDensity(new AhrensDieterMarsagliaTsangGammaSampler(rng, alphaGamma, thetaGammaLargerThanOne), - gammaMin, gammaMax2, "gamma.case2.txt"); - - final double scalePareto = 23.45; - final double shapePareto = 0.789; - final double paretoMin = 23; - final double paretoMax = 400; - app.createDensity(new InverseTransformParetoSampler(rng, scalePareto, shapePareto), - paretoMin, paretoMax, "pareto.txt"); - - final double loUniform = -9.876; - final double hiUniform = 5.432; - app.createDensity(new ContinuousUniformSampler(rng, loUniform, hiUniform), - loUniform, hiUniform, "uniform.txt"); - - final double scaleLogNormal = 2.345; - final double shapeLogNormal = 0.1234; - final double logNormalMin = 5; - final double logNormalMax = 25; - app.createDensity(new LogNormalSampler(new ZigguratNormalizedGaussianSampler(rng), - scaleLogNormal, shapeLogNormal), - logNormalMin, logNormalMax, "lognormal.ziggurat.txt"); - app.createDensity(new LogNormalSampler(new MarsagliaNormalizedGaussianSampler(rng), - scaleLogNormal, shapeLogNormal), - logNormalMin, logNormalMax, "lognormal.marsaglia.txt"); - app.createDensity(new LogNormalSampler(new BoxMullerNormalizedGaussianSampler(rng), - scaleLogNormal, shapeLogNormal), - logNormalMin, logNormalMax, "lognormal.boxmuller.txt"); - } -} http://git-wip-us.apache.org/repos/asf/commons-rng/blob/2fdb5227/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/sampling/UniformSamplingVisualCheck.java ---------------------------------------------------------------------- diff --git a/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/sampling/UniformSamplingVisualCheck.java b/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/sampling/UniformSamplingVisualCheck.java deleted file mode 100644 index b7c901c..0000000 --- a/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/sampling/UniformSamplingVisualCheck.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * 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 org.apache.commons.rng.sampling.distribution.ZigguratNormalizedGaussianSampler; -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 artefacts - * 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). - */ -public class UniformSamplingVisualCheck { - /** RNG. */ - private final UniformRandomProvider rng = RandomSource.create(RandomSource.XOR_SHIFT_1024_S); - /** Samplers. */ - private final ContinuousSampler[] samplers = new ContinuousSampler[] { - new ZigguratNormalizedGaussianSampler(rng), - new MarsagliaNormalizedGaussianSampler(rng), - new BoxMullerNormalizedGaussianSampler(rng), - }; - - /** - * Program entry point. - * - * @param args Unused. - */ - public static void main(String[] args) { - final float lo = 0.1f; - final int bands = 2; - float hi = lo; - for (int i = 0; i < bands; i++) { - hi = Math.nextUp(hi); - } - System.out.printf("# lo=%.10e hi=%.10e", lo, hi); - System.out.println(); - - final UniformSamplingVisualCheck app = new UniformSamplingVisualCheck(); - - while (true) { - System.out.printf("%.16e\t", app.rng.nextDouble()); - - for (ContinuousSampler s : app.samplers) { - while (true) { - final double r = s.sample(); - if (r < lo || - r > hi) { - // Discard numbers outside the tiny region. - continue; - } - - System.out.printf("%.16e ", r); - break; - } - } - - System.out.println(); - } - } -} http://git-wip-us.apache.org/repos/asf/commons-rng/blob/2fdb5227/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/sampling/package-info.java ---------------------------------------------------------------------- diff --git a/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/sampling/package-info.java b/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/sampling/package-info.java deleted file mode 100644 index 8f7a268..0000000 --- a/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/sampling/package-info.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * 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. - */ - -/** - * <h3>Sampling</h3> - * - * <p> - * This package contains usage examples of the samplers provided in the - * <a href="http://commons.apache.org/rng">Commons RNG</a> library. - * </p> - */ - -package org.apache.commons.rng.examples.sampling; http://git-wip-us.apache.org/repos/asf/commons-rng/blob/2fdb5227/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/stress/GeneratorsList.java ---------------------------------------------------------------------- diff --git a/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/stress/GeneratorsList.java b/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/stress/GeneratorsList.java deleted file mode 100644 index 037f60b..0000000 --- a/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/stress/GeneratorsList.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * 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.util.List; -import java.util.ArrayList; -import java.util.Iterator; - -import org.apache.commons.rng.UniformRandomProvider; -import org.apache.commons.rng.simple.RandomSource; - -/** - * List of generators. - */ -public class GeneratorsList implements Iterable<UniformRandomProvider> { - /** List. */ - private final List<UniformRandomProvider> list = new ArrayList<UniformRandomProvider>(); - - /** - * Creates list. - */ - public GeneratorsList() { - list.add(RandomSource.create(RandomSource.JDK)); - list.add(RandomSource.create(RandomSource.MT)); - list.add(RandomSource.create(RandomSource.WELL_512_A)); - list.add(RandomSource.create(RandomSource.WELL_1024_A)); - list.add(RandomSource.create(RandomSource.WELL_19937_A)); - list.add(RandomSource.create(RandomSource.WELL_19937_C)); - list.add(RandomSource.create(RandomSource.WELL_44497_A)); - list.add(RandomSource.create(RandomSource.WELL_44497_B)); - list.add(RandomSource.create(RandomSource.ISAAC)); - list.add(RandomSource.create(RandomSource.MT_64)); - list.add(RandomSource.create(RandomSource.SPLIT_MIX_64)); - list.add(RandomSource.create(RandomSource.XOR_SHIFT_1024_S)); - list.add(RandomSource.create(RandomSource.TWO_CMRES)); - list.add(RandomSource.create(RandomSource.MWC_256)); - list.add(RandomSource.create(RandomSource.KISS)); - } - - /** {@inheritDoc} */ - @Override - public Iterator<UniformRandomProvider> iterator() { - return list.iterator(); - } -} http://git-wip-us.apache.org/repos/asf/commons-rng/blob/2fdb5227/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/stress/RandomStressTester.java ---------------------------------------------------------------------- diff --git a/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/stress/RandomStressTester.java b/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/stress/RandomStressTester.java deleted file mode 100644 index 1cad0dd..0000000 --- a/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/stress/RandomStressTester.java +++ /dev/null @@ -1,292 +0,0 @@ -/* - * 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.util.List; -import java.util.ArrayList; -import java.util.Arrays; -import java.io.IOException; -import java.io.File; -import java.io.PrintWriter; -import java.io.FileWriter; -import java.io.DataOutputStream; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; - -import org.apache.commons.rng.UniformRandomProvider; - -/** - * Class that can be used for testing a 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. - * - * The <a href="http://www.phy.duke.edu/~rgb/General/dieharder.php"> - * "dieharder"</a> test suite is such a software. - * - * Example of command line, assuming that "examples.jar" specifies this - * class as the "main" class (see {@link #main(String[]) main} method): - * <pre><code> - * $ java -jar examples.jar \ - * report/dh_ \ - * 4 \ - * org.apache.commons.rng.examples.stress.GeneratorsList \ - * /usr/bin/dieharder -a -g 200 -Y 1 -k 2 - * </code></pre> - */ -public class RandomStressTester { - /** Comment prefix. */ - private static final String C = "# "; - /** New line. */ - private static final String N = "\n"; - /** Command line. */ - private final List<String> cmdLine; - /** Output prefix. */ - private final String fileOutputPrefix; - - /** - * Creates the application. - * - * @param cmd Command line. - * @param outputPrefix Output prefix for file reports. - */ - private RandomStressTester(List<String> cmd, - String outputPrefix) { - final File exec = new File(cmd.get(0)); - if (!exec.exists() || - !exec.canExecute()) { - throw new IllegalArgumentException("Program is not executable: " + exec); - } - - cmdLine = new ArrayList<String>(cmd); - fileOutputPrefix = outputPrefix; - - final File reportDir = new File(fileOutputPrefix).getParentFile(); - if (!reportDir.exists() || - !reportDir.isDirectory() || - !reportDir.canWrite()) { - throw new IllegalArgumentException("Invalid output directory: " + reportDir); - } - } - - /** - * Program's entry point. - * - * @param args Application's arguments. - * The order is as follows: - * <ol> - * <li>Output prefix: Filename prefix where the output of the analysis will - * written to. The appended suffix is the index of the instance within the - * list of generators to be tested.</li> - * <li>Number of threads to use concurrently: One thread will process one of - * the generators to be tested.</li> - * <li>Name of a class that implements {@code Iterable<UniformRandomProvider>} - * (and defines a default constructor): Each generator of the list will be - * tested by one instance of the analyzer program</li> - * <li>Path to the executable: this is the analyzer software that reads 32-bits - * integers from stdin.</li> - * <li>All remaining arguments are passed to the executable.</li> - * </ol> - */ - public static void main(String[] args) { - final String output = args[0]; - final int numThreads = Integer.parseInt(args[1]); - - final Iterable<UniformRandomProvider> rngList = createGeneratorsList(args[2]); - - final List<String> cmdLine = new ArrayList<String>(); - cmdLine.addAll(Arrays.asList(Arrays.copyOfRange(args, 3, args.length))); - - final RandomStressTester app = new RandomStressTester(cmdLine, output); - - try { - app.run(rngList, numThreads); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - /** - * Creates the tasks and starts the processes. - * - * @param generators List of generators to be analyzed. - * @param numConcurrentTasks Number of concurrent tasks. - * Twice as many threads will be started: one thread for the RNG and one - * for the analyzer. - * @throws IOException if an error occurs when writing to the disk. - */ - private void run(Iterable<UniformRandomProvider> generators, - int numConcurrentTasks) - throws IOException { - // Parallel execution. - final ExecutorService service = Executors.newFixedThreadPool(numConcurrentTasks); - - // Placeholder (output will be "null"). - final List<Future<?>> execOutput = new ArrayList<Future<?>>(); - - // Run tasks. - int count = 0; - for (UniformRandomProvider rng : generators) { - final File output = new File(fileOutputPrefix + (++count)); - final Runnable r = new Task(rng, output); - execOutput.add(service.submit(r)); - } - - // Wait for completion (ignoring return value). - try { - for (Future<?> f : execOutput) { - try { - f.get(); - } catch (ExecutionException e) { - System.err.println(e.getCause().getMessage()); - } - } - } catch (InterruptedException ignored) {} - - // Terminate all threads. - service.shutdown(); - } - - /** - * Creates the list of generators to be tested. - * - * @param name Name of the class that contains the generators to be - * analyzed. - * @return the list of generators. - * @throws IllegalStateException if an error occurs during instantiation. - */ - private static Iterable<UniformRandomProvider> createGeneratorsList(String name) { - try { - return (Iterable<UniformRandomProvider>) Class.forName(name).newInstance(); - } catch (ClassNotFoundException| - InstantiationException| - IllegalAccessException e) { - throw new RuntimeException(e); - } - } - - /** - * Pipes random numbers to the standard input of an analyzer. - */ - private class Task implements Runnable { - /** Directory for reports of the tester processes. */ - private final File output; - /** RNG to be tested. */ - private final UniformRandomProvider rng; - - /** - * Creates the task. - * - * @param random RNG to be tested. - * @param report Report file. - */ - Task(UniformRandomProvider random, - File report) { - rng = random; - output = report; - } - - /** {@inheritDoc} */ - @Override - public void run() { - try { - // Write header. - printHeader(output, rng); - - // Start test suite. - final ProcessBuilder builder = new ProcessBuilder(cmdLine); - builder.redirectOutput(ProcessBuilder.Redirect.appendTo(output)); - final Process testingProcess = builder.start(); - final DataOutputStream sink = new DataOutputStream(testingProcess.getOutputStream()); - - final long startTime = System.nanoTime(); - - try { - while (true) { - sink.writeInt(rng.nextInt()); - } - } catch (IOException e) { - // Hopefully getting here when the analyzing software terminates. - } - - final long endTime = System.nanoTime(); - - // Write footer. - printFooter(output, endTime - startTime); - - } catch (IOException e) { - throw new RuntimeException("Failed to start task: " + e.getMessage()); - } - } - } - - /** - * @param output File. - * @param rng Generator being tested. - * @param cmdLine - * @throws IOException if there was a problem opening or writing to - * the {@code output} file. - */ - private void printHeader(File output, - UniformRandomProvider rng) - throws IOException { - final StringBuilder sb = new StringBuilder(); - sb.append(C).append(N); - sb.append(C).append("RNG: ").append(rng.toString()).append(N); - sb.append(C).append(N); - sb.append(C).append("Java: ").append(System.getProperty("java.version")).append(N); - sb.append(C).append("Runtime: ").append(System.getProperty("java.runtime.version", "?")).append(N); - sb.append(C).append("JVM: ").append(System.getProperty("java.vm.name")) - .append(" ").append(System.getProperty("java.vm.version")).append(N); - sb.append(C).append("OS: ").append(System.getProperty("os.name")) - .append(" ").append(System.getProperty("os.version")) - .append(" ").append(System.getProperty("os.arch")).append(N); - sb.append(C).append(N); - - sb.append(C).append("Analyzer: "); - for (String s : cmdLine) { - sb.append(s).append(" "); - } - sb.append(N); - sb.append(C).append(N); - - final PrintWriter w = new PrintWriter(new FileWriter(output, true)); - w.print(sb.toString()); - w.close(); - } - - /** - * @param output File. - * @param nanoTime Duration of the run. - * @throws IOException if there was a problem opening or writing to - * the {@code output} file. - */ - private void printFooter(File output, - long nanoTime) - throws IOException { - final PrintWriter w = new PrintWriter(new FileWriter(output, true)); - w.println(C); - - final double duration = ((double) nanoTime) * 1e-9 / 60; - w.println(C + "Test duration: " + duration + " minutes"); - - w.println(C); - w.close(); - } -} http://git-wip-us.apache.org/repos/asf/commons-rng/blob/2fdb5227/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/stress/package-info.java ---------------------------------------------------------------------- diff --git a/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/stress/package-info.java b/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/stress/package-info.java deleted file mode 100644 index 5b59e08..0000000 --- a/commons-rng-examples/src/main/java/org/apache/commons/rng/examples/stress/package-info.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * 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. - */ - -/** - * <h3>Stress test application</h3> - * - * <p> - * 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. - * </p> - */ - -package org.apache.commons.rng.examples.stress;