You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by ah...@apache.org on 2019/02/14 13:59:23 UTC
[commons-rng] branch master updated (c547833 -> 8e1c529)
This is an automated email from the ASF dual-hosted git repository.
aherbert pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/commons-rng.git.
from c547833 Fixed test coverage in MersenneTwister64Test
new edcdf9a RNG-69: Added a Geometric sampler
new 77cfd26 RNG-69: Updated code formatting and GeometricSampler javadoc
new e18e0fb Merge branch 'improvement-RNG-69' of https://github.com/aherbert/commons-rng into improvement-RNG-69
new 2b24bf7 Formatted code and javadoc
new 1a93589 Track changes
new 9fcc3c8 Merge branch 'improvement-RNG-69'
new 9f54e57 RNG-67: Instructions for how to build and run the examples-stress code
new 25467f5 Merge branch 'improvement-RNG-67' of https://github.com/aherbert/commons-rng into improvement-RNG-67
new d301d58 Track changes
new 6e7e5f4 Merge branch 'improvement-RNG-67'
new ad8739b RNG-68: Add private classes for each algorithm
new 251dc2e RNG-68: Fixed formatting
new b7b40cf Merge branch 'improvement-RNG-68' of https://github.com/aherbert/commons-rng into improvement-RNG-68
new e8ca1f6 Track changes.
new 1afd499 Merge branch 'improvement-RNG-68'
new 26cfa30 Updated checkstyle to use the latest checkstyle version (8.17)
new 8e1c529 Fixed checkstyle violation
The 17 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
.../distribution/GeometricSamplersPerformance.java | 191 +++++++++++++++++++++
.../jmh/distribution/SamplersPerformance.java | 19 +-
commons-rng-examples/examples-stress/pom.xml | 45 +++++
.../rng/examples/stress/IntGeneratorsList.java | 41 +++--
.../rng/examples/stress/LongGeneratorsList.java | 41 +++--
.../examples-stress/stress_test.md | 76 ++++++++
.../AhrensDieterMarsagliaTsangGammaSampler.java | 174 +++++++++++++------
.../sampling/distribution/GeometricSampler.java | 150 ++++++++++++++++
.../distribution/DiscreteSamplersList.java | 4 +
.../distribution/GeometricSamplerTest.java | 94 ++++++++++
pom.xml | 120 +++++++------
src/changes/changes.xml | 12 +-
src/main/resources/checkstyle/checkstyle.xml | 60 ++-----
13 files changed, 825 insertions(+), 202 deletions(-)
create mode 100644 commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/distribution/GeometricSamplersPerformance.java
copy commons-rng-simple/src/main/java/org/apache/commons/rng/simple/internal/Long2LongArray.java => commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/IntGeneratorsList.java (53%)
copy commons-rng-simple/src/main/java/org/apache/commons/rng/simple/internal/Long2LongArray.java => commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/LongGeneratorsList.java (53%)
create mode 100644 commons-rng-examples/examples-stress/stress_test.md
create mode 100644 commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/GeometricSampler.java
create mode 100644 commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/GeometricSamplerTest.java
[commons-rng] 07/17: Formatted code and javadoc
Posted by ah...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
aherbert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-rng.git
commit 2b24bf79a3bb119cb0389771971b32e2a5a796e4
Author: aherbert <ah...@apache.org>
AuthorDate: Thu Feb 14 12:26:03 2019 +0000
Formatted code and javadoc
---
.../distribution/GeometricSamplersPerformance.java | 5 ++--
.../sampling/distribution/GeometricSampler.java | 14 +++++----
.../distribution/GeometricSamplerTest.java | 33 ++++++++++++----------
3 files changed, 29 insertions(+), 23 deletions(-)
diff --git a/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/distribution/GeometricSamplersPerformance.java b/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/distribution/GeometricSamplersPerformance.java
index 60e86ad..bf3cdf9 100644
--- a/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/distribution/GeometricSamplersPerformance.java
+++ b/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/distribution/GeometricSamplersPerformance.java
@@ -134,8 +134,9 @@ public class GeometricSamplersPerformance {
// ---
// Note: if cumulativeProbability == 0 then log1p(-0) is zero and the result
// after the range check is 0.
- // Note: if cumulativeProbability == 1 then log1p(-1) is negative infinity, the result of
- // the divide is positive infinity and the result after the range check is Integer.MAX_VALUE.
+ // Note: if cumulativeProbability == 1 then log1p(-1) is negative infinity, the result
+ // of the divide is positive infinity and the result after the range check is
+ // Integer.MAX_VALUE.
return Math.max(0, (int) Math.ceil(Math.log1p(-cumulativeProbability) / log1mProbabilityOfSuccess - 1));
}
}
diff --git a/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/GeometricSampler.java b/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/GeometricSampler.java
index ba62ac4..2197d4c 100644
--- a/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/GeometricSampler.java
+++ b/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/GeometricSampler.java
@@ -78,7 +78,8 @@ public class GeometricSampler implements DiscreteSampler {
/**
* @param rng Generator of uniformly distributed random numbers
- * @param probabilityOfSuccess The probability of success (must be {@code 0<p<1})
+ * @param probabilityOfSuccess The probability of success (must be in the range
+ * {@code [0 < probabilityOfSuccess < 1]})
*/
GeometricExponentialSampler(UniformRandomProvider rng, double probabilityOfSuccess) {
this.rng = rng;
@@ -116,13 +117,14 @@ public class GeometricSampler implements DiscreteSampler {
*
* @param rng Generator of uniformly distributed random numbers
* @param probabilityOfSuccess The probability of success
- * @throws IllegalArgumentException if {@code probabilityOfSuccess} is not in the range [0 <
- * probabilityOfSuccess <= 1]
+ * @throws IllegalArgumentException if {@code probabilityOfSuccess} is not in the range
+ * {@code [0 < probabilityOfSuccess <= 1]})
*/
public GeometricSampler(UniformRandomProvider rng, double probabilityOfSuccess) {
if (probabilityOfSuccess <= 0 || probabilityOfSuccess > 1) {
throw new IllegalArgumentException(
- "Probability of success must be in the range [0 < p <= 1]: " + probabilityOfSuccess);
+ "Probability of success (p) must be in the range [0 < p <= 1]: "
+ + probabilityOfSuccess);
}
delegate = probabilityOfSuccess == 1 ?
GeometricP1Sampler.INSTANCE :
@@ -132,8 +134,8 @@ public class GeometricSampler implements DiscreteSampler {
/**
* Create a sample from a geometric distribution.
*
- * <p>The sample will take the values in the set {@code [0, 1, 2, ...]}, equivalent to the number of
- * failures before the first success.
+ * <p>The sample will take the values in the set {@code [0, 1, 2, ...]}, equivalent to the
+ * number of failures before the first success.
*/
@Override
public int sample() {
diff --git a/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/GeometricSamplerTest.java b/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/GeometricSamplerTest.java
index 00f1000..c3267bf 100644
--- a/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/GeometricSamplerTest.java
+++ b/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/GeometricSamplerTest.java
@@ -17,6 +17,7 @@
package org.apache.commons.rng.sampling.distribution;
import org.apache.commons.rng.UniformRandomProvider;
+import org.apache.commons.rng.core.source64.SplitMix64;
import org.apache.commons.rng.simple.RandomSource;
import org.junit.Assert;
import org.junit.Test;
@@ -26,8 +27,8 @@ import org.junit.Test;
*/
public class GeometricSamplerTest {
/**
- * Test the edge case where the probability of success is 1. This is a valid geometric distribution
- * where the sample should always be 0.
+ * Test the edge case where the probability of success is 1. This is a valid geometric
+ * distribution where the sample should always be 0.
*/
@Test
public void testProbabilityOfSuccessIsOneGeneratesZeroForSamples() {
@@ -45,18 +46,20 @@ public class GeometricSamplerTest {
*/
@Test
public void testProbabilityOfSuccessIsOneSamplerToString() {
- final UniformRandomProvider rng = RandomSource.create(RandomSource.SPLIT_MIX_64);
- final GeometricSampler sampler = new GeometricSampler(rng, 1);
- Assert.assertTrue("Missing 'Geometric' from toString", sampler.toString().contains("Geometric"));
+ final UniformRandomProvider unusedRng = new SplitMix64(0L);
+ final GeometricSampler sampler = new GeometricSampler(unusedRng, 1);
+ Assert.assertTrue("Missing 'Geometric' from toString",
+ sampler.toString().contains("Geometric"));
}
/**
* Test the edge case where the probability of success is nearly 0. This is a valid geometric
- * distribution but the sample is clipped to max integer value because the underlying exponential
- * has a mean of positive infinity (effectively the sample is from a truncated distribution).
+ * distribution but the sample is clipped to max integer value because the underlying
+ * exponential has a mean of positive infinity (effectively the sample is from a truncated
+ * distribution).
*
- * <p>This test can be changed in future if a lower bound limit for the probability of success is
- * introduced.
+ * <p>This test can be changed in future if a lower bound limit for the probability of success
+ * is introduced.
*/
@Test
public void testProbabilityOfSuccessIsAlmostZeroGeneratesMaxValueForSamples() {
@@ -64,8 +67,8 @@ public class GeometricSamplerTest {
final GeometricSampler sampler = new GeometricSampler(rng, Double.MIN_VALUE);
// All samples should be max value
for (int i = 0; i < 10; i++) {
- Assert.assertEquals("p=(almost 0) should have Integer.MAX_VALUE for all samples", Integer.MAX_VALUE,
- sampler.sample());
+ Assert.assertEquals("p=(almost 0) should have Integer.MAX_VALUE for all samples",
+ Integer.MAX_VALUE, sampler.sample());
}
}
@@ -75,8 +78,8 @@ public class GeometricSamplerTest {
@SuppressWarnings("unused")
@Test(expected = IllegalArgumentException.class)
public void testProbabilityOfSuccessAboveOneThrows() {
- final UniformRandomProvider rng = RandomSource.create(RandomSource.SPLIT_MIX_64, Long.valueOf(0));
- new GeometricSampler(rng, Math.nextUp(1.0));
+ final UniformRandomProvider unusedRng = new SplitMix64(0L);
+ new GeometricSampler(unusedRng, Math.nextUp(1.0));
}
/**
@@ -85,7 +88,7 @@ public class GeometricSamplerTest {
@SuppressWarnings("unused")
@Test(expected = IllegalArgumentException.class)
public void testProbabilityOfSuccessIsZeroThrows() {
- final UniformRandomProvider rng = RandomSource.create(RandomSource.SPLIT_MIX_64, Long.valueOf(0));
- new GeometricSampler(rng, 0);
+ final UniformRandomProvider unusedRng = new SplitMix64(0L);
+ new GeometricSampler(unusedRng, 0);
}
}
[commons-rng] 04/17: RNG-67: Instructions for how to build and run
the examples-stress code
Posted by ah...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
aherbert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-rng.git
commit 9f54e579197a9c937110aff7df43dcbcd65375f5
Author: aherbert <a....@sussex.ac.uk>
AuthorDate: Tue Jan 29 10:24:09 2019 +0000
RNG-67: Instructions for how to build and run the examples-stress code
---
commons-rng-examples/examples-stress/pom.xml | 45 +++++++++++++
.../rng/examples/stress/IntGeneratorsList.java | 49 ++++++++++++++
.../rng/examples/stress/LongGeneratorsList.java | 49 ++++++++++++++
.../examples-stress/stress_test.md | 76 ++++++++++++++++++++++
4 files changed, 219 insertions(+)
diff --git a/commons-rng-examples/examples-stress/pom.xml b/commons-rng-examples/examples-stress/pom.xml
index a7cf345..ef2bae2 100644
--- a/commons-rng-examples/examples-stress/pom.xml
+++ b/commons-rng-examples/examples-stress/pom.xml
@@ -45,6 +45,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>
+
+ <uberjar.name>examples-stress</uberjar.name>
+ <project.mainClass>org.apache.commons.rng.examples.stress.RandomStressTester</project.mainClass>
</properties>
<dependencies>
@@ -59,4 +62,46 @@
</dependency>
</dependencies>
+ <profiles>
+ <profile>
+ <id>examples-stress</id>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-shade-plugin</artifactId>
+ <executions>
+ <execution>
+ <phase>package</phase>
+ <goals>
+ <goal>shade</goal>
+ </goals>
+ <configuration>
+ <finalName>${uberjar.name}</finalName>
+ <transformers>
+ <transformer
+ implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
+ <mainClass>${project.mainClass}</mainClass>
+ </transformer>
+ </transformers>
+ <filters>
+ <filter>
+ <!-- Shading signed JARs will fail without this. http://stackoverflow.com/questions/999489/invalid-signature-file-when-attempting-to-run-a-jar -->
+ <artifact>*:*</artifact>
+ <excludes>
+ <exclude>META-INF/*.SF</exclude>
+ <exclude>META-INF/*.DSA</exclude>
+ <exclude>META-INF/*.RSA</exclude>
+ </excludes>
+ </filter>
+ </filters>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+ </profiles>
+
</project>
diff --git a/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/IntGeneratorsList.java b/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/IntGeneratorsList.java
new file mode 100644
index 0000000..72d15d1
--- /dev/null
+++ b/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/IntGeneratorsList.java
@@ -0,0 +1,49 @@
+/*
+ * 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.core.source32.IntProvider;
+
+/**
+ * List of generators that use {@link IntProvider} as a base class.
+ */
+public class IntGeneratorsList implements Iterable<UniformRandomProvider> {
+ /** List of generators. */
+ private final List<UniformRandomProvider> list = new ArrayList<>();
+
+ /**
+ * Creates list.
+ */
+ public IntGeneratorsList() {
+ for (UniformRandomProvider rng : new GeneratorsList()) {
+ if (rng instanceof IntProvider) {
+ list.add(rng);
+ }
+ }
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public Iterator<UniformRandomProvider> iterator() {
+ return list.iterator();
+ }
+}
diff --git a/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/LongGeneratorsList.java b/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/LongGeneratorsList.java
new file mode 100644
index 0000000..259b1bd
--- /dev/null
+++ b/commons-rng-examples/examples-stress/src/main/java/org/apache/commons/rng/examples/stress/LongGeneratorsList.java
@@ -0,0 +1,49 @@
+/*
+ * 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.core.source64.LongProvider;
+
+/**
+ * List of generators that use {@link LongProvider} as a base class.
+ */
+public class LongGeneratorsList implements Iterable<UniformRandomProvider> {
+ /** List of generators. */
+ private final List<UniformRandomProvider> list = new ArrayList<>();
+
+ /**
+ * Creates list.
+ */
+ public LongGeneratorsList() {
+ for (UniformRandomProvider rng : new GeneratorsList()) {
+ if (rng instanceof LongProvider) {
+ list.add(rng);
+ }
+ }
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public Iterator<UniformRandomProvider> iterator() {
+ return list.iterator();
+ }
+}
diff --git a/commons-rng-examples/examples-stress/stress_test.md b/commons-rng-examples/examples-stress/stress_test.md
new file mode 100644
index 0000000..081ff8b
--- /dev/null
+++ b/commons-rng-examples/examples-stress/stress_test.md
@@ -0,0 +1,76 @@
+<!---
+ 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.
+-->
+
+Apache Commons RNG Stress Test Example
+===================
+
+The stress test module contains an application for calling external tools that perform stringent
+uniformity tests. The following shows an example of how to run DieHarder and TestU01.
+
+Installation on Linux
+---------------------
+
+This assumes that the source code has been checked out and the current working directory is
+`commons-rng-examples/examples-stress`.
+
+### TestU01
+
+This can be installed from [Test01](http://simul.iro.umontreal.ca/testu01/tu01.html) or using
+the available packages:
+
+ > apt-get install libtestu01 libtestu01-dev testu01-bin
+
+A simple bridge is provided to read the integers from `stdin` and pass them to the TestU01 library.
+This can be compiled using:
+
+ > gcc src/main/c/stdin2testu01.c -o stdin2testu01 -ltestu01 -lprobdist -lmylib -lm
+
+### DieHarder
+
+This can be install from [DieHarder](http://webhome.phy.duke.edu/~rgb/General/dieharder.php) or
+using the available package:
+
+ > apt-get install dieharder
+
+The `dieharder` executable can read integers from `stdin` for analysis.
+
+Running on Linux
+----------------
+
+Build the `examples-stress` jar file:
+
+ > mvn package -P examples-stress
+
+This will create a single jar file with all the dependencies in the `target` directory.
+
+The jar file requires the following arguments:
+
+| Argument | Description | Example |
+| --------- | ----------- | ------- |
+| path | Output filename prefix | target/dh_ |
+| n | Number of processors | 4 |
+| GeneratorsList class | Fully qualified class name of a provider for the supported random generators | org.apache.commons.rng.examples.stress.(GeneratorsList/IntGeneratorsList/LongGeneratorsList) |
+| executable | The test tool | dieharder, stdin2testu01 |
+| ... | Arguments for the test tool | dieharder: -a -g 200 -Y 1 -k 2, stdin2testu01: SmallCrush, Crush, BigCrush |
+
+### TestU01
+
+ > java -jar target/examples-stress.jar target/tu_ 4 org.apache.commons.rng.examples.stress.GeneratorsList ./stdin2testu01 BigCrush
+
+### DieHarder
+
+ > java -jar target/examples-stress.jar target/dh_ 4 org.apache.commons.rng.examples.stress.GeneratorsList /usr/bin/dieharder -a -g 200 -Y 1 -k 2
[commons-rng] 02/17: RNG-68: Fixed formatting
Posted by ah...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
aherbert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-rng.git
commit 251dc2eec99c37b3ad3da8b429568a29f77ca6e9
Author: aherbert <a....@sussex.ac.uk>
AuthorDate: Mon Jan 28 10:39:16 2019 +0000
RNG-68: Fixed formatting
---
.../distribution/AhrensDieterMarsagliaTsangGammaSampler.java | 6 ++----
1 file changed, 2 insertions(+), 4 deletions(-)
diff --git a/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/AhrensDieterMarsagliaTsangGammaSampler.java b/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/AhrensDieterMarsagliaTsangGammaSampler.java
index ab2b176..42a50e4 100644
--- a/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/AhrensDieterMarsagliaTsangGammaSampler.java
+++ b/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/AhrensDieterMarsagliaTsangGammaSampler.java
@@ -115,7 +115,6 @@ public class AhrensDieterMarsagliaTsangGammaSampler
if (p <= 1) {
// Step 2:
-
final double x = Math.pow(p, oneOverTheta);
final double u2 = rng.nextDouble();
@@ -127,7 +126,6 @@ public class AhrensDieterMarsagliaTsangGammaSampler
}
// Step 3:
-
final double x = -Math.log((bGSOptim - p) * oneOverTheta);
final double u2 = rng.nextDouble();
@@ -162,8 +160,8 @@ public class AhrensDieterMarsagliaTsangGammaSampler
* @param theta Theta scale parameter of the distribution.
*/
LargeThetaAhrensDieterMarsagliaTsangGammaSampler(UniformRandomProvider rng,
- double alpha,
- double theta) {
+ double alpha,
+ double theta) {
super(rng, alpha, theta);
gaussian = new ZigguratNormalizedGaussianSampler(rng);
dOptim = theta - ONE_THIRD;
[commons-rng] 06/17: Merge branch 'improvement-RNG-69' of
https://github.com/aherbert/commons-rng into improvement-RNG-69
Posted by ah...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
aherbert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-rng.git
commit e18e0fbcb852cd74cb8106ad513773f5d4b5ab01
Merge: c547833 77cfd26
Author: aherbert <ah...@apache.org>
AuthorDate: Thu Feb 14 12:09:44 2019 +0000
Merge branch 'improvement-RNG-69' of
https://github.com/aherbert/commons-rng into improvement-RNG-69
.../distribution/GeometricSamplersPerformance.java | 190 +++++++++++++++++++++
.../jmh/distribution/SamplersPerformance.java | 19 ++-
.../sampling/distribution/GeometricSampler.java | 148 ++++++++++++++++
.../distribution/DiscreteSamplersList.java | 4 +
.../distribution/GeometricSamplerTest.java | 91 ++++++++++
5 files changed, 448 insertions(+), 4 deletions(-)
diff --cc commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/DiscreteSamplersList.java
index 21cd20b,3e93c86..b9e1bc0
--- a/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/DiscreteSamplersList.java
+++ b/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/DiscreteSamplersList.java
@@@ -49,9 -46,13 +49,13 @@@ public class DiscreteSamplersList
// Geometric ("inverse method").
final double probSuccessGeometric = 0.21;
- add(LIST, new org.apache.commons.math3.distribution.GeometricDistribution(null, probSuccessGeometric),
+ add(LIST, new org.apache.commons.math3.distribution.GeometricDistribution(rng, probSuccessGeometric),
MathArrays.sequence(10, 0, 1),
RandomSource.create(RandomSource.ISAAC));
+ // Geometric.
- add(LIST, new org.apache.commons.math3.distribution.GeometricDistribution(null, probSuccessGeometric),
++ add(LIST, new org.apache.commons.math3.distribution.GeometricDistribution(rng, probSuccessGeometric),
+ MathArrays.sequence(10, 0, 1),
+ new GeometricSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S), probSuccessGeometric));
// Hypergeometric ("inverse method").
final int popSizeHyper = 34;
[commons-rng] 15/17: Merge branch 'improvement-RNG-68'
Posted by ah...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
aherbert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-rng.git
commit 1afd499226120fafe11022b310dc0e67c62345c2
Merge: 6e7e5f4 e8ca1f6
Author: aherbert <ah...@apache.org>
AuthorDate: Thu Feb 14 12:50:52 2019 +0000
Merge branch 'improvement-RNG-68'
Closes #17
.../AhrensDieterMarsagliaTsangGammaSampler.java | 174 +++++++++++++++------
src/changes/changes.xml | 4 +
2 files changed, 126 insertions(+), 52 deletions(-)
[commons-rng] 10/17: Merge branch 'improvement-RNG-67' of
https://github.com/aherbert/commons-rng into improvement-RNG-67
Posted by ah...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
aherbert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-rng.git
commit 25467f51aeec111876f2adddf79a3e9545a26246
Merge: 9fcc3c8 9f54e57
Author: aherbert <ah...@apache.org>
AuthorDate: Thu Feb 14 12:32:12 2019 +0000
Merge branch 'improvement-RNG-67' of https://github.com/aherbert/commons-rng into improvement-RNG-67
commons-rng-examples/examples-stress/pom.xml | 45 +++++++++++++
.../rng/examples/stress/IntGeneratorsList.java | 49 ++++++++++++++
.../rng/examples/stress/LongGeneratorsList.java | 49 ++++++++++++++
.../examples-stress/stress_test.md | 76 ++++++++++++++++++++++
4 files changed, 219 insertions(+)
[commons-rng] 17/17: Fixed checkstyle violation
Posted by ah...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
aherbert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-rng.git
commit 8e1c529efc8617053cc896dd14748b70cf2c107a
Author: aherbert <ah...@apache.org>
AuthorDate: Thu Feb 14 13:58:30 2019 +0000
Fixed checkstyle violation
---
.../apache/commons/rng/sampling/distribution/GeometricSampler.java | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/GeometricSampler.java b/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/GeometricSampler.java
index 2197d4c..757367d 100644
--- a/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/GeometricSampler.java
+++ b/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/GeometricSampler.java
@@ -123,8 +123,8 @@ public class GeometricSampler implements DiscreteSampler {
public GeometricSampler(UniformRandomProvider rng, double probabilityOfSuccess) {
if (probabilityOfSuccess <= 0 || probabilityOfSuccess > 1) {
throw new IllegalArgumentException(
- "Probability of success (p) must be in the range [0 < p <= 1]: "
- + probabilityOfSuccess);
+ "Probability of success (p) must be in the range [0 < p <= 1]: " +
+ probabilityOfSuccess);
}
delegate = probabilityOfSuccess == 1 ?
GeometricP1Sampler.INSTANCE :
[commons-rng] 01/17: RNG-68: Add private classes for each algorithm
Posted by ah...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
aherbert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-rng.git
commit ad8739b2290ae8ea34954b08fd496c6ca07c3b33
Author: aherbert <a....@sussex.ac.uk>
AuthorDate: Mon Jan 28 10:33:09 2019 +0000
RNG-68: Add private classes for each algorithm
---
.../AhrensDieterMarsagliaTsangGammaSampler.java | 174 +++++++++++++++------
1 file changed, 123 insertions(+), 51 deletions(-)
diff --git a/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/AhrensDieterMarsagliaTsangGammaSampler.java b/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/AhrensDieterMarsagliaTsangGammaSampler.java
index d34902d..ab2b176 100644
--- a/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/AhrensDieterMarsagliaTsangGammaSampler.java
+++ b/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/AhrensDieterMarsagliaTsangGammaSampler.java
@@ -44,48 +44,68 @@ import org.apache.commons.rng.UniformRandomProvider;
public class AhrensDieterMarsagliaTsangGammaSampler
extends SamplerBase
implements ContinuousSampler {
- /** 1/3 */
- private static final double ONE_THIRD = 1d / 3;
- /** The shape parameter. */
- private final double theta;
- /** The alpha parameter. */
- private final double alpha;
- /** Inverse of "theta". */
- private final double oneOverTheta;
- /** Optimization (see code). */
- private final double bGSOptim;
- /** Optimization (see code). */
- private final double dOptim;
- /** Optimization (see code). */
- private final double cOptim;
- /** Gaussian sampling. */
- private final NormalizedGaussianSampler gaussian;
- /** Underlying source of randomness. */
- private final UniformRandomProvider rng;
+ /** The appropriate gamma sampler for the parameters. */
+ private final ContinuousSampler delegate;
/**
- * @param rng Generator of uniformly distributed random numbers.
- * @param alpha Alpha parameter of the distribution.
- * @param theta Theta parameter of the distribution.
+ * Base class for a sampler from the Gamma distribution.
*/
- public AhrensDieterMarsagliaTsangGammaSampler(UniformRandomProvider rng,
- double alpha,
- double theta) {
- super(null);
- this.rng = rng;
- this.alpha = alpha;
- this.theta = theta;
- gaussian = new ZigguratNormalizedGaussianSampler(rng);
- oneOverTheta = 1 / theta;
- bGSOptim = 1 + theta / Math.E;
- dOptim = theta - ONE_THIRD;
- cOptim = ONE_THIRD / Math.sqrt(dOptim);
+ private abstract static class BaseAhrensDieterMarsagliaTsangGammaSampler
+ implements ContinuousSampler {
+
+ /** Underlying source of randomness. */
+ protected final UniformRandomProvider rng;
+ /** The shape parameter. */
+ protected final double theta;
+ /** The alpha parameter. */
+ protected final double alpha;
+
+ /**
+ * @param rng Generator of uniformly distributed random numbers.
+ * @param alpha Alpha shape parameter of the distribution.
+ * @param theta Theta scale parameter of the distribution.
+ */
+ BaseAhrensDieterMarsagliaTsangGammaSampler(UniformRandomProvider rng,
+ double alpha,
+ double theta) {
+ this.rng = rng;
+ this.alpha = alpha;
+ this.theta = theta;
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public String toString() {
+ return "Ahrens-Dieter-Marsaglia-Tsang Gamma deviate [" + rng.toString() + "]";
+ }
}
- /** {@inheritDoc} */
- @Override
- public double sample() {
- if (theta < 1) {
+ /**
+ * Class to sample from the Gamma distribution when {@code 0 < theta < 1}.
+ */
+ private static class SmallThetaAhrensDieterMarsagliaTsangGammaSampler
+ extends BaseAhrensDieterMarsagliaTsangGammaSampler {
+
+ /** Inverse of "theta". */
+ private final double oneOverTheta;
+ /** Optimization (see code). */
+ private final double bGSOptim;
+
+ /**
+ * @param rng Generator of uniformly distributed random numbers.
+ * @param alpha Alpha shape parameter of the distribution.
+ * @param theta Theta scale parameter of the distribution.
+ */
+ SmallThetaAhrensDieterMarsagliaTsangGammaSampler(UniformRandomProvider rng,
+ double alpha,
+ double theta) {
+ super(rng, alpha, theta);
+ oneOverTheta = 1 / theta;
+ bGSOptim = 1 + theta / Math.E;
+ }
+
+ @Override
+ public double sample() {
// [1]: p. 228, Algorithm GS.
while (true) {
@@ -102,24 +122,56 @@ public class AhrensDieterMarsagliaTsangGammaSampler
if (u2 > Math.exp(-x)) {
// Reject.
continue;
- } else {
- return alpha * x;
}
- } else {
- // Step 3:
+ return alpha * x;
+ }
- final double x = -Math.log((bGSOptim - p) * oneOverTheta);
- final double u2 = rng.nextDouble();
+ // Step 3:
- if (u2 > Math.pow(x, theta - 1)) {
- // Reject.
- continue;
- } else {
- return alpha * x;
- }
+ final double x = -Math.log((bGSOptim - p) * oneOverTheta);
+ final double u2 = rng.nextDouble();
+
+ if (u2 > Math.pow(x, theta - 1)) {
+ // Reject.
+ continue;
}
+ return alpha * x;
}
- } else {
+ }
+ }
+
+ /**
+ * Class to sample from the Gamma distribution when the {@code theta >= 1}.
+ */
+ private static class LargeThetaAhrensDieterMarsagliaTsangGammaSampler
+ extends BaseAhrensDieterMarsagliaTsangGammaSampler {
+
+ /** 1/3 */
+ private static final double ONE_THIRD = 1d / 3;
+
+ /** Optimization (see code). */
+ private final double dOptim;
+ /** Optimization (see code). */
+ private final double cOptim;
+ /** Gaussian sampling. */
+ private final NormalizedGaussianSampler gaussian;
+
+ /**
+ * @param rng Generator of uniformly distributed random numbers.
+ * @param alpha Alpha shape parameter of the distribution.
+ * @param theta Theta scale parameter of the distribution.
+ */
+ LargeThetaAhrensDieterMarsagliaTsangGammaSampler(UniformRandomProvider rng,
+ double alpha,
+ double theta) {
+ super(rng, alpha, theta);
+ gaussian = new ZigguratNormalizedGaussianSampler(rng);
+ dOptim = theta - ONE_THIRD;
+ cOptim = ONE_THIRD / Math.sqrt(dOptim);
+ }
+
+ @Override
+ public double sample() {
while (true) {
final double x = gaussian.sample();
final double oPcTx = 1 + cOptim * x;
@@ -144,9 +196,29 @@ public class AhrensDieterMarsagliaTsangGammaSampler
}
}
+ /**
+ * @param rng Generator of uniformly distributed random numbers.
+ * @param alpha Alpha shape parameter of the distribution.
+ * @param theta Theta scale parameter of the distribution.
+ */
+ public AhrensDieterMarsagliaTsangGammaSampler(UniformRandomProvider rng,
+ double alpha,
+ double theta) {
+ super(null);
+ delegate = theta < 1 ?
+ new SmallThetaAhrensDieterMarsagliaTsangGammaSampler(rng, alpha, theta) :
+ new LargeThetaAhrensDieterMarsagliaTsangGammaSampler(rng, alpha, theta);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public double sample() {
+ return delegate.sample();
+ }
+
/** {@inheritDoc} */
@Override
public String toString() {
- return "Ahrens-Dieter-Marsaglia-Tsang Gamma deviate [" + rng.toString() + "]";
+ return delegate.toString();
}
}
[commons-rng] 13/17: Merge branch 'improvement-RNG-68' of
https://github.com/aherbert/commons-rng into improvement-RNG-68
Posted by ah...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
aherbert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-rng.git
commit b7b40cf39822bc33fac8ac17356ce0f01def93bc
Merge: 6e7e5f4 251dc2e
Author: aherbert <ah...@apache.org>
AuthorDate: Thu Feb 14 12:39:34 2019 +0000
Merge branch 'improvement-RNG-68' of https://github.com/aherbert/commons-rng into improvement-RNG-68
.../AhrensDieterMarsagliaTsangGammaSampler.java | 174 +++++++++++++++------
1 file changed, 122 insertions(+), 52 deletions(-)
[commons-rng] 12/17: Merge branch 'improvement-RNG-67'
Posted by ah...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
aherbert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-rng.git
commit 6e7e5f4a35b4173a4ea5a2629bd8a1e17dd43ba1
Merge: 9fcc3c8 d301d58
Author: aherbert <ah...@apache.org>
AuthorDate: Thu Feb 14 12:38:15 2019 +0000
Merge branch 'improvement-RNG-67'
Closes #18
commons-rng-examples/examples-stress/pom.xml | 45 +++++++++++++
.../rng/examples/stress/IntGeneratorsList.java | 49 ++++++++++++++
.../rng/examples/stress/LongGeneratorsList.java | 49 ++++++++++++++
.../examples-stress/stress_test.md | 76 ++++++++++++++++++++++
src/changes/changes.xml | 4 +-
5 files changed, 222 insertions(+), 1 deletion(-)
[commons-rng] 09/17: Merge branch 'improvement-RNG-69'
Posted by ah...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
aherbert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-rng.git
commit 9fcc3c84f0a16cbc12836a01a3c6fa766c08c784
Merge: c547833 1a93589
Author: aherbert <ah...@apache.org>
AuthorDate: Thu Feb 14 12:28:28 2019 +0000
Merge branch 'improvement-RNG-69'
Closes #19
.../distribution/GeometricSamplersPerformance.java | 191 +++++++++++++++++++++
.../jmh/distribution/SamplersPerformance.java | 19 +-
.../sampling/distribution/GeometricSampler.java | 150 ++++++++++++++++
.../distribution/DiscreteSamplersList.java | 4 +
.../distribution/GeometricSamplerTest.java | 94 ++++++++++
src/changes/changes.xml | 4 +-
6 files changed, 457 insertions(+), 5 deletions(-)
[commons-rng] 11/17: Track changes
Posted by ah...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
aherbert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-rng.git
commit d301d58aeb51d61611ecf8cefd177ba0d2f6e870
Author: aherbert <ah...@apache.org>
AuthorDate: Thu Feb 14 12:37:41 2019 +0000
Track changes
---
src/changes/changes.xml | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 8ddab98..f9be7f0 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -75,12 +75,14 @@ re-run tests that fail, and pass the build if they succeed
within the allotted number of reruns (the test will be marked
as 'flaky' in the report).
">
+ <action dev="aherbert" type="add" issue="RNG-67">
+ Instructions for how to build and run the examples-stress code.
+ </action>
<action dev="aherbert" type="add" issue="RNG-69">
New "GeometricSampler" class.
</action>
</release>
-
<release version="1.2" date="2018-12-12" description="
This is a minor release of Apache Commons RNG, containing a
few new features and performance improvements.
[commons-rng] 05/17: RNG-69: Updated code formatting and
GeometricSampler javadoc
Posted by ah...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
aherbert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-rng.git
commit 77cfd26485c126c6245a9ae70a27000dbad8492f
Author: aherbert <a....@sussex.ac.uk>
AuthorDate: Tue Jan 29 12:29:38 2019 +0000
RNG-69: Updated code formatting and GeometricSampler javadoc
---
.../rng/sampling/distribution/GeometricSampler.java | 18 +++++++++++-------
.../sampling/distribution/DiscreteSamplersList.java | 2 +-
.../sampling/distribution/GeometricSamplerTest.java | 2 +-
3 files changed, 13 insertions(+), 9 deletions(-)
diff --git a/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/GeometricSampler.java b/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/GeometricSampler.java
index ab2a6c4..ba62ac4 100644
--- a/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/GeometricSampler.java
+++ b/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/GeometricSampler.java
@@ -25,16 +25,20 @@ import org.apache.commons.rng.UniformRandomProvider;
* <p>This distribution samples the number of failures before the first success taking values in the
* set {@code [0, 1, 2, ...]}.
*
- * <p>The sample is computed using a related an exponential distribution. If X is an exponentially
- * distributed random variable with parameter λ, then Y = floor(X) is a geometrically distributed
- * random variable with parameter p = 1 − e<sup>−λ</sup>, with {@code p} the probability of success.
+ * <p>The sample is computed using a related an exponential distribution. If {@code X} is an
+ * exponentially distributed random variable with parameter λ, then {@code Y = floor(X)} is a
+ * geometrically distributed random variable with parameter p = 1 − e<sup>−λ</sup>, with {@code p}
+ * the probability of success.
*
- * <p>Note: As the probability of success ({@code p}) tends towards zero the mean of the
+ * <p>This sampler outperforms using the {@link InverseTransformDiscreteSampler} with an appropriate
+ * Geometric inverse cumulative probability function.
+ *
+ * <p>Usage note: As the probability of success ({@code p}) tends towards zero the mean of the
* distribution ({@code (1-p)/p}) tends towards infinity and due to the use of {@code int} for the
- * sample this results in truncation of the distribution.
+ * sample this can result in truncation of the distribution.
*
* @see <a
- * href="https://en.wikipedia.org/wiki/Geometric_distribution#Related_distributions">geometric
+ * href="https://en.wikipedia.org/wiki/Geometric_distribution#Related_distributions">Geometric
* distribution - related distributions</a>
*
* @since 1.3
@@ -118,7 +122,7 @@ public class GeometricSampler implements DiscreteSampler {
public GeometricSampler(UniformRandomProvider rng, double probabilityOfSuccess) {
if (probabilityOfSuccess <= 0 || probabilityOfSuccess > 1) {
throw new IllegalArgumentException(
- "Probability of success must be in the range [0 < p <= 1]: " + probabilityOfSuccess);
+ "Probability of success must be in the range [0 < p <= 1]: " + probabilityOfSuccess);
}
delegate = probabilityOfSuccess == 1 ?
GeometricP1Sampler.INSTANCE :
diff --git a/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/DiscreteSamplersList.java b/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/DiscreteSamplersList.java
index 3f9adb8..3e93c86 100644
--- a/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/DiscreteSamplersList.java
+++ b/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/DiscreteSamplersList.java
@@ -50,7 +50,7 @@ public class DiscreteSamplersList {
MathArrays.sequence(10, 0, 1),
RandomSource.create(RandomSource.ISAAC));
// Geometric.
- add(LIST, new org.apache.commons.math3.distribution.GeometricDistribution(probSuccessGeometric),
+ add(LIST, new org.apache.commons.math3.distribution.GeometricDistribution(null, probSuccessGeometric),
MathArrays.sequence(10, 0, 1),
new GeometricSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S), probSuccessGeometric));
diff --git a/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/GeometricSamplerTest.java b/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/GeometricSamplerTest.java
index 8c5a39e..00f1000 100644
--- a/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/GeometricSamplerTest.java
+++ b/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/GeometricSamplerTest.java
@@ -65,7 +65,7 @@ public class GeometricSamplerTest {
// All samples should be max value
for (int i = 0; i < 10; i++) {
Assert.assertEquals("p=(almost 0) should have Integer.MAX_VALUE for all samples", Integer.MAX_VALUE,
- sampler.sample());
+ sampler.sample());
}
}
[commons-rng] 16/17: Updated checkstyle to use the latest
checkstyle version (8.17)
Posted by ah...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
aherbert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-rng.git
commit 26cfa3022f6e8449557562272ae5bcddb7615056
Author: aherbert <ah...@apache.org>
AuthorDate: Thu Feb 14 13:53:45 2019 +0000
Updated checkstyle to use the latest checkstyle version (8.17)
This version of checkstyle requires java 8 and so the plugin
configuration has been moved to a profile activated by JDK 1.8+.
---
pom.xml | 120 +++++++++++++++------------
src/main/resources/checkstyle/checkstyle.xml | 60 +++-----------
2 files changed, 78 insertions(+), 102 deletions(-)
diff --git a/pom.xml b/pom.xml
index 00a9684..36ac983 100644
--- a/pom.xml
+++ b/pom.xml
@@ -108,6 +108,7 @@
<maven.compiler.target>1.6</maven.compiler.target>
<rng.pmd.version>3.9.0</rng.pmd.version>
<rng.checkstyle.version>3.0.0</rng.checkstyle.version>
+ <rng.checkstyle.dep.version>8.17</rng.checkstyle.dep.version>
<rng.mathjax.version>2.7.2</rng.mathjax.version>
<!-- Workaround to avoid duplicating config files. -->
<rng.parent.dir>${basedir}</rng.parent.dir>
@@ -196,20 +197,7 @@
</ignorePathsToDelete>
</configuration>
</plugin>
-
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <executions>
- <execution>
- <id>validate</id>
- <phase>validate</phase>
- <goals>
- <goal>check</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
+ <!-- maven-checkstyle-plugin runs in JDK 8+ profile -->
<plugin>
<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs-maven-plugin</artifactId>
@@ -257,25 +245,6 @@
</plugin>
</plugins>
-
- <pluginManagement>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <version>${rng.checkstyle.version}</version>
- <configuration>
- <includeTestSourceDirectory>false</includeTestSourceDirectory>
- <configLocation>${rng.parent.dir}/src/main/resources/checkstyle/checkstyle.xml</configLocation>
- <headerLocation>${rng.parent.dir}/src/main/resources/checkstyle/license-header.txt</headerLocation>
- <logViolationsToConsole>false</logViolationsToConsole>
- <failOnViolation>false</failOnViolation>
- <resourceExcludes>NOTICE.txt,LICENSE.txt</resourceExcludes>
- <excludes>**/module-info.java</excludes>
- </configuration>
- </plugin>
- </plugins>
- </pluginManagement>
</build>
<reporting>
@@ -333,25 +302,7 @@
<excludeFilterFile>${rng.parent.dir}/src/main/resources/spotbugs/spotbugs-exclude-filter.xml</excludeFilterFile>
</configuration>
</plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <version>${rng.checkstyle.version}</version>
- <configuration>
- <configLocation>${rng.parent.dir}/src/main/resources/checkstyle/checkstyle.xml</configLocation>
- <headerLocation>${rng.parent.dir}/src/main/resources/checkstyle/license-header.txt</headerLocation>
- <enableRulesSummary>false</enableRulesSummary>
- <includeResources>false</includeResources>
- <excludes>**/module-info.java</excludes>
- </configuration>
- <reportSets>
- <reportSet>
- <reports>
- <report>checkstyle</report>
- </reports>
- </reportSet>
- </reportSets>
- </plugin>
+ <!-- maven-checkstyle-plugin runs in JDK 8+ profile -->
<plugin>
<artifactId>maven-pmd-plugin</artifactId>
<version>${rng.pmd.version}</version>
@@ -567,6 +518,70 @@
</plugins>
</build>
</profile>
+ <!-- profile to allow the use of plugin versions that require Java 8+ -->
+ <profile>
+ <id>jdk8-plugins</id>
+ <activation>
+ <jdk>[1.8,)</jdk>
+ </activation>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <version>${rng.checkstyle.version}</version>
+ <dependencies>
+ <dependency>
+ <groupId>com.puppycrawl.tools</groupId>
+ <artifactId>checkstyle</artifactId>
+ <version>${rng.checkstyle.dep.version}</version>
+ </dependency>
+ </dependencies>
+ <configuration>
+ <includeTestSourceDirectory>false</includeTestSourceDirectory>
+ <configLocation>${rng.parent.dir}/src/main/resources/checkstyle/checkstyle.xml</configLocation>
+ <headerLocation>${rng.parent.dir}/src/main/resources/checkstyle/license-header.txt</headerLocation>
+ <logViolationsToConsole>false</logViolationsToConsole>
+ <failOnViolation>false</failOnViolation>
+ <resourceExcludes>NOTICE.txt,LICENSE.txt</resourceExcludes>
+ <excludes>**/module-info.java</excludes>
+ </configuration>
+ <executions>
+ <execution>
+ <id>validate</id>
+ <phase>validate</phase>
+ <goals>
+ <goal>check</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+ <reporting>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <version>${rng.checkstyle.version}</version>
+ <configuration>
+ <configLocation>${rng.parent.dir}/src/main/resources/checkstyle/checkstyle.xml</configLocation>
+ <headerLocation>${rng.parent.dir}/src/main/resources/checkstyle/license-header.txt</headerLocation>
+ <enableRulesSummary>false</enableRulesSummary>
+ <includeResources>false</includeResources>
+ <excludes>**/module-info.java</excludes>
+ </configuration>
+ <reportSets>
+ <reportSet>
+ <reports>
+ <report>checkstyle</report>
+ </reports>
+ </reportSet>
+ </reportSets>
+ </plugin>
+ </plugins>
+ </reporting>
+ </profile>
<!--
Profiles for modules with special requirements.
@@ -582,7 +597,6 @@
</modules>
</profile>
-
<profile>
<id>release</id>
<modules>
diff --git a/src/main/resources/checkstyle/checkstyle.xml b/src/main/resources/checkstyle/checkstyle.xml
index a138af6..d867cbf 100644
--- a/src/main/resources/checkstyle/checkstyle.xml
+++ b/src/main/resources/checkstyle/checkstyle.xml
@@ -62,9 +62,6 @@
<property name="classes" value="java.lang.Boolean, java.lang.String"/>
</module>
- <!-- Required for SuppressionCommentFilter below -->
- <module name="FileContentsHolder"/>
-
<!-- Import should be explicit, really needed and only from pure java packages -->
<module name="AvoidStarImport" />
<module name="UnusedImports" />
@@ -137,6 +134,17 @@
<!-- <module name="TodoComment" /> -->
+ <!-- Setup special comments to suppress specific checks from source files -->
+ <module name="SuppressionCommentFilter">
+ <property name="offCommentFormat" value="CHECKSTYLE\: stop ([\w\|]+)"/>
+ <property name="onCommentFormat" value="CHECKSTYLE\: resume ([\w\|]+)"/>
+ <property name="checkFormat" value="$1"/>
+ </module>
+ <module name="SuppressionCommentFilter">
+ <property name="offCommentFormat" value="CHECKSTYLE\: stop all"/>
+ <property name="onCommentFormat" value="CHECKSTYLE\: resume all"/>
+ </module>
+
</module>
<!-- Verify that EVERY source file has the appropriate license -->
@@ -153,50 +161,4 @@
<!-- Require package javadoc -->
<module name="JavadocPackage"/>
- <!-- Setup special comments to suppress specific checks from source files -->
- <module name="SuppressionCommentFilter">
- <property name="offCommentFormat" value="CHECKSTYLE\: stop JavadocVariable"/>
- <property name="onCommentFormat" value="CHECKSTYLE\: resume JavadocVariable"/>
- <property name="checkFormat" value="JavadocVariable"/>
- </module>
- <module name="SuppressionCommentFilter">
- <property name="offCommentFormat" value="CHECKSTYLE\: stop JavadocMethodCheck"/>
- <property name="onCommentFormat" value="CHECKSTYLE\: resume JavadocMethodCheck"/>
- <property name="checkFormat" value="JavadocMethodCheck"/>
- </module>
- <module name="SuppressionCommentFilter">
- <property name="offCommentFormat" value="CHECKSTYLE\: stop ConstantName"/>
- <property name="onCommentFormat" value="CHECKSTYLE\: resume ConstantName"/>
- <property name="checkFormat" value="ConstantName"/>
- </module>
- <module name="SuppressionCommentFilter">
- <property name="offCommentFormat" value="CHECKSTYLE\: stop HideUtilityClassConstructor"/>
- <property name="onCommentFormat" value="CHECKSTYLE\: resume HideUtilityClassConstructor"/>
- <property name="checkFormat" value="HideUtilityClassConstructor"/>
- </module>
- <module name="SuppressionCommentFilter">
- <property name="offCommentFormat" value="CHECKSTYLE\: stop MultipleVariableDeclarations"/>
- <property name="onCommentFormat" value="CHECKSTYLE\: resume MultipleVariableDeclarations"/>
- <property name="checkFormat" value="MultipleVariableDeclarations"/>
- </module>
- <module name="SuppressionCommentFilter">
- <property name="offCommentFormat" value="CHECKSTYLE\: stop IllegalCatch"/>
- <property name="onCommentFormat" value="CHECKSTYLE\: resume IllegalCatch"/>
- <property name="checkFormat" value="IllegalCatch"/>
- </module>
- <module name="SuppressionCommentFilter">
- <property name="offCommentFormat" value="CHECKSTYLE\: stop DeclarationOrder"/>
- <property name="onCommentFormat" value="CHECKSTYLE\: resume DeclarationOrder"/>
- <property name="checkFormat" value="DeclarationOrder"/>
- </module>
- <module name="SuppressionCommentFilter">
- <property name="offCommentFormat" value="CHECKSTYLE\: stop RedundantModifier"/>
- <property name="onCommentFormat" value="CHECKSTYLE\: resume RedundantModifier"/>
- <property name="checkFormat" value="RedundantModifier"/>
- </module>
- <module name="SuppressionCommentFilter">
- <property name="offCommentFormat" value="CHECKSTYLE\: stop all"/>
- <property name="onCommentFormat" value="CHECKSTYLE\: resume all"/>
- </module>
</module>
-
[commons-rng] 14/17: Track changes.
Posted by ah...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
aherbert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-rng.git
commit e8ca1f613d6af0a6d694d91c6b1291c73ac98e59
Author: aherbert <ah...@apache.org>
AuthorDate: Thu Feb 14 12:50:30 2019 +0000
Track changes.
---
src/changes/changes.xml | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index f9be7f0..94b74d0 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -75,6 +75,10 @@ re-run tests that fail, and pass the build if they succeed
within the allotted number of reruns (the test will be marked
as 'flaky' in the report).
">
+ <action dev="aherbert" type="update" issue="RNG-68">
+ ""AhrensDieterMarsagliaTsangGammaSampler": Algorithms for small and large theta have
+ been delegated to specialised classes.
+ </action>
<action dev="aherbert" type="add" issue="RNG-67">
Instructions for how to build and run the examples-stress code.
</action>
[commons-rng] 03/17: RNG-69: Added a Geometric sampler
Posted by ah...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
aherbert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-rng.git
commit edcdf9affa4648609120e5882f83facf2fb1ef05
Author: aherbert <a....@sussex.ac.uk>
AuthorDate: Mon Jan 28 16:24:54 2019 +0000
RNG-69: Added a Geometric sampler
This outperforms using the InverseTransformDiscreteSampler with an
appropriate Geometric inverse cumulative probability function. A JMH
benchmark has been added to demonstrate the performance.
---
.../distribution/GeometricSamplersPerformance.java | 190 +++++++++++++++++++++
.../jmh/distribution/SamplersPerformance.java | 19 ++-
.../sampling/distribution/GeometricSampler.java | 144 ++++++++++++++++
.../distribution/DiscreteSamplersList.java | 8 +-
.../distribution/GeometricSamplerTest.java | 91 ++++++++++
5 files changed, 446 insertions(+), 6 deletions(-)
diff --git a/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/distribution/GeometricSamplersPerformance.java b/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/distribution/GeometricSamplersPerformance.java
new file mode 100644
index 0000000..60e86ad
--- /dev/null
+++ b/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/distribution/GeometricSamplersPerformance.java
@@ -0,0 +1,190 @@
+/*
+ * 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.jmh.distribution;
+
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.BenchmarkMode;
+import org.openjdk.jmh.annotations.Mode;
+import org.openjdk.jmh.annotations.Warmup;
+import org.openjdk.jmh.annotations.Measurement;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.annotations.Fork;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Param;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.OutputTimeUnit;
+import org.openjdk.jmh.infra.Blackhole;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.commons.rng.UniformRandomProvider;
+import org.apache.commons.rng.simple.RandomSource;
+import org.apache.commons.rng.sampling.distribution.DiscreteInverseCumulativeProbabilityFunction;
+import org.apache.commons.rng.sampling.distribution.DiscreteSampler;
+import org.apache.commons.rng.sampling.distribution.GeometricSampler;
+import org.apache.commons.rng.sampling.distribution.InverseTransformDiscreteSampler;
+
+/**
+ * Executes a benchmark to compare the speed of generation of Geometric random numbers
+ * using different methods.
+ */
+@BenchmarkMode(Mode.AverageTime)
+@OutputTimeUnit(TimeUnit.MICROSECONDS)
+@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
+@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
+@State(Scope.Benchmark)
+@Fork(value = 1, jvmArgs = {"-server", "-Xms128M", "-Xmx128M"})
+public class GeometricSamplersPerformance {
+ /** Number of samples per run. */
+ private static final int NUM_SAMPLES = 10000000;
+
+ /**
+ * The RandomSource's to use for testing.
+ */
+ @State(Scope.Benchmark)
+ public static class Sources {
+ /**
+ * RNG providers.
+ */
+ @Param({"SPLIT_MIX_64",
+ "MWC_256",
+ "JDK" })
+ private String randomSourceName;
+
+ /** RNG. */
+ private UniformRandomProvider generator;
+
+ /**
+ * @return the RNG.
+ */
+ public UniformRandomProvider getGenerator() {
+ return generator;
+ }
+
+ /** Instantiates generator. */
+ @Setup
+ public void setup() {
+ final RandomSource randomSource = RandomSource.valueOf(randomSourceName);
+ generator = RandomSource.create(randomSource);
+ }
+ }
+
+ /**
+ * The probability of success for testing.
+ */
+ @State(Scope.Benchmark)
+ public static class ProbabilityOfSuccess {
+ /**
+ * The probability.
+ */
+ @Param({ "0.1", "0.3"})
+ private double probability;
+
+ /**
+ * Gets the probability of success.
+ *
+ * @return the probability of success
+ */
+ public double getProbability() {
+ return probability;
+ }
+ }
+
+ /**
+ * Define the inverse cumulative probability function for the Geometric distribution.
+ *
+ * <p>Adapted from org.apache.commons.math3.distribution.GeometricDistribution.
+ */
+ private static class GeometricDiscreteInverseCumulativeProbabilityFunction
+ implements DiscreteInverseCumulativeProbabilityFunction {
+ /**
+ * {@code log(1 - p)} where p is the probability of success.
+ */
+ private final double log1mProbabilityOfSuccess;
+
+ /**
+ * @param probabilityOfSuccess the probability of success
+ */
+ GeometricDiscreteInverseCumulativeProbabilityFunction(double probabilityOfSuccess) {
+ // No validation that 0 < p <= 1
+ log1mProbabilityOfSuccess = Math.log1p(-probabilityOfSuccess);
+ }
+
+ @Override
+ public int inverseCumulativeProbability(double cumulativeProbability) {
+ // This is the equivalent of floor(log(u)/ln(1-p))
+ // where:
+ // u = cumulative probability
+ // p = probability of success
+ // See: https://en.wikipedia.org/wiki/Geometric_distribution#Related_distributions
+ // ---
+ // Note: if cumulativeProbability == 0 then log1p(-0) is zero and the result
+ // after the range check is 0.
+ // Note: if cumulativeProbability == 1 then log1p(-1) is negative infinity, the result of
+ // the divide is positive infinity and the result after the range check is Integer.MAX_VALUE.
+ return Math.max(0, (int) Math.ceil(Math.log1p(-cumulativeProbability) / log1mProbabilityOfSuccess - 1));
+ }
+ }
+
+ /**
+ * Exercises a discrete sampler.
+ *
+ * @param sampler Sampler.
+ * @param bh Data sink.
+ */
+ private static void runSample(DiscreteSampler sampler,
+ Blackhole bh) {
+ for (int i = 0; i < NUM_SAMPLES; i++) {
+ bh.consume(sampler.sample());
+ }
+ }
+
+ // Benchmarks methods below.
+
+ /**
+ * Run geometric sampler.
+ *
+ * @param sources Source of randomness.
+ * @param success The probability of success.
+ * @param bh Data sink.
+ */
+ @Benchmark
+ public void runGeometricSampler(Sources sources,
+ ProbabilityOfSuccess success,
+ Blackhole bh) {
+ runSample(new GeometricSampler(sources.getGenerator(), success.getProbability()), bh);
+ }
+
+ /**
+ * Run geometric sampler.
+ *
+ * @param sources Source of randomness.
+ * @param success The probability of success.
+ * @param bh Data sink.
+ */
+ @Benchmark
+ public void runGeometricInverseTranformSampler(Sources sources,
+ ProbabilityOfSuccess success,
+ Blackhole bh) {
+ final DiscreteInverseCumulativeProbabilityFunction geometricFunction =
+ new GeometricDiscreteInverseCumulativeProbabilityFunction(success.getProbability());
+ final DiscreteSampler inverseMethodSampler =
+ new InverseTransformDiscreteSampler(sources.getGenerator(),
+ geometricFunction);
+ runSample(inverseMethodSampler, bh);
+ }
+}
diff --git a/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/distribution/SamplersPerformance.java b/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/distribution/SamplersPerformance.java
index 963d8bd..ad2d096 100644
--- a/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/distribution/SamplersPerformance.java
+++ b/commons-rng-examples/examples-jmh/src/main/java/org/apache/commons/rng/examples/jmh/distribution/SamplersPerformance.java
@@ -44,6 +44,7 @@ import org.apache.commons.rng.sampling.distribution.LogNormalSampler;
import org.apache.commons.rng.sampling.distribution.ChengBetaSampler;
import org.apache.commons.rng.sampling.distribution.ContinuousUniformSampler;
import org.apache.commons.rng.sampling.distribution.DiscreteUniformSampler;
+import org.apache.commons.rng.sampling.distribution.GeometricSampler;
import org.apache.commons.rng.sampling.distribution.RejectionInversionZipfSampler;
import org.apache.commons.rng.sampling.distribution.PoissonSampler;
@@ -110,8 +111,8 @@ public class SamplersPerformance {
* @param sampler Sampler.
* @param bh Data sink.
*/
- private void runSample(ContinuousSampler sampler,
- Blackhole bh) {
+ private static void runSample(ContinuousSampler sampler,
+ Blackhole bh) {
for (int i = 0; i < NUM_SAMPLES; i++) {
bh.consume(sampler.sample());
}
@@ -123,8 +124,8 @@ public class SamplersPerformance {
* @param sampler Sampler.
* @param bh Data sink.
*/
- private void runSample(DiscreteSampler sampler,
- Blackhole bh) {
+ private static void runSample(DiscreteSampler sampler,
+ Blackhole bh) {
for (int i = 0; i < NUM_SAMPLES; i++) {
bh.consume(sampler.sample());
}
@@ -261,4 +262,14 @@ public class SamplersPerformance {
Blackhole bh) {
runSample(new PoissonSampler(sources.getGenerator(), 8.9), bh);
}
+
+ /**
+ * @param sources Source of randomness.
+ * @param bh Data sink.
+ */
+ @Benchmark
+ public void runGeometricSampler(Sources sources,
+ Blackhole bh) {
+ runSample(new GeometricSampler(sources.getGenerator(), 0.21), bh);
+ }
}
diff --git a/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/GeometricSampler.java b/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/GeometricSampler.java
new file mode 100644
index 0000000..ab2a6c4
--- /dev/null
+++ b/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/GeometricSampler.java
@@ -0,0 +1,144 @@
+/*
+ * 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.sampling.distribution;
+
+import org.apache.commons.rng.UniformRandomProvider;
+
+/**
+ * Sampling from a <a href="https://en.wikipedia.org/wiki/Geometric_distribution">geometric
+ * distribution</a>.
+ *
+ * <p>This distribution samples the number of failures before the first success taking values in the
+ * set {@code [0, 1, 2, ...]}.
+ *
+ * <p>The sample is computed using a related an exponential distribution. If X is an exponentially
+ * distributed random variable with parameter λ, then Y = floor(X) is a geometrically distributed
+ * random variable with parameter p = 1 − e<sup>−λ</sup>, with {@code p} the probability of success.
+ *
+ * <p>Note: As the probability of success ({@code p}) tends towards zero the mean of the
+ * distribution ({@code (1-p)/p}) tends towards infinity and due to the use of {@code int} for the
+ * sample this results in truncation of the distribution.
+ *
+ * @see <a
+ * href="https://en.wikipedia.org/wiki/Geometric_distribution#Related_distributions">geometric
+ * distribution - related distributions</a>
+ *
+ * @since 1.3
+ */
+public class GeometricSampler implements DiscreteSampler {
+ /** The appropriate geometric sampler for the parameters. */
+ private final DiscreteSampler delegate;
+
+ /**
+ * Sample from the geometric distribution when the probability of success is 1.
+ */
+ private static class GeometricP1Sampler implements DiscreteSampler {
+ /** The single instance. */
+ static final GeometricP1Sampler INSTANCE = new GeometricP1Sampler();
+
+ @Override
+ public int sample() {
+ // When probability of success is 1 the sample is always zero
+ return 0;
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public String toString() {
+ return "Geometric(p=1) deviate";
+ }
+ }
+
+ /**
+ * Sample from the geometric distribution by using a related exponential distribution.
+ */
+ private static class GeometricExponentialSampler implements DiscreteSampler {
+ /** Underlying source of randomness. Used only for the {@link #toString()} method. */
+ private final UniformRandomProvider rng;
+ /** The related exponential sampler for the geometric distribution. */
+ private final AhrensDieterExponentialSampler exponentialSampler;
+
+ /**
+ * @param rng Generator of uniformly distributed random numbers
+ * @param probabilityOfSuccess The probability of success (must be {@code 0<p<1})
+ */
+ GeometricExponentialSampler(UniformRandomProvider rng, double probabilityOfSuccess) {
+ this.rng = rng;
+ // Use a related exponential distribution:
+ // λ = −ln(1 − probabilityOfSuccess)
+ // exponential mean = 1 / λ
+ // --
+ // Note on validation:
+ // If probabilityOfSuccess == Math.nextDown(1.0) the exponential mean is >0 (valid).
+ // If probabilityOfSuccess == Double.MIN_VALUE the exponential mean is +Infinity
+ // and the sample will always be Integer.MAX_VALUE (the distribution is truncated). It
+ // is noted in the class Javadoc that the use of a small p leads to truncation so
+ // no checks are made for this case.
+ final double exponentialMean = 1.0 / (-Math.log1p(-probabilityOfSuccess));
+ exponentialSampler = new AhrensDieterExponentialSampler(rng, exponentialMean);
+ }
+
+ @Override
+ public int sample() {
+ // Return the floor of the exponential sample
+ return (int) Math.floor(exponentialSampler.sample());
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public String toString() {
+ return "Geometric deviate [" + rng.toString() + "]";
+ }
+ }
+
+ /**
+ * Creates a new geometric distribution sampler. The samples will be provided in the set
+ * {@code k=[0, 1, 2, ...]} where {@code k} indicates the number of failures before the first
+ * success.
+ *
+ * @param rng Generator of uniformly distributed random numbers
+ * @param probabilityOfSuccess The probability of success
+ * @throws IllegalArgumentException if {@code probabilityOfSuccess} is not in the range [0 <
+ * probabilityOfSuccess <= 1]
+ */
+ public GeometricSampler(UniformRandomProvider rng, double probabilityOfSuccess) {
+ if (probabilityOfSuccess <= 0 || probabilityOfSuccess > 1) {
+ throw new IllegalArgumentException(
+ "Probability of success must be in the range [0 < p <= 1]: " + probabilityOfSuccess);
+ }
+ delegate = probabilityOfSuccess == 1 ?
+ GeometricP1Sampler.INSTANCE :
+ new GeometricExponentialSampler(rng, probabilityOfSuccess);
+ }
+
+ /**
+ * Create a sample from a geometric distribution.
+ *
+ * <p>The sample will take the values in the set {@code [0, 1, 2, ...]}, equivalent to the number of
+ * failures before the first success.
+ */
+ @Override
+ public int sample() {
+ return delegate.sample();
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public String toString() {
+ return delegate.toString();
+ }
+}
diff --git a/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/DiscreteSamplersList.java b/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/DiscreteSamplersList.java
index 23122c7..3f9adb8 100644
--- a/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/DiscreteSamplersList.java
+++ b/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/DiscreteSamplersList.java
@@ -46,9 +46,13 @@ public class DiscreteSamplersList {
// Geometric ("inverse method").
final double probSuccessGeometric = 0.21;
- add(LIST, new org.apache.commons.math3.distribution.GeometricDistribution(probSuccessGeometric),
+ add(LIST, new org.apache.commons.math3.distribution.GeometricDistribution(null, probSuccessGeometric),
MathArrays.sequence(10, 0, 1),
RandomSource.create(RandomSource.ISAAC));
+ // Geometric.
+ add(LIST, new org.apache.commons.math3.distribution.GeometricDistribution(probSuccessGeometric),
+ MathArrays.sequence(10, 0, 1),
+ new GeometricSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S), probSuccessGeometric));
// Hypergeometric ("inverse method").
final int popSizeHyper = 34;
@@ -197,7 +201,7 @@ public class DiscreteSamplersList {
/**
* @param dist Distribution.
* @param points Points.
- * @return the probabilities of the given points according to the distribution.
+ * @return the probabilities of the given points according to the distribution.
*/
private static double[] getProbabilities(org.apache.commons.math3.distribution.IntegerDistribution dist,
int[] points) {
diff --git a/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/GeometricSamplerTest.java b/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/GeometricSamplerTest.java
new file mode 100644
index 0000000..8c5a39e
--- /dev/null
+++ b/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/GeometricSamplerTest.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.sampling.distribution;
+
+import org.apache.commons.rng.UniformRandomProvider;
+import org.apache.commons.rng.simple.RandomSource;
+import org.junit.Assert;
+import org.junit.Test;
+
+/**
+ * Test for the {@link GeometricSampler}. The tests hit edge cases for the sampler.
+ */
+public class GeometricSamplerTest {
+ /**
+ * Test the edge case where the probability of success is 1. This is a valid geometric distribution
+ * where the sample should always be 0.
+ */
+ @Test
+ public void testProbabilityOfSuccessIsOneGeneratesZeroForSamples() {
+ final UniformRandomProvider rng = RandomSource.create(RandomSource.SPLIT_MIX_64);
+ final GeometricSampler sampler = new GeometricSampler(rng, 1);
+ // All samples should be 0
+ for (int i = 0; i < 10; i++) {
+ Assert.assertEquals("p=1 should have 0 for all samples", 0, sampler.sample());
+ }
+ }
+
+ /**
+ * Test the edge case where the probability of success is 1 since it uses a different
+ * {@link Object#toString()} method to the normal case tested elsewhere.
+ */
+ @Test
+ public void testProbabilityOfSuccessIsOneSamplerToString() {
+ final UniformRandomProvider rng = RandomSource.create(RandomSource.SPLIT_MIX_64);
+ final GeometricSampler sampler = new GeometricSampler(rng, 1);
+ Assert.assertTrue("Missing 'Geometric' from toString", sampler.toString().contains("Geometric"));
+ }
+
+ /**
+ * Test the edge case where the probability of success is nearly 0. This is a valid geometric
+ * distribution but the sample is clipped to max integer value because the underlying exponential
+ * has a mean of positive infinity (effectively the sample is from a truncated distribution).
+ *
+ * <p>This test can be changed in future if a lower bound limit for the probability of success is
+ * introduced.
+ */
+ @Test
+ public void testProbabilityOfSuccessIsAlmostZeroGeneratesMaxValueForSamples() {
+ final UniformRandomProvider rng = RandomSource.create(RandomSource.SPLIT_MIX_64);
+ final GeometricSampler sampler = new GeometricSampler(rng, Double.MIN_VALUE);
+ // All samples should be max value
+ for (int i = 0; i < 10; i++) {
+ Assert.assertEquals("p=(almost 0) should have Integer.MAX_VALUE for all samples", Integer.MAX_VALUE,
+ sampler.sample());
+ }
+ }
+
+ /**
+ * Test probability of success {@code >1} is not allowed.
+ */
+ @SuppressWarnings("unused")
+ @Test(expected = IllegalArgumentException.class)
+ public void testProbabilityOfSuccessAboveOneThrows() {
+ final UniformRandomProvider rng = RandomSource.create(RandomSource.SPLIT_MIX_64, Long.valueOf(0));
+ new GeometricSampler(rng, Math.nextUp(1.0));
+ }
+
+ /**
+ * Test probability of success {@code 0} is not allowed.
+ */
+ @SuppressWarnings("unused")
+ @Test(expected = IllegalArgumentException.class)
+ public void testProbabilityOfSuccessIsZeroThrows() {
+ final UniformRandomProvider rng = RandomSource.create(RandomSource.SPLIT_MIX_64, Long.valueOf(0));
+ new GeometricSampler(rng, 0);
+ }
+}
[commons-rng] 08/17: Track changes
Posted by ah...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
aherbert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-rng.git
commit 1a935898f60569314313defb5a1c022d5325d45b
Author: aherbert <ah...@apache.org>
AuthorDate: Thu Feb 14 12:27:51 2019 +0000
Track changes
---
src/changes/changes.xml | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 2610b5b..8ddab98 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -75,7 +75,9 @@ re-run tests that fail, and pass the build if they succeed
within the allotted number of reruns (the test will be marked
as 'flaky' in the report).
">
-
+ <action dev="aherbert" type="add" issue="RNG-69">
+ New "GeometricSampler" class.
+ </action>
</release>