Refactored code contents of module "commons-rng-examples" into sub-modules.
Module "commons-rng-examples" hosts codes that are not part of the library, but are provided as usage examples, or documentation tools. Project: http://git-wip-us.apache.org/repos/asf/commons-rng/repo Commit: http://git-wip-us.apache.org/repos/asf/commons-rng/commit/2fdb5227 Tree: http://git-wip-us.apache.org/repos/asf/commons-rng/tree/2fdb5227 Diff: http://git-wip-us.apache.org/repos/asf/commons-rng/diff/2fdb5227 Branch: refs/heads/master Commit: 2fdb5227f2d3dcf3ead63dcc369b96447c7a0316 Parents: 5364938 Author: Gilles <er...@apache.org> Authored: Tue Feb 13 19:26:25 2018 +0100 Committer: Gilles <er...@apache.org> Committed: Tue Feb 13 19:26:25 2018 +0100 ---------------------------------------------------------------------- .../examples-quadrature/LICENSE.txt | 275 +++++++++++++++++ .../examples-quadrature/NOTICE.txt | 5 + .../examples-quadrature/pom.xml | 62 ++++ .../rng/examples/quadrature/ComputePi.java | 91 ++++++ .../quadrature/MonteCarloIntegration.java | 90 ++++++ .../rng/examples/quadrature/package-info.java | 27 ++ .../examples-sampling/LICENSE.txt | 275 +++++++++++++++++ .../examples-sampling/NOTICE.txt | 5 + commons-rng-examples/examples-sampling/pom.xml | 62 ++++ .../ProbabilityDensityApproximation.java | 200 +++++++++++++ .../sampling/UniformSamplingVisualCheck.java | 81 +++++ .../rng/examples/sampling/package-info.java | 27 ++ .../examples-stress/LICENSE.txt | 275 +++++++++++++++++ commons-rng-examples/examples-stress/NOTICE.txt | 5 + commons-rng-examples/examples-stress/pom.xml | 62 ++++ .../examples-stress/src/main/c/stdin2testu01.c | 127 ++++++++ .../rng/examples/stress/GeneratorsList.java | 59 ++++ .../rng/examples/stress/RandomStressTester.java | 292 +++++++++++++++++++ .../rng/examples/stress/package-info.java | 28 ++ commons-rng-examples/pom.xml | 32 +- commons-rng-examples/src/main/c/stdin2testu01.c | 127 -------- .../rng/examples/integration/ComputePi.java | 91 ------ .../integration/MonteCarloIntegration.java | 90 ------ .../rng/examples/integration/package-info.java | 27 -- .../commons/rng/examples/package-info.java | 26 -- .../ProbabilityDensityApproximation.java | 200 ------------- .../sampling/UniformSamplingVisualCheck.java | 81 ----- .../rng/examples/sampling/package-info.java | 27 -- .../rng/examples/stress/GeneratorsList.java | 59 ---- .../rng/examples/stress/RandomStressTester.java | 292 ------------------- .../rng/examples/stress/package-info.java | 28 -- 31 files changed, 2068 insertions(+), 1060 deletions(-) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/commons-rng/blob/2fdb5227/commons-rng-examples/examples-quadrature/LICENSE.txt ---------------------------------------------------------------------- diff --git a/commons-rng-examples/examples-quadrature/LICENSE.txt b/commons-rng-examples/examples-quadrature/LICENSE.txt new file mode 100644 index 0000000..de777e4 --- /dev/null +++ b/commons-rng-examples/examples-quadrature/LICENSE.txt @@ -0,0 +1,275 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed 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. + +================================================================================ + +Class "org.apache.commons.rng.internal.source64.MersenneTwister64" contains +Java code partly ported from the reference implementation in C. +That source file contained the following notice: + + Copyright (C) 2004, Makoto Matsumoto and Takuji Nishimura, + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. The names of its contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +================================================================================ + +Class "org.apache.commons.rng.internal.source32.MersenneTwister" contains +Java code partly ported from the reference implementation in C. +That source file contained the following notice: + + Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. The names of its contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +================================================================================ http://git-wip-us.apache.org/repos/asf/commons-rng/blob/2fdb5227/commons-rng-examples/examples-quadrature/NOTICE.txt ---------------------------------------------------------------------- diff --git a/commons-rng-examples/examples-quadrature/NOTICE.txt b/commons-rng-examples/examples-quadrature/NOTICE.txt new file mode 100644 index 0000000..b2eab86 --- /dev/null +++ b/commons-rng-examples/examples-quadrature/NOTICE.txt @@ -0,0 +1,5 @@ +Apache Commons RNG +Copyright 2016-2018 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). http://git-wip-us.apache.org/repos/asf/commons-rng/blob/2fdb5227/commons-rng-examples/examples-quadrature/pom.xml ---------------------------------------------------------------------- diff --git a/commons-rng-examples/examples-quadrature/pom.xml b/commons-rng-examples/examples-quadrature/pom.xml new file mode 100644 index 0000000..3e916ab --- /dev/null +++ b/commons-rng-examples/examples-quadrature/pom.xml @@ -0,0 +1,62 @@ +<?xml version="1.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. +--> +<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" + xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.apache.commons</groupId> + <artifactId>commons-rng-examples</artifactId> + <version>1.1-SNAPSHOT</version> + </parent> + + <groupId>org.apache.commons</groupId> + <artifactId>commons-rng-examples-quadrature</artifactId> + <version>1.1-SNAPSHOT</version> + <name>Apache Commons RNG Quadrature Test Example</name> + + <description>Application for calling external tools that perform stringent uniformity tests. + Code in this module is not part of the public API.</description> + + <properties> + <maven.compiler.source>1.7</maven.compiler.source> + <maven.compiler.target>1.7</maven.compiler.target> + + <!-- OSGi --> + <commons.osgi.symbolicName>org.apache.commons.rng.examples.quadrature</commons.osgi.symbolicName> + <commons.osgi.export>org.apache.commons.rng.examples.quadrature</commons.osgi.export> + <!-- Java 9+ --> + <commons.automatic.module.name>org.apache.commons.rng.examples.quadrature</commons.automatic.module.name> + <!-- Workaround to avoid duplicating config files. --> + <rng.parent.dir>${basedir}/../..</rng.parent.dir> + </properties> + + <dependencies> + <dependency> + <groupId>org.apache.commons</groupId> + <artifactId>commons-rng-simple</artifactId> + </dependency> + + <dependency> + <groupId>org.apache.commons</groupId> + <artifactId>commons-rng-sampling</artifactId> + </dependency> + </dependencies> + +</project> http://git-wip-us.apache.org/repos/asf/commons-rng/blob/2fdb5227/commons-rng-examples/examples-quadrature/src/main/java/org/apache/commons/rng/examples/quadrature/ComputePi.java ---------------------------------------------------------------------- diff --git a/commons-rng-examples/examples-quadrature/src/main/java/org/apache/commons/rng/examples/quadrature/ComputePi.java b/commons-rng-examples/examples-quadrature/src/main/java/org/apache/commons/rng/examples/quadrature/ComputePi.java new file mode 100644 index 0000000..5e959da --- /dev/null +++ b/commons-rng-examples/examples-quadrature/src/main/java/org/apache/commons/rng/examples/quadrature/ComputePi.java @@ -0,0 +1,91 @@ +/* + * 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.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/examples-quadrature/src/main/java/org/apache/commons/rng/examples/quadrature/MonteCarloIntegration.java ---------------------------------------------------------------------- diff --git a/commons-rng-examples/examples-quadrature/src/main/java/org/apache/commons/rng/examples/quadrature/MonteCarloIntegration.java b/commons-rng-examples/examples-quadrature/src/main/java/org/apache/commons/rng/examples/quadrature/MonteCarloIntegration.java new file mode 100644 index 0000000..d15a5be --- /dev/null +++ b/commons-rng-examples/examples-quadrature/src/main/java/org/apache/commons/rng/examples/quadrature/MonteCarloIntegration.java @@ -0,0 +1,90 @@ +/* + * 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; + +/** + * <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/examples-quadrature/src/main/java/org/apache/commons/rng/examples/quadrature/package-info.java ---------------------------------------------------------------------- diff --git a/commons-rng-examples/examples-quadrature/src/main/java/org/apache/commons/rng/examples/quadrature/package-info.java b/commons-rng-examples/examples-quadrature/src/main/java/org/apache/commons/rng/examples/quadrature/package-info.java new file mode 100644 index 0000000..ac1719d --- /dev/null +++ b/commons-rng-examples/examples-quadrature/src/main/java/org/apache/commons/rng/examples/quadrature/package-info.java @@ -0,0 +1,27 @@ +/* + * 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.quadrature; http://git-wip-us.apache.org/repos/asf/commons-rng/blob/2fdb5227/commons-rng-examples/examples-sampling/LICENSE.txt ---------------------------------------------------------------------- diff --git a/commons-rng-examples/examples-sampling/LICENSE.txt b/commons-rng-examples/examples-sampling/LICENSE.txt new file mode 100644 index 0000000..de777e4 --- /dev/null +++ b/commons-rng-examples/examples-sampling/LICENSE.txt @@ -0,0 +1,275 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed 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. + +================================================================================ + +Class "org.apache.commons.rng.internal.source64.MersenneTwister64" contains +Java code partly ported from the reference implementation in C. +That source file contained the following notice: + + Copyright (C) 2004, Makoto Matsumoto and Takuji Nishimura, + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. The names of its contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +================================================================================ + +Class "org.apache.commons.rng.internal.source32.MersenneTwister" contains +Java code partly ported from the reference implementation in C. +That source file contained the following notice: + + Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. The names of its contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +================================================================================ http://git-wip-us.apache.org/repos/asf/commons-rng/blob/2fdb5227/commons-rng-examples/examples-sampling/NOTICE.txt ---------------------------------------------------------------------- diff --git a/commons-rng-examples/examples-sampling/NOTICE.txt b/commons-rng-examples/examples-sampling/NOTICE.txt new file mode 100644 index 0000000..b2eab86 --- /dev/null +++ b/commons-rng-examples/examples-sampling/NOTICE.txt @@ -0,0 +1,5 @@ +Apache Commons RNG +Copyright 2016-2018 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). http://git-wip-us.apache.org/repos/asf/commons-rng/blob/2fdb5227/commons-rng-examples/examples-sampling/pom.xml ---------------------------------------------------------------------- diff --git a/commons-rng-examples/examples-sampling/pom.xml b/commons-rng-examples/examples-sampling/pom.xml new file mode 100644 index 0000000..490211d --- /dev/null +++ b/commons-rng-examples/examples-sampling/pom.xml @@ -0,0 +1,62 @@ +<?xml version="1.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. +--> +<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" + xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.apache.commons</groupId> + <artifactId>commons-rng-examples</artifactId> + <version>1.1-SNAPSHOT</version> + </parent> + + <groupId>org.apache.commons</groupId> + <artifactId>commons-rng-examples-sampling</artifactId> + <version>1.1-SNAPSHOT</version> + <name>Apache Commons RNG Sampling Test Example</name> + + <description>Application for calling external tools that perform stringent uniformity tests. + Code in this module is not part of the public API.</description> + + <properties> + <maven.compiler.source>1.7</maven.compiler.source> + <maven.compiler.target>1.7</maven.compiler.target> + + <!-- OSGi --> + <commons.osgi.symbolicName>org.apache.commons.rng.examples.sampling</commons.osgi.symbolicName> + <commons.osgi.export>org.apache.commons.rng.examples.sampling</commons.osgi.export> + <!-- Java 9+ --> + <commons.automatic.module.name>org.apache.commons.rng.examples.sampling</commons.automatic.module.name> + <!-- Workaround to avoid duplicating config files. --> + <rng.parent.dir>${basedir}/../..</rng.parent.dir> + </properties> + + <dependencies> + <dependency> + <groupId>org.apache.commons</groupId> + <artifactId>commons-rng-simple</artifactId> + </dependency> + + <dependency> + <groupId>org.apache.commons</groupId> + <artifactId>commons-rng-sampling</artifactId> + </dependency> + </dependencies> + +</project> http://git-wip-us.apache.org/repos/asf/commons-rng/blob/2fdb5227/commons-rng-examples/examples-sampling/src/main/java/org/apache/commons/rng/examples/sampling/ProbabilityDensityApproximation.java ---------------------------------------------------------------------- diff --git a/commons-rng-examples/examples-sampling/src/main/java/org/apache/commons/rng/examples/sampling/ProbabilityDensityApproximation.java b/commons-rng-examples/examples-sampling/src/main/java/org/apache/commons/rng/examples/sampling/ProbabilityDensityApproximation.java new file mode 100644 index 0000000..3fa5ace --- /dev/null +++ b/commons-rng-examples/examples-sampling/src/main/java/org/apache/commons/rng/examples/sampling/ProbabilityDensityApproximation.java @@ -0,0 +1,200 @@ +/* + * 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/examples-sampling/src/main/java/org/apache/commons/rng/examples/sampling/UniformSamplingVisualCheck.java ---------------------------------------------------------------------- diff --git a/commons-rng-examples/examples-sampling/src/main/java/org/apache/commons/rng/examples/sampling/UniformSamplingVisualCheck.java b/commons-rng-examples/examples-sampling/src/main/java/org/apache/commons/rng/examples/sampling/UniformSamplingVisualCheck.java new file mode 100644 index 0000000..b7c901c --- /dev/null +++ b/commons-rng-examples/examples-sampling/src/main/java/org/apache/commons/rng/examples/sampling/UniformSamplingVisualCheck.java @@ -0,0 +1,81 @@ +/* + * 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/examples-sampling/src/main/java/org/apache/commons/rng/examples/sampling/package-info.java ---------------------------------------------------------------------- diff --git a/commons-rng-examples/examples-sampling/src/main/java/org/apache/commons/rng/examples/sampling/package-info.java b/commons-rng-examples/examples-sampling/src/main/java/org/apache/commons/rng/examples/sampling/package-info.java new file mode 100644 index 0000000..8f7a268 --- /dev/null +++ b/commons-rng-examples/examples-sampling/src/main/java/org/apache/commons/rng/examples/sampling/package-info.java @@ -0,0 +1,27 @@ +/* + * 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/examples-stress/LICENSE.txt ---------------------------------------------------------------------- diff --git a/commons-rng-examples/examples-stress/LICENSE.txt b/commons-rng-examples/examples-stress/LICENSE.txt new file mode 100644 index 0000000..de777e4 --- /dev/null +++ b/commons-rng-examples/examples-stress/LICENSE.txt @@ -0,0 +1,275 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed 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. + +================================================================================ + +Class "org.apache.commons.rng.internal.source64.MersenneTwister64" contains +Java code partly ported from the reference implementation in C. +That source file contained the following notice: + + Copyright (C) 2004, Makoto Matsumoto and Takuji Nishimura, + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. The names of its contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +================================================================================ + +Class "org.apache.commons.rng.internal.source32.MersenneTwister" contains +Java code partly ported from the reference implementation in C. +That source file contained the following notice: + + Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. The names of its contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +================================================================================ http://git-wip-us.apache.org/repos/asf/commons-rng/blob/2fdb5227/commons-rng-examples/examples-stress/NOTICE.txt ---------------------------------------------------------------------- diff --git a/commons-rng-examples/examples-stress/NOTICE.txt b/commons-rng-examples/examples-stress/NOTICE.txt new file mode 100644 index 0000000..b2eab86 --- /dev/null +++ b/commons-rng-examples/examples-stress/NOTICE.txt @@ -0,0 +1,5 @@ +Apache Commons RNG +Copyright 2016-2018 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). http://git-wip-us.apache.org/repos/asf/commons-rng/blob/2fdb5227/commons-rng-examples/examples-stress/pom.xml ---------------------------------------------------------------------- diff --git a/commons-rng-examples/examples-stress/pom.xml b/commons-rng-examples/examples-stress/pom.xml new file mode 100644 index 0000000..9f2c9c9 --- /dev/null +++ b/commons-rng-examples/examples-stress/pom.xml @@ -0,0 +1,62 @@ +<?xml version="1.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. +--> +<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" + xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.apache.commons</groupId> + <artifactId>commons-rng-examples</artifactId> + <version>1.1-SNAPSHOT</version> + </parent> + + <groupId>org.apache.commons</groupId> + <artifactId>commons-rng-examples-stress</artifactId> + <version>1.1-SNAPSHOT</version> + <name>Apache Commons RNG Stress Test Example</name> + + <description>Application for calling external tools that perform stringent uniformity tests. + Code in this module is not part of the public API.</description> + + <properties> + <maven.compiler.source>1.7</maven.compiler.source> + <maven.compiler.target>1.7</maven.compiler.target> + + <!-- OSGi --> + <commons.osgi.symbolicName>org.apache.commons.rng.examples.stress</commons.osgi.symbolicName> + <commons.osgi.export>org.apache.commons.rng.examples.stress</commons.osgi.export> + <!-- Java 9+ --> + <commons.automatic.module.name>org.apache.commons.rng.examples.stress</commons.automatic.module.name> + <!-- Workaround to avoid duplicating config files. --> + <rng.parent.dir>${basedir}/../..</rng.parent.dir> + </properties> + + <dependencies> + <dependency> + <groupId>org.apache.commons</groupId> + <artifactId>commons-rng-simple</artifactId> + </dependency> + + <dependency> + <groupId>org.apache.commons</groupId> + <artifactId>commons-rng-sampling</artifactId> + </dependency> + </dependencies> + +</project>