index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/commons-rng/commons-rng-client-api/src/main/java/org/apache/commons
Create_ds/commons-rng/commons-rng-client-api/src/main/java/org/apache/commons/rng/package-info.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This package contains the library's interface to be used by client * code that needs a generator of sequences of pseudo-random numbers * that are <i>uniformly distributed</i> in a specified range. */ package org.apache.commons.rng;
2,900
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/CollectionSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.apache.commons.rng.UniformRandomProvider; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Tests for {@link CollectionSampler}. */ class CollectionSamplerTest { @Test void testSampleTrivial() { final ArrayList<String> list = new ArrayList<>(); list.add("Apache"); list.add("Commons"); list.add("RNG"); final CollectionSampler<String> sampler = new CollectionSampler<>(RandomAssert.createRNG(), list); final String word = sampler.sample(); for (final String w : list) { if (word.equals(w)) { return; } } Assertions.fail(word + " not in list"); } @Test void testSamplePrecondition() { final UniformRandomProvider rng = RandomAssert.seededRNG(); // Must fail for empty collection. final List<String> empty = Collections.emptyList(); Assertions.assertThrows(IllegalArgumentException.class, () -> new CollectionSampler<>(rng, empty)); } /** * Test the SharedStateSampler implementation. */ @Test void testSharedStateSampler() { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final List<String> list = Arrays.asList("Apache", "Commons", "RNG"); final CollectionSampler<String> sampler1 = new CollectionSampler<>(rng1, list); final CollectionSampler<String> sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } }
2,901
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/CombinationSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling; import java.util.Arrays; import org.apache.commons.math3.stat.inference.ChiSquareTest; import org.apache.commons.math3.util.CombinatoricsUtils; import org.apache.commons.rng.UniformRandomProvider; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Tests for {@link CombinationSampler}. */ class CombinationSamplerTest { @Test void testSampleIsInDomain() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final int n = 6; for (int k = 1; k <= n; k++) { final CombinationSampler sampler = new CombinationSampler(rng, n, k); final int[] random = sampler.sample(); for (final int s : random) { assertIsInDomain(n, s); } } } @Test void testUniformWithKlessThanHalfN() { final int n = 8; final int k = 2; assertUniformSamples(n, k); } @Test void testUniformWithKmoreThanHalfN() { final int n = 8; final int k = 6; assertUniformSamples(n, k); } @Test void testSampleWhenNequalsKIsNotShuffled() { final UniformRandomProvider rng = RandomAssert.seededRNG(); // Check n == k boundary case. // This is allowed but the sample is not shuffled. for (int n = 1; n < 3; n++) { final int k = n; final CombinationSampler sampler = new CombinationSampler(rng, n, k); final int[] sample = sampler.sample(); Assertions.assertEquals(n, sample.length, "Incorrect sample length"); for (int i = 0; i < n; i++) { Assertions.assertEquals(i, sample[i], "Sample was shuffled"); } } } @Test void testKgreaterThanNThrows() { final UniformRandomProvider rng = RandomAssert.seededRNG(); // Must fail for k > n. final int n = 2; final int k = 3; Assertions.assertThrows(IllegalArgumentException.class, () -> new CombinationSampler(rng, n, k)); } @Test void testNequalsZeroThrows() { final UniformRandomProvider rng = RandomAssert.seededRNG(); // Must fail for n = 0. final int n = 0; final int k = 3; Assertions.assertThrows(IllegalArgumentException.class, () -> new CombinationSampler(rng, n, k)); } @Test void testKequalsZeroThrows() { final UniformRandomProvider rng = RandomAssert.seededRNG(); // Must fail for k = 0. final int n = 2; final int k = 0; Assertions.assertThrows(IllegalArgumentException.class, () -> new CombinationSampler(rng, n, k)); } @Test void testNisNegativeThrows() { final UniformRandomProvider rng = RandomAssert.seededRNG(); // Must fail for n <= 0. final int n = -1; final int k = 3; Assertions.assertThrows(IllegalArgumentException.class, () -> new CombinationSampler(rng, n, k)); } @Test void testKisNegativeThrows() { final UniformRandomProvider rng = RandomAssert.seededRNG(); // Must fail for k <= 0. final int n = 0; final int k = -1; Assertions.assertThrows(IllegalArgumentException.class, () -> new CombinationSampler(rng, n, k)); } /** * Test the SharedStateSampler implementation. */ @Test void testSharedStateSampler() { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final int n = 17; final int k = 3; final CombinationSampler sampler1 = new CombinationSampler(rng1, n, k); final CombinationSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } //// Support methods. /** * Asserts the sample value is in the range 0 to n-1. * * @param n the n * @param value the sample value */ private static void assertIsInDomain(int n, int value) { if (value < 0 || value >= n) { Assertions.fail("sample " + value + " not in the domain " + n); } } private void assertUniformSamples(int n, int k) { // The C(n, k) should generate a sample of unspecified order. // To test this each combination is allocated a unique code // based on setting k of the first n-bits in an integer. // Codes are positive for all combinations of bits that use k-bits, // otherwise they are negative. final int totalBitCombinations = 1 << n; final int[] codeLookup = new int[totalBitCombinations]; Arrays.fill(codeLookup, -1); // initialize as negative int codes = 0; for (int i = 0; i < totalBitCombinations; i++) { if (Integer.bitCount(i) == k) { // This is a valid sample so allocate a code codeLookup[i] = codes++; } } // The number of combinations C(n, k) is the binomial coefficient Assertions.assertEquals(CombinatoricsUtils.binomialCoefficient(n, k), codes, "Incorrect number of combination codes"); final long[] observed = new long[codes]; final int numSamples = 6000; final UniformRandomProvider rng = RandomAssert.createRNG(); final CombinationSampler sampler = new CombinationSampler(rng, n, k); for (int i = 0; i < numSamples; i++) { observed[findCode(codeLookup, sampler.sample())]++; } // Chi squared test of uniformity final double numExpected = numSamples / (double) codes; final double[] expected = new double[codes]; Arrays.fill(expected, numExpected); final ChiSquareTest chiSquareTest = new ChiSquareTest(); // Pass if we cannot reject null hypothesis that distributions are the same. Assertions.assertFalse(chiSquareTest.chiSquareTest(expected, observed, 0.001)); } private static int findCode(int[] codeLookup, int[] sample) { // Each sample index is used to set a bit in an integer. // The resulting bits should be a valid code. int bits = 0; for (final int s : sample) { // This shift will be from 0 to n-1 since it is from the // domain of size n. bits |= 1 << s; } if (bits >= codeLookup.length) { Assertions.fail("Bad bit combination: " + Arrays.toString(sample)); } final int code = codeLookup[bits]; if (code < 0) { Assertions.fail("Bad bit code: " + Arrays.toString(sample)); } return code; } }
2,902
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/DiscreteProbabilityCollectionSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.apache.commons.rng.UniformRandomProvider; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test class for {@link DiscreteProbabilityCollectionSampler}. */ class DiscreteProbabilityCollectionSamplerTest { /** RNG. */ private final UniformRandomProvider rng = RandomAssert.createRNG(); @Test void testPrecondition1() { // Size mismatch final List<Double> collection = Arrays.asList(1d, 2d); final double[] probabilities = {0}; Assertions.assertThrows(IllegalArgumentException.class, () -> new DiscreteProbabilityCollectionSampler<>(rng, collection, probabilities)); } @Test void testPrecondition2() { // Negative probability final List<Double> collection = Arrays.asList(1d, 2d); final double[] probabilities = {0, -1}; Assertions.assertThrows(IllegalArgumentException.class, () -> new DiscreteProbabilityCollectionSampler<>(rng, collection, probabilities)); } @Test void testPrecondition3() { // Probabilities do not sum above 0 final List<Double> collection = Arrays.asList(1d, 2d); final double[] probabilities = {0, 0}; Assertions.assertThrows(IllegalArgumentException.class, () -> new DiscreteProbabilityCollectionSampler<>(rng, collection, probabilities)); } @Test void testPrecondition4() { // NaN probability final List<Double> collection = Arrays.asList(1d, 2d); final double[] probabilities = {0, Double.NaN}; Assertions.assertThrows(IllegalArgumentException.class, () -> new DiscreteProbabilityCollectionSampler<>(rng, collection, probabilities)); } @Test void testPrecondition5() { // Infinite probability final List<Double> collection = Arrays.asList(1d, 2d); final double[] probabilities = {0, Double.POSITIVE_INFINITY}; Assertions.assertThrows(IllegalArgumentException.class, () -> new DiscreteProbabilityCollectionSampler<>(rng, collection, probabilities)); } @Test void testPrecondition6() { // Empty Map<T, Double> not allowed final Map<String, Double> collection = Collections.emptyMap(); Assertions.assertThrows(IllegalArgumentException.class, () -> new DiscreteProbabilityCollectionSampler<>(rng, collection)); } @Test void testPrecondition7() { // Empty List<T> not allowed final List<Double> collection = Collections.emptyList(); final double[] probabilities = {}; Assertions.assertThrows(IllegalArgumentException.class, () -> new DiscreteProbabilityCollectionSampler<>(rng, collection, probabilities)); } @Test void testSample() { final DiscreteProbabilityCollectionSampler<Double> sampler = new DiscreteProbabilityCollectionSampler<>(rng, Arrays.asList(3d, -1d, 3d, 7d, -2d, 8d), new double[] {0.2, 0.2, 0.3, 0.3, 0, 0}); final double expectedMean = 3.4; final double expectedVariance = 7.84; final int n = 100000000; double sum = 0; double sumOfSquares = 0; for (int i = 0; i < n; i++) { final double rand = sampler.sample(); sum += rand; sumOfSquares += rand * rand; } final double mean = sum / n; Assertions.assertEquals(expectedMean, mean, 1e-3); final double variance = sumOfSquares / n - mean * mean; Assertions.assertEquals(expectedVariance, variance, 2e-3); } @Test void testSampleUsingMap() { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final List<Integer> items = Arrays.asList(1, 3, 4, 6, 9); final double[] probabilities = {0.1, 0.2, 0.3, 0.4, 0.5}; final DiscreteProbabilityCollectionSampler<Integer> sampler1 = new DiscreteProbabilityCollectionSampler<>(rng1, items, probabilities); // Create a map version. The map iterator must be ordered so use a TreeMap. final Map<Integer, Double> map = new TreeMap<>(); for (int i = 0; i < probabilities.length; i++) { map.put(items.get(i), probabilities[i]); } final DiscreteProbabilityCollectionSampler<Integer> sampler2 = new DiscreteProbabilityCollectionSampler<>(rng2, map); for (int i = 0; i < 50; i++) { Assertions.assertEquals(sampler1.sample(), sampler2.sample()); } } /** * Edge-case test: * Create a sampler that will return 1 for nextDouble() forcing the search to * identify the end item of the cumulative probability array. */ @Test void testSampleWithProbabilityAtLastItem() { // Ensure the samples pick probability 0 (the first item) and then // a probability (for the second item) that hits an edge case. final UniformRandomProvider dummyRng = new UniformRandomProvider() { private int count; @Override public long nextLong() { return 0; } @Override public double nextDouble() { // Return 0 then the 1.0 for the probability return (count++ == 0) ? 0 : 1.0; } }; final List<Double> items = Arrays.asList(1d, 2d); final DiscreteProbabilityCollectionSampler<Double> sampler = new DiscreteProbabilityCollectionSampler<>(dummyRng, items, new double[] {0.5, 0.5}); final Double item1 = sampler.sample(); final Double item2 = sampler.sample(); // Check they are in the list Assertions.assertTrue(items.contains(item1), "Sample item1 is not from the list"); Assertions.assertTrue(items.contains(item2), "Sample item2 is not from the list"); // Test the two samples are different items Assertions.assertNotSame(item1, item2, "Item1 and 2 should be different"); } /** * Test the SharedStateSampler implementation. */ @Test void testSharedStateSampler() { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final List<Double> items = Arrays.asList(1d, 2d, 3d, 4d); final DiscreteProbabilityCollectionSampler<Double> sampler1 = new DiscreteProbabilityCollectionSampler<>(rng1, items, new double[] {0.1, 0.2, 0.3, 0.4}); final DiscreteProbabilityCollectionSampler<Double> sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } }
2,903
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/PermutationSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling; import java.util.Arrays; import org.apache.commons.math3.stat.inference.ChiSquareTest; import org.apache.commons.rng.UniformRandomProvider; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Tests for {@link PermutationSampler}. */ class PermutationSamplerTest { @Test void testSampleTrivial() { final int n = 6; final int k = 3; final PermutationSampler sampler = new PermutationSampler(RandomAssert.seededRNG(), n, k); final int[] random = sampler.sample(); SAMPLE: for (final int s : random) { for (int i = 0; i < n; i++) { if (i == s) { continue SAMPLE; } } Assertions.fail("number " + s + " not in array"); } } @Test void testSampleChiSquareTest() { final int n = 3; final int k = 3; final int[][] p = {{0, 1, 2}, {0, 2, 1}, {1, 0, 2}, {1, 2, 0}, {2, 0, 1}, {2, 1, 0}}; runSampleChiSquareTest(n, k, p); } @Test void testSubSampleChiSquareTest() { final int n = 4; final int k = 2; final int[][] p = {{0, 1}, {1, 0}, {0, 2}, {2, 0}, {0, 3}, {3, 0}, {1, 2}, {2, 1}, {1, 3}, {3, 1}, {2, 3}, {3, 2}}; runSampleChiSquareTest(n, k, p); } @Test void testSampleBoundaryCase() { final UniformRandomProvider rng = RandomAssert.seededRNG(); // Check size = 1 boundary case. final PermutationSampler sampler = new PermutationSampler(rng, 1, 1); final int[] perm = sampler.sample(); Assertions.assertEquals(1, perm.length); Assertions.assertEquals(0, perm[0]); } @Test void testSamplePrecondition1() { final UniformRandomProvider rng = RandomAssert.seededRNG(); // Must fail for k > n. Assertions.assertThrows(IllegalArgumentException.class, () -> new PermutationSampler(rng, 2, 3)); } @Test void testSamplePrecondition2() { final UniformRandomProvider rng = RandomAssert.seededRNG(); // Must fail for n = 0. Assertions.assertThrows(IllegalArgumentException.class, () -> new PermutationSampler(rng, 0, 0)); } @Test void testSamplePrecondition3() { final UniformRandomProvider rng = RandomAssert.seededRNG(); // Must fail for k < n < 0. Assertions.assertThrows(IllegalArgumentException.class, () -> new PermutationSampler(rng, -1, 0)); } @Test void testSamplePrecondition4() { final UniformRandomProvider rng = RandomAssert.seededRNG(); // Must fail for k < n < 0. Assertions.assertThrows(IllegalArgumentException.class, () -> new PermutationSampler(rng, 1, -1)); } @Test void testNatural() { final int n = 4; final int[] expected = {0, 1, 2, 3}; final int[] natural = PermutationSampler.natural(n); for (int i = 0; i < n; i++) { Assertions.assertEquals(expected[i], natural[i]); } } @Test void testNaturalZero() { final int[] natural = PermutationSampler.natural(0); Assertions.assertEquals(0, natural.length); } @Test void testShuffleNoDuplicates() { final int n = 100; final int[] orig = PermutationSampler.natural(n); final UniformRandomProvider rng = RandomAssert.seededRNG(); PermutationSampler.shuffle(rng, orig); // Test that all (unique) entries exist in the shuffled array. final int[] count = new int[n]; for (int i = 0; i < n; i++) { count[orig[i]] += 1; } for (int i = 0; i < n; i++) { Assertions.assertEquals(1, count[i]); } } @Test void testShuffleTail() { final int[] orig = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; final int[] list = orig.clone(); final int start = 4; final UniformRandomProvider rng = RandomAssert.createRNG(); PermutationSampler.shuffle(rng, list, start, false); // Ensure that all entries below index "start" did not move. for (int i = 0; i < start; i++) { Assertions.assertEquals(orig[i], list[i]); } // Ensure that at least one entry has moved. boolean ok = false; for (int i = start; i < orig.length - 1; i++) { if (orig[i] != list[i]) { ok = true; break; } } Assertions.assertTrue(ok); } @Test void testShuffleHead() { final int[] orig = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; final int[] list = orig.clone(); final int start = 4; final UniformRandomProvider rng = RandomAssert.createRNG(); PermutationSampler.shuffle(rng, list, start, true); // Ensure that all entries above index "start" did not move. for (int i = start + 1; i < orig.length; i++) { Assertions.assertEquals(orig[i], list[i]); } // Ensure that at least one entry has moved. boolean ok = false; for (int i = 0; i <= start; i++) { if (orig[i] != list[i]) { ok = true; break; } } Assertions.assertTrue(ok); } /** * Test the SharedStateSampler implementation. */ @Test void testSharedStateSampler() { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final int n = 17; final int k = 13; final PermutationSampler sampler1 = new PermutationSampler(rng1, n, k); final PermutationSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } //// Support methods. private void runSampleChiSquareTest(int n, int k, int[][] p) { final int len = p.length; final long[] observed = new long[len]; final int numSamples = 6000; final double numExpected = numSamples / (double) len; final double[] expected = new double[len]; Arrays.fill(expected, numExpected); final UniformRandomProvider rng = RandomAssert.createRNG(); final PermutationSampler sampler = new PermutationSampler(rng, n, k); for (int i = 0; i < numSamples; i++) { observed[findPerm(p, sampler.sample())]++; } // Pass if we cannot reject null hypothesis that distributions are the same. final ChiSquareTest chiSquareTest = new ChiSquareTest(); Assertions.assertFalse(chiSquareTest.chiSquareTest(expected, observed, 0.001)); } private static int findPerm(int[][] p, int[] samp) { for (int i = 0; i < p.length; i++) { if (Arrays.equals(p[i], samp)) { return i; } } Assertions.fail("Permutation not found"); return -1; } }
2,904
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/UnitSphereSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling; import java.util.Arrays; import org.apache.commons.math3.stat.inference.ChiSquareTest; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.core.source64.SplitMix64; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test for {@link UnitSphereSampler}. */ class UnitSphereSamplerTest { /** 2 pi */ private static final double TWO_PI = 2 * Math.PI; /** * Test a non-positive dimension. */ @Test void testInvalidDimensionThrows() { // Use instance constructor not factory constructor to exercise 1.X public API Assertions.assertThrows(IllegalArgumentException.class, () -> new UnitSphereSampler(0, null)); } /** * Test a non-positive dimension. */ @Test void testInvalidDimensionThrowsWithFactoryConstructor() { Assertions.assertThrows(IllegalArgumentException.class, () -> UnitSphereSampler.of(null, 0)); } /** * Test the distribution of points in one dimension. */ @Test void testDistribution1D() { testDistribution1D(false); } /** * Test the distribution of points in one dimension with the factory constructor. */ @Test void testDistribution1DWithFactoryConstructor() { testDistribution1D(true); } /** * Test the distribution of points in one dimension. * RNG-130: All samples should be 1 or -1. */ private static void testDistribution1D(boolean factoryConstructor) { final UniformRandomProvider rng = RandomAssert.createRNG(); final UnitSphereSampler generator = createUnitSphereSampler(1, rng, factoryConstructor); final int samples = 10000; // Count the negatives. int count = 0; for (int i = 0; i < samples; i++) { // Test the deprecated method once in the test suite. @SuppressWarnings("deprecation") final double[] v = generator.nextVector(); Assertions.assertEquals(1, v.length); final double d = v[0]; if (d == -1.0) { count++; } else if (d != 1.0) { // RNG-130: All samples should be 1 or -1. Assertions.fail("Invalid unit length: " + d); } } // Test the number of negatives is approximately 50% assertMonobit(count, samples); } /** * Assert that the number of 1 bits is approximately 50%. This is based upon a fixed-step "random * walk" of +1/-1 from zero. * * <p>The test is equivalent to the NIST Monobit test with a fixed p-value of 0.01. The number of * bits is recommended to be above 100.</p> * * @see <a href="https://csrc.nist.gov/publications/detail/sp/800-22/rev-1a/final">Bassham, et al * (2010) NIST SP 800-22: A Statistical Test Suite for Random and Pseudorandom Number * Generators for Cryptographic Applications. Section 2.1.</a> * * @param bitCount The bit count. * @param numberOfBits Number of bits. */ private static void assertMonobit(int bitCount, int numberOfBits) { // Convert the bit count into a number of +1/-1 steps. final double sum = 2.0 * bitCount - numberOfBits; // The reference distribution is Normal with a standard deviation of sqrt(n). // Check the absolute position is not too far from the mean of 0 with a fixed // p-value of 0.01 taken from a 2-tailed Normal distribution. Computation of // the p-value requires the complimentary error function. final double absSum = Math.abs(sum); final double max = Math.sqrt(numberOfBits) * 2.576; Assertions.assertTrue(absSum <= max, () -> "Walked too far astray: " + absSum + " > " + max + " (test will fail randomly about 1 in 100 times)"); } /** * Test the distribution of points in two dimensions. */ @Test void testDistribution2D() { testDistribution2D(false); } /** * Test the distribution of points in two dimensions with the factory constructor. */ @Test void testDistribution2DWithFactoryConstructor() { testDistribution2D(true); } /** * Test the distribution of points in two dimensions. * Obtains polar coordinates and checks the angle distribution is uniform. */ private static void testDistribution2D(boolean factoryConstructor) { final UniformRandomProvider rng = RandomAssert.createRNG(); final UnitSphereSampler generator = createUnitSphereSampler(2, rng, factoryConstructor); // In 2D, angles with a given vector should be uniformly distributed. final int angleBins = 200; final long[] observed = new long[angleBins]; final int steps = 100000; for (int i = 0; i < steps; ++i) { final double[] v = generator.sample(); Assertions.assertEquals(2, v.length); Assertions.assertEquals(1.0, length(v), 1e-10); // Get the polar angle bin from xy final int angleBin = angleBin(angleBins, v[0], v[1]); observed[angleBin]++; } final double[] expected = new double[observed.length]; Arrays.fill(expected, (double) steps / observed.length); final double p = new ChiSquareTest().chiSquareTest(expected, observed); Assertions.assertFalse(p < 0.01, () -> "p-value too small: " + p); } /** * Test the distribution of points in three dimensions. */ @Test void testDistribution3D() { testDistribution3D(false); } /** * Test the distribution of points in three dimensions with the factory constructor. */ @Test void testDistribution3DWithFactoryConstructor() { testDistribution3D(true); } /** * Test the distribution of points in three dimensions. * Obtains spherical coordinates and checks the distribution is uniform. */ private static void testDistribution3D(boolean factoryConstructor) { final UniformRandomProvider rng = RandomAssert.createRNG(); final UnitSphereSampler generator = createUnitSphereSampler(3, rng, factoryConstructor); // Get 3D spherical coordinates. Assign to a bin. // // polar angle (theta) in [0, 2pi) // azimuthal angle (phi) in [0, pi) // // theta = arctan(y/x) and is uniformly distributed // phi = arccos(z); and cos(phi) is uniformly distributed final int angleBins = 20; final int depthBins = 10; final long[] observed = new long[angleBins * depthBins]; final int steps = 1000000; for (int i = 0; i < steps; ++i) { final double[] v = generator.sample(); Assertions.assertEquals(3, v.length); Assertions.assertEquals(1.0, length(v), 1e-10); // Get the polar angle bin from xy final int angleBin = angleBin(angleBins, v[0], v[1]); // Map cos(phi) = z from [-1, 1) to [0, 1) then assign a bin final int depthBin = (int) (depthBins * (v[2] + 1) / 2); observed[depthBin * angleBins + angleBin]++; } final double[] expected = new double[observed.length]; Arrays.fill(expected, (double) steps / observed.length); final double p = new ChiSquareTest().chiSquareTest(expected, observed); Assertions.assertFalse(p < 0.01, () -> "p-value too small: " + p); } /** * Test the distribution of points in four dimensions. */ @Test void testDistribution4D() { testDistribution4D(false); } /** * Test the distribution of points in four dimensions with the factory constructor. */ @Test void testDistribution4DWithFactoryConstructor() { testDistribution4D(true); } /** * Test the distribution of points in four dimensions. * Checks the surface of the 3-sphere can be used to generate uniform samples within a circle. */ private static void testDistribution4D(boolean factoryConstructor) { final UniformRandomProvider rng = RandomAssert.createRNG(); final UnitSphereSampler generator = createUnitSphereSampler(4, rng, factoryConstructor); // No uniform distribution of spherical coordinates for a 3-sphere. // https://en.wikipedia.org/wiki/N-sphere#Spherical_coordinates // Here we exploit the fact that the uniform distribution of a (n+1)-sphere // when discarding two coordinates is uniform within a n-ball. // Thus any two coordinates of the 4 are uniform within a circle. // Here we separately test pairs (0, 1) and (2, 3). // Note: We cannot create a single bin from the two bins in each circle as they are // not independent. A point close to the edge in one circle requires a point close to // the centre in the other circle to create a unit radius from all 4 coordinates. // This test exercises the N-dimension sampler and demonstrates the vectors obey // properties of the (n+1)-sphere. // Divide the circle into layers of concentric rings and an angle. final int layers = 10; final int angleBins = 20; // Compute the radius for each layer to have the same area // (i.e. incrementally larger concentric circles must increase area by a constant). // r = sqrt(fraction * maxArea / pi) // Unit circle has area pi so we just use sqrt(fraction). final double[] r = new double[layers]; for (int i = 1; i < layers; i++) { r[i - 1] = Math.sqrt((double) i / layers); } // The final radius should be 1.0. r[layers - 1] = 1.0; final long[] observed1 = new long[layers * angleBins]; final long[] observed2 = new long[observed1.length]; final int steps = 1000000; for (int i = 0; i < steps; ++i) { final double[] v = generator.sample(); Assertions.assertEquals(4, v.length); Assertions.assertEquals(1.0, length(v), 1e-10); // Circle 1 observed1[circleBin(angleBins, r, v[0], v[1])]++; // Circle 2 observed2[circleBin(angleBins, r, v[2], v[3])]++; } final double[] expected = new double[observed1.length]; Arrays.fill(expected, (double) steps / observed1.length); final ChiSquareTest chi = new ChiSquareTest(); final double p1 = chi.chiSquareTest(expected, observed1); Assertions.assertFalse(p1 < 0.01, () -> "Circle 1 p-value too small: " + p1); final double p2 = chi.chiSquareTest(expected, observed2); Assertions.assertFalse(p2 < 0.01, () -> "Circle 2 p-value too small: " + p2); } /** * Compute a bin inside the circle using the polar angle theta and the radius thresholds. * * @param angleBins the number of angle bins * @param r the radius bin thresholds (ascending order) * @param x the x coordinate * @param y the y coordinate * @return the bin */ private static int circleBin(int angleBins, double[] r, double x, double y) { final int angleBin = angleBin(angleBins, x, y); final int radiusBin = radiusBin(r, x, y); return radiusBin * angleBins + angleBin; } /** * Compute an angle bin from the xy vector. The bin will represent the range [0, 2pi). * * @param angleBins the number of angle bins * @param x the x coordinate * @param y the y coordinate * @return the bin */ private static int angleBin(int angleBins, double x, double y) { final double angle = Math.atan2(y, x); // Map [-pi, pi) to [0, 1) then assign a bin return (int) (angleBins * (angle + Math.PI) / TWO_PI); } /** * Compute a radius bin from the xy vector. The bin is assigned if the length of the vector * is above the threshold of the bin. * * @param r the radius bin thresholds (ascending order) * @param x the x coordinate * @param y the y coordinate * @return the bin */ private static int radiusBin(double[] r, double x, double y) { final double length = Math.sqrt(x * x + y * y); // Note: The bin should be uniformly distributed. // A test using a custom binary search (avoiding double NaN checks) // shows the simple loop over a small number of bins is comparable in speed. // The loop is preferred for simplicity. A binary search may be better // if the number of bins is increased. for (int layer = 0; layer < r.length; layer++) { if (length <= r[layer]) { return layer; } } // Unreachable if the xy component is from a vector of length <= 1 throw new AssertionError("Invalid sample length: " + length); } /** * Test infinite recursion occurs with a bad provider in 2D. */ @Test void testBadProvider2D() { Assertions.assertThrows(StackOverflowError.class, () -> testBadProvider(2)); } /** * Test infinite recursion occurs with a bad provider in 3D. */ @Test void testBadProvider3D() { Assertions.assertThrows(StackOverflowError.class, () -> testBadProvider(3)); } /** * Test infinite recursion occurs with a bad provider in 4D. */ @Test void testBadProvider4D() { Assertions.assertThrows(StackOverflowError.class, () -> testBadProvider(4)); } /** * Test the edge case where the normalisation sum to divide by is always zero. * This test requires generation of Gaussian samples with the value 0. * The sample eventually fails due to infinite recursion. * See RNG-55. * * @param dimension the dimension */ private static void testBadProvider(final int dimension) { // A provider that will create zero valued Gaussian samples // from the ZigguratNormalizedGaussianSampler. final UniformRandomProvider bad = new SplitMix64(0L) { @Override public long nextLong() { return 0; } }; UnitSphereSampler.of(bad, dimension).sample(); } /** * Test the edge case where the normalisation sum to divide by is zero for 2D. */ @Test void testInvalidInverseNormalisation2D() { testInvalidInverseNormalisationND(2); } /** * Test the edge case where the normalisation sum to divide by is zero for 3D. */ @Test void testInvalidInverseNormalisation3D() { testInvalidInverseNormalisationND(3); } /** * Test the edge case where the normalisation sum to divide by is zero for 4D. */ @Test void testInvalidInverseNormalisation4D() { testInvalidInverseNormalisationND(4); } /** * Test the edge case where the normalisation sum to divide by is zero. * This test requires generation of Gaussian samples with the value 0. * See RNG-55. */ private static void testInvalidInverseNormalisationND(final int dimension) { // Create a provider that will create a bad first sample but then recover. // This checks recursion will return a good value. final UniformRandomProvider bad = new SplitMix64(0x1a2b3cL) { private int count = -2 * dimension; @Override public long nextLong() { // Return enough zeros to create Gaussian samples of zero for all coordinates. return count++ < 0 ? 0 : super.nextLong(); } }; final double[] vector = UnitSphereSampler.of(bad, dimension).sample(); Assertions.assertEquals(dimension, vector.length); Assertions.assertEquals(1.0, length(vector), 1e-10); } /** * Test to demonstrate that using floating-point equality of the norm squared with * zero is valid. Any norm squared after zero should produce a valid scaling factor. */ @Test void testNextNormSquaredAfterZeroIsValid() { // The sampler explicitly handles length == 0 using recursion. // Anything above zero should be valid. final double normSq = Math.nextUp(0.0); // Map to the scaling factor final double f = 1 / Math.sqrt(normSq); // As long as this is finite positive then the sampler is valid Assertions.assertTrue(f > 0 && f <= Double.MAX_VALUE); } /** * Test the SharedStateSampler implementation for 1D. */ @Test void testSharedStateSampler1D() { testSharedStateSampler(1, false); } /** * Test the SharedStateSampler implementation for 2D. */ @Test void testSharedStateSampler2D() { testSharedStateSampler(2, false); } /** * Test the SharedStateSampler implementation for 3D. */ @Test void testSharedStateSampler3D() { testSharedStateSampler(3, false); } /** * Test the SharedStateSampler implementation for 4D. */ @Test void testSharedStateSampler4D() { testSharedStateSampler(4, false); } /** * Test the SharedStateSampler implementation for 1D using the factory constructor. */ @Test void testSharedStateSampler1DWithFactoryConstructor() { testSharedStateSampler(1, true); } /** * Test the SharedStateSampler implementation for 2D using the factory constructor. */ @Test void testSharedStateSampler2DWithFactoryConstructor() { testSharedStateSampler(2, true); } /** * Test the SharedStateSampler implementation for 3D using the factory constructor. */ @Test void testSharedStateSampler3DWithFactoryConstructor() { testSharedStateSampler(3, true); } /** * Test the SharedStateSampler implementation for 4D using the factory constructor. */ @Test void testSharedStateSampler4DWithFactoryConstructor() { testSharedStateSampler(4, true); } /** * Test the SharedStateSampler implementation for the given dimension. * * @param dimension the dimension * @param factoryConstructor true to use the factory constructor */ private static void testSharedStateSampler(int dimension, boolean factoryConstructor) { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final UnitSphereSampler sampler1 = createUnitSphereSampler(dimension, rng1, factoryConstructor); final UnitSphereSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * Creates a UnitSphereSampler. * * @param dimension the dimension * @param rng the source of randomness * @param factoryConstructor true to use the factory constructor * @return the sampler */ private static UnitSphereSampler createUnitSphereSampler(int dimension, UniformRandomProvider rng, boolean factoryConstructor) { return factoryConstructor ? UnitSphereSampler.of(rng, dimension) : new UnitSphereSampler(dimension, rng); } /** * @return the length (L2-norm) of given vector. */ private static double length(double[] vector) { double total = 0; for (final double d : vector) { total += d * d; } return Math.sqrt(total); } }
2,905
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/CompositeSamplersTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling; import java.util.Arrays; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.math3.stat.inference.ChiSquareTest; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.CompositeSamplers.Builder; import org.apache.commons.rng.sampling.CompositeSamplers.DiscreteProbabilitySampler; import org.apache.commons.rng.sampling.CompositeSamplers.DiscreteProbabilitySamplerFactory; import org.apache.commons.rng.sampling.distribution.AliasMethodDiscreteSampler; import org.apache.commons.rng.sampling.distribution.ContinuousSampler; import org.apache.commons.rng.sampling.distribution.DiscreteSampler; import org.apache.commons.rng.sampling.distribution.GuideTableDiscreteSampler; import org.apache.commons.rng.sampling.distribution.LongSampler; import org.apache.commons.rng.sampling.distribution.SharedStateContinuousSampler; import org.apache.commons.rng.sampling.distribution.SharedStateDiscreteSampler; import org.apache.commons.rng.sampling.distribution.SharedStateLongSampler; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test class for {@link CompositeSamplers}. */ class CompositeSamplersTest { /** * Test the default implementations of the discrete probability sampler factory. */ @Test void testDiscreteProbabilitySampler() { final UniformRandomProvider rng = RandomAssert.createRNG(); final double[] probabilities = {0.1, 0.2, 0.3, 0.4}; final ChiSquareTest chisq = new ChiSquareTest(); final int n = 1000000; for (final DiscreteProbabilitySampler item : DiscreteProbabilitySampler.values()) { final DiscreteSampler sampler = item.create(rng, probabilities.clone()); final long[] observed = new long[probabilities.length]; for (int i = 0; i < n; i++) { observed[sampler.sample()]++; } final double p = chisq.chiSquareTest(probabilities, observed); Assertions.assertFalse(p < 0.001, () -> item + " p-value too small: " + p); } } /** * Test an empty builder cannot build a sampler. */ @Test void testEmptyBuilderThrows() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final Builder<SharedStateObjectSampler<Integer>> builder = CompositeSamplers .newSharedStateObjectSamplerBuilder(); Assertions.assertEquals(0, builder.size()); Assertions.assertThrows(IllegalStateException.class, () -> builder.build(rng)); } /** * Test adding null sampler to a builder. */ @Test void testNullSharedStateObjectSamplerThrows() { final Builder<SharedStateObjectSampler<Integer>> builder = CompositeSamplers .newSharedStateObjectSamplerBuilder(); Assertions.assertThrows(NullPointerException.class, () -> builder.add(null, 1.0)); } /** * Test invalid weights (zero, negative, NaN, infinte). */ @Test void testInvalidWeights() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final Builder<SharedStateObjectSampler<Integer>> builder = CompositeSamplers .newSharedStateObjectSamplerBuilder(); final RangeSampler sampler = new RangeSampler(45, 63, rng); // Zero weight is ignored Assertions.assertEquals(0, builder.size()); builder.add(sampler, 0.0); Assertions.assertEquals(0, builder.size()); final double[] bad = {-1, Double.NaN, Double.POSITIVE_INFINITY}; for (final double weight : bad) { Assertions.assertThrows(IllegalArgumentException.class, () -> builder.add(sampler, weight), () -> "Did not detect invalid weight: " + weight); } } /** * Test a single sampler added to the builder is returned without a composite. */ @Test void testSingleSharedStateObjectSampler() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final Builder<SharedStateObjectSampler<Integer>> builder = CompositeSamplers .newSharedStateObjectSamplerBuilder(); final RangeSampler sampler = new RangeSampler(45, 63, rng); builder.add(sampler, 1.0); Assertions.assertEquals(1, builder.size()); final SharedStateObjectSampler<Integer> composite = builder.build(rng); Assertions.assertSame(sampler, composite); } /** * Test sampling is uniform across several ObjectSampler samplers. */ @Test void testObjectSamplerSamples() { final Builder<ObjectSampler<Integer>> builder = CompositeSamplers.newObjectSamplerBuilder(); final UniformRandomProvider rng = RandomAssert.createRNG(); final int n = 15; final int min = -134; final int max = 2097; addObjectSamplers(builder, n, min, max, rng); assertObjectSamplerSamples(builder.build(rng), min, max); } /** * Test sampling is uniform across several SharedStateObjectSampler samplers. */ @Test void testSharedStateObjectSamplerSamples() { final Builder<SharedStateObjectSampler<Integer>> builder = CompositeSamplers .newSharedStateObjectSamplerBuilder(); final UniformRandomProvider rng = RandomAssert.createRNG(); final int n = 11; final int min = 42; final int max = 678; addObjectSamplers(builder, n, min, max, rng); // Exercise the shared state interface final UniformRandomProvider rng1 = RandomAssert.createRNG(); assertObjectSamplerSamples(builder.build(rng).withUniformRandomProvider(rng1), min, max); } /** * Test sampling is uniform across several SharedStateObjectSampler samplers * using a custom factory that implements SharedStateDiscreteSampler. */ @Test void testSharedStateObjectSamplerSamplesWithCustomSharedStateDiscreteSamplerFactory() { final Builder<SharedStateObjectSampler<Integer>> builder = CompositeSamplers .newSharedStateObjectSamplerBuilder(); final AtomicInteger factoryCount = new AtomicInteger(); builder.setFactory(new DiscreteProbabilitySamplerFactory() { @Override public DiscreteSampler create(UniformRandomProvider rng, double[] probabilities) { factoryCount.incrementAndGet(); // Use an expanded table with a non-default alpha return AliasMethodDiscreteSampler.of(rng, probabilities, 2); } }); final UniformRandomProvider rng = RandomAssert.createRNG(); final int n = 7; final int min = -610; final int max = 745; addObjectSamplers(builder, n, min, max, rng); // Exercise the shared state interface final UniformRandomProvider rng1 = RandomAssert.createRNG(); assertObjectSamplerSamples(builder.build(rng).withUniformRandomProvider(rng1), min, max); Assertions.assertEquals(1, factoryCount.get(), "Factory should not be used to create the shared state sampler"); } /** * Test sampling is uniform across several SharedStateObjectSampler samplers * using a custom factory that implements DiscreteSampler (so must be wrapped). */ @Test void testSharedStateObjectSamplerSamplesWithCustomDiscreteSamplerFactory() { final Builder<SharedStateObjectSampler<Integer>> builder = CompositeSamplers .newSharedStateObjectSamplerBuilder(); final AtomicInteger factoryCount = new AtomicInteger(); builder.setFactory(new DiscreteProbabilitySamplerFactory() { @Override public DiscreteSampler create(UniformRandomProvider rng, double[] probabilities) { factoryCount.incrementAndGet(); // Wrap so it is not a SharedStateSamplerInstance. final DiscreteSampler sampler = GuideTableDiscreteSampler.of(rng, probabilities, 2); // Destroy the probabilities to check that custom factories are not trusted. Arrays.fill(probabilities, Double.NaN); return new DiscreteSampler() { @Override public int sample() { return sampler.sample(); } }; } }); final UniformRandomProvider rng = RandomAssert.createRNG(); final int n = 14; final int min = 56; final int max = 2033; addObjectSamplers(builder, n, min, max, rng); // Exercise the shared state interface. // This tests the custom factory is used twice. final UniformRandomProvider rng1 = RandomAssert.createRNG(); assertObjectSamplerSamples(builder.build(rng).withUniformRandomProvider(rng1), min, max); Assertions.assertEquals(2, factoryCount.get(), "Factory should be used to create the shared state sampler"); } /** * Test sampling is uniform across several ObjectSampler samplers with a uniform * weighting. This tests an edge case where there is no requirement for a * sampler from a discrete probability distribution as the distribution is * uniform. */ @Test void testObjectSamplerSamplesWithUniformWeights() { final Builder<ObjectSampler<Integer>> builder = CompositeSamplers.newObjectSamplerBuilder(); final UniformRandomProvider rng = RandomAssert.createRNG(); final int max = 60; final int interval = 10; for (int min = 0; min < max; min += interval) { builder.add(new RangeSampler(min, min + interval, rng), 1.0); } assertObjectSamplerSamples(builder.build(rng), 0, max); } /** * Test sampling is uniform across several ObjectSampler samplers with very * large weights. This tests an edge case where the weights with sum to * infinity. */ @Test void testObjectSamplerSamplesWithVeryLargeWeights() { final Builder<ObjectSampler<Integer>> builder = CompositeSamplers.newObjectSamplerBuilder(); final UniformRandomProvider rng = RandomAssert.createRNG(); // Ratio 4:4:2:1 // The weights will sum to infinity as they are more than 2^1024. final double w4 = 0x1.0p1023; final double w2 = 0x1.0p1022; final double w1 = 0x1.0p1021; Assertions.assertEquals(Double.POSITIVE_INFINITY, w4 + w4 + w2 + w1); builder.add(new RangeSampler(0, 40, rng), w4); builder.add(new RangeSampler(40, 80, rng), w4); builder.add(new RangeSampler(80, 100, rng), w2); builder.add(new RangeSampler(100, 110, rng), w1); assertObjectSamplerSamples(builder.build(rng), 0, 110); } /** * Test sampling is uniform across several ObjectSampler samplers with very * small weights. This tests an edge case where the weights divided by their sum * are valid (due to accurate floating-point division) but cannot be multiplied * by the reciprocal of the sum. */ @Test void testObjectSamplerSamplesWithSubNormalWeights() { final Builder<ObjectSampler<Integer>> builder = CompositeSamplers.newObjectSamplerBuilder(); final UniformRandomProvider rng = RandomAssert.createRNG(); // Ratio 4:4:2:1 // The weights are very small sub-normal numbers final double w4 = Double.MIN_VALUE * 4; final double w2 = Double.MIN_VALUE * 2; final double w1 = Double.MIN_VALUE; final double sum = w4 + w4 + w2 + w1; // Cannot do a divide by multiplying by the reciprocal Assertions.assertEquals(Double.POSITIVE_INFINITY, 1.0 / sum); // A divide works so the sampler should work Assertions.assertEquals(4.0 / 11, w4 / sum); Assertions.assertEquals(2.0 / 11, w2 / sum); Assertions.assertEquals(1.0 / 11, w1 / sum); builder.add(new RangeSampler(0, 40, rng), w4); builder.add(new RangeSampler(40, 80, rng), w4); builder.add(new RangeSampler(80, 100, rng), w2); builder.add(new RangeSampler(100, 110, rng), w1); assertObjectSamplerSamples(builder.build(rng), 0, 110); } /** * Add samplers to the builder that sample from contiguous ranges between the * minimum and maximum. Note: {@code max - min >= n} * * @param builder the builder * @param n the number of samplers (must be {@code >= 2}) * @param min the minimum (inclusive) * @param max the maximum (exclusive) * @param rng the source of randomness */ private static void addObjectSamplers(Builder<? super SharedStateObjectSampler<Integer>> builder, int n, int min, int max, UniformRandomProvider rng) { // Create the ranges using n-1 random ticks in the range (min, max), // adding the limits and then sorting in ascending order. // The samplers are then constructed: // // min-------A-----B----max // Sampler 1 = [min, A) // Sampler 2 = [A, B) // Sampler 3 = [B, max) // Use a combination sampler to ensure the ticks are unique in the range. // This will throw if the range is negative. final int range = max - min - 1; int[] ticks = new CombinationSampler(rng, range, n - 1).sample(); // Shift the ticks into the range for (int i = 0; i < ticks.length; i++) { ticks[i] += min + 1; } // Add the min and max ticks = Arrays.copyOf(ticks, n + 1); ticks[n - 1] = min; ticks[n] = max; Arrays.sort(ticks); // Sample within the ranges between the ticks final int before = builder.size(); for (int i = 1; i < ticks.length; i++) { final RangeSampler sampler = new RangeSampler(ticks[i - 1], ticks[i], rng); // Weight using the range builder.add(sampler, sampler.range); } Assertions.assertEquals(n, builder.size() - before, "Failed to add the correct number of samplers"); } /** * Assert sampling is uniform between the minimum and maximum. * * @param sampler the sampler * @param min the minimum (inclusive) * @param max the maximum (exclusive) */ private static void assertObjectSamplerSamples(ObjectSampler<Integer> sampler, int min, int max) { final int n = 100000; final long[] observed = new long[max - min]; for (int i = 0; i < n; i++) { observed[sampler.sample() - min]++; } final double[] expected = new double[observed.length]; Arrays.fill(expected, (double) n / expected.length); final double p = new ChiSquareTest().chiSquareTest(expected, observed); Assertions.assertFalse(p < 0.001, () -> "p-value too small: " + p); } /** * Test sampling is uniform across several DiscreteSampler samplers. */ @Test void testDiscreteSamplerSamples() { final Builder<DiscreteSampler> builder = CompositeSamplers.newDiscreteSamplerBuilder(); final UniformRandomProvider rng = RandomAssert.createRNG(); final int n = 15; final int min = -134; final int max = 2097; addDiscreteSamplers(builder, n, min, max, rng); assertDiscreteSamplerSamples(builder.build(rng), min, max); } /** * Test sampling is uniform across several SharedStateDiscreteSampler samplers. */ @Test void testSharedStateDiscreteSamplerSamples() { final Builder<SharedStateDiscreteSampler> builder = CompositeSamplers.newSharedStateDiscreteSamplerBuilder(); final UniformRandomProvider rng = RandomAssert.createRNG(); final int n = 11; final int min = 42; final int max = 678; addDiscreteSamplers(builder, n, min, max, rng); assertDiscreteSamplerSamples(builder.build(rng), min, max); } /** * Add samplers to the builder that sample from contiguous ranges between the * minimum and maximum. Note: {@code max - min >= n} * * @param builder the builder * @param n the number of samplers (must be {@code >= 2}) * @param min the minimum (inclusive) * @param max the maximum (exclusive) * @param rng the source of randomness */ private static void addDiscreteSamplers(Builder<? super SharedStateDiscreteSampler> builder, int n, int min, int max, UniformRandomProvider rng) { // Create the ranges using n-1 random ticks in the range (min, max), // adding the limits and then sorting in ascending order. // The samplers are then constructed: // // min-------A-----B----max // Sampler 1 = [min, A) // Sampler 2 = [A, B) // Sampler 3 = [B, max) // Use a combination sampler to ensure the ticks are unique in the range. // This will throw if the range is negative. final int range = max - min - 1; int[] ticks = new CombinationSampler(rng, range, n - 1).sample(); // Shift the ticks into the range for (int i = 0; i < ticks.length; i++) { ticks[i] += min + 1; } // Add the min and max ticks = Arrays.copyOf(ticks, n + 1); ticks[n - 1] = min; ticks[n] = max; Arrays.sort(ticks); // Sample within the ranges between the ticks final int before = builder.size(); for (int i = 1; i < ticks.length; i++) { final IntRangeSampler sampler = new IntRangeSampler(rng, ticks[i - 1], ticks[i]); // Weight using the range builder.add(sampler, sampler.range); } Assertions.assertEquals(n, builder.size() - before, "Failed to add the correct number of samplers"); } /** * Assert sampling is uniform between the minimum and maximum. * * @param sampler the sampler * @param min the minimum (inclusive) * @param max the maximum (exclusive) */ private static void assertDiscreteSamplerSamples(DiscreteSampler sampler, int min, int max) { final int n = 100000; final long[] observed = new long[max - min]; for (int i = 0; i < n; i++) { observed[sampler.sample() - min]++; } final double[] expected = new double[observed.length]; Arrays.fill(expected, (double) n / expected.length); final double p = new ChiSquareTest().chiSquareTest(expected, observed); Assertions.assertFalse(p < 0.001, () -> "p-value too small: " + p); } /** * Test sampling is uniform across several ContinuousSampler samplers. */ @Test void testContinuousSamplerSamples() { final Builder<ContinuousSampler> builder = CompositeSamplers.newContinuousSamplerBuilder(); final UniformRandomProvider rng = RandomAssert.createRNG(); final int n = 15; final double min = 67.2; final double max = 2033.8; addContinuousSamplers(builder, n, min, max, rng); assertContinuousSamplerSamples(builder.build(rng), min, max); } /** * Test sampling is uniform across several SharedStateContinuousSampler samplers. */ @Test void testSharedStateContinuousSamplerSamples() { final Builder<SharedStateContinuousSampler> builder = CompositeSamplers .newSharedStateContinuousSamplerBuilder(); final UniformRandomProvider rng = RandomAssert.createRNG(); final int n = 11; final double min = -15.7; final double max = 123.4; addContinuousSamplers(builder, n, min, max, rng); assertContinuousSamplerSamples(builder.build(rng), min, max); } /** * Add samplers to the builder that sample from contiguous ranges between the * minimum and maximum. Note: {@code max - min >= n} * * @param builder the builder * @param n the number of samplers (must be {@code >= 2}) * @param min the minimum (inclusive) * @param max the maximum (exclusive) * @param rng the source of randomness */ private static void addContinuousSamplers(Builder<? super SharedStateContinuousSampler> builder, int n, double min, double max, UniformRandomProvider rng) { // Create the ranges using n-1 random ticks in the range (min, max), // adding the limits and then sorting in ascending order. // The samplers are then constructed: // // min-------A-----B----max // Sampler 1 = [min, A) // Sampler 2 = [A, B) // Sampler 3 = [B, max) // For double values it is extremely unlikely the same value will be generated. // An assertion is performed to ensure we create the correct number of samplers. DoubleRangeSampler sampler = new DoubleRangeSampler(rng, min, max); final double[] ticks = new double[n + 1]; ticks[0] = min; ticks[1] = max; // Shift the ticks into the range for (int i = 2; i < ticks.length; i++) { ticks[i] = sampler.sample(); } Arrays.sort(ticks); // Sample within the ranges between the ticks final int before = builder.size(); for (int i = 1; i < ticks.length; i++) { sampler = new DoubleRangeSampler(rng, ticks[i - 1], ticks[i]); // Weight using the range builder.add(sampler, sampler.range()); } Assertions.assertEquals(n, builder.size() - before, "Failed to add the correct number of samplers"); } /** * Assert sampling is uniform between the minimum and maximum. * * @param sampler the sampler * @param min the minimum (inclusive) * @param max the maximum (exclusive) */ private static void assertContinuousSamplerSamples(ContinuousSampler sampler, double min, double max) { final int n = 100000; final int bins = 200; final long[] observed = new long[bins]; final double scale = bins / (max - min); for (int i = 0; i < n; i++) { // scale the sample into a bin within the range: // bin = bins * (x - min) / (max - min) observed[(int) (scale * (sampler.sample() - min))]++; } final double[] expected = new double[observed.length]; Arrays.fill(expected, (double) n / expected.length); final double p = new ChiSquareTest().chiSquareTest(expected, observed); Assertions.assertFalse(p < 0.001, () -> "p-value too small: " + p); } /** * Test sampling is uniform across several LongSampler samplers. */ @Test void testLongSamplerSamples() { final Builder<LongSampler> builder = CompositeSamplers.newLongSamplerBuilder(); final UniformRandomProvider rng = RandomAssert.createRNG(); final int n = 15; final long min = -134; final long max = 1L << 54; addLongSamplers(builder, n, min, max, rng); assertLongSamplerSamples(builder.build(rng), min, max); } /** * Test sampling is uniform across several SharedStateLongSampler samplers. */ @Test void testSharedStateLongSamplerSamples() { final Builder<SharedStateLongSampler> builder = CompositeSamplers.newSharedStateLongSamplerBuilder(); final UniformRandomProvider rng = RandomAssert.createRNG(); final int n = 11; final long min = 42; final long max = 1L << 53; addLongSamplers(builder, n, min, max, rng); assertLongSamplerSamples(builder.build(rng), min, max); } /** * Add samplers to the builder that sample from contiguous ranges between the * minimum and maximum. Note: {@code max - min >= n} * * @param builder the builder * @param n the number of samplers (must be {@code >= 2}) * @param min the minimum (inclusive) * @param max the maximum (exclusive) * @param rng the source of randomness */ private static void addLongSamplers(Builder<? super SharedStateLongSampler> builder, int n, long min, long max, UniformRandomProvider rng) { // Create the ranges using n-1 random ticks in the range (min, max), // adding the limits and then sorting in ascending order. // The samplers are then constructed: // // min-------A-----B----max // Sampler 1 = [min, A) // Sampler 2 = [A, B) // Sampler 3 = [B, max) // For long values it is extremely unlikely the same value will be generated. // An assertion is performed to ensure we create the correct number of samplers. LongRangeSampler sampler = new LongRangeSampler(rng, min, max); final long[] ticks = new long[n + 1]; ticks[0] = min; ticks[1] = max; // Shift the ticks into the range for (int i = 2; i < ticks.length; i++) { ticks[i] = sampler.sample(); } Arrays.sort(ticks); // Sample within the ranges between the ticks final int before = builder.size(); for (int i = 1; i < ticks.length; i++) { sampler = new LongRangeSampler(rng, ticks[i - 1], ticks[i]); // Weight using the range builder.add(sampler, sampler.range); } Assertions.assertEquals(n, builder.size() - before, "Failed to add the correct number of samplers"); } /** * Assert sampling is uniform between the minimum and maximum. * * @param sampler the sampler * @param min the minimum (inclusive) * @param max the maximum (exclusive) */ private static void assertLongSamplerSamples(LongSampler sampler, long min, long max) { final int n = 100000; final int bins = 200; final long[] observed = new long[bins]; final long range = max - min; for (int i = 0; i < n; i++) { // scale the sample into a bin within the range: observed[(int) (bins * (sampler.sample() - min) / range)]++; } final double[] expected = new double[observed.length]; Arrays.fill(expected, (double) n / expected.length); final double p = new ChiSquareTest().chiSquareTest(expected, observed); Assertions.assertFalse(p < 0.001, () -> "p-value too small: " + p); } /** * Test the SharedStateSampler implementation for the composite * SharedStateObjectSampler. */ @Test void testSharedStateObjectSampler() { testSharedStateObjectSampler(false); } /** * Test the SharedStateSampler implementation for the composite * SharedStateObjectSampler with a factory that does not support a shared state sampler. */ @Test void testSharedStateObjectSamplerWithCustomFactory() { testSharedStateObjectSampler(true); } /** * Test the SharedStateSampler implementation for the composite * SharedStateObjectSampler. * * @param customFactory Set to true to use a custom discrete sampler factory that does not * support a shared stated sampler. */ private static void testSharedStateObjectSampler(boolean customFactory) { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final Builder<SharedStateObjectSampler<Integer>> builder = CompositeSamplers .newSharedStateObjectSamplerBuilder(); if (customFactory) { addFactoryWithNoSharedStateSupport(builder); } // Sample within the ranges between the ticks final int[] ticks = {6, 13, 42, 99}; for (int i = 1; i < ticks.length; i++) { final RangeSampler sampler = new RangeSampler(ticks[i - 1], ticks[i], rng1); // Weight using the range builder.add(sampler, sampler.range); } final SharedStateObjectSampler<Integer> sampler1 = builder.build(rng1); final SharedStateObjectSampler<Integer> sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * Test the SharedStateSampler implementation for the composite * SharedStateDiscreteSampler. */ @Test void testSharedStateDiscreteSampler() { testSharedStateDiscreteSampler(false); } /** * Test the SharedStateSampler implementation for the composite * SharedStateDiscreteSampler with a factory that does not support a shared state sampler. */ @Test void testSharedStateDiscreteSamplerWithCustomFactory() { testSharedStateDiscreteSampler(true); } /** * Test the SharedStateSampler implementation for the composite * SharedStateDiscreteSampler. * * @param customFactory Set to true to use a custom discrete sampler factory that does not * support a shared stated sampler. */ private static void testSharedStateDiscreteSampler(boolean customFactory) { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final Builder<SharedStateDiscreteSampler> builder = CompositeSamplers.newSharedStateDiscreteSamplerBuilder(); if (customFactory) { addFactoryWithNoSharedStateSupport(builder); } // Sample within the ranges between the ticks final int[] ticks = {-3, 5, 14, 22}; for (int i = 1; i < ticks.length; i++) { final IntRangeSampler sampler = new IntRangeSampler(rng1, ticks[i - 1], ticks[i]); // Weight using the range builder.add(sampler, sampler.range); } final SharedStateDiscreteSampler sampler1 = builder.build(rng1); final SharedStateDiscreteSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * Test the SharedStateSampler implementation for the composite * SharedStateContinuousSampler. */ @Test void testSharedStateContinuousSampler() { testSharedStateContinuousSampler(false); } /** * Test the SharedStateSampler implementation for the composite * SharedStateContinuousSampler with a factory that does not support a shared state sampler. */ @Test void testSharedStateContinuousSamplerWithCustomFactory() { testSharedStateContinuousSampler(true); } /** * Test the SharedStateSampler implementation for the composite * SharedStateContinuousSampler. * * @param customFactory Set to true to use a custom discrete sampler factory that does not * support a shared stated sampler. */ private static void testSharedStateContinuousSampler(boolean customFactory) { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final Builder<SharedStateContinuousSampler> builder = CompositeSamplers .newSharedStateContinuousSamplerBuilder(); if (customFactory) { addFactoryWithNoSharedStateSupport(builder); } // Sample within the ranges between the ticks final double[] ticks = {7.89, 13.99, 21.7, 35.6, 45.5}; for (int i = 1; i < ticks.length; i++) { final DoubleRangeSampler sampler = new DoubleRangeSampler(rng1, ticks[i - 1], ticks[i]); // Weight using the range builder.add(sampler, sampler.range()); } final SharedStateContinuousSampler sampler1 = builder.build(rng1); final SharedStateContinuousSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * Adds a DiscreteSamplerFactory to the builder that creates samplers that do not share state. * * @param builder the builder */ private static void addFactoryWithNoSharedStateSupport(Builder<?> builder) { builder.setFactory(new DiscreteProbabilitySamplerFactory() { @Override public DiscreteSampler create(UniformRandomProvider rng, double[] probabilities) { // Wrap so it is not a SharedStateSamplerInstance. final DiscreteSampler sampler = GuideTableDiscreteSampler.of(rng, probabilities, 2); // Destroy the probabilities to check that custom factories are not trusted. Arrays.fill(probabilities, Double.NaN); return new DiscreteSampler() { @Override public int sample() { return sampler.sample(); } }; } }); } /** * Test the SharedStateSampler implementation for the composite * SharedStateLongSampler. */ @Test void testSharedStateLongSampler() { testSharedStateLongSampler(false); } /** * Test the SharedStateSampler implementation for the composite * SharedStateLongSampler with a factory that does not support a shared state sampler. */ @Test void testSharedStateLongSamplerWithCustomFactory() { testSharedStateLongSampler(true); } /** * Test the SharedStateSampler implementation for the composite * SharedStateLongSampler. * * @param customFactory Set to true to use a custom discrete sampler factory that does not * support a shared stated sampler. */ private static void testSharedStateLongSampler(boolean customFactory) { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final Builder<SharedStateLongSampler> builder = CompositeSamplers.newSharedStateLongSamplerBuilder(); if (customFactory) { addFactoryWithNoSharedStateSupport(builder); } // Sample within the ranges between the ticks final long[] ticks = {-32634628368L, 516234712, 1472839427384234L, 72364572187368423L}; for (int i = 1; i < ticks.length; i++) { final LongRangeSampler sampler = new LongRangeSampler(rng1, ticks[i - 1], ticks[i]); // Weight using the range builder.add(sampler, sampler.range); } final SharedStateLongSampler sampler1 = builder.build(rng1); final SharedStateLongSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * Sample an object {@code Integer} from a range. */ private static class RangeSampler implements SharedStateObjectSampler<Integer> { private final int min; private final int range; private final UniformRandomProvider rng; /** * @param min the minimum (inclusive) * @param max the maximum (exclusive) * @param rng the source of randomness */ RangeSampler(int min, int max, UniformRandomProvider rng) { this.min = min; this.range = max - min; this.rng = rng; } @Override public Integer sample() { return min + rng.nextInt(range); } @Override public SharedStateObjectSampler<Integer> withUniformRandomProvider(UniformRandomProvider generator) { return new RangeSampler(min, min + range, generator); } } /** * Sample a primitive {@code integer} from a range. */ private static class IntRangeSampler implements SharedStateDiscreteSampler { private final int min; private final int range; private final UniformRandomProvider rng; /** * @param rng the source of randomness * @param min the minimum (inclusive) * @param max the maximum (exclusive) */ IntRangeSampler(UniformRandomProvider rng, int min, int max) { this.min = min; this.range = max - min; this.rng = rng; } @Override public int sample() { return min + rng.nextInt(range); } @Override public SharedStateDiscreteSampler withUniformRandomProvider(UniformRandomProvider generator) { return new IntRangeSampler(generator, min, min + range); } } /** * Sample a primitive {@code double} from a range between a and b. */ private static class DoubleRangeSampler implements SharedStateContinuousSampler { private final double a; private final double b; private final UniformRandomProvider rng; /** * @param rng the source of randomness * @param a bound a * @param b bound b */ DoubleRangeSampler(UniformRandomProvider rng, double a, double b) { this.a = a; this.b = b; this.rng = rng; } /** * Get the range from a to b. * * @return the range */ double range() { return Math.abs(b - a); } @Override public double sample() { // a + u * (b - a) == u * b + (1 - u) * a final double u = rng.nextDouble(); return u * b + (1 - u) * a; } @Override public SharedStateContinuousSampler withUniformRandomProvider(UniformRandomProvider generator) { return new DoubleRangeSampler(generator, a, b); } } /** * Sample a primitive {@code long} from a range. */ private static class LongRangeSampler implements SharedStateLongSampler { private final long min; private final long range; private final UniformRandomProvider rng; /** * @param rng the source of randomness * @param min the minimum (inclusive) * @param max the maximum (exclusive) */ LongRangeSampler(UniformRandomProvider rng, long min, long max) { this.min = min; this.range = max - min; this.rng = rng; } @Override public long sample() { return min + rng.nextLong(range); } @Override public SharedStateLongSampler withUniformRandomProvider(UniformRandomProvider generator) { return new LongRangeSampler(generator, min, min + range); } } }
2,906
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/ObjectSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling; import java.util.concurrent.ThreadLocalRandom; import org.apache.commons.rng.UniformRandomProvider; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; /** * Tests the default methods in the {@link ObjectSampler} interface. */ class ObjectSamplerTest { @Test void testSamplesUnlimitedSize() { final ObjectSampler<Double> s = RandomAssert.createRNG()::nextDouble; Assertions.assertEquals(Long.MAX_VALUE, s.samples().spliterator().estimateSize()); } @RepeatedTest(value = 3) void testSamples() { final UniformRandomProvider[] rngs = RandomAssert.createRNG(2); final ObjectSampler<Double> s1 = rngs[0]::nextDouble; final ObjectSampler<Double> s2 = rngs[1]::nextDouble; final int count = ThreadLocalRandom.current().nextInt(3, 13); Assertions.assertArrayEquals(createSamples(s1, count), s2.samples().limit(count).toArray()); } @ParameterizedTest @ValueSource(ints = {0, 1, 2, 5, 13}) void testSamples(int streamSize) { final UniformRandomProvider[] rngs = RandomAssert.createRNG(2); final ObjectSampler<Double> s1 = rngs[0]::nextDouble; final ObjectSampler<Double> s2 = rngs[1]::nextDouble; Assertions.assertArrayEquals(createSamples(s1, streamSize), s2.samples(streamSize).toArray()); } /** * Creates an array of samples. * * @param sampler Source of samples. * @param count Number of samples. * @return the samples */ private static Double[] createSamples(ObjectSampler<Double> sampler, int count) { final Double[] data = new Double[count]; for (int i = 0; i < count; i++) { // Explicit boxing data[i] = Double.valueOf(sampler.sample()); } return data; } }
2,907
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/ArraySamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling; import java.util.Arrays; import org.apache.commons.math3.stat.inference.ChiSquareTest; import org.apache.commons.rng.UniformRandomProvider; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; /** * Tests for {@link ArraySampler}. */ class ArraySamplerTest { @Test void testNullArguments() { final UniformRandomProvider rng = RandomAssert.seededRNG(); // To generate a NPE for the RNG requires shuffle conditions to be satisfied (length > 1). final boolean[] a = {false, false}; final byte[] b = {0, 0}; final char[] c = {0, 0}; final double[] d = {0, 0}; final float[] e = {0, 0}; final int[] f = {0, 0}; final long[] g = {0, 0}; final short[] h = {0, 0}; final Object[] i = {new Object(), new Object()}; // Shuffle full length ArraySampler.shuffle(rng, a); ArraySampler.shuffle(rng, b); ArraySampler.shuffle(rng, c); ArraySampler.shuffle(rng, d); ArraySampler.shuffle(rng, e); ArraySampler.shuffle(rng, f); ArraySampler.shuffle(rng, g); ArraySampler.shuffle(rng, h); ArraySampler.shuffle(rng, i); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(null, a)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(null, b)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(null, c)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(null, d)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(null, e)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(null, f)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(null, g)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(null, h)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(null, i)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(rng, (boolean[]) null)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(rng, (byte[]) null)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(rng, (char[]) null)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(rng, (double[]) null)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(rng, (float[]) null)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(rng, (int[]) null)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(rng, (long[]) null)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(rng, (short[]) null)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(rng, (Object[]) null)); // Shuffle with sub-range ArraySampler.shuffle(rng, a, 0, 2); ArraySampler.shuffle(rng, b, 0, 2); ArraySampler.shuffle(rng, c, 0, 2); ArraySampler.shuffle(rng, d, 0, 2); ArraySampler.shuffle(rng, e, 0, 2); ArraySampler.shuffle(rng, f, 0, 2); ArraySampler.shuffle(rng, g, 0, 2); ArraySampler.shuffle(rng, h, 0, 2); ArraySampler.shuffle(rng, i, 0, 2); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(null, a, 0, 2)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(null, b, 0, 2)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(null, c, 0, 2)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(null, d, 0, 2)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(null, e, 0, 2)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(null, f, 0, 2)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(null, g, 0, 2)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(null, h, 0, 2)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(null, i, 0, 2)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(rng, (boolean[]) null, 0, 2)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(rng, (byte[]) null, 0, 2)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(rng, (char[]) null, 0, 2)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(rng, (double[]) null, 0, 2)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(rng, (float[]) null, 0, 2)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(rng, (int[]) null, 0, 2)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(rng, (long[]) null, 0, 2)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(rng, (short[]) null, 0, 2)); Assertions.assertThrows(NullPointerException.class, () -> ArraySampler.shuffle(rng, (Object[]) null, 0, 2)); } @ParameterizedTest @ValueSource(ints = {0, 1, 3}) void testReturnedReference(int length) { final UniformRandomProvider rng = RandomAssert.seededRNG(); final boolean[] a = new boolean[length]; final byte[] b = new byte[length]; final char[] c = new char[length]; final double[] d = new double[length]; final float[] e = new float[length]; final int[] f = new int[length]; final long[] g = new long[length]; final short[] h = new short[length]; final Object[] i = new Object[length]; Assertions.assertSame(a, ArraySampler.shuffle(rng, a)); Assertions.assertSame(b, ArraySampler.shuffle(rng, b)); Assertions.assertSame(c, ArraySampler.shuffle(rng, c)); Assertions.assertSame(d, ArraySampler.shuffle(rng, d)); Assertions.assertSame(e, ArraySampler.shuffle(rng, e)); Assertions.assertSame(f, ArraySampler.shuffle(rng, f)); Assertions.assertSame(g, ArraySampler.shuffle(rng, g)); Assertions.assertSame(h, ArraySampler.shuffle(rng, h)); Assertions.assertSame(i, ArraySampler.shuffle(rng, i)); } @ParameterizedTest @CsvSource({ "0, 0, 0", "0, 2, 2", "0, 2, 4", "1, 3, 4", "2, 4, 4", }) void testReturnedReferenceRange(int from, int to, int length) { final UniformRandomProvider rng = RandomAssert.seededRNG(); final boolean[] a = new boolean[length]; final byte[] b = new byte[length]; final char[] c = new char[length]; final double[] d = new double[length]; final float[] e = new float[length]; final int[] f = new int[length]; final long[] g = new long[length]; final short[] h = new short[length]; final Object[] i = new Object[length]; Assertions.assertSame(a, ArraySampler.shuffle(rng, a, from, to)); Assertions.assertSame(b, ArraySampler.shuffle(rng, b, from, to)); Assertions.assertSame(c, ArraySampler.shuffle(rng, c, from, to)); Assertions.assertSame(d, ArraySampler.shuffle(rng, d, from, to)); Assertions.assertSame(e, ArraySampler.shuffle(rng, e, from, to)); Assertions.assertSame(f, ArraySampler.shuffle(rng, f, from, to)); Assertions.assertSame(g, ArraySampler.shuffle(rng, g, from, to)); Assertions.assertSame(h, ArraySampler.shuffle(rng, h, from, to)); Assertions.assertSame(i, ArraySampler.shuffle(rng, i, from, to)); } // Shuffle tests for randomness performed on int[]. // All other implementations must match int[] shuffle. /** * Test an invalid sub-range. * * <p>Note if the range is invalid then any shuffle will eventually raise * an out-of-bounds exception when the invalid part of the range is encountered. * This may destructively modify the input before the exception. This test * verifies the RNG is never invoked and the input is unchanged. * * <p>This is only tested on int[]. * We assume all other methods check the sub-range in the same way. */ @ParameterizedTest @CsvSource({ "-1, 10, 20", // from < 0 "10, 0, 20", // from > to "10, -1, 20", // from > to; to < 0 "10, 20, 15", // to > length "-20, -10, 10", // length >= to - from > 0; from < to < 0 "-10, 10, 10", // from < 0; to - from > length // Overflow of differences // -2147483648 == Integer.MIN_VALUE "10, -2147483648, 20", // length > to - from > 0; to < from }) void testInvalidSubRange(int from, int to, int length) { final int[] array = PermutationSampler.natural(length); final int[] original = array.clone(); final UniformRandomProvider rng = new UniformRandomProvider() { @Override public long nextLong() { Assertions.fail("Preconditions should fail before RNG is used"); return 0; } }; Assertions.assertThrows(IndexOutOfBoundsException.class, () -> ArraySampler.shuffle(rng, array, from, to)); Assertions.assertArrayEquals(original, array, "Array was destructively modified"); } /** * Test that all (unique) entries exist in the shuffled array. */ @ParameterizedTest @ValueSource(ints = {13, 42, 100}) void testShuffleNoDuplicates(int length) { final int[] array = PermutationSampler.natural(length); final UniformRandomProvider rng = RandomAssert.seededRNG(); final int[] count = new int[length]; for (int j = 1; j <= 10; j++) { ArraySampler.shuffle(rng, array); for (int i = 0; i < count.length; i++) { count[array[i]]++; } for (int i = 0; i < count.length; i++) { Assertions.assertEquals(j, count[i], "Shuffle duplicated data"); } } } /** * Test that all (unique) entries exist in the shuffled sub-range of the array. */ @ParameterizedTest @CsvSource({ "0, 10, 10", "5, 10, 10", "0, 5, 10", "5, 10, 15", }) void testShuffleSubRangeNoDuplicates(int from, int to, int length) { // Natural sequence in the sub-range final int[] array = natural(from, to, length); final UniformRandomProvider rng = RandomAssert.seededRNG(); final int[] count = new int[to - from]; for (int j = 1; j <= 10; j++) { ArraySampler.shuffle(rng, array, from, to); for (int i = 0; i < from; i++) { Assertions.assertEquals(i - from, array[i], "Shuffle changed data < from"); } for (int i = from; i < to; i++) { count[array[i]]++; } for (int i = to; i < length; i++) { Assertions.assertEquals(i - from, array[i], "Shuffle changed data >= to"); } for (int i = 0; i < count.length; i++) { Assertions.assertEquals(j, count[i], "Shuffle duplicated data"); } } } /** * Test that shuffle of the full range using the range arguments matches a full-range shuffle. */ @ParameterizedTest @ValueSource(ints = {9, 17}) void testShuffleFullRangeMatchesShuffle(int length) { final int[] array1 = PermutationSampler.natural(length); final int[] array2 = array1.clone(); final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); for (int j = 1; j <= 10; j++) { ArraySampler.shuffle(rng1, array1); ArraySampler.shuffle(rng2, array2, 0, length); Assertions.assertArrayEquals(array1, array2); } } /** * Test that shuffle of a sub-range using the range arguments matches a full-range shuffle * of an equivalent length array. */ @ParameterizedTest @CsvSource({ "5, 10, 10", "0, 5, 10", "5, 10, 15", }) void testShuffleSubRangeMatchesShuffle(int from, int to, int length) { final int[] array1 = PermutationSampler.natural(to - from); // Natural sequence in the sub-range final int[] array2 = natural(from, to, length); final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); for (int j = 1; j <= 10; j++) { ArraySampler.shuffle(rng1, array1); ArraySampler.shuffle(rng2, array2, from, to); Assertions.assertArrayEquals(array1, Arrays.copyOfRange(array2, from, to)); } } @ParameterizedTest @ValueSource(ints = {13, 16}) void testShuffleIsRandom(int length) { final int[] array = PermutationSampler.natural(length); final UniformRandomProvider rng = RandomAssert.createRNG(); final long[][] counts = new long[length][length]; for (int j = 1; j <= 1000; j++) { ArraySampler.shuffle(rng, array); for (int i = 0; i < length; i++) { counts[i][array[i]]++; } } final double p = new ChiSquareTest().chiSquareTest(counts); Assertions.assertFalse(p < 1e-3, () -> "p-value too small: " + p); } @ParameterizedTest @CsvSource({ "0, 10, 10", "7, 18, 18", "0, 13, 20", "5, 17, 20", }) void testShuffleSubRangeIsRandom(int from, int to, int length) { // Natural sequence in the sub-range final int[] array = natural(from, to, length); final UniformRandomProvider rng = RandomAssert.createRNG(); final int n = to - from; final long[][] counts = new long[n][n]; for (int j = 1; j <= 1000; j++) { ArraySampler.shuffle(rng, array, from, to); for (int i = 0; i < n; i++) { counts[i][array[from + i]]++; } } final double p = new ChiSquareTest().chiSquareTest(counts); Assertions.assertFalse(p < 1e-3, () -> "p-value too small: " + p); } // Test other implementations. Include zero length arrays. @ParameterizedTest @ValueSource(ints = {0, 13, 16}) void testShuffle(int length) { final int[] a = PermutationSampler.natural(length); final byte[] b = bytes(a); final char[] c = chars(a); final double[] d = doubles(a); final float[] e = floats(a); final long[] f = longs(a); final short[] g = shorts(a); final Integer[] h = boxed(a); ArraySampler.shuffle(RandomAssert.seededRNG(), a); ArraySampler.shuffle(RandomAssert.seededRNG(), b); ArraySampler.shuffle(RandomAssert.seededRNG(), c); ArraySampler.shuffle(RandomAssert.seededRNG(), d); ArraySampler.shuffle(RandomAssert.seededRNG(), e); ArraySampler.shuffle(RandomAssert.seededRNG(), f); ArraySampler.shuffle(RandomAssert.seededRNG(), g); ArraySampler.shuffle(RandomAssert.seededRNG(), h); Assertions.assertArrayEquals(a, ints(b), "byte"); Assertions.assertArrayEquals(a, ints(c), "char"); Assertions.assertArrayEquals(a, ints(d), "double"); Assertions.assertArrayEquals(a, ints(e), "float"); Assertions.assertArrayEquals(a, ints(f), "long"); Assertions.assertArrayEquals(a, ints(g), "short"); Assertions.assertArrayEquals(a, ints(h), "Object"); } @ParameterizedTest @CsvSource({ "0, 0, 0", "0, 10, 10", "7, 18, 18", "0, 13, 20", "5, 17, 20", // Test is limited to max length 127 by signed byte "57, 121, 127", }) void testShuffleSubRange(int from, int to, int length) { final int[] a = PermutationSampler.natural(length); final byte[] b = bytes(a); final char[] c = chars(a); final double[] d = doubles(a); final float[] e = floats(a); final long[] f = longs(a); final short[] g = shorts(a); final Integer[] h = boxed(a); ArraySampler.shuffle(RandomAssert.seededRNG(), a, from, to); ArraySampler.shuffle(RandomAssert.seededRNG(), b, from, to); ArraySampler.shuffle(RandomAssert.seededRNG(), c, from, to); ArraySampler.shuffle(RandomAssert.seededRNG(), d, from, to); ArraySampler.shuffle(RandomAssert.seededRNG(), e, from, to); ArraySampler.shuffle(RandomAssert.seededRNG(), f, from, to); ArraySampler.shuffle(RandomAssert.seededRNG(), g, from, to); ArraySampler.shuffle(RandomAssert.seededRNG(), h, from, to); Assertions.assertArrayEquals(a, ints(b), "byte"); Assertions.assertArrayEquals(a, ints(c), "char"); Assertions.assertArrayEquals(a, ints(d), "double"); Assertions.assertArrayEquals(a, ints(e), "float"); Assertions.assertArrayEquals(a, ints(f), "long"); Assertions.assertArrayEquals(a, ints(g), "short"); Assertions.assertArrayEquals(a, ints(h), "Object"); } // Special case for boolean[]. // Use a larger array and it is very unlikely a shuffle of bits will be the same. // This cannot be done with the other arrays as the limit is 127 for a "universal" number. // Here we compare to the byte[] shuffle, not the int[] array shuffle. This allows // the input array to be generated as random bytes which is more random than the // alternating 0, 1, 0 of the lowest bit in a natural sequence. This may make the test // most robust to detecting the boolean shuffle swapping around the wrong pairs. @ParameterizedTest @ValueSource(ints = {0, 1234}) void testShuffleBoolean(int length) { final byte[] a = randomBitsAsBytes(length); final boolean[] b = booleans(a); ArraySampler.shuffle(RandomAssert.seededRNG(), a); ArraySampler.shuffle(RandomAssert.seededRNG(), b); Assertions.assertArrayEquals(a, bytes(b)); } @ParameterizedTest @CsvSource({ "0, 0, 0", "0, 1000, 1000", "100, 1000, 1000", "0, 900, 1000", "100, 1100, 1200", }) void testShuffleBooleanSubRange(int from, int to, int length) { final byte[] a = randomBitsAsBytes(length); final boolean[] b = booleans(a); ArraySampler.shuffle(RandomAssert.seededRNG(), a, from, to); ArraySampler.shuffle(RandomAssert.seededRNG(), b, from, to); Assertions.assertArrayEquals(a, bytes(b)); } /** * Creates a natural sequence (0, 1, ..., n-1) in the sub-range {@code [from, to)} * where {@code n = to - from}. Values outside the sub-range are a continuation * of the sequence in either direction. * * @param from Lower-bound (inclusive) of the sub-range * @param to Upper-bound (exclusive) of the sub-range * @param length Upper-bound (exclusive) of the range * @return an array whose entries are the numbers 0, 1, ..., {@code n}-1. */ private static int[] natural(int from, int to, int length) { final int[] array = new int[length]; for (int i = 0; i < from; i++) { array[i] = i - from; } for (int i = from; i < to; i++) { array[i] = i - from; } for (int i = to; i < length; i++) { array[i] = i - from; } return array; } /** * Create random bits of the specified length stored as bytes using {0, 1}. * * @param length Length of the array. * @return the bits, 1 per byte */ private static byte[] randomBitsAsBytes(int length) { // Random bytes final byte[] a = new byte[length]; RandomAssert.createRNG().nextBytes(a); // Convert to boolean bits: 0 or 1 for (int i = 0; i < length; i++) { a[i] = (byte) (a[i] & 1); } return a; } // Conversion helpers // Special case for boolean <=> bytes as {0, 1} private static boolean[] booleans(byte[] in) { final boolean[] out = new boolean[in.length]; for (int i = 0; i < in.length; i++) { out[i] = (in[i] & 1) == 1; } return out; } private static byte[] bytes(boolean[] in) { final byte[] out = new byte[in.length]; for (int i = 0; i < in.length; i++) { out[i] = in[i] ? (byte) 1 : 0; } return out; } // Conversion helpers using standard primitive conversions. // This may involve narrowing conversions so "universal" numbers are // limited to lower 0 by char and upper 127 by byte. private static byte[] bytes(int[] in) { final byte[] out = new byte[in.length]; for (int i = 0; i < in.length; i++) { out[i] = (byte) in[i]; } return out; } private static char[] chars(int[] in) { final char[] out = new char[in.length]; for (int i = 0; i < in.length; i++) { out[i] = (char) in[i]; } return out; } private static double[] doubles(int[] in) { final double[] out = new double[in.length]; for (int i = 0; i < in.length; i++) { out[i] = in[i]; } return out; } private static float[] floats(int[] in) { final float[] out = new float[in.length]; for (int i = 0; i < in.length; i++) { out[i] = in[i]; } return out; } private static long[] longs(int[] in) { final long[] out = new long[in.length]; for (int i = 0; i < in.length; i++) { out[i] = in[i]; } return out; } private static short[] shorts(int[] in) { final short[] out = new short[in.length]; for (int i = 0; i < in.length; i++) { out[i] = (short) in[i]; } return out; } private static int[] ints(byte[] in) { final int[] out = new int[in.length]; for (int i = 0; i < in.length; i++) { out[i] = in[i]; } return out; } private static int[] ints(char[] in) { final int[] out = new int[in.length]; for (int i = 0; i < in.length; i++) { out[i] = in[i]; } return out; } private static int[] ints(double[] in) { final int[] out = new int[in.length]; for (int i = 0; i < in.length; i++) { out[i] = (int) in[i]; } return out; } private static int[] ints(float[] in) { final int[] out = new int[in.length]; for (int i = 0; i < in.length; i++) { out[i] = (int) in[i]; } return out; } private static int[] ints(long[] in) { final int[] out = new int[in.length]; for (int i = 0; i < in.length; i++) { out[i] = (int) in[i]; } return out; } private static int[] ints(short[] in) { final int[] out = new int[in.length]; for (int i = 0; i < in.length; i++) { out[i] = in[i]; } return out; } private static Integer[] boxed(int[] in) { return Arrays.stream(in).boxed().toArray(Integer[]::new); } private static int[] ints(Integer[] in) { return Arrays.stream(in).mapToInt(Integer::intValue).toArray(); } }
2,908
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/RandomAssert.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling; import org.junit.jupiter.api.Assertions; import java.util.EnumSet; import java.util.concurrent.ThreadLocalRandom; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Stream; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.distribution.ContinuousSampler; import org.apache.commons.rng.sampling.distribution.DiscreteSampler; import org.apache.commons.rng.sampling.distribution.LongSampler; import org.apache.commons.rng.simple.RandomSource; /** * Utility class for testing random samplers. */ public final class RandomAssert { /** Number of samples to generate to test for equal sequences. */ private static final int SAMPLES = 10; /** Default seed for the default generator. */ private static final Long DEFAULT_SEED; static { DEFAULT_SEED = Long.valueOf(RandomSource.createLong()); // Record this to allow debugging of tests that failed with the seeded generator Logger.getLogger(RandomAssert.class.getName()).log(Level.INFO, () -> "Default seed: " + DEFAULT_SEED); } /** The sources for a new random generator instance. */ private static final RandomSource[] SOURCES; static { final EnumSet<RandomSource> set = EnumSet.allOf(RandomSource.class); // Remove all generators that do not pass Test U01 BigCrush or // fail PractRand before 4 TiB of output. // See: https://commons.apache.org/proper/commons-rng/userguide/rng.html#a5._Quality set.remove(RandomSource.JDK); set.remove(RandomSource.WELL_512_A); set.remove(RandomSource.WELL_1024_A); set.remove(RandomSource.WELL_19937_A); set.remove(RandomSource.WELL_19937_C); set.remove(RandomSource.WELL_44497_A); set.remove(RandomSource.WELL_44497_B); set.remove(RandomSource.MT); set.remove(RandomSource.XOR_SHIFT_1024_S); set.remove(RandomSource.TWO_CMRES); set.remove(RandomSource.TWO_CMRES_SELECT); set.remove(RandomSource.MT_64); set.remove(RandomSource.XOR_SHIFT_1024_S_PHI); set.remove(RandomSource.XO_RO_SHI_RO_64_S); set.remove(RandomSource.XO_SHI_RO_128_PLUS); set.remove(RandomSource.XO_RO_SHI_RO_128_PLUS); set.remove(RandomSource.XO_SHI_RO_256_PLUS); set.remove(RandomSource.XO_SHI_RO_512_PLUS); set.remove(RandomSource.PCG_MCG_XSH_RS_32); set.remove(RandomSource.XO_RO_SHI_RO_1024_S); SOURCES = set.toArray(new RandomSource[0]); } /** * Class contains only static methods. */ private RandomAssert() {} /** * Exercise the {@link ContinuousSampler} interface, and * ensure that the two samplers produce the same sequence. * * @param sampler1 First sampler. * @param sampler2 Second sampler. */ public static void assertProduceSameSequence(ContinuousSampler sampler1, ContinuousSampler sampler2) { for (int i = 0; i < SAMPLES; i++) { Assertions.assertEquals(sampler1.sample(), sampler2.sample()); } } /** * Exercise the {@link DiscreteSampler} interface, and * ensure that the two samplers produce the same sequence. * * @param sampler1 First sampler. * @param sampler2 Second sampler. */ public static void assertProduceSameSequence(DiscreteSampler sampler1, DiscreteSampler sampler2) { for (int i = 0; i < SAMPLES; i++) { Assertions.assertEquals(sampler1.sample(), sampler2.sample()); } } /** * Exercise the {@link LongSampler} interface, and * ensure that the two samplers produce the same sequence. * * @param sampler1 First sampler. * @param sampler2 Second sampler. */ public static void assertProduceSameSequence(LongSampler sampler1, LongSampler sampler2) { for (int i = 0; i < SAMPLES; i++) { Assertions.assertEquals(sampler1.sample(), sampler2.sample()); } } /** * Exercise the {@link ObjectSampler} interface, and * ensure that the two samplers produce the same sequence. * * <p>Arrays are tested using {@link Assertions#assertArrayEquals(Object[], Object[])} * which handles primitive arrays using exact equality and objects using * {@link Object#equals(Object)}. Otherwise {@link Assertions#assertEquals(Object, Object)} * is used which makes use of {@link Object#equals(Object)}.</p> * * <p>This should be used to test samplers of any type by wrapping the sample method * to an anonymous {@link ObjectSampler} class.</p> * * @param sampler1 First sampler. * @param sampler2 Second sampler. */ public static <T> void assertProduceSameSequence(ObjectSampler<T> sampler1, ObjectSampler<T> sampler2) { for (int i = 0; i < SAMPLES; i++) { final T value1 = sampler1.sample(); final T value2 = sampler2.sample(); if (isArray(value1) && isArray(value2)) { // JUnit assertArrayEquals will handle nested primitive arrays Assertions.assertArrayEquals(new Object[] {value1}, new Object[] {value2}); } else { Assertions.assertEquals(value1, value2); } } } /** * Checks if the object is an array. * * @param object Object. * @return true if an array */ private static boolean isArray(Object object) { return object != null && object.getClass().isArray(); } /** * Create a new random generator instance. The implementation will be randomly chosen * from a selection of high-quality generators. * * <p>This is a helper method to return a generator for use in testing where the * underlying source should not impact the test. This ensures the test is robust upon * repeat invocation across different JVM instances where the generator will most * likely be different. * * <p>Note that use of this method is preferable to use of a fixed seed generator. Any * test that is flaky when using this method may require an update to the test * assumptions and assertions. * * <p>It should be noted that repeat invocations of a failing test by the surefire plugin * will receive a different instance. * * @return the uniform random provider * @see RandomSource#create() */ public static UniformRandomProvider createRNG() { return SOURCES[ThreadLocalRandom.current().nextInt(SOURCES.length)].create(); } /** * Create a count of new identical random generator instances. The implementation will be * randomly chosen from a selection of high-quality generators. Each instance * will be a copy created from the same seed and thus outputs the same sequence. * * <p>This is a helper method to return generators for use in parallel testing * where the underlying source should not impact the test. This ensures the test * is robust upon repeat invocation across different JVM instances where the * generator will most likely be different. * * <p>Note that use of this method is preferable to use of a fixed seed * generator. Any test that is flaky when using this method may require an * update to the test assumptions and assertions. * * <p>It should be noted that repeat invocations of a failing test by the * surefire plugin will receive different instances. * * @param count Number of copies to create. * @return the uniform random provider * @see RandomSource#create() * @see RandomSource#createSeed() */ public static UniformRandomProvider[] createRNG(int count) { final RandomSource source = SOURCES[ThreadLocalRandom.current().nextInt(SOURCES.length)]; final byte[] seed = source.createSeed(); return Stream.generate(() -> source.create(seed)) .limit(count) .toArray(UniformRandomProvider[]::new); } /** * Create a new random generator instance with a fixed seed. The implementation is a * high-quality generator with a low construction cost. The seed is expected to be * different between invocations of the Java Virtual Machine. * * <p>This is a helper method to return a generator for use in testing where the * underlying source should not impact the test. This ensures the test is robust upon * repeat invocation across different JVM instances where the generator will most * likely be different. * * <p>Note that use of this method is preferable to use of a fixed seed generator as it provides * a single entry point to update tests that use a deterministic output from a RNG. * * <p>This method should be used in preference to {@link RandomAssert#createRNG()} when: * <ul> * <li>the test requires multiple instances of a generator with the same output * <li>the test requires a functioning generator but the output is not of consequence * </ul> * * <p>It should be noted that repeat invocations of a failing test by the surefire plugin * will receive an instance with the same seed. If a test may fail due to stochastic conditions * then consider using {@link RandomAssert#createRNG()} which will obtain a different RNG * for repeat test executions. * * @return the uniform random provider * @see RandomSource#create() * @see #createRNG() */ public static UniformRandomProvider seededRNG() { return RandomSource.SPLIT_MIX_64.create(DEFAULT_SEED); } }
2,909
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/ListSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Set; import java.util.function.Supplier; import org.apache.commons.math3.stat.inference.ChiSquareTest; import org.apache.commons.rng.UniformRandomProvider; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Tests for {@link ListSampler}. */ class ListSamplerTest { @Test void testSample() { final String[][] c = {{"0", "1"}, {"0", "2"}, {"0", "3"}, {"0", "4"}, {"1", "2"}, {"1", "3"}, {"1", "4"}, {"2", "3"}, {"2", "4"}, {"3", "4"}}; final long[] observed = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; final double[] expected = {100, 100, 100, 100, 100, 100, 100, 100, 100, 100}; final HashSet<String> cPop = new HashSet<>(); // {0, 1, 2, 3, 4}. for (int i = 0; i < 5; i++) { cPop.add(Integer.toString(i)); } final List<Set<String>> sets = new ArrayList<>(); // 2-sets from 5. for (int i = 0; i < 10; i++) { final HashSet<String> hs = new HashSet<>(); hs.add(c[i][0]); hs.add(c[i][1]); sets.add(hs); } final UniformRandomProvider rng = RandomAssert.createRNG(); for (int i = 0; i < 1000; i++) { observed[findSample(sets, ListSampler.sample(rng, new ArrayList<>(cPop), 2))]++; } // Pass if we cannot reject null hypothesis that distributions are the same. final ChiSquareTest chiSquareTest = new ChiSquareTest(); Assertions.assertFalse(chiSquareTest.chiSquareTest(expected, observed, 0.001)); } @Test void testSampleWhole() { // Sample of size = size of collection must return the same collection. final List<String> list = new ArrayList<>(); list.add("one"); final UniformRandomProvider rng = RandomAssert.seededRNG(); final List<String> one = ListSampler.sample(rng, list, 1); Assertions.assertEquals(1, one.size()); Assertions.assertTrue(one.contains("one")); } @Test void testSamplePrecondition1() { // Must fail for sample size > collection size. final List<String> list = new ArrayList<>(); list.add("one"); final UniformRandomProvider rng = RandomAssert.seededRNG(); Assertions.assertThrows(IllegalArgumentException.class, () -> ListSampler.sample(rng, list, 2)); } @Test void testSamplePrecondition2() { // Must fail for empty collection. final List<String> list = new ArrayList<>(); final UniformRandomProvider rng = RandomAssert.seededRNG(); Assertions.assertThrows(IllegalArgumentException.class, () -> ListSampler.sample(rng, list, 1)); } @Test void testShuffle() { final UniformRandomProvider rng = RandomAssert.createRNG(); final List<Integer> orig = new ArrayList<>(); for (int i = 0; i < 10; i++) { orig.add((i + 1) * rng.nextInt()); } final List<Integer> arrayList = new ArrayList<>(orig); ListSampler.shuffle(rng, arrayList); // Ensure that at least one entry has moved. Assertions.assertTrue(compare(orig, arrayList, 0, orig.size(), false), "ArrayList"); final List<Integer> linkedList = new LinkedList<>(orig); ListSampler.shuffle(rng, linkedList); // Ensure that at least one entry has moved. Assertions.assertTrue(compare(orig, linkedList, 0, orig.size(), false), "LinkedList"); } @Test void testShuffleTail() { final UniformRandomProvider rng = RandomAssert.createRNG(); final List<Integer> orig = new ArrayList<>(); for (int i = 0; i < 10; i++) { orig.add((i + 1) * rng.nextInt()); } final List<Integer> list = new ArrayList<>(orig); final int start = 4; ListSampler.shuffle(rng, list, start, false); // Ensure that all entries below index "start" did not move. Assertions.assertTrue(compare(orig, list, 0, start, true)); // Ensure that at least one entry has moved. Assertions.assertTrue(compare(orig, list, start, orig.size(), false)); } @Test void testShuffleHead() { final UniformRandomProvider rng = RandomAssert.createRNG(); final List<Integer> orig = new ArrayList<>(); for (int i = 0; i < 10; i++) { orig.add((i + 1) * rng.nextInt()); } final List<Integer> list = new ArrayList<>(orig); final int start = 4; ListSampler.shuffle(rng, list, start, true); // Ensure that all entries above index "start" did not move. Assertions.assertTrue(compare(orig, list, start + 1, orig.size(), true)); // Ensure that at least one entry has moved. Assertions.assertTrue(compare(orig, list, 0, start + 1, false)); } /** * Test shuffle matches {@link PermutationSampler#shuffle(UniformRandomProvider, int[])}. * The implementation may be different but the result is a Fisher-Yates shuffle so the * output order should match. */ @Test void testShuffleMatchesPermutationSamplerShuffle() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final List<Integer> orig = new ArrayList<>(); for (int i = 0; i < 10; i++) { orig.add((i + 1) * rng.nextInt()); } assertShuffleMatchesPermutationSamplerShuffle(new ArrayList<>(orig)); assertShuffleMatchesPermutationSamplerShuffle(new LinkedList<>(orig)); } /** * Test shuffle matches {@link PermutationSampler#shuffle(UniformRandomProvider, int[], int, boolean)}. * The implementation may be different but the result is a Fisher-Yates shuffle so the * output order should match. */ @Test void testShuffleMatchesPermutationSamplerShuffleDirectional() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final List<Integer> orig = new ArrayList<>(); for (int i = 0; i < 10; i++) { orig.add((i + 1) * rng.nextInt()); } assertShuffleMatchesPermutationSamplerShuffle(new ArrayList<>(orig), 4, true); assertShuffleMatchesPermutationSamplerShuffle(new ArrayList<>(orig), 4, false); assertShuffleMatchesPermutationSamplerShuffle(new LinkedList<>(orig), 4, true); assertShuffleMatchesPermutationSamplerShuffle(new LinkedList<>(orig), 4, false); } /** * This test hits the edge case when a LinkedList is small enough that the algorithm * using a RandomAccess list is faster than the one with an iterator. */ @Test void testShuffleWithSmallLinkedList() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final int size = 3; final List<Integer> orig = new ArrayList<>(); for (int i = 0; i < size; i++) { orig.add((i + 1) * rng.nextInt()); } // When the size is small there is a chance that the list has no entries that move. // E.g. The number of permutations of 3 items is only 6 giving a 1/6 chance of no change. // So repeat test that the small shuffle matches the PermutationSampler. // 10 times is (1/6)^10 or 1 in 60,466,176 of no change. for (int i = 0; i < 10; i++) { assertShuffleMatchesPermutationSamplerShuffle(new LinkedList<>(orig), size - 1, true); } } //// Support methods. /** * If {@code same == true}, return {@code true} if all entries are * the same; if {@code same == false}, return {@code true} if at * least one entry is different. */ private static <T> boolean compare(List<T> orig, List<T> list, int start, int end, boolean same) { for (int i = start; i < end; i++) { if (!orig.get(i).equals(list.get(i))) { return !same; } } return same; } private static <T extends Set<String>> int findSample(List<T> u, Collection<String> sampList) { final String[] samp = sampList.toArray(new String[sampList.size()]); for (int i = 0; i < u.size(); i++) { final T set = u.get(i); final HashSet<String> sampSet = new HashSet<>(); for (int j = 0; j < samp.length; j++) { sampSet.add(samp[j]); } if (set.equals(sampSet)) { return i; } } Assertions.fail("Sample not found: { " + samp[0] + ", " + samp[1] + " }"); return -1; } /** * Assert the shuffle matches {@link PermutationSampler#shuffle(UniformRandomProvider, int[])}. * * @param list Array whose entries will be shuffled (in-place). */ private static void assertShuffleMatchesPermutationSamplerShuffle(List<Integer> list) { final int[] array = new int[list.size()]; ListIterator<Integer> it = list.listIterator(); for (int i = 0; i < array.length; i++) { array[i] = it.next(); } // Identical RNGs final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); ListSampler.shuffle(rng1, list); PermutationSampler.shuffle(rng2, array); final Supplier<String> msg = () -> "Type=" + list.getClass().getSimpleName(); it = list.listIterator(); for (int i = 0; i < array.length; i++) { Assertions.assertEquals(array[i], it.next().intValue(), msg); } } /** * Assert the shuffle matches {@link PermutationSampler#shuffle(UniformRandomProvider, int[], int, boolean)}. * * @param list Array whose entries will be shuffled (in-place). * @param start Index at which shuffling begins. * @param towardHead Shuffling is performed for index positions between * {@code start} and either the end (if {@code false}) or the beginning * (if {@code true}) of the array. */ private static void assertShuffleMatchesPermutationSamplerShuffle(List<Integer> list, int start, boolean towardHead) { final int[] array = new int[list.size()]; ListIterator<Integer> it = list.listIterator(); for (int i = 0; i < array.length; i++) { array[i] = it.next(); } // Identical RNGs final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); ListSampler.shuffle(rng1, list, start, towardHead); PermutationSampler.shuffle(rng2, array, start, towardHead); final Supplier<String> msg = () -> String.format("Type=%s start=%d towardHead=%b", list.getClass().getSimpleName(), start, towardHead); it = list.listIterator(); for (int i = 0; i < array.length; i++) { Assertions.assertEquals(array[i], it.next().intValue(), msg); } } }
2,910
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/shape/CoordinatesTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.shape; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test for {@link Coordinates} utility class. */ class CoordinatesTest { /** * Test {@link Coordinates#requireFinite(double[], String)} detects infinite and NaN. */ @Test void testRequireFiniteWithMessageThrows() { final double[] c = {0, 1, 2}; final String message = "This should be prepended"; Assertions.assertSame(c, Coordinates.requireFinite(c, message)); final double[] bad = {Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NaN}; for (int i = 0; i < c.length; i++) { final int ii = i; for (final double d : bad) { final double value = c[i]; c[i] = d; final IllegalArgumentException ex = Assertions.assertThrows(IllegalArgumentException.class, () -> Coordinates.requireFinite(c, message), () -> String.format("Did not detect non-finite coordinate: %d = %s", ii, d)); Assertions.assertTrue(ex.getMessage().startsWith(message), "Missing message prefix"); c[i] = value; } } } /** * Test {@link Coordinates#requireLength(double[], int, String)} detects invalid lengths. */ @Test void testRequireLengthWithMessageThrows() { final String message = "This should be prepended"; for (final double[] c : new double[][] {{0, 1}, {0, 1, 2}}) { final int length = c.length; Assertions.assertSame(c, Coordinates.requireLength(c, length, message)); IllegalArgumentException ex = Assertions.assertThrows(IllegalArgumentException.class, () -> Coordinates.requireLength(c, length - 1, message), () -> "Did not detect length was too long: " + (length - 1)); Assertions.assertTrue(ex.getMessage().startsWith(message), "Missing message prefix"); ex = Assertions.assertThrows(IllegalArgumentException.class, () -> Coordinates.requireLength(c, length + 1, message), () -> "Did not detect length was too short: " + (length + 1)); Assertions.assertTrue(ex.getMessage().startsWith(message), "Missing message prefix"); } } }
2,911
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/shape/BoxSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.shape; import java.util.Arrays; import org.apache.commons.math3.stat.inference.ChiSquareTest; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.apache.commons.rng.sampling.UnitSphereSampler; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test for {@link BoxSampler}. */ class BoxSamplerTest { /** * Test an unsupported dimension. */ @Test void testInvalidDimensionThrows() { final UniformRandomProvider rng = RandomAssert.seededRNG(); Assertions.assertThrows(IllegalArgumentException.class, () -> BoxSampler.of(rng, new double[1], new double[1])); } /** * Test a dimension mismatch between vertices. */ @Test void testDimensionMismatchThrows() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final double[] c2 = new double[2]; final double[] c3 = new double[3]; for (double[][] c : new double[][][] { {c2, c3}, {c3, c2}, }) { Assertions.assertThrows(IllegalArgumentException.class, () -> BoxSampler.of(rng, c[0], c[1]), () -> String.format("Did not detect dimension mismatch: %d,%d", c[0].length, c[1].length)); } } /** * Test non-finite vertices. */ @Test void testNonFiniteVertexCoordinates() { final UniformRandomProvider rng = RandomAssert.seededRNG(); // A valid box final double[][] c = new double[][] { {0, 1, 2}, {-1, 2, 3} }; Assertions.assertNotNull(BoxSampler.of(rng, c[0], c[1])); final double[] bad = {Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NaN}; for (int i = 0; i < c.length; i++) { final int ii = i; for (int j = 0; j < c[0].length; j++) { final int jj = j; for (final double d : bad) { final double value = c[i][j]; c[i][j] = d; Assertions.assertThrows(IllegalArgumentException.class, () -> BoxSampler.of(rng, c[0], c[1]), () -> String.format("Did not detect non-finite coordinate: %d,%d = %s", ii, jj, d)); c[i][j] = value; } } } } /** * Test a box with coordinates that are separated by more than * {@link Double#MAX_VALUE} in 2D. */ @Test void testExtremeValueCoordinates2D() { testExtremeValueCoordinates(2); } /** * Test a box with coordinates that are separated by more than * {@link Double#MAX_VALUE} in 3D. */ @Test void testExtremeValueCoordinates3D() { testExtremeValueCoordinates(3); } /** * Test a box with coordinates that are separated by more than * {@link Double#MAX_VALUE} in 4D. */ @Test void testExtremeValueCoordinates4D() { testExtremeValueCoordinates(4); } /** * Test a box with coordinates that are separated by more than * {@link Double#MAX_VALUE}. * * @param dimension the dimension */ private static void testExtremeValueCoordinates(int dimension) { final double[][] c1 = new double[2][dimension]; final double[][] c2 = new double[2][dimension]; // Create a valid box that can be scaled Arrays.fill(c1[0], -1); Arrays.fill(c1[1], 1); // Extremely large value for scaling. Use a power of 2 for exact scaling. final double scale = 0x1.0p1023; for (int i = 0; i < c1.length; i++) { // Scale the second box for (int j = 0; j < dimension; j++) { c2[i][j] = c1[i][j] * scale; } } // Show the box is too big to compute vectors between points. Assertions.assertEquals(Double.POSITIVE_INFINITY, c2[1][0] - c2[0][0], "Expect vector b - a to be infinite in the x dimension"); final BoxSampler sampler1 = BoxSampler.of( RandomAssert.seededRNG(), c1[0], c1[1]); final BoxSampler sampler2 = BoxSampler.of( RandomAssert.seededRNG(), c2[0], c2[1]); for (int n = 0; n < 10; n++) { final double[] a = sampler1.sample(); final double[] b = sampler2.sample(); for (int i = 0; i < a.length; i++) { a[i] *= scale; } Assertions.assertArrayEquals(a, b); } } /** * Test the distribution of points in 2D. */ @Test void testDistribution2D() { testDistributionND(2); } /** * Test the distribution of points in 3D. */ @Test void testDistribution3D() { testDistributionND(3); } /** * Test the distribution of points in 4D. */ @Test void testDistribution4D() { testDistributionND(4); } /** * Test the distribution of points in N dimensions. The output coordinates * should be uniform in the box. * * @param dimension the dimension */ private static void testDistributionND(int dimension) { final UniformRandomProvider rng = RandomAssert.createRNG(); final UnitSphereSampler sphere = UnitSphereSampler.of(rng, dimension); final double[] a = sphere.sample(); final double[] b = sphere.sample(); // Assign bins final int bins = 10; final int samplesPerBin = 20; // To test uniformity within the box assign the position to a bin using: // x - a // ----- * bins // b - a // Pre-compute scaling final double[] scale = new double[dimension]; // Precompute the bin offset for each increasing dimension: // 1, bins, bins*bins, bins*bins*bins, ... final int[] offset = new int[dimension]; for (int i = 0; i < dimension; i++) { scale[i] = 1.0 / (b[i] - a[i]); offset[i] = (int) Math.pow(bins, i); } // Expect a uniform distribution final double[] expected = new double[(int) Math.pow(bins, dimension)]; Arrays.fill(expected, 1.0); // Increase the loops and use a null seed (i.e. randomly generated) to verify robustness final BoxSampler sampler = BoxSampler.of(rng, a, b); final int samples = expected.length * samplesPerBin; for (int n = 0; n < 1; n++) { // Assign each coordinate to a region inside the box final long[] observed = new long[expected.length]; for (int i = 0; i < samples; i++) { final double[] x = sampler.sample(); Assertions.assertEquals(dimension, x.length); int index = 0; for (int j = 0; j < dimension; j++) { final double c = (x[j] - a[j]) * scale[j]; Assertions.assertTrue(c >= 0.0 && c <= 1.0, "Not within the box"); // Get the bin for this dimension (assumes c != 1.0) final int bin = (int) (c * bins); // Add to the final bin index index += bin * offset[j]; } // Assign the uniform deviate to a bin observed[index]++; } final double p = new ChiSquareTest().chiSquareTest(expected, observed); Assertions.assertFalse(p < 0.001, () -> "p-value too small: " + p); } } /** * Test the SharedStateSampler implementation for 2D. */ @Test void testSharedStateSampler2D() { testSharedStateSampler(2); } /** * Test the SharedStateSampler implementation for 3D. */ @Test void testSharedStateSampler3D() { testSharedStateSampler(3); } /** * Test the SharedStateSampler implementation for 4D. */ @Test void testSharedStateSampler4D() { testSharedStateSampler(4); } /** * Test the SharedStateSampler implementation for the given dimension. */ private static void testSharedStateSampler(int dimension) { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final double[] c1 = createCoordinate(1, dimension); final double[] c2 = createCoordinate(2, dimension); final BoxSampler sampler1 = BoxSampler.of(rng1, c1, c2); final BoxSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * Test the input vectors are copied and not used by reference for 2D. */ @Test void testChangedInputCoordinates2D() { testChangedInputCoordinates(2); } /** * Test the input vectors are copied and not used by reference for 3D. */ @Test void testChangedInputCoordinates3D() { testChangedInputCoordinates(3); } /** * Test the input vectors are copied and not used by reference for 4D. */ @Test void testChangedInputCoordinates4D() { testChangedInputCoordinates(4); } /** * Test the input vectors are copied and not used by reference for the given * dimension. * * @param dimension the dimension */ private static void testChangedInputCoordinates(int dimension) { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final double[] c1 = createCoordinate(1, dimension); final double[] c2 = createCoordinate(2, dimension); final BoxSampler sampler1 = BoxSampler.of(rng1, c1, c2); // Check the input vectors are copied and not used by reference. // Change them in place and create a new sampler. It should have different output // translated by the offset. final double offset = 10; for (int i = 0; i < dimension; i++) { c1[i] += offset; c2[i] += offset; } final BoxSampler sampler2 = BoxSampler.of(rng2, c1, c2); for (int n = 0; n < 3; n++) { final double[] s1 = sampler1.sample(); final double[] s2 = sampler2.sample(); Assertions.assertEquals(s1.length, s2.length); Assertions.assertFalse(Arrays.equals(s1, s2), "First sampler has used the vertices by reference"); for (int i = 0; i < dimension; i++) { Assertions.assertEquals(s1[i] + offset, s2[i], 1e-10); } } } /** * Creates the coordinate of length specified by the dimension filled with * the given value and the dimension index: x + i. * * @param x the value for index 0 * @param dimension the dimension * @return the coordinate */ private static double[] createCoordinate(double x, int dimension) { final double[] coord = new double[dimension]; for (int i = 0; i < dimension; i++) { coord[0] = x + i; } return coord; } }
2,912
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/shape/TriangleSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.shape; import java.util.Arrays; import org.apache.commons.math3.stat.inference.ChiSquareTest; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test for {@link TriangleSampler}. */ class TriangleSamplerTest { // Precomputed 3D and 4D rotation matrices for forward and backward transforms // created using the matlab function by jodag: // https://stackoverflow.com/questions/50337642/how-to-calculate-a-rotation-matrix-in-n-dimensions-given-the-point-to-rotate-an /** 3D rotation around the vector [1; 2; 3] by pi/4. */ private static final double[][] F3 = { {0.728027725387508, -0.525104821111919, 0.440727305612110}, {0.608788597915763, 0.790790557990391, -0.063456571298848}, {-0.315201640406345, 0.314507901710379, 0.895395278995195}}; /** 3D rotation around the vector [1; 2; 3] by -pi/4. */ private static final double[][] R3 = { {0.728027725387508, 0.608788597915762, -0.315201640406344}, {-0.525104821111919, 0.790790557990391, 0.314507901710379}, {0.440727305612110, -0.063456571298848, 0.895395278995195}}; /** 4D rotation around the orthogonal vectors [1 0; 0 1; 1 0; 0 1] by pi/4. */ private static final double[][] F4 = { {0.853553390593274, -0.353553390593274, 0.146446609406726, 0.353553390593274}, {0.353553390593274, 0.853553390593274, -0.353553390593274, 0.146446609406726}, {0.146446609406726, 0.353553390593274, 0.853553390593274, -0.353553390593274}, {-0.353553390593274, 0.146446609406726, 0.353553390593274, 0.853553390593274}}; /** 4D rotation around the orthogonal vectors [1 0; 0 1; 1 0; 0 1] by -pi/4. */ private static final double[][] R4 = { {0.853553390593274, 0.353553390593274, 0.146446609406726, -0.353553390593274}, {-0.353553390593274, 0.853553390593274, 0.353553390593274, 0.146446609406726}, {0.146446609406726, -0.353553390593274, 0.853553390593274, 0.353553390593274}, {0.353553390593274, 0.146446609406726, -0.353553390593274, 0.853553390593274}}; /** * Test the sampling assumptions used to transform coordinates outside the triangle * back inside the triangle. */ @Test void testSamplingAssumptions() { // The separation between the 2^53 dyadic rationals in the interval [0, 1) final double delta = 0x1.0p-53; double s = 0.5; double t = 0.5 + delta; // This value cannot be exactly represented and is rounded final double spt = s + t; // Test that (1 - (1-s) - (1-t)) is not equal to (s + t - 1). // This is due to the rounding to store s + t as a double. final double expected = 1 - (1 - s) - (1 - t); Assertions.assertNotEquals(expected, spt - 1); Assertions.assertNotEquals(expected, s + t - 1); // For any uniform deviate u in [0, 1], u - 1 is exact, thus s - 1 is exact // and s - 1 + t is exact. Assertions.assertEquals(expected, s - 1 + t); // Test that a(1 - s - t) + sb + tc does not overflow is s+t = 1 final double max = Double.MAX_VALUE; s -= delta; final UniformRandomProvider rng = RandomAssert.createRNG(); for (int n = 0; n < 100; n++) { Assertions.assertNotEquals(Double.POSITIVE_INFINITY, (1 - s - t) * max + s * max + t * max); s = rng.nextDouble(); t = 1.0 - s; } } /** * Test an unsupported dimension. */ @Test void testInvalidDimensionThrows() { final UniformRandomProvider rng = RandomAssert.seededRNG(); Assertions.assertThrows(IllegalArgumentException.class, () -> TriangleSampler.of(rng, new double[1], new double[1], new double[1])); } /** * Test a dimension mismatch between vertices. */ @Test void testDimensionMismatchThrows() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final double[] c2 = new double[2]; final double[] c3 = new double[3]; for (double[][] c : new double[][][] { {c2, c2, c3}, {c2, c3, c2}, {c3, c2, c2}, {c2, c3, c3}, {c3, c3, c2}, {c3, c2, c3}, }) { Assertions.assertThrows(IllegalArgumentException.class, () -> TriangleSampler.of(rng, c[0], c[1], c[2]), () -> String.format("Did not detect dimension mismatch: %d,%d,%d", c[0].length, c[1].length, c[2].length)); } } /** * Test non-finite vertices. */ @Test void testNonFiniteVertexCoordinates() { final UniformRandomProvider rng = RandomAssert.seededRNG(); // A valid triangle final double[][] c = new double[][] { {0, 0, 1}, {2, 1, 0}, {-1, 2, 3} }; Assertions.assertNotNull(TriangleSampler.of(rng, c[0], c[1], c[2])); final double[] bad = {Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NaN}; for (int i = 0; i < c.length; i++) { final int ii = i; for (int j = 0; j < c[0].length; j++) { final int jj = j; for (final double d : bad) { final double value = c[i][j]; c[i][j] = d; Assertions.assertThrows(IllegalArgumentException.class, () -> TriangleSampler.of(rng, c[0], c[1], c[2]), () -> String.format("Did not detect non-finite coordinate: %d,%d = %s", ii, jj, d)); c[i][j] = value; } } } } /** * Test a triangle with coordinates that are separated by more than * {@link Double#MAX_VALUE} in two dimensions. */ @Test void testExtremeValueCoordinates2D() { testExtremeValueCoordinates(2); } /** * Test a triangle with coordinates that are separated by more than * {@link Double#MAX_VALUE} in three dimensions. */ @Test void testExtremeValueCoordinates3D() { testExtremeValueCoordinates(3); } /** * Test a triangle with coordinates that are separated by more than * {@link Double#MAX_VALUE} in four dimensions. */ @Test void testExtremeValueCoordinates4D() { testExtremeValueCoordinates(4); } /** * Test a triangle with coordinates that are separated by more than * {@link Double#MAX_VALUE}. * * @param dimension the dimension */ private static void testExtremeValueCoordinates(int dimension) { final double[][] c1 = new double[3][dimension]; final double[][] c2 = new double[3][dimension]; // Create a valid triangle that can be scaled c1[0][0] = -1; c1[0][1] = -1; c1[1][0] = 1; c1[1][1] = 1; c1[2][0] = 1; c1[2][1] = -1; // Extremely large value for scaling. Use a power of 2 for exact scaling. final double scale = 0x1.0p1023; for (int i = 0; i < 3; i++) { // Fill the remaining dimensions with 1 or -1 for (int j = 2; j < dimension; j++) { c1[i][j] = 1 - (j & 0x2); } // Scale the second triangle for (int j = 0; j < dimension; j++) { c2[i][j] = c1[i][j] * scale; } } // Show the triangle is too big to compute vectors between points. Assertions.assertEquals(Double.POSITIVE_INFINITY, c2[2][0] - c2[0][0], "Expect vector c - a to be infinite in the x dimension"); Assertions.assertEquals(Double.NEGATIVE_INFINITY, c2[2][1] - c2[1][1], "Expect vector c - b to be infinite in the y dimension"); final TriangleSampler sampler1 = TriangleSampler.of( RandomAssert.seededRNG(), c1[0], c1[1], c1[2]); final TriangleSampler sampler2 = TriangleSampler.of( RandomAssert.seededRNG(), c2[0], c2[1], c2[2]); for (int n = 0; n < 10; n++) { final double[] a = sampler1.sample(); final double[] b = sampler2.sample(); for (int i = 0; i < a.length; i++) { a[i] *= scale; } Assertions.assertArrayEquals(a, b); } } /** * Test the distribution of points in two dimensions. */ @Test void testDistribution2D() { testDistributionND(2); } /** * Test the distribution of points in three dimensions. */ @Test void testDistribution3D() { testDistributionND(3); } /** * Test the distribution of points in four dimensions. */ @Test void testDistribution4D() { testDistributionND(4); } /** * Test the distribution of points in N dimensions. The output coordinates * should be uniform in the triangle. * * <p>ND is supported by transforming 2D triangles to ND, sampling in ND then * transforming back to 2D. The transformed results should have a zero * coordinate for indices above 1. Supports 2 to 4 dimensions. * * @param dimension the dimension in the range [2, 4] */ private static void testDistributionND(int dimension) { // Create 3 triangles that form a 3x4 rectangle: // b-----c // |\ /| // | \ / | // | e | // | \ | // | \| // a-----d // // Sample from them proportional to the area: // adb = 4 * 3 / 2 = 6 // bce = 3 * 2 / 2 = 3 // cde = 4 * 1.5 / 2 = 3 // The samples in the ratio 2:1:1 should be uniform within the rectangle. final double[] a = {0, 0}; final double[] b = {0, 4}; final double[] c = {3, 4}; final double[] d = {3, 0}; final double[] e = {1.5, 2}; // Assign bins final int bins = 20; final int samplesPerBin = 10; // Scale factors to assign x,y to a bin final double sx = bins / 3.0; final double sy = bins / 4.0; // Expect a uniform distribution (this is rescaled by the ChiSquareTest) final double[] expected = new double[bins * bins]; Arrays.fill(expected, 1); // Support ND by applying a rotation transform to the 2D triangles to generate // n-coordinates. The samples are transformed back and should be uniform in 2D. Transform forward; Transform reverse; if (dimension == 4) { forward = new ForwardTransform(F4); reverse = new ReverseTransform(R4); } else if (dimension == 3) { forward = new ForwardTransform(F3); reverse = new ReverseTransform(R3); } else if (dimension == 2) { forward = reverse = new Transform2Dto2D(); } else { throw new AssertionError("Unsupported dimension: " + dimension); } // Increase the loops to verify robustness final UniformRandomProvider rng = RandomAssert.createRNG(); final TriangleSampler sampler1 = TriangleSampler.of(rng, forward.apply(a), forward.apply(d), forward.apply(b)); final TriangleSampler sampler2 = TriangleSampler.of(rng, forward.apply(b), forward.apply(c), forward.apply(e)); final TriangleSampler sampler3 = TriangleSampler.of(rng, forward.apply(c), forward.apply(d), forward.apply(e)); final Triangle triangle1 = new Triangle(a, d, b); final Triangle triangle2 = new Triangle(b, c, e); final Triangle triangle3 = new Triangle(c, d, e); final int samples = expected.length * samplesPerBin; for (int n = 0; n < 1; n++) { // Assign each coordinate to a region inside the combined rectangle final long[] observed = new long[expected.length]; // Sample according to the area of each triangle (ratio 2:1:1) for (int i = 0; i < samples; i += 4) { addObservation(reverse.apply(sampler1.sample()), observed, bins, sx, sy, triangle1); addObservation(reverse.apply(sampler1.sample()), observed, bins, sx, sy, triangle1); addObservation(reverse.apply(sampler2.sample()), observed, bins, sx, sy, triangle2); addObservation(reverse.apply(sampler3.sample()), observed, bins, sx, sy, triangle3); } final double p = new ChiSquareTest().chiSquareTest(expected, observed); Assertions.assertFalse(p < 0.001, () -> "p-value too small: " + p); } } /** * Adds the observation. Coordinates are mapped using the offsets, scaled and * then cast to an integer bin. * * <pre> * binx = (int) (x * sx) * </pre> * * @param v the sample (2D coordinate xy) * @param observed the observations * @param bins the numbers of bins in the x dimension * @param sx the scale to convert the x coordinate to the x bin * @param sy the scale to convert the y coordinate to the y bin * @param triangle the triangle the sample should be within */ private static void addObservation(double[] v, long[] observed, int bins, double sx, double sy, Triangle triangle) { final double x = v[0]; final double y = v[1]; // Test the point is triangle the triangle Assertions.assertTrue(triangle.contains(x, y)); // Add to the correct bin after using the offset final int binx = (int) (x * sx); final int biny = (int) (y * sy); observed[biny * bins + binx]++; } /** * Test the SharedStateSampler implementation for 2D. */ @Test void testSharedStateSampler2D() { testSharedStateSampler(2); } /** * Test the SharedStateSampler implementation for 3D. */ @Test void testSharedStateSampler3D() { testSharedStateSampler(3); } /** * Test the SharedStateSampler implementation for 4D. */ @Test void testSharedStateSampler4D() { testSharedStateSampler(4); } /** * Test the SharedStateSampler implementation for the given dimension. */ private static void testSharedStateSampler(int dimension) { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final double[] c1 = createCoordinate(1, dimension); final double[] c2 = createCoordinate(2, dimension); final double[] c3 = createCoordinate(-3, dimension); final TriangleSampler sampler1 = TriangleSampler.of(rng1, c1, c2, c3); final TriangleSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * Test the input vectors are copied and not used by reference for 2D. */ @Test void testChangedInputCoordinates2D() { testChangedInputCoordinates(2); } /** * Test the input vectors are copied and not used by reference for 3D. */ @Test void testChangedInputCoordinates3D() { testChangedInputCoordinates(3); } /** * Test the input vectors are copied and not used by reference for 4D. */ @Test void testChangedInputCoordinates4D() { testChangedInputCoordinates(4); } /** * Test the input vectors are copied and not used by reference for the given * dimension. * * @param dimension the dimension */ private static void testChangedInputCoordinates(int dimension) { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final double[] c1 = createCoordinate(1, dimension); final double[] c2 = createCoordinate(2, dimension); final double[] c3 = createCoordinate(-3, dimension); final TriangleSampler sampler1 = TriangleSampler.of(rng1, c1, c2, c3); // Check the input vectors are copied and not used by reference. // Change them in place and create a new sampler. It should have different output // translated by the offset. final double offset = 10; for (int i = 0; i < dimension; i++) { c1[i] += offset; c2[i] += offset; c3[i] += offset; } final TriangleSampler sampler2 = TriangleSampler.of(rng2, c1, c2, c3); for (int n = 0; n < 3; n++) { final double[] s1 = sampler1.sample(); final double[] s2 = sampler2.sample(); Assertions.assertEquals(s1.length, s2.length); Assertions.assertFalse(Arrays.equals(s1, s2), "First sampler has used the vertices by reference"); for (int i = 0; i < dimension; i++) { Assertions.assertEquals(s1[i] + offset, s2[i], 1e-10); } } } /** * Creates the coordinate of length specified by the dimension filled with * the given value and the dimension index: x + i. * * @param x the value for index 0 * @param dimension the dimension * @return the coordinate */ private static double[] createCoordinate(double x, int dimension) { final double[] coord = new double[dimension]; for (int i = 0; i < dimension; i++) { coord[0] = x + i; } return coord; } /** * Test the transform generates 3D coordinates and can reverse them. */ @Test void testTransform3D() { testTransformND(3); } /** * Test the transform generates 4D coordinates and can reverse them. */ @Test void testTransform4D() { testTransformND(4); } /** * Test the transform generates ND coordinates and can reverse them. * * @param dimension the dimension */ private static void testTransformND(int dimension) { Transform forward; Transform reverse; if (dimension == 4) { forward = new ForwardTransform(F4); reverse = new ReverseTransform(R4); } else if (dimension == 3) { forward = new ForwardTransform(F3); reverse = new ReverseTransform(R3); } else if (dimension == 2) { forward = reverse = new Transform2Dto2D(); } else { throw new AssertionError("Unsupported dimension: " + dimension); } final UniformRandomProvider rng = RandomAssert.seededRNG(); double sum = 0; for (int n = 0; n < 10; n++) { final double[] a = new double[] {rng.nextDouble(), rng.nextDouble()}; final double[] b = forward.apply(a); Assertions.assertEquals(dimension, b.length); for (int i = 2; i < dimension; i++) { sum += Math.abs(b[i]); } final double[] c = reverse.apply(b); Assertions.assertArrayEquals(a, c, 1e-10); } // Check that higher dimension coordinates are generated. // Note: Initially higher dimensions are zero. final double actual = sum; final double nonZeroThreshold = 0.01; Assertions.assertTrue(actual > nonZeroThreshold, () -> "No non-zero higher dimension coordinates: " + actual + " <= " + nonZeroThreshold); } /** * Test 3D rotations forward and reverse. */ @Test void testRotations3D() { final double[] x = {1, 0.5, 0}; final double[] y = multiply(F3, x); Assertions.assertArrayEquals(new double[] {0.465475314831549, 1.004183876910958, -0.157947689551155}, y, 1e-10); Assertions.assertEquals(length(x), length(y), 1e-10); final double[] x2 = multiply(R3, y); Assertions.assertArrayEquals(x, x2, 1e-10); } /** * Test 4D rotations forward and reverse. */ @Test void testRotations4D() { final double[] x = {1, 0.5, 0, 0}; final double[] y = multiply(F4, x); Assertions.assertArrayEquals( new double[] {0.676776695296637, 0.780330085889911, 0.323223304703363, -0.280330085889911}, y, 1e-10); Assertions.assertEquals(length(x), length(y), 1e-10); final double[] x2 = multiply(R4, y); Assertions.assertArrayEquals(x, x2, 1e-10); } /** * Matrix multiplication. It is assumed the matrix is square and matches (or exceeds) * the vector length. * * @param m the matrix * @param v the vector * @return the result */ private static double[] multiply(double[][] matrix, double[] v) { final int n = matrix.length; final int m = v.length; final double[] r = new double[n]; for (int i = 0; i < n; i++) { double sum = 0; for (int j = 0; j < m; j++) { sum += matrix[i][j] * v[j]; } r[i] = sum; } return r; } /** * @return the length (L2-norm) of given vector. */ private static double length(double[] vector) { double total = 0; for (final double d : vector) { total += d * d; } return Math.sqrt(total); } /** * Test the triangle contains predicate. */ @Test void testTriangleContains() { final Triangle triangle = new Triangle(1, 2, 3, 1, 0.5, 6); // Vertices Assertions.assertTrue(triangle.contains(1, 2)); Assertions.assertTrue(triangle.contains(3, 1)); Assertions.assertTrue(triangle.contains(0.5, 6)); // Edge Assertions.assertTrue(triangle.contains(0.75, 4)); // Inside Assertions.assertTrue(triangle.contains(1.5, 3)); // Outside Assertions.assertFalse(triangle.contains(0, 20)); Assertions.assertFalse(triangle.contains(-20, 0)); Assertions.assertFalse(triangle.contains(6, 6)); // Just outside Assertions.assertFalse(triangle.contains(0.75, 4 - 1e-10)); // Note: // Touching triangles can both have the point triangle. // This predicate is not suitable for assigning points uniquely to // non-overlapping triangles that share an edge. final Triangle triangle2 = new Triangle(1, 2, 3, 1, 0, -2); Assertions.assertTrue(triangle.contains(2, 1.5)); Assertions.assertTrue(triangle2.contains(2, 1.5)); } /** * Define a transform on coordinates. */ private interface Transform { /** * Apply the transform. * * @param coord the coordinates * @return the new coordinates */ double[] apply(double[] coord); } /** * Transform coordinates from 2D to a higher dimension using the rotation matrix. */ private static class ForwardTransform implements Transform { private final double[][] r; /** * @param r the rotation matrix */ ForwardTransform(double[][] r) { this.r = r; } @Override public double[] apply(double[] coord) { return multiply(r, coord); } } /** * Transform coordinates from a higher dimension to 2D using the rotation matrix. * The result should be in the 2D plane (i.e. higher dimensions of the transformed vector * are asserted to be zero). */ private static class ReverseTransform implements Transform { private final double[][] r; private final int n; /** * @param r the rotation matrix */ ReverseTransform(double[][] r) { this.r = r; n = r.length; } @Override public double[] apply(double[] coord) { Assertions.assertEquals(n, coord.length); final double[] x = multiply(r, coord); // This should reverse the 2D transform and return to the XY plane. for (int i = 2; i < x.length; i++) { Assertions.assertEquals(0.0, x[i], 1e-14); } return new double[] {x[0], x[1]}; } } /** * No-operation transform on 2D input. Asserts the input coordinates are length 2. */ private static class Transform2Dto2D implements Transform { @Override public double[] apply(double[] coord) { Assertions.assertEquals(2, coord.length); return coord; } } /** * Class to test if a point is inside the triangle. * * <p>This function has been adapted from a StackOverflow post by Cédric Dufour. It converts the * point to unscaled barycentric coordinates (s,t) and tests they are within the triangle. * (Scaling would be done by dividing by twice the area of the triangle.) * * <h2>Warning</h2> * * <p>This assigns points on the edges as inside irrespective of edge orientation. Thus * back-to-back touching triangles can both have the point inside them. A predicate for geometry * applications where the point must be within a unique non-overlapping triangle should use * a different solution, e.g. assigning new points to the result of a triangulation. * For testing sampling within the triangle this predicate is acceptable. * * @see <a * href="https://stackoverflow.com/questions/2049582/how-to-determine-if-a-point-is-in-a-2d-triangle?lq=1"> * Point in a triangle</a> * @see <a href="https://stackoverflow.com/a/34093754">Point inside triangle by Cédric Dufour</a> */ private static class Triangle { private final double p2x; private final double p2y; private final double dX21; private final double dY12; private final double dY20; private final double dX02; private final double d; /** * Create an instance. * * @param p0 triangle vertex 0 * @param p1 triangle vertex 1 * @param p2 triangle vertex 2 */ Triangle(double[] p0, double[] p1, double[] p2) { this(p0[0], p0[1], p1[0], p1[1], p2[0], p2[1]); } /** * Create an instance. * * @param p0x triangle vertex 0 x coordinate * @param p0y triangle vertex 0 y coordinate * @param p1x triangle vertex 1 x coordinate * @param p1y triangle vertex 1 y coordinate * @param p2x triangle vertex 2 x coordinate * @param p2y triangle vertex 2 y coordinate */ Triangle(double p0x, double p0y, double p1x, double p1y, double p2x, double p2y) { this.p2x = p2x; this.p2y = p2y; // Precompute factors dX21 = p2x - p1x; dY12 = p1y - p2y; dY20 = p2y - p0y; dX02 = p0x - p2x; // d = twice the signed area of the triangle d = dY12 * (p0x - p2x) + dX21 * (p0y - p2y); } /** * Check whether or not the triangle contains the given point. * * @param px the point x coordinate * @param py the point y coordinate * @return true if inside the triangle */ boolean contains(double px, double py) { // Barycentric coordinates: // p = p0 + (p1 - p0) * s + (p2 - p0) * t // The point p is inside the triangle if 0 <= s <= 1 and 0 <= t <= 1 and s + t <= 1 // // The following solves s and t. // Some factors are precomputed. final double dX = px - p2x; final double dY = py - p2y; final double s = dY12 * dX + dX21 * dY; final double t = dY20 * dX + dX02 * dY; if (d < 0) { return s <= 0 && t <= 0 && s + t >= d; } return s >= 0 && t >= 0 && s + t <= d; } } }
2,913
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/shape/TetrahedronSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.shape; import java.util.Arrays; import org.apache.commons.math3.stat.inference.ChiSquareTest; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test for {@link TetrahedronSampler}. */ class TetrahedronSamplerTest { /** * Test invalid vertex dimensions (i.e. not 3D coordinates). */ @Test void testInvalidDimensionThrows() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final double[] ok = new double[3]; final double[] bad = new double[2]; final double[][] c = {ok, ok, ok, ok}; for (int i = 0; i < c.length; i++) { final int ii = i; c[i] = bad; Assertions.assertThrows(IllegalArgumentException.class, () -> TetrahedronSampler.of(rng, c[0], c[1], c[2], c[3]), () -> String.format("Did not detect invalid dimension for vertex: %d", ii)); c[i] = ok; } } /** * Test non-finite vertices. */ @Test void testNonFiniteVertexCoordinates() { final UniformRandomProvider rng = RandomAssert.seededRNG(); // A valid tetrahedron final double[][] c = new double[][] { {1, 1, 1}, {1, -1, 1}, {-1, 1, 1}, {1, 1, -1} }; Assertions.assertNotNull(TetrahedronSampler.of(rng, c[0], c[1], c[2], c[3])); final double[] bad = {Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NaN}; for (int i = 0; i < c.length; i++) { final int ii = i; for (int j = 0; j < c[0].length; j++) { final int jj = j; for (final double d : bad) { final double value = c[i][j]; c[i][j] = d; Assertions.assertThrows(IllegalArgumentException.class, () -> TetrahedronSampler.of(rng, c[0], c[1], c[2], c[3]), () -> String.format("Did not detect non-finite coordinate: %d,%d = %s", ii, jj, d)); c[i][j] = value; } } } } /** * Test a tetrahedron with coordinates that are separated by more than * {@link Double#MAX_VALUE}. */ @Test void testExtremeValueCoordinates() { // Create a valid tetrahedron that can be scaled final double[][] c1 = new double[][] { {1, 1, 1}, {1, -1, -1}, {-1, -1, 1}, {-1, 1, -1} }; final double[][] c2 = new double[4][3]; // Extremely large value for scaling. Use a power of 2 for exact scaling. final double scale = 0x1.0p1023; for (int i = 0; i < c1.length; i++) { // Scale the second tetrahedron for (int j = 0; j < 3; j++) { c2[i][j] = c1[i][j] * scale; } } // Show the tetrahedron is too big to compute vectors between points. Assertions.assertEquals(Double.NEGATIVE_INFINITY, c2[2][0] - c2[0][0], "Expect vector c - a to be infinite in the x dimension"); Assertions.assertEquals(Double.NEGATIVE_INFINITY, c2[2][1] - c2[3][1], "Expect vector c - d to be infinite in the y dimension"); Assertions.assertEquals(Double.POSITIVE_INFINITY, c2[2][2] - c2[1][2], "Expect vector c - b to be infinite in the z dimension"); final TetrahedronSampler sampler1 = TetrahedronSampler.of( RandomAssert.seededRNG(), c1[0], c1[1], c1[2], c1[3]); final TetrahedronSampler sampler2 = TetrahedronSampler.of( RandomAssert.seededRNG(), c2[0], c2[1], c2[2], c2[3]); for (int n = 0; n < 10; n++) { final double[] a = sampler1.sample(); final double[] b = sampler2.sample(); for (int i = 0; i < a.length; i++) { a[i] *= scale; } Assertions.assertArrayEquals(a, b); } } /** * Test the distribution of points in three dimensions. 6 tetrahedra are used to create * a box. The distribution should be uniform inside the box. */ @Test void testDistribution() { // Create the lower and upper limits of the box final double lx = -1; final double ly = -2; final double lz = 1; final double ux = 3; final double uy = 4; final double uz = 5; // Create vertices abcd and efgh for the lower and upper rectangles // (in the XY plane) of the box final double[] a = {lx, ly, lz}; final double[] b = {ux, ly, lz}; final double[] c = {ux, uy, lz}; final double[] d = {lx, uy, lz}; final double[] e = {lx, ly, uz}; final double[] f = {ux, ly, uz}; final double[] g = {ux, uy, uz}; final double[] h = {lx, uy, uz}; // Assign bins final int bins = 10; // Samples should be a multiple of 6 (due to combining 6 equal volume tetrahedra) final int samplesPerBin = 12; // Scale factors to assign x,y,z to a bin final double sx = bins / (ux - lx); final double sy = bins / (uy - ly); final double sz = bins / (uz - lz); // Compute factor to allocate bin index: // index = x + y * binsX + z * binsX * binsY final int binsXy = bins * bins; // Expect a uniform distribution (this is rescaled by the ChiSquareTest) final double[] expected = new double[binsXy * bins]; Arrays.fill(expected, 1); // Increase the loops to verify robustness final UniformRandomProvider rng = RandomAssert.createRNG(); // Cut the box into 6 equal volume tetrahedra by cutting the box in half three times, // cutting diagonally through each of the three pairs of opposing faces. In this way, // the tetrahedra all share one of the main diagonals of the box (d-f). // See the cuts used for the marching tetrahedra algorithm: // https://en.wikipedia.org/wiki/Marching_tetrahedra final TetrahedronSampler[] samplers = {TetrahedronSampler.of(rng, d, f, b, c), TetrahedronSampler.of(rng, d, f, c, g), TetrahedronSampler.of(rng, d, f, g, h), TetrahedronSampler.of(rng, d, f, h, e), TetrahedronSampler.of(rng, d, f, e, a), TetrahedronSampler.of(rng, d, f, a, b)}; // To determine the sample is inside the correct tetrahedron it is projected to the // 4 faces of the tetrahedron along the face normals. The distance should be negative // when the face normals are orientated outwards. final Tetrahedron[] tetrahedrons = {new Tetrahedron(d, f, b, c), new Tetrahedron(d, f, c, g), new Tetrahedron(d, f, g, h), new Tetrahedron(d, f, h, e), new Tetrahedron(d, f, e, a), new Tetrahedron(d, f, a, b)}; final int samples = expected.length * samplesPerBin; for (int n = 0; n < 1; n++) { // Assign each coordinate to a region inside the combined box final long[] observed = new long[expected.length]; // Equal volume tetrahedra so sample from each one for (int i = 0; i < samples; i += 6) { for (int j = 0; j < 6; j++) { addObservation(samplers[j].sample(), observed, bins, binsXy, lx, ly, lz, sx, sy, sz, tetrahedrons[j]); } } final double p = new ChiSquareTest().chiSquareTest(expected, observed); Assertions.assertFalse(p < 0.001, () -> "p-value too small: " + p); } } /** * Adds the observation. Coordinates are mapped using the offsets, scaled and * then cast to an integer bin. * * <pre> * binx = (int) ((x - lx) * sx) * </pre> * * @param v the sample (3D coordinate xyz) * @param observed the observations * @param binsX the numbers of bins in the x dimension * @param binsXy the numbers of bins in the combined x and y dimensions * @param lx the lower limit to convert the x coordinate to the x bin * @param ly the lower limit to convert the y coordinate to the y bin * @param lz the lower limit to convert the z coordinate to the z bin * @param sx the scale to convert the x coordinate to the x bin * @param sy the scale to convert the y coordinate to the y bin * @param sz the scale to convert the z coordinate to the z bin * @param tetrahedron the tetrahedron the sample should be within */ // CHECKSTYLE: stop ParameterNumberCheck private static void addObservation(double[] v, long[] observed, int binsX, int binsXy, double lx, double ly, double lz, double sx, double sy, double sz, Tetrahedron tetrahedron) { Assertions.assertEquals(3, v.length); // Test the point is inside the correct tetrahedron Assertions.assertTrue(tetrahedron.contains(v), "Not inside the tetrahedron"); final double x = v[0]; final double y = v[1]; final double z = v[2]; // Add to the correct bin after using the offset final int binx = (int) ((x - lx) * sx); final int biny = (int) ((y - ly) * sy); final int binz = (int) ((z - lz) * sz); observed[binz * binsXy + biny * binsX + binx]++; } // CHECKSTYLE: resume ParameterNumberCheck /** * Test the SharedStateSampler implementation. */ @Test void testSharedStateSampler() { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final double[] c1 = createCoordinate(-1); final double[] c2 = createCoordinate(2); final double[] c3 = createCoordinate(-3); final double[] c4 = createCoordinate(4); final TetrahedronSampler sampler1 = TetrahedronSampler.of(rng1, c1, c2, c3, c4); final TetrahedronSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * Test the input vectors are copied and not used by reference. */ @Test void testChangedInputCoordinates() { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final double[] c1 = createCoordinate(1); final double[] c2 = createCoordinate(2); final double[] c3 = createCoordinate(-3); final double[] c4 = createCoordinate(-4); final TetrahedronSampler sampler1 = TetrahedronSampler.of(rng1, c1, c2, c3, c4); // Check the input vectors are copied and not used by reference. // Change them in place and create a new sampler. It should have different output // translated by the offset. final double offset = 10; for (int i = 0; i < 3; i++) { c1[i] += offset; c2[i] += offset; c3[i] += offset; c4[i] += offset; } final TetrahedronSampler sampler2 = TetrahedronSampler.of(rng2, c1, c2, c3, c4); for (int n = 0; n < 5; n++) { final double[] s1 = sampler1.sample(); final double[] s2 = sampler2.sample(); Assertions.assertEquals(3, s1.length); Assertions.assertEquals(3, s2.length); for (int i = 0; i < 3; i++) { Assertions.assertEquals(s1[i] + offset, s2[i], 1e-10); } } } /** * Test the tetrahedron contains predicate. */ @Test void testTetrahedronContains() { final double[][] c1 = new double[][] { {1, 1, 1}, {1, -1, -1}, {-1, -1, 1}, {-1, 1, -1} }; final Tetrahedron tetrahedron = new Tetrahedron(c1[0], c1[1], c1[2], c1[3]); // Testing points on the vertices, edges or faces are subject to floating point error final double epsilon = 1e-14; // Vertices for (int i = 0; i < 4; i++) { Assertions.assertTrue(tetrahedron.contains(c1[i], epsilon)); } // Edge Assertions.assertTrue(tetrahedron.contains(new double[] {1, 0, 0}, epsilon)); Assertions.assertTrue(tetrahedron.contains(new double[] {0.5, 0.5, 1}, epsilon)); // Just inside the edge Assertions.assertTrue(tetrahedron.contains(new double[] {1 - 1e-10, 0, 0})); Assertions.assertTrue(tetrahedron.contains(new double[] {0.5, 0.5, 1 - 1e-10})); // Just outside the edge Assertions.assertFalse(tetrahedron.contains(new double[] {1, 0, 1e-10}, epsilon)); Assertions.assertFalse(tetrahedron.contains(new double[] {0.5, 0.5 + 1e-10, 1}, epsilon)); // Face double x = 1.0 / 3; Assertions.assertTrue(tetrahedron.contains(new double[] {x, -x, x}, epsilon)); Assertions.assertTrue(tetrahedron.contains(new double[] {-x, -x, -x}, epsilon)); Assertions.assertTrue(tetrahedron.contains(new double[] {x, x, -x}, epsilon)); Assertions.assertTrue(tetrahedron.contains(new double[] {-x, x, x}, epsilon)); // Just outside the face x += 1e-10; Assertions.assertFalse(tetrahedron.contains(new double[] {x, -x, x}, epsilon)); Assertions.assertFalse(tetrahedron.contains(new double[] {-x, -x, -x}, epsilon)); Assertions.assertFalse(tetrahedron.contains(new double[] {x, x, -x}, epsilon)); Assertions.assertFalse(tetrahedron.contains(new double[] {-x, x, x}, epsilon)); // Inside Assertions.assertTrue(tetrahedron.contains(new double[] {0, 0, 0})); Assertions.assertTrue(tetrahedron.contains(new double[] {0.5, 0.25, -0.1})); // Outside Assertions.assertFalse(tetrahedron.contains(new double[] {0, 20, 0})); Assertions.assertFalse(tetrahedron.contains(new double[] {-20, 0, 0})); Assertions.assertFalse(tetrahedron.contains(new double[] {6, 6, 4})); } /** * Creates the coordinate of length 3 filled with * the given value and the dimension index: x + i. * * @param x the value for index 0 * @return the coordinate */ private static double[] createCoordinate(double x) { final double[] coord = new double[3]; for (int i = 0; i < 3; i++) { coord[0] = x + i; } return coord; } /** * Class to test if a point is inside the tetrahedron. * * <p>Computes the outer pointing face normals for the tetrahedron. A point is inside * if the point lies below each of the face planes of the shape. * * @see <a href="https://mathworld.wolfram.com/Point-PlaneDistance.html">Point-Plane distance</a> */ private static class Tetrahedron { /** The face normals. */ private final double[][] n; /** The distance of each face from the origin. */ private final double[] d; /** * Create an instance. * * @param v1 The first vertex. * @param v2 The second vertex. * @param v3 The third vertex. * @param v4 The fourth vertex. */ Tetrahedron(double[] v1, double[] v2, double[] v3, double[] v4) { // Compute the centre of each face final double[][] x = new double[][] { centre(v1, v2, v3), centre(v2, v3, v4), centre(v3, v4, v1), centre(v4, v1, v2) }; // Compute the normal for each face n = new double[][] { normal(v1, v2, v3), normal(v2, v3, v4), normal(v3, v4, v1), normal(v4, v1, v2) }; // Given the plane: // 0 = ax + by + cz + d // Where abc is the face normal and d is the distance of the plane from the origin. // Compute d: // d = -(ax + by + cz) d = new double[] { -dot(n[0], x[0]), -dot(n[1], x[1]), -dot(n[2], x[2]), -dot(n[3], x[3]), }; // Compute the distance of the other vertex from each face plane. // When below the distance should be negative. Orient each normal so this is true. // // This distance D of a point xyz to the plane is: // D = ax + by + cz + d // Above plane: // ax + by + cz + d > 0 // ax + by + cz > -d final double[][] other = {v4, v1, v2, v3}; for (int i = 0; i < 4; i++) { if (dot(n[i], other[i]) > -d[i]) { // Swap orientation n[i][0] = -n[i][0]; n[i][1] = -n[i][1]; n[i][2] = -n[i][2]; d[i] = -d[i]; } } } /** * Compute the centre of the triangle face. * * @param a The first vertex. * @param b The second vertex. * @param c The third vertex. * @return the centre */ private static double[] centre(double[] a, double[] b, double[] c) { return new double[] { (a[0] + b[0] + c[0]) / 3, (a[1] + b[1] + c[1]) / 3, (a[2] + b[2] + c[2]) / 3 }; } /** * Compute the normal of the triangle face. * * @param a The first vertex. * @param b The second vertex. * @param c The third vertex. * @return the normal */ private static double[] normal(double[] a, double[] b, double[] c) { final double[] v1 = subtract(b, a); final double[] v2 = subtract(c, a); // Cross product final double[] normal = { v1[1] * v2[2] - v1[2] * v2[1], v1[2] * v2[0] - v1[0] * v2[2], v1[0] * v2[1] - v1[1] * v2[0] }; // Normalise final double scale = 1.0 / Math.sqrt(dot(normal, normal)); normal[0] *= scale; normal[1] *= scale; normal[2] *= scale; return normal; } /** * Compute the dot product of vector {@code a} and {@code b}. * * <pre> * a.b = a.x * b.x + a.y * b.y + a.z * b.z * </pre> * * @param a the first vector * @param b the second vector * @return the dot product */ private static double dot(double[] a, double[] b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } /** * Subtract the second term from the first: {@code a - b}. * * @param a The first term. * @param b The second term. * @return the vector {@code a - b} */ private static double[] subtract(double[] a, double[] b) { return new double[] { a[0] - b[0], a[1] - b[1], a[2] - b[2] }; } /** * Check whether or not the tetrahedron contains the given point. * * @param x the coordinate * @return true if inside the tetrahedron */ boolean contains(double[] x) { // Must be below all the face planes for (int i = 0; i < 4; i++) { // This distance D of a point xyz to the plane is: // D = ax + by + cz + d // Above plane: // ax + by + cz + d > 0 // ax + by + cz > -d if (dot(n[i], x) > -d[i]) { return false; } } return true; } /** * Check whether or not the tetrahedron contains the given point * within the given absolute epsilon. * * @param x the coordinate * @param epsilon the epsilon * @return true if inside the tetrahedron */ boolean contains(double[] x, double epsilon) { for (int i = 0; i < 4; i++) { // As above but with an epsilon above zero if (dot(n[i], x) > epsilon - d[i]) { return false; } } return true; } } }
2,914
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/shape/LineSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.shape; import java.util.Arrays; import org.apache.commons.math3.stat.inference.ChiSquareTest; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.apache.commons.rng.sampling.UnitSphereSampler; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test for {@link LineSampler}. */ class LineSamplerTest { /** * Test an unsupported dimension. */ @Test void testInvalidDimensionThrows() { final UniformRandomProvider rng = RandomAssert.seededRNG(); Assertions.assertThrows(IllegalArgumentException.class, () -> LineSampler.of(rng, new double[0], new double[0])); } /** * Test a dimension mismatch between vertices. */ @Test void testDimensionMismatchThrows() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final double[] c2 = new double[2]; final double[] c3 = new double[3]; for (double[][] c : new double[][][] { {c2, c3}, {c3, c2}, }) { Assertions.assertThrows(IllegalArgumentException.class, () -> LineSampler.of(rng, c[0], c[1]), () -> String.format("Did not detect dimension mismatch: %d,%d", c[0].length, c[1].length)); } } /** * Test non-finite vertices. */ @Test void testNonFiniteVertexCoordinates() { final UniformRandomProvider rng = RandomAssert.seededRNG(); // A valid line final double[][] c = new double[][] { {0, 1, 2}, {-1, 2, 3} }; Assertions.assertNotNull(LineSampler.of(rng, c[0], c[1])); final double[] bad = {Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NaN}; for (int i = 0; i < c.length; i++) { final int ii = i; for (int j = 0; j < c[0].length; j++) { final int jj = j; for (final double d : bad) { final double value = c[i][j]; c[i][j] = d; Assertions.assertThrows(IllegalArgumentException.class, () -> LineSampler.of(rng, c[0], c[1]), () -> String.format("Did not detect non-finite coordinate: %d,%d = %s", ii, jj, d)); c[i][j] = value; } } } } /** * Test a line with coordinates that are separated by more than * {@link Double#MAX_VALUE} in 1D. */ @Test void testExtremeValueCoordinates1D() { testExtremeValueCoordinates(1); } /** * Test a line with coordinates that are separated by more than * {@link Double#MAX_VALUE} in 2D. */ @Test void testExtremeValueCoordinates2D() { testExtremeValueCoordinates(2); } /** * Test a line with coordinates that are separated by more than * {@link Double#MAX_VALUE} in 3D. */ @Test void testExtremeValueCoordinates3D() { testExtremeValueCoordinates(3); } /** * Test a line with coordinates that are separated by more than * {@link Double#MAX_VALUE} in 4D. */ @Test void testExtremeValueCoordinates4D() { testExtremeValueCoordinates(4); } /** * Test a line with coordinates that are separated by more than * {@link Double#MAX_VALUE}. * * @param dimension the dimension */ private static void testExtremeValueCoordinates(int dimension) { final double[][] c1 = new double[2][dimension]; final double[][] c2 = new double[2][dimension]; // Create a valid line that can be scaled Arrays.fill(c1[0], -1); Arrays.fill(c1[1], 1); // Extremely large value for scaling. Use a power of 2 for exact scaling. final double scale = 0x1.0p1023; for (int i = 0; i < c1.length; i++) { // Scale the second line for (int j = 0; j < dimension; j++) { c2[i][j] = c1[i][j] * scale; } } // Show the line is too big to compute vectors between points. Assertions.assertEquals(Double.POSITIVE_INFINITY, c2[1][0] - c2[0][0], "Expect vector b - a to be infinite in the x dimension"); final LineSampler sampler1 = LineSampler.of( RandomAssert.seededRNG(), c1[0], c1[1]); final LineSampler sampler2 = LineSampler.of( RandomAssert.seededRNG(), c2[0], c2[1]); for (int n = 0; n < 10; n++) { final double[] a = sampler1.sample(); final double[] b = sampler2.sample(); for (int i = 0; i < a.length; i++) { a[i] *= scale; } Assertions.assertArrayEquals(a, b); } } /** * Test the distribution of points in 1D. */ @Test void testDistribution1D() { testDistributionND(1); } /** * Test the distribution of points in 2D. */ @Test void testDistribution2D() { testDistributionND(2); } /** * Test the distribution of points in 3D. */ @Test void testDistribution3D() { testDistributionND(3); } /** * Test the distribution of points in 4D. */ @Test void testDistribution4D() { testDistributionND(4); } /** * Test the distribution of points in N dimensions. The output coordinates * should be uniform in the line. * * @param dimension the dimension */ private static void testDistributionND(int dimension) { final UniformRandomProvider rng = RandomAssert.createRNG(); double[] a; double[] b; if (dimension == 1) { a = new double[] {rng.nextDouble()}; b = new double[] {-rng.nextDouble()}; } else { final UnitSphereSampler sphere = UnitSphereSampler.of(rng, dimension); a = sphere.sample(); b = sphere.sample(); } // To test uniformity on the line all fractional lengths along each dimension // should be the same constant: // x - a // ----- = C // b - a // This should be uniformly distributed in the range [0, 1]. // Pre-compute scaling: final double[] scale = new double[dimension]; for (int i = 0; i < dimension; i++) { scale[i] = 1.0 / (b[i] - a[i]); } // Assign bins final int bins = 100; final int samplesPerBin = 20; // Expect a uniform distribution final double[] expected = new double[bins]; Arrays.fill(expected, 1.0 / bins); // Increase the loops and use a null seed (i.e. randomly generated) to verify robustness final LineSampler sampler = LineSampler.of(rng, a, b); final int samples = expected.length * samplesPerBin; for (int n = 0; n < 1; n++) { // Assign each coordinate to a region inside the line final long[] observed = new long[expected.length]; for (int i = 0; i < samples; i++) { final double[] x = sampler.sample(); Assertions.assertEquals(dimension, x.length); final double c = (x[0] - a[0]) * scale[0]; Assertions.assertTrue(c >= 0.0 && c <= 1.0, "Not uniformly distributed"); for (int j = 1; j < dimension; j++) { Assertions.assertEquals(c, (x[j] - a[j]) * scale[j], 1e-14, "Not on the line"); } // Assign the uniform deviate to a bin. Assumes c != 1.0. observed[(int) (c * bins)]++; } final double p = new ChiSquareTest().chiSquareTest(expected, observed); Assertions.assertFalse(p < 0.001, () -> "p-value too small: " + p); } } /** * Test the SharedStateSampler implementation for 1D. */ @Test void testSharedStateSampler1D() { testSharedStateSampler(1); } /** * Test the SharedStateSampler implementation for 2D. */ @Test void testSharedStateSampler2D() { testSharedStateSampler(2); } /** * Test the SharedStateSampler implementation for 3D. */ @Test void testSharedStateSampler3D() { testSharedStateSampler(3); } /** * Test the SharedStateSampler implementation for 4D. */ @Test void testSharedStateSampler4D() { testSharedStateSampler(4); } /** * Test the SharedStateSampler implementation for the given dimension. */ private static void testSharedStateSampler(int dimension) { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final double[] c1 = createCoordinate(1, dimension); final double[] c2 = createCoordinate(2, dimension); final LineSampler sampler1 = LineSampler.of(rng1, c1, c2); final LineSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * Test the input vectors are copied and not used by reference for 1D. */ @Test void testChangedInputCoordinates1D() { testChangedInputCoordinates(1); } /** * Test the input vectors are copied and not used by reference for 2D. */ @Test void testChangedInputCoordinates2D() { testChangedInputCoordinates(2); } /** * Test the input vectors are copied and not used by reference for 3D. */ @Test void testChangedInputCoordinates3D() { testChangedInputCoordinates(3); } /** * Test the input vectors are copied and not used by reference for 4D. */ @Test void testChangedInputCoordinates4D() { testChangedInputCoordinates(4); } /** * Test the input vectors are copied and not used by reference for the given * dimension. * * @param dimension the dimension */ private static void testChangedInputCoordinates(int dimension) { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final double[] c1 = createCoordinate(1, dimension); final double[] c2 = createCoordinate(2, dimension); final LineSampler sampler1 = LineSampler.of(rng1, c1, c2); // Check the input vectors are copied and not used by reference. // Change them in place and create a new sampler. It should have different output // translated by the offset. final double offset = 10; for (int i = 0; i < dimension; i++) { c1[i] += offset; c2[i] += offset; } final LineSampler sampler2 = LineSampler.of(rng2, c1, c2); for (int n = 0; n < 3; n++) { final double[] s1 = sampler1.sample(); final double[] s2 = sampler2.sample(); Assertions.assertEquals(s1.length, s2.length); Assertions.assertFalse(Arrays.equals(s1, s2), "First sampler has used the vertices by reference"); for (int i = 0; i < dimension; i++) { Assertions.assertEquals(s1[i] + offset, s2[i], 1e-10); } } } /** * Creates the coordinate of length specified by the dimension filled with * the given value and the dimension index: x + i. * * @param x the value for index 0 * @param dimension the dimension * @return the coordinate */ private static double[] createCoordinate(double x, int dimension) { final double[] coord = new double[dimension]; for (int i = 0; i < dimension; i++) { coord[0] = x + i; } return coord; } }
2,915
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/shape/UnitBallSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.shape; import java.util.Arrays; import java.util.function.DoubleUnaryOperator; import org.apache.commons.math3.stat.inference.ChiSquareTest; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.core.source64.SplitMix64; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test for {@link UnitBallSampler}. */ class UnitBallSamplerTest { /** * Test a non-positive dimension. */ @Test void testInvalidDimensionThrows() { final UniformRandomProvider rng = RandomAssert.seededRNG(); Assertions.assertThrows(IllegalArgumentException.class, () -> UnitBallSampler.of(rng, 0)); } /** * Test the distribution of points in one dimension. */ @Test void testDistribution1D() { testDistributionND(1); } /** * Test the distribution of points in two dimensions. */ @Test void testDistribution2D() { testDistributionND(2); } /** * Test the distribution of points in three dimensions. */ @Test void testDistribution3D() { testDistributionND(3); } /** * Test the distribution of points in four dimensions. */ @Test void testDistribution4D() { testDistributionND(4); } /** * Test the distribution of points in five dimensions. */ @Test void testDistribution5D() { testDistributionND(5); } /** * Test the distribution of points in six dimensions. */ @Test void testDistribution6D() { testDistributionND(6); } /** * Test the distribution of points in n dimensions. The output coordinates * should be uniform in the unit n-ball. The unit n-ball is divided into inner * n-balls. The radii of the internal n-balls are varied to ensure that successive layers * have the same volume. This assigns each coordinate to an inner n-ball layer and an * orthant using the sign bits of the coordinates. The number of samples in each bin * should be the same. * * @see <a href="https://en.wikipedia.org/wiki/Volume_of_an_n-ball">Volume of an n-ball</a> * @see <a href="https://en.wikipedia.org/wiki/Orthant">Orthant</a> */ private static void testDistributionND(int dimension) { // The number of inner layers and samples has been selected by trial and error using // random seeds and multiple runs to ensure correctness of the test (i.e. it fails with // approximately the fraction expected for the test p-value). // A fixed seed is used to make the test suite robust. final int layers = 10; final int samplesPerBin = 20; final int orthants = 1 << dimension; // Compute the radius for each layer to have the same volume. final double volume = createVolumeFunction(dimension).applyAsDouble(1); final DoubleUnaryOperator radius = createRadiusFunction(dimension); final double[] r = new double[layers]; for (int i = 1; i < layers; i++) { r[i - 1] = radius.applyAsDouble(volume * ((double) i / layers)); } // The final radius should be 1.0. Any coordinates with a radius above 1 // should fail so explicitly set the value as 1. r[layers - 1] = 1.0; // Expect a uniform distribution final double[] expected = new double[layers * orthants]; final int samples = samplesPerBin * expected.length; Arrays.fill(expected, (double) samples / layers); // Increase the loops to verify robustness final UniformRandomProvider rng = RandomAssert.createRNG(); final UnitBallSampler sampler = UnitBallSampler.of(rng, dimension); for (int loop = 0; loop < 1; loop++) { // Assign each coordinate to a layer inside the ball and an orthant using the sign final long[] observed = new long[layers * orthants]; NEXT: for (int i = 0; i < samples; i++) { final double[] v = sampler.sample(); final double length = length(v); for (int layer = 0; layer < layers; layer++) { if (length <= r[layer]) { final int orthant = orthant(v); observed[layer * orthants + orthant]++; continue NEXT; } } // Radius above 1 Assertions.fail("Invalid sample length: " + length); } final double p = new ChiSquareTest().chiSquareTest(expected, observed); Assertions.assertFalse(p < 0.001, () -> "p-value too small: " + p); } } /** * Test the edge case where the normalisation sum to divide by is zero for 3D. */ @Test void testInvalidInverseNormalisation3D() { testInvalidInverseNormalisationND(3); } /** * Test the edge case where the normalisation sum to divide by is zero for 4D. */ @Test void testInvalidInverseNormalisation4D() { testInvalidInverseNormalisationND(4); } /** * Test the edge case where the normalisation sum to divide by is zero. * This test requires generation of Gaussian samples with the value 0. */ private static void testInvalidInverseNormalisationND(final int dimension) { // Create a provider that will create a bad first sample but then recover. // This checks recursion will return a good value. final UniformRandomProvider bad = new SplitMix64(0x1a2b3cL) { private int count = -2 * dimension; @Override public long nextLong() { // Return enough zeros to create Gaussian samples of zero for all coordinates. return count++ < 0 ? 0 : super.nextLong(); } }; final double[] vector = UnitBallSampler.of(bad, dimension).sample(); Assertions.assertEquals(dimension, vector.length); // A non-zero coordinate should occur with a SplitMix which returns 0 only once. Assertions.assertNotEquals(0.0, length(vector)); } /** * Test the SharedStateSampler implementation for 1D. */ @Test void testSharedStateSampler1D() { testSharedStateSampler(1); } /** * Test the SharedStateSampler implementation for 2D. */ @Test void testSharedStateSampler2D() { testSharedStateSampler(2); } /** * Test the SharedStateSampler implementation for 3D. */ @Test void testSharedStateSampler3D() { testSharedStateSampler(3); } /** * Test the SharedStateSampler implementation for 4D. */ @Test void testSharedStateSampler4D() { testSharedStateSampler(4); } /** * Test the SharedStateSampler implementation for the given dimension. */ private static void testSharedStateSampler(int dimension) { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final UnitBallSampler sampler1 = UnitBallSampler.of(rng1, dimension); final UnitBallSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * @return the length (L2-norm) of given vector. */ private static double length(double[] vector) { double total = 0; for (double d : vector) { total += d * d; } return Math.sqrt(total); } /** * Assign an orthant to the vector using the sign of each component. * The i<sup>th</sup> bit is set in the orthant for the i<sup>th</sup> component * if the component is negative. * * @return the orthant in the range [0, vector.length) * @see <a href="https://en.wikipedia.org/wiki/Orthant">Orthant</a> */ private static int orthant(double[] vector) { int orthant = 0; for (int i = 0; i < vector.length; i++) { if (vector[i] < 0) { orthant |= 1 << i; } } return orthant; } /** * Check the n-ball volume functions can map the radius to the volume and back. * These functions are used to divide the n-ball into uniform volume bins to test sampling * within the n-ball. */ @Test void checkVolumeFunctions() { final double[] radii = {0, 0.1, 0.25, 0.5, 0.75, 1.0}; for (int n = 1; n <= 6; n++) { final DoubleUnaryOperator volume = createVolumeFunction(n); final DoubleUnaryOperator radius = createRadiusFunction(n); for (final double r : radii) { Assertions.assertEquals(r, radius.applyAsDouble(volume.applyAsDouble(r)), 1e-10); } } } /** * Creates a function to compute the volume of a ball of the given dimension * from the radius. * * @param dimension the dimension * @return the volume function * @see <a href="https://en.wikipedia.org/wiki/Volume_of_an_n-ball">Volume of an n-ball</a> */ private static DoubleUnaryOperator createVolumeFunction(final int dimension) { if (dimension == 1) { return r -> r * 2; } else if (dimension == 2) { return r -> Math.PI * r * r; } else if (dimension == 3) { final double factor = 4 * Math.PI / 3; return r -> factor * Math.pow(r, 3); } else if (dimension == 4) { final double factor = Math.PI * Math.PI / 2; return r -> factor * Math.pow(r, 4); } else if (dimension == 5) { final double factor = 8 * Math.PI * Math.PI / 15; return r -> factor * Math.pow(r, 5); } else if (dimension == 6) { final double factor = Math.pow(Math.PI, 3) / 6; return r -> factor * Math.pow(r, 6); } throw new IllegalStateException("Unsupported dimension: " + dimension); } /** * Creates a function to compute the radius of a ball of the given dimension * from the volume. * * @param dimension the dimension * @return the radius function * @see <a href="https://en.wikipedia.org/wiki/Volume_of_an_n-ball">Volume of an n-ball</a> */ private static DoubleUnaryOperator createRadiusFunction(final int dimension) { if (dimension == 1) { return v -> v * 0.5; } else if (dimension == 2) { return v -> Math.sqrt(v / Math.PI); } else if (dimension == 3) { final double factor = 3.0 / (4 * Math.PI); return v -> Math.cbrt(v * factor); } else if (dimension == 4) { final double factor = 2.0 / (Math.PI * Math.PI); return v -> Math.pow(v * factor, 0.25); } else if (dimension == 5) { final double factor = 15.0 / (8 * Math.PI * Math.PI); return v -> Math.pow(v * factor, 0.2); } else if (dimension == 6) { final double factor = 6.0 / Math.pow(Math.PI, 3); return v -> Math.pow(v * factor, 1.0 / 6); } throw new IllegalStateException("Unsupported dimension: " + dimension); } }
2,916
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/DirichletSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import java.util.Arrays; import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.commons.math3.stat.correlation.Covariance; import org.apache.commons.math3.stat.descriptive.moment.Mean; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.core.source64.SplitMix64; import org.apache.commons.rng.sampling.RandomAssert; import org.apache.commons.rng.simple.RandomSource; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test for {@link DirichletSampler}. */ class DirichletSamplerTest { @Test void testDistributionThrowsWithInvalidNumberOfCategories() { final UniformRandomProvider rng = RandomAssert.seededRNG(); Assertions.assertThrows(IllegalArgumentException.class, () -> DirichletSampler.of(rng, 1.0)); } @Test void testDistributionThrowsWithZeroConcentration() { final UniformRandomProvider rng = RandomAssert.seededRNG(); Assertions.assertThrows(IllegalArgumentException.class, () -> DirichletSampler.of(rng, 1.0, 0.0)); } @Test void testDistributionThrowsWithNaNConcentration() { final UniformRandomProvider rng = RandomAssert.seededRNG(); Assertions.assertThrows(IllegalArgumentException.class, () -> DirichletSampler.of(rng, 1.0, Double.NaN)); } @Test void testDistributionThrowsWithInfiniteConcentration() { final UniformRandomProvider rng = RandomAssert.seededRNG(); Assertions.assertThrows(IllegalArgumentException.class, () -> DirichletSampler.of(rng, 1.0, Double.POSITIVE_INFINITY)); } @Test void testSymmetricDistributionThrowsWithInvalidNumberOfCategories() { final UniformRandomProvider rng = RandomAssert.seededRNG(); Assertions.assertThrows(IllegalArgumentException.class, () -> DirichletSampler.symmetric(rng, 1, 1.0)); } @Test void testSymmetricDistributionThrowsWithZeroConcentration() { final UniformRandomProvider rng = RandomAssert.seededRNG(); Assertions.assertThrows(IllegalArgumentException.class, () -> DirichletSampler.symmetric(rng, 2, 0.0)); } @Test void testSymmetricDistributionThrowsWithNaNConcentration() { final UniformRandomProvider rng = RandomAssert.seededRNG(); Assertions.assertThrows(IllegalArgumentException.class, () -> DirichletSampler.symmetric(rng, 2, Double.NaN)); } @Test void testSymmetricDistributionThrowsWithInfiniteConcentration() { final UniformRandomProvider rng = RandomAssert.seededRNG(); Assertions.assertThrows(IllegalArgumentException.class, () -> DirichletSampler.symmetric(rng, 2, Double.POSITIVE_INFINITY)); } /** * Create condition so that all samples are zero and it is impossible to normalise the * samples to sum to 1. These should be ignored and the sample is repeated until * normalisation is possible. */ @Test void testInvalidSampleIsIgnored() { // An RNG implementation which should create zero samples from the underlying // exponential sampler for an initial sequence. final UniformRandomProvider rng = new SplitMix64(0L) { private int i; @Override public long next() { return i++ < 10 ? 0L : super.next(); } }; // Alpha=1 will use an exponential sampler final DirichletSampler sampler = DirichletSampler.symmetric(rng, 2, 1.0); assertSample(2, sampler.sample()); } @Test void testSharedStateSampler() { final RandomSource randomSource = RandomSource.XO_RO_SHI_RO_128_PP; final byte[] seed = randomSource.createSeed(); final UniformRandomProvider rng1 = randomSource.create(seed); final UniformRandomProvider rng2 = randomSource.create(seed); final DirichletSampler sampler1 = DirichletSampler.of(rng1, 1, 2, 3); final DirichletSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } @Test void testSharedStateSamplerForSymmetricCase() { final RandomSource randomSource = RandomSource.XO_RO_SHI_RO_128_PP; final byte[] seed = randomSource.createSeed(); final UniformRandomProvider rng1 = randomSource.create(seed); final UniformRandomProvider rng2 = randomSource.create(seed); final DirichletSampler sampler1 = DirichletSampler.symmetric(rng1, 2, 1.5); final DirichletSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } @Test void testSymmetricCaseMatchesGeneralCase() { final RandomSource randomSource = RandomSource.XO_RO_SHI_RO_128_PP; final byte[] seed = randomSource.createSeed(); final UniformRandomProvider rng1 = randomSource.create(seed); final UniformRandomProvider rng2 = randomSource.create(seed); final int k = 3; final double[] alphas = new double[k]; for (final double alpha : new double[] {0.5, 1.0, 1.5}) { Arrays.fill(alphas, alpha); final DirichletSampler sampler1 = DirichletSampler.symmetric(rng1, k, alpha); final DirichletSampler sampler2 = DirichletSampler.of(rng2, alphas); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } } /** * Test the toString method. This is added to ensure coverage. */ @Test void testToString() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final DirichletSampler sampler1 = DirichletSampler.symmetric(rng, 2, 1.0); final DirichletSampler sampler2 = DirichletSampler.of(rng, 0.5, 1, 1.5); Assertions.assertTrue(sampler1.toString().toLowerCase().contains("dirichlet")); Assertions.assertTrue(sampler2.toString().toLowerCase().contains("dirichlet")); } @Test void testSampling1() { assertSamples(1, 2, 3); } @Test void testSampling2() { assertSamples(1, 1, 1); } @Test void testSampling3() { assertSamples(0.5, 1, 1.5); } @Test void testSampling4() { assertSamples(1, 3); } @Test void testSampling5() { assertSamples(1, 2, 3, 4); } /** * Assert samples from the distribution. The variates are tested against the expected * mean and covariance for the given concentration parameters. * * @param alpha Concentration parameters. */ private static void assertSamples(double... alpha) { // No fixed seed. Failed tests will be repeated by the JUnit test runner. final UniformRandomProvider rng = RandomAssert.createRNG(); final DirichletSampler sampler = DirichletSampler.of(rng, alpha); final int k = alpha.length; final double[][] samples = new double[100000][]; for (int i = 0; i < samples.length; i++) { final double[] x = sampler.sample(); assertSample(k, x); samples[i] = x; } // Computation of moments: // https://en.wikipedia.org/wiki/Dirichlet_distribution#Moments // Compute the sum of the concentration parameters: alpha0 double alpha0 = 0; for (int i = 0; i < k; i++) { alpha0 += alpha[i]; } // Use a moderate tolerance. // Differences are usually observed in the 3rd significant figure. final double relativeTolerance = 5e-2; // Mean = alpha[i] / alpha0 final double[] means = getColumnMeans(samples); for (int i = 0; i < k; i++) { final double mean = alpha[i] / alpha0; Assertions.assertEquals(mean, means[i], mean * relativeTolerance, "Mean"); } // Variance = alpha_i (alpha_0 - alpha_i) / alpha_0^2 (alpha_0 + 1) // Covariance = -alpha_i * alpha_j / alpha_0^2 (alpha_0 + 1) final double[][] covars = getCovariance(samples); final double denom = alpha0 * alpha0 * (alpha0 + 1); for (int i = 0; i < k; i++) { final double var = alpha[i] * (alpha0 - alpha[i]) / denom; Assertions.assertEquals(var, covars[i][i], var * relativeTolerance, "Variance"); for (int j = i + 1; j < k; j++) { final double covar = -alpha[i] * alpha[j] / denom; Assertions.assertEquals(covar, covars[i][j], Math.abs(covar) * relativeTolerance, "Covariance"); } } } /** * Assert the sample has the correct length and sums to 1. * * @param k Expected number of categories. * @param x Sample. */ private static void assertSample(int k, double[] x) { Assertions.assertEquals(k, x.length, "Number of categories"); // There are always at least 2 categories double sum = x[0] + x[1]; // Sum the rest for (int i = 2; i < x.length; i++) { sum += x[i]; } Assertions.assertEquals(1.0, sum, 1e-10, "Invalid sum"); } /** * Gets the column means. This is done using the same method as the means in the * Apache Commons Math Covariance class by using the Mean class. * * @param data the data * @return the column means */ private static double[] getColumnMeans(double[][] data) { final Array2DRowRealMatrix m = new Array2DRowRealMatrix(data, false); final Mean mean = new Mean(); final double[] means = new double[m.getColumnDimension()]; for (int i = 0; i < means.length; i++) { means[i] = mean.evaluate(m.getColumn(i)); } return means; } /** * Gets the covariance. * * @param data the data * @return the covariance */ private static double[][] getCovariance(double[][] data) { final Array2DRowRealMatrix m = new Array2DRowRealMatrix(data, false); return new Covariance(m).getCovarianceMatrix().getData(); } }
2,917
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/InternalUtilsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.math3.special.Gamma; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.apache.commons.rng.sampling.distribution.InternalUtils.FactorialLog; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test for the {@link InternalUtils}. */ class InternalUtilsTest { /** The maximum value for n! that is representable as a long. */ private static final int MAX_REPRESENTABLE = 20; @Test void testFactorial() { Assertions.assertEquals(1L, InternalUtils.factorial(0)); long result = 1; for (int n = 1; n <= MAX_REPRESENTABLE; n++) { result *= n; Assertions.assertEquals(result, InternalUtils.factorial(n)); } } @Test void testFactorialThrowsWhenNegative() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> InternalUtils.factorial(-1)); } @Test void testFactorialThrowsWhenNotRepresentableAsLong() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> InternalUtils.factorial(MAX_REPRESENTABLE + 1)); } @Test void testFactorialLog() { // Cache size allows some of the factorials to be cached and some // to be under the precomputed factorials. FactorialLog factorialLog = FactorialLog.create().withCache(MAX_REPRESENTABLE / 2); Assertions.assertEquals(0, factorialLog.value(0), 1e-10); for (int n = 1; n <= MAX_REPRESENTABLE + 5; n++) { // Use Commons math to compute logGamma(1 + n); double expected = Gamma.logGamma(1 + n); Assertions.assertEquals(expected, factorialLog.value(n), 1e-10); } } @Test void testFactorialLogCacheSizeAboveRepresentableFactorials() { final int limit = MAX_REPRESENTABLE + 5; FactorialLog factorialLog = FactorialLog.create().withCache(limit); for (int n = MAX_REPRESENTABLE; n <= limit; n++) { // Use Commons math to compute logGamma(1 + n); double expected = Gamma.logGamma(1 + n); Assertions.assertEquals(expected, factorialLog.value(n), 1e-10); } } @Test void testFactorialLogCacheExpansion() { // There is no way to determine if the cache values were reused but this test // exercises the method to ensure it does not error. final FactorialLog factorialLog = FactorialLog.create() // Edge case where cache should not be copied (<2) .withCache(1) // Expand .withCache(5) // Expand more .withCache(10) // Contract .withCache(5); for (int n = 1; n <= 5; n++) { // Use Commons math to compute logGamma(1 + n); double expected = Gamma.logGamma(1 + n); Assertions.assertEquals(expected, factorialLog.value(n), 1e-10); } } @Test void testLogFactorialThrowsWhenNegative() { final FactorialLog factorialLog = FactorialLog.create(); Assertions.assertThrows(IndexOutOfBoundsException.class, () -> factorialLog.value(-1)); } @Test void testLogFactorialWithCacheThrowsWhenNegative() { final FactorialLog factorialLog = FactorialLog.create(); Assertions.assertThrows(NegativeArraySizeException.class, () -> factorialLog.withCache(-1)); } @Test void testMakeDouble() { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); for (int i = 0; i < 10; i++) { // Assume the RNG is outputting in [0, 1) using the same method Assertions.assertEquals(rng1.nextDouble(), InternalUtils.makeDouble(rng2.nextLong())); } } @Test void testMakeNonZeroDouble() { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final double u = 0x1.0p-53; for (int i = 0; i < 10; i++) { // Assume the RNG is outputting in [0, 1) // The non-zero method should shift this to (0, 1] Assertions.assertEquals(rng1.nextDouble() + u, InternalUtils.makeNonZeroDouble(rng2.nextLong())); } } }
2,918
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/ContinuousSamplerTestData.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import java.util.Arrays; /** * Data store for {@link ContinuousSamplerParametricTest}. */ class ContinuousSamplerTestData { private final ContinuousSampler sampler; private final double[] deciles; ContinuousSamplerTestData(ContinuousSampler sampler, double[] deciles) { this.sampler = sampler; this.deciles = deciles.clone(); } public ContinuousSampler getSampler() { return sampler; } public double[] getDeciles() { return deciles.clone(); } @Override public String toString() { return sampler.toString() + ": deciles=" + Arrays.toString(deciles); } }
2,919
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/UniformLongSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import java.util.Locale; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.core.source64.LongProvider; import org.apache.commons.rng.core.source64.SplitMix64; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; /** * Test for the {@link UniformLongSampler}. The tests hit edge cases for the sampler * and demonstrates uniformity of output when the underlying RNG output is uniform. * * <p>Note: No statistical tests for uniformity are performed on the output. The tests * are constructed on the premise that the underlying sampling methods correctly * use the random bits from {@link UniformRandomProvider}. Correctness * for a small range is tested against {@link UniformRandomProvider#nextLong(long)} * and correctness for a large range is tested that the {@link UniformRandomProvider#nextLong()} * is within the range limits. Power of two ranges are tested against a bit shift * of a random long. */ class UniformLongSamplerTest { /** * Test the constructor with a bad range. */ @Test void testConstructorThrowsWithLowerAboveUpper() { final long upper = 55; final long lower = upper + 1; final UniformRandomProvider rng = RandomAssert.seededRNG(); Assertions.assertThrows(IllegalArgumentException.class, () -> UniformLongSampler.of(rng, lower, upper)); } @Test void testSamplesWithRangeOf1() { final long upper = 99; final long lower = upper; final UniformRandomProvider rng = RandomAssert.createRNG(); final UniformLongSampler sampler = UniformLongSampler.of(rng, lower, upper); for (int i = 0; i < 5; i++) { Assertions.assertEquals(lower, sampler.sample()); } } /** * Test samples with a full long range. * The output should be the same as the long values produced from a RNG. */ @Test void testSamplesWithFullRange() { final long upper = Long.MAX_VALUE; final long lower = Long.MIN_VALUE; final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final UniformLongSampler sampler = UniformLongSampler.of(rng2, lower, upper); for (int i = 0; i < 10; i++) { Assertions.assertEquals(rng1.nextLong(), sampler.sample()); } } /** * Test samples with a non-power of 2 range. * The output should be the same as the long values produced from a RNG * based on o.a.c.rng.core.BaseProvider as the rejection algorithm is * the same. */ @ParameterizedTest @ValueSource(longs = {234293789329234L, 145, 69987, 12673586268L, 234785389445435L, Long.MAX_VALUE}) void testSamplesWithSmallNonPowerOf2Range(long upper) { for (final long lower : new long[] {-13, 0, 13}) { final long n = upper - lower + 1; // Skip overflow ranges if (n < 0) { continue; } Assertions.assertNotEquals(0, n & (n - 1), "Power of 2 is invalid here"); // Largest multiple of the upper bound. // floor(2^63 / range) * range // Computed as 2^63 - 2 % 63 with unsigned integers. final long m = Long.MIN_VALUE - Long.remainderUnsigned(Long.MIN_VALUE, n); // Check the method used in the sampler Assertions.assertEquals(m, (Long.MIN_VALUE / n) * -n); // Use an RNG that forces the rejection path on the first few samples // This occurs when the positive value is above the limit set by the // largest multiple of upper that does not overflow. final UniformRandomProvider rng1 = createRngWithFullBitsOnFirstCall(m); final UniformRandomProvider rng2 = createRngWithFullBitsOnFirstCall(m); final UniformLongSampler sampler = UniformLongSampler.of(rng2, lower, upper); for (int i = 0; i < 100; i++) { Assertions.assertEquals(lower + rng1.nextLong(n), sampler.sample()); } } } /** * Creates a RNG which will return full bits for the first sample, then bits * too high for the configured limit for a few iterations. * * @param m Upper limit for a sample * @return the uniform random provider */ private static UniformRandomProvider createRngWithFullBitsOnFirstCall(long m) { return new SplitMix64(0L) { private int i; @Override public long next() { int j = i++; if (j == 0) { // Full bits return -1L; } else if (j < 6) { // A value just above or below the limit. // Assumes m is positive and the sampler uses >>> 1 to extract // a positive value. return (m + 3 - j) << 1; } return super.next(); } }; } /** * Test samples with a power of 2 range. * This tests the minimum and maximum output should be the range limits. */ @Test void testSamplesWithPowerOf2Range() { final UniformRandomProvider rngZeroBits = new LongProvider() { @Override public long next() { // No bits return 0L; } }; final UniformRandomProvider rngAllBits = new LongProvider() { @Override public long next() { // All bits return -1L; } }; final long lower = -3; UniformLongSampler sampler; // The upper range for a positive long is 2^63-1. So the max positive power of // 2 is 2^62. However the sampler should handle a bit shift of 63 to create a range // of Long.MIN_VALUE as this is a power of 2 as an unsigned long (2^63). for (int i = 0; i < 64; i++) { final long range = 1L << i; final long upper = lower + range - 1; sampler = UniformLongSampler.of(rngZeroBits, lower, upper); Assertions.assertEquals(lower, sampler.sample(), "Zero bits sample"); sampler = UniformLongSampler.of(rngAllBits, lower, upper); Assertions.assertEquals(upper, sampler.sample(), "All bits sample"); } } /** * Test samples with a power of 2 range. * This tests the output is created using a bit shift. */ @Test void testSamplesWithPowerOf2RangeIsBitShift() { final long lower = 0; UniformLongSampler sampler; // Power of 2 sampler used for a bit shift of 1 to 63. for (int i = 1; i <= 63; i++) { // Upper is inclusive so subtract 1 final long upper = (1L << i) - 1; final int shift = 64 - i; final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); sampler = UniformLongSampler.of(rng2, lower, upper); for (int j = 0; j < 10; j++) { Assertions.assertEquals(rng1.nextLong() >>> shift, sampler.sample()); } } } /** * Test samples with a large non-power of 2 range. * This tests the large range algorithm uses a rejection method. */ @Test void testSamplesWithLargeNonPowerOf2RangeIsRejectionMethod() { // Create a range bigger than 2^63 final long upper = Long.MAX_VALUE / 2 + 1; final long lower = Long.MIN_VALUE / 2 - 1; final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final UniformLongSampler sampler = UniformLongSampler.of(rng2, lower, upper); for (int i = 0; i < 10; i++) { // Get the expected value by the rejection method long expected; do { expected = rng1.nextLong(); } while (expected < lower || expected > upper); Assertions.assertEquals(expected, sampler.sample()); } } @Test void testOffsetSamplesWithNonPowerOf2Range() { assertOffsetSamples(257); } @Test void testOffsetSamplesWithPowerOf2Range() { assertOffsetSamples(256); } @Test void testOffsetSamplesWithRangeOf1() { assertOffsetSamples(1); } private static void assertOffsetSamples(long range) { final UniformRandomProvider[] rngs = RandomAssert.createRNG(3); final UniformRandomProvider rng1 = rngs[0]; final UniformRandomProvider rng2 = rngs[1]; final UniformRandomProvider rng3 = rngs[2]; // Since the upper limit is inclusive range = range - 1; final long offsetLo = -13; final long offsetHi = 42; final UniformLongSampler sampler = UniformLongSampler.of(rng1, 0, range); final UniformLongSampler samplerLo = UniformLongSampler.of(rng2, offsetLo, offsetLo + range); final UniformLongSampler samplerHi = UniformLongSampler.of(rng3, offsetHi, offsetHi + range); for (int i = 0; i < 10; i++) { final long sample1 = sampler.sample(); final long sample2 = samplerLo.sample(); final long sample3 = samplerHi.sample(); Assertions.assertEquals(sample1 + offsetLo, sample2, "Incorrect negative offset sample"); Assertions.assertEquals(sample1 + offsetHi, sample3, "Incorrect positive offset sample"); } } /** * Test the sample uniformity when using a small range that is a power of 2. */ @Test void testSampleUniformityWithPowerOf2Range() { // Test using a RNG that outputs a counter of integers. // The n most significant bits will be represented uniformly over a // sequence that is a 2^n long. final UniformRandomProvider rng = new LongProvider() { private long bits = 0; @Override public long next() { // We reverse the bits because the most significant bits are used return Long.reverse(bits++); } }; // n = upper range exclusive final int n = 32; // power of 2 final int[] histogram = new int[n]; final long lower = 0; final long upper = n - 1; final UniformLongSampler sampler = UniformLongSampler.of(rng, lower, upper); final int expected = 2; for (int i = expected * n; i-- > 0;) { histogram[(int) sampler.sample()]++; } // This should be even across the entire range for (int value : histogram) { Assertions.assertEquals(expected, value); } } @Test void testSharedStateSamplerWithSmallRange() { assertSharedStateSampler(5, 67); } @Test void testSharedStateSamplerWithLargeRange() { // Set the range so rejection below or above the threshold occurs with approximately // p=0.25 for each bound. assertSharedStateSampler(Long.MIN_VALUE / 2 - 1, Long.MAX_VALUE / 2 + 1); } @Test void testSharedStateSamplerWithPowerOf2Range() { assertSharedStateSampler(0, (1L << 45) - 1); } @Test void testSharedStateSamplerWithRangeOf1() { assertSharedStateSampler(968757657572323L, 968757657572323L); } /** * Test the SharedStateSampler implementation returns the same sequence as the source sampler * when using an identical RNG. * * @param lower Lower. * @param upper Upper. */ private static void assertSharedStateSampler(long lower, long upper) { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final UniformLongSampler sampler1 = UniformLongSampler.of(rng1, lower, upper); final UniformLongSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } @Test void testToStringWithSmallRange() { assertToString(5, 67); } @Test void testToStringWithLargeRange() { assertToString(-99999999, Long.MAX_VALUE); } @Test void testToStringWithPowerOf2Range() { // Note the range is upper - lower + 1 assertToString(0, 31); } @Test void testToStringWithRangeOf1() { assertToString(9, 9); } /** * Test the toString method contains the term "uniform". This is true of all samplers * even for a fixed sample from a range of 1. * * @param lower Lower. * @param upper Upper. */ private static void assertToString(long lower, long upper) { final UniformRandomProvider rng = RandomAssert.seededRNG(); final UniformLongSampler sampler = UniformLongSampler.of(rng, lower, upper); Assertions.assertTrue(sampler.toString().toLowerCase(Locale.US).contains("uniform")); } }
2,920
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/LargeMeanPoissonSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.apache.commons.rng.sampling.distribution.LargeMeanPoissonSampler.LargeMeanPoissonSamplerState; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * This test checks the {@link LargeMeanPoissonSampler} can be created * from a saved state. */ class LargeMeanPoissonSamplerTest { // Edge cases for construction /** * Test the constructor with a bad mean. */ @Test void testConstructorThrowsWithMeanLargerThanUpperBound() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final double mean = Integer.MAX_VALUE / 2 + 1; Assertions.assertThrows(IllegalArgumentException.class, () -> LargeMeanPoissonSampler.of(rng, mean)); } /** * Test the constructor with a mean below 1. */ @Test void testConstructorThrowsWithMeanBelow1() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final double mean = Math.nextDown(1); Assertions.assertThrows(IllegalArgumentException.class, () -> LargeMeanPoissonSampler.of(rng, mean)); } /** * Test the constructor using the state with a negative fractional mean. */ @Test void testConstructorThrowsWithStateAndNegativeFractionalMean() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final LargeMeanPoissonSamplerState state = new LargeMeanPoissonSampler(rng, 1).getState(); Assertions.assertThrows(IllegalArgumentException.class, () -> new LargeMeanPoissonSampler(rng, state, -0.1)); } /** * Test the constructor with a non-fractional mean. */ @Test void testConstructorThrowsWithStateAndNonFractionalMean() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final LargeMeanPoissonSamplerState state = new LargeMeanPoissonSampler(rng, 1).getState(); Assertions.assertThrows(IllegalArgumentException.class, () -> new LargeMeanPoissonSampler(rng, state, 1.1)); } /** * Test the constructor with fractional mean of 1. */ @Test void testConstructorThrowsWithStateAndFractionalMeanOne() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final LargeMeanPoissonSamplerState state = new LargeMeanPoissonSampler(rng, 1).getState(); Assertions.assertThrows(IllegalArgumentException.class, () -> new LargeMeanPoissonSampler(rng, state, 1)); } // Sampling tests /** * Test the {@link LargeMeanPoissonSampler} returns the same samples when it * is created using the saved state. */ @Test void testCanComputeSameSamplesWhenConstructedWithState() { // Two identical RNGs final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); // The sampler is suitable for mean > 40 for (int i = 40; i < 44; i++) { // Test integer mean (no SmallMeanPoissonSampler required) testPoissonSamples(rng1, rng2, i); // Test non-integer mean (SmallMeanPoissonSampler required) testPoissonSamples(rng1, rng2, i + 0.5); } } /** * Test the {@link LargeMeanPoissonSampler} returns the same samples when it * is created using the saved state. The random providers must be * identical (including state). * * @param rng1 the first random provider * @param rng2 the second random provider * @param mean the mean */ private static void testPoissonSamples( final UniformRandomProvider rng1, final UniformRandomProvider rng2, double mean) { final LargeMeanPoissonSampler s1 = new LargeMeanPoissonSampler(rng1, mean); final int n = (int) Math.floor(mean); final double lambdaFractional = mean - n; final LargeMeanPoissonSamplerState state1 = s1.getState(); final LargeMeanPoissonSampler s2 = new LargeMeanPoissonSampler(rng2, state1, lambdaFractional); final LargeMeanPoissonSamplerState state2 = s2.getState(); Assertions.assertEquals(state1.getLambda(), state2.getLambda(), "State lambdas are not equal"); Assertions.assertNotSame(state1, state2, "States are the same object"); RandomAssert.assertProduceSameSequence(s1, s2); } /** * Test the SharedStateSampler implementation. */ @Test void testSharedStateSamplerWithFractionalMean() { testSharedStateSampler(34.5); } /** * Test the SharedStateSampler implementation with the edge case when there is no * small mean sampler (i.e. no fraction part to the mean). */ @Test void testSharedStateSamplerWithIntegerMean() { testSharedStateSampler(34.0); } /** * Test the SharedStateSampler implementation. * * @param mean Mean. */ private static void testSharedStateSampler(double mean) { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final SharedStateDiscreteSampler sampler1 = LargeMeanPoissonSampler.of(rng1, mean); final SharedStateDiscreteSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } }
2,921
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/MarsagliaNormalisedGaussianSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.core.source32.IntProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test for the {@link MarsagliaNormalizedGaussianSampler}. */ class MarsagliaNormalisedGaussianSamplerTest { /** * Test the SharedStateSampler implementation. */ @Test void testSharedStateSampler() { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final SharedStateContinuousSampler sampler1 = MarsagliaNormalizedGaussianSampler.<MarsagliaNormalizedGaussianSampler>of(rng1); final SharedStateContinuousSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * Test the edge case where the pair of samples are rejected. This occurs when the distance * of the pair is outside the unit circle or lies on the origin. */ @Test void testSamplePairIsRejected() { final double value = 0.25; final UniformRandomProvider rng = new IntProvider() { private int i; @Override public int next() { // Not used return 0; } @Override public double nextDouble() { i++; if (i <= 2) { // First two samples are one. // This is outside the unit circle. return 1.0; } if (i <= 4) { // Next two samples are 0.5. // The pair lies at the origin. return 0.5; } return value; } }; final MarsagliaNormalizedGaussianSampler sampler = new MarsagliaNormalizedGaussianSampler(rng); // Compute as per the algorithm final double x = 2 * value - 1; final double r2 = x * x + x * x; final double expected = x * Math.sqrt(-2 * Math.log(r2) / r2); Assertions.assertEquals(expected, sampler.sample()); } }
2,922
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/DiscreteUniformSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import java.util.Locale; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.core.source32.IntProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.apache.commons.rng.simple.RandomSource; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test for the {@link DiscreteUniformSampler}. The tests hit edge cases for the sampler * and demonstrates uniformity of output when the underlying RNG output is uniform. */ class DiscreteUniformSamplerTest { /** * Test the constructor with a bad range. */ @Test void testConstructorThrowsWithLowerAboveUpper() { final int upper = 55; final int lower = upper + 1; final UniformRandomProvider rng = RandomAssert.seededRNG(); Assertions.assertThrows(IllegalArgumentException.class, () -> DiscreteUniformSampler.of(rng, lower, upper)); } @Test void testSamplesWithRangeOf1() { final int upper = 99; final int lower = upper; final UniformRandomProvider rng = RandomAssert.createRNG(); final SharedStateDiscreteSampler sampler = DiscreteUniformSampler.of(rng, lower, upper); for (int i = 0; i < 5; i++) { Assertions.assertEquals(lower, sampler.sample()); } } /** * Test samples with a full integer range. * The output should be the same as the int values produced from a RNG. */ @Test void testSamplesWithFullRange() { final int upper = Integer.MAX_VALUE; final int lower = Integer.MIN_VALUE; final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final SharedStateDiscreteSampler sampler = DiscreteUniformSampler.of(rng2, lower, upper); for (int i = 0; i < 10; i++) { Assertions.assertEquals(rng1.nextInt(), sampler.sample()); } } /** * Test samples with a non-power of 2 range. * The output should be the same as the long values produced from a RNG * based on o.a.c.rng.core.BaseProvider as the rejection algorithm is * the same. */ @Test void testSamplesWithSmallNonPowerOf2Range() { final int upper = 257; for (final int lower : new int[] {-13, 0, 13}) { final int n = upper - lower + 1; final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final SharedStateDiscreteSampler sampler = DiscreteUniformSampler.of(rng2, lower, upper); for (int i = 0; i < 10; i++) { Assertions.assertEquals(lower + rng1.nextInt(n), sampler.sample()); } } } /** * Test samples with a power of 2 range. * This tests the minimum and maximum output should be the range limits. */ @Test void testSamplesWithPowerOf2Range() { final UniformRandomProvider rngZeroBits = new IntProvider() { @Override public int next() { // No bits return 0; } }; final UniformRandomProvider rngAllBits = new IntProvider() { @Override public int next() { // All bits return -1; } }; final int lower = -3; DiscreteUniformSampler sampler; // The upper range for a positive integer is 2^31-1. So the max positive power of // 2 is 2^30. However the sampler should handle a bit shift of 31 to create a range // of Integer.MIN_VALUE as this is a power of 2 as an unsigned int (2^31). for (int i = 0; i < 32; i++) { final int range = 1 << i; final int upper = lower + range - 1; sampler = new DiscreteUniformSampler(rngZeroBits, lower, upper); Assertions.assertEquals(lower, sampler.sample(), "Zero bits sample"); sampler = new DiscreteUniformSampler(rngAllBits, lower, upper); Assertions.assertEquals(upper, sampler.sample(), "All bits sample"); } } /** * Test samples with a power of 2 range. * This tests the output is created using a bit shift. */ @Test void testSamplesWithPowerOf2RangeIsBitShift() { final int lower = 0; SharedStateDiscreteSampler sampler; // Power of 2 sampler used for a bit shift of 1 to 31. for (int i = 1; i <= 31; i++) { // Upper is inclusive so subtract 1 final int upper = (1 << i) - 1; final int shift = 32 - i; final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); sampler = DiscreteUniformSampler.of(rng2, lower, upper); for (int j = 0; j < 10; j++) { Assertions.assertEquals(rng1.nextInt() >>> shift, sampler.sample()); } } } /** * Test samples with a large non-power of 2 range. * This tests the large range algorithm uses a rejection method. */ @Test void testSamplesWithLargeNonPowerOf2RangeIsRejectionMethod() { // Create a range bigger than 2^63 final int upper = Integer.MAX_VALUE / 2 + 1; final int lower = Integer.MIN_VALUE / 2 - 1; final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final SharedStateDiscreteSampler sampler = DiscreteUniformSampler.of(rng2, lower, upper); for (int i = 0; i < 10; i++) { // Get the expected value by the rejection method long expected; do { expected = rng1.nextInt(); } while (expected < lower || expected > upper); Assertions.assertEquals(expected, sampler.sample()); } } @Test void testOffsetSamplesWithNonPowerOf2Range() { assertOffsetSamples(257); } @Test void testOffsetSamplesWithPowerOf2Range() { assertOffsetSamples(256); } @Test void testOffsetSamplesWithRangeOf1() { assertOffsetSamples(1); } private static void assertOffsetSamples(int range) { final Long seed = RandomSource.createLong(); final UniformRandomProvider rng1 = RandomSource.SPLIT_MIX_64.create(seed); final UniformRandomProvider rng2 = RandomSource.SPLIT_MIX_64.create(seed); final UniformRandomProvider rng3 = RandomSource.SPLIT_MIX_64.create(seed); // Since the upper limit is inclusive range = range - 1; final int offsetLo = -13; final int offsetHi = 42; final SharedStateDiscreteSampler sampler = DiscreteUniformSampler.of(rng1, 0, range); final SharedStateDiscreteSampler samplerLo = DiscreteUniformSampler.of(rng2, offsetLo, offsetLo + range); final SharedStateDiscreteSampler samplerHi = DiscreteUniformSampler.of(rng3, offsetHi, offsetHi + range); for (int i = 0; i < 10; i++) { final int sample1 = sampler.sample(); final int sample2 = samplerLo.sample(); final int sample3 = samplerHi.sample(); Assertions.assertEquals(sample1 + offsetLo, sample2, "Incorrect negative offset sample"); Assertions.assertEquals(sample1 + offsetHi, sample3, "Incorrect positive offset sample"); } } /** * Test the sample uniformity when using a small range that is not a power of 2. */ @Test void testSampleUniformityWithNonPowerOf2Range() { // Test using a RNG that outputs an evenly spaced set of integers. // Create a Weyl sequence using George Marsaglia’s increment from: // Marsaglia, G (July 2003). "Xorshift RNGs". Journal of Statistical Software. 8 (14). // https://en.wikipedia.org/wiki/Weyl_sequence final UniformRandomProvider rng = new IntProvider() { private final int increment = 362437; // Start at the highest positive number private final int start = Integer.MIN_VALUE - increment; private int bits = start; @Override public int next() { // Output until the first wrap. The entire sequence will be uniform. // Note this is not the full period of the sequence. // Expect ((1L << 32) / increment) numbers = 11850 int result = bits += increment; if (result < start) { return result; } throw new IllegalStateException("end of sequence"); } }; // n = upper range exclusive final int n = 37; // prime final int[] histogram = new int[n]; final int lower = 0; final int upper = n - 1; final SharedStateDiscreteSampler sampler = DiscreteUniformSampler.of(rng, lower, upper); try { while (true) { histogram[sampler.sample()]++; } } catch (IllegalStateException ex) { // Expected end of sequence } // The sequence will result in either x or (x+1) samples in each bin (i.e. uniform). int min = histogram[0]; int max = histogram[0]; for (int value : histogram) { min = Math.min(min, value); max = Math.max(max, value); } Assertions.assertTrue(max - min <= 1, "Not uniform, max = " + max + ", min=" + min); } /** * Test the sample uniformity when using a small range that is a power of 2. */ @Test void testSampleUniformityWithPowerOf2Range() { // Test using a RNG that outputs a counter of integers. // The n most significant bits will be represented uniformly over a // sequence that is a 2^n long. final UniformRandomProvider rng = new IntProvider() { private int bits = 0; @Override public int next() { // We reverse the bits because the most significant bits are used return Integer.reverse(bits++); } }; // n = upper range exclusive final int n = 32; // power of 2 final int[] histogram = new int[n]; final int lower = 0; final int upper = n - 1; final SharedStateDiscreteSampler sampler = DiscreteUniformSampler.of(rng, lower, upper); final int expected = 2; for (int i = expected * n; i-- > 0;) { histogram[sampler.sample()]++; } // This should be even across the entire range for (int value : histogram) { Assertions.assertEquals(expected, value); } } /** * Test the sample rejection when using a range that is not a power of 2. The rejection * algorithm of Lemire (2019) splits the entire 32-bit range into intervals of size 2^32/n. It * will reject the lowest value in each interval that is over sampled. This test uses 0 * as the first value from the RNG and tests it is rejected. */ @Test void testSampleRejectionWithNonPowerOf2Range() { // Test using a RNG that returns a sequence. // The first value of zero should produce a sample that is rejected. final int[] value = new int[1]; final UniformRandomProvider rng = new IntProvider() { @Override public int next() { return value[0]++; } }; // n = upper range exclusive. // Use a prime number to select the rejection algorithm. final int n = 37; final int lower = 0; final int upper = n - 1; final SharedStateDiscreteSampler sampler = DiscreteUniformSampler.of(rng, lower, upper); final int sample = sampler.sample(); Assertions.assertEquals(0, sample, "Sample is incorrect"); Assertions.assertEquals(2, value[0], "Sample should be produced from 2nd value"); } @Test void testSharedStateSamplerWithSmallRange() { testSharedStateSampler(5, 67); } @Test void testSharedStateSamplerWithLargeRange() { // Set the range so rejection below or above the threshold occurs with approximately p=0.25 testSharedStateSampler(Integer.MIN_VALUE / 2 - 1, Integer.MAX_VALUE / 2 + 1); } @Test void testSharedStateSamplerWithPowerOf2Range() { testSharedStateSampler(0, 31); } @Test void testSharedStateSamplerWithRangeOf1() { testSharedStateSampler(9, 9); } /** * Test the SharedStateSampler implementation. * * @param lower Lower. * @param upper Upper. */ private static void testSharedStateSampler(int lower, int upper) { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); // Use instance constructor not factory constructor to exercise 1.X public API final SharedStateDiscreteSampler sampler1 = new DiscreteUniformSampler(rng1, lower, upper); final SharedStateDiscreteSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } @Test void testToStringWithSmallRange() { assertToString(5, 67); } @Test void testToStringWithLargeRange() { assertToString(-99999999, Integer.MAX_VALUE); } @Test void testToStringWithPowerOf2Range() { // Note the range is upper - lower + 1 assertToString(0, 31); } @Test void testToStringWithRangeOf1() { assertToString(9, 9); } /** * Test the toString method contains the term "uniform". This is true of all samplers * even for a fixed sample from a range of 1. * * @param lower Lower. * @param upper Upper. */ private static void assertToString(int lower, int upper) { final UniformRandomProvider rng = RandomAssert.seededRNG(); final DiscreteUniformSampler sampler = new DiscreteUniformSampler(rng, lower, upper); Assertions.assertTrue(sampler.toString().toLowerCase(Locale.US).contains("uniform")); } }
2,923
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/GuideTableDiscreteSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.math3.distribution.BinomialDistribution; import org.apache.commons.math3.distribution.PoissonDistribution; import org.apache.commons.math3.stat.inference.ChiSquareTest; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; /** * Test for the {@link GuideTableDiscreteSampler}. */ class GuideTableDiscreteSamplerTest { @Test void testConstructorThrowsWithNullProbabilites() { assertConstructorThrows(null, 1.0); } @Test void testConstructorThrowsWithZeroLengthProbabilites() { assertConstructorThrows(new double[0], 1.0); } @Test void testConstructorThrowsWithNegativeProbabilites() { assertConstructorThrows(new double[] {-1, 0.1, 0.2}, 1.0); } @Test void testConstructorThrowsWithNaNProbabilites() { assertConstructorThrows(new double[] {0.1, Double.NaN, 0.2}, 1.0); } @Test void testConstructorThrowsWithInfiniteProbabilites() { assertConstructorThrows(new double[] {0.1, Double.POSITIVE_INFINITY, 0.2}, 1.0); } @Test void testConstructorThrowsWithInfiniteSumProbabilites() { assertConstructorThrows(new double[] {Double.MAX_VALUE, Double.MAX_VALUE}, 1.0); } @Test void testConstructorThrowsWithZeroSumProbabilites() { assertConstructorThrows(new double[4], 1.0); } @Test void testConstructorThrowsWithZeroAlpha() { assertConstructorThrows(new double[] {0.5, 0.5}, 0.0); } @Test void testConstructorThrowsWithNegativeAlpha() { assertConstructorThrows(new double[] {0.5, 0.5}, -1.0); } /** * Assert the factory constructor throws an {@link IllegalArgumentException}. * * @param probabilities the probabilities * @param alpha the alpha */ private static void assertConstructorThrows(double[] probabilities, double alpha) { final UniformRandomProvider rng = RandomAssert.seededRNG(); Assertions.assertThrows(IllegalArgumentException.class, () -> GuideTableDiscreteSampler.of(rng, probabilities, alpha)); } @Test void testToString() { final UniformRandomProvider rng = RandomAssert.createRNG(); final SharedStateDiscreteSampler sampler = GuideTableDiscreteSampler.of(rng, new double[] {0.5, 0.5}, 1.0); Assertions.assertTrue(sampler.toString().toLowerCase().contains("guide table")); } /** * Test sampling from a binomial distribution. */ @Test void testBinomialSamples() { final int trials = 67; final double probabilityOfSuccess = 0.345; final BinomialDistribution dist = new BinomialDistribution(null, trials, probabilityOfSuccess); final double[] expected = new double[trials + 1]; for (int i = 0; i < expected.length; i++) { expected[i] = dist.probability(i); } checkSamples(expected, 1.0); } /** * Test sampling from a Poisson distribution. */ @Test void testPoissonSamples() { final double mean = 3.14; final PoissonDistribution dist = new PoissonDistribution(null, mean, PoissonDistribution.DEFAULT_EPSILON, PoissonDistribution.DEFAULT_MAX_ITERATIONS); final int maxN = dist.inverseCumulativeProbability(1 - 1e-6); final double[] expected = new double[maxN]; for (int i = 0; i < expected.length; i++) { expected[i] = dist.probability(i); } checkSamples(expected, 1.0); } /** * Test sampling from a non-uniform distribution of probabilities (these sum to 1). * The alpha used in the default (1.0) or a smaller or larger value than the default. */ @ParameterizedTest @ValueSource(doubles = {1.0, 0.1, 10.0}) void testNonUniformSamplesWithProbabilities(double alpha) { final double[] expected = {0.1, 0.2, 0.3, 0.1, 0.3}; checkSamples(expected, alpha); } /** * Test sampling from a non-uniform distribution of observations (i.e. the sum is not 1 as per * probabilities). */ @Test void testNonUniformSamplesWithObservations() { final double[] expected = {1, 2, 3, 1, 3}; checkSamples(expected, 1.0); } /** * Test sampling from a non-uniform distribution of probabilities (these sum to 1). * Extra zero-values are added. */ @Test void testNonUniformSamplesWithZeroProbabilities() { final double[] expected = {0.1, 0, 0.2, 0.3, 0.1, 0.3, 0}; checkSamples(expected, 1.0); } /** * Test sampling from a non-uniform distribution of observations (i.e. the sum is not 1 as per * probabilities). Extra zero-values are added. */ @Test void testNonUniformSamplesWithZeroObservations() { final double[] expected = {1, 2, 3, 0, 1, 3, 0}; checkSamples(expected, 1.0); } /** * Test sampling from a uniform distribution. This is an edge case where there * are no probabilities less than the mean. */ @Test void testUniformSamplesWithNoObservationLessThanTheMean() { final double[] expected = {2, 2, 2, 2, 2, 2}; checkSamples(expected, 1.0); } /** * Check the distribution of samples match the expected probabilities. * * <p>If the expected probability is zero then this should never be sampled. The non-zero * probabilities are compared to the sample distribution using a Chi-square test.</p> * * @param probabilies the probabilities * @param alpha the alpha */ private static void checkSamples(double[] probabilies, double alpha) { final UniformRandomProvider rng = RandomAssert.createRNG(); final SharedStateDiscreteSampler sampler = GuideTableDiscreteSampler.of(rng, probabilies, alpha); final int numberOfSamples = 10000; final long[] samples = new long[probabilies.length]; for (int i = 0; i < numberOfSamples; i++) { samples[sampler.sample()]++; } // Handle a test with some zero-probability observations by mapping them out. // The results is the Chi-square test is performed using only the non-zero probabilities. int mapSize = 0; for (int i = 0; i < probabilies.length; i++) { if (probabilies[i] != 0) { mapSize++; } } final double[] expected = new double[mapSize]; final long[] observed = new long[mapSize]; for (int i = 0; i < probabilies.length; i++) { if (probabilies[i] == 0) { Assertions.assertEquals(0, samples[i], "No samples expected from zero probability"); } else { // This can be added for the Chi-square test --mapSize; expected[mapSize] = probabilies[i]; observed[mapSize] = samples[i]; } } final ChiSquareTest chiSquareTest = new ChiSquareTest(); // Pass if we cannot reject null hypothesis that the distributions are the same. Assertions.assertFalse(chiSquareTest.chiSquareTest(expected, observed, 0.001)); } /** * Test the SharedStateSampler implementation. */ @Test void testSharedStateSampler() { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final double[] probabilities = {0.1, 0, 0.2, 0.3, 0.1, 0.3, 0}; final SharedStateDiscreteSampler sampler1 = GuideTableDiscreteSampler.of(rng1, probabilities); final SharedStateDiscreteSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } }
2,924
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/BoxMullerGaussianSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test for the {@link BoxMullerGaussianSampler}. The tests hit edge cases for the sampler. */ class BoxMullerGaussianSamplerTest { /** * Test the constructor with a bad standard deviation. */ @SuppressWarnings({"deprecation"}) @Test void testConstructorThrowsWithZeroStandardDeviation() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final double mean = 1; final double standardDeviation = 0; Assertions.assertThrows(IllegalArgumentException.class, () -> new BoxMullerGaussianSampler(rng, mean, standardDeviation)); } }
2,925
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/PoissonSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * This test checks the {@link PoissonSampler} can be created * from a saved state. */ class PoissonSamplerTest { /** * Test the SharedStateSampler implementation with a mean below 40. */ @Test void testSharedStateSamplerWithSmallMean() { testSharedStateSampler(34.5); } /** * Test the SharedStateSampler implementation with a mean above 40. */ @Test void testSharedStateSamplerWithLargeMean() { testSharedStateSampler(67.8); } /** * Test the SharedStateSampler implementation. * * @param mean Mean. */ private static void testSharedStateSampler(double mean) { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); // Use instance constructor not factory constructor to exercise 1.X public API final SharedStateDiscreteSampler sampler1 = new PoissonSampler(rng1, mean); final SharedStateDiscreteSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * Test the toString method. This is added to ensure coverage as the factory constructor * used in other tests does not create an instance of the wrapper class. */ @Test void testToString() { final UniformRandomProvider rng = RandomAssert.seededRNG(); Assertions.assertTrue(new PoissonSampler(rng, 1.23).toString().toLowerCase().contains("poisson")); } }
2,926
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/ZigguratNormalizedGaussianSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test for {@link ZigguratNormalizedGaussianSampler}. */ class ZigguratNormalizedGaussianSamplerTest { // Cf. RNG-56 @Test void testInfiniteLoop() { // A bad implementation whose only purpose is to force access // to the rarest branch. // nextLong() returns Long.MAX_VALUE final UniformRandomProvider bad = () -> Long.MAX_VALUE; // Infinite loop (in v1.1). final ZigguratNormalizedGaussianSampler sampler = new ZigguratNormalizedGaussianSampler(bad); Assertions.assertThrows(StackOverflowError.class, () -> sampler.sample()); } /** * Test the SharedStateSampler implementation. */ @Test void testSharedStateSampler() { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final SharedStateContinuousSampler sampler1 = ZigguratNormalizedGaussianSampler.<ZigguratNormalizedGaussianSampler>of(rng1); final SharedStateContinuousSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } }
2,927
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/ContinuousSamplerParametricTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; /** * Tests for random deviates generators. */ class ContinuousSamplerParametricTest { private static Iterable<ContinuousSamplerTestData> getSamplerTestData() { return ContinuousSamplersList.list(); } @ParameterizedTest @MethodSource("getSamplerTestData") void testSampling(ContinuousSamplerTestData data) { check(20000, data.getSampler(), data.getDeciles()); } /** * Performs a chi-square test of homogeneity of the observed * distribution with the expected distribution. * Tests are performed at the 1% level and an average failure rate * higher than 5% causes the test case to fail. * * @param sampler Sampler. * @param sampleSize Number of random values to generate. * @param deciles Deciles. */ private static void check(long sampleSize, ContinuousSampler sampler, double[] deciles) { final int numTests = 50; // Do not change (statistical test assumes that dof = 9). final int numBins = 10; // dof = numBins - 1 // Run the tests. int numFailures = 0; final double expected = sampleSize / (double) numBins; final long[] observed = new long[numBins]; // Chi-square critical value with 9 degrees of freedom // and 1% significance level. final double chi2CriticalValue = 21.665994333461924; // For storing chi2 larger than the critical value. final List<Double> failedStat = new ArrayList<>(); try { final int lastDecileIndex = numBins - 1; for (int i = 0; i < numTests; i++) { Arrays.fill(observed, 0); SAMPLE: for (long j = 0; j < sampleSize; j++) { final double value = sampler.sample(); for (int k = 0; k < lastDecileIndex; k++) { if (value < deciles[k]) { ++observed[k]; continue SAMPLE; } } ++observed[lastDecileIndex]; } // Compute chi-square. double chi2 = 0; for (int k = 0; k < numBins; k++) { final double diff = observed[k] - expected; chi2 += diff * diff / expected; } // Statistics check. if (chi2 > chi2CriticalValue) { failedStat.add(chi2); ++numFailures; } } } catch (Exception e) { // Should never happen. throw new RuntimeException("Unexpected", e); } // The expected number of failed tests can be modelled as a Binomial distribution // B(n, p) with n=50, p=0.01 (50 tests with a 1% significance level). // The cumulative probability of the number of failed tests (X) is: // x P(X>x) // 1 0.0894 // 2 0.0138 // 3 0.0016 if (numFailures > 3) { // Test will fail with 0.16% probability Assertions.fail(String.format( "%s: Too many failures for sample size = %d " + "(%d out of %d tests failed, chi2 > %.3f=%s)", sampler, sampleSize, numFailures, numTests, chi2CriticalValue, failedStat.stream().map(d -> String.format("%.3f", d)) .collect(Collectors.joining(", ", "[", "]")))); } } }
2,928
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/BoxMullerNormalisedGaussianSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Test; /** * Test for the {@link BoxMullerNormalizedGaussianSampler}. */ class BoxMullerNormalisedGaussianSamplerTest { /** * Test the SharedStateSampler implementation. */ @Test void testSharedStateSampler() { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final SharedStateContinuousSampler sampler1 = BoxMullerNormalizedGaussianSampler.<BoxMullerNormalizedGaussianSampler>of(rng1); final SharedStateContinuousSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } }
2,929
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/LongSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import java.util.concurrent.ThreadLocalRandom; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; /** * Tests the default methods in the {@link LongSampler} interface. */ class LongSamplerTest { @Test void testSamplesUnlimitedSize() { final LongSampler s = RandomAssert.createRNG()::nextLong; Assertions.assertEquals(Long.MAX_VALUE, s.samples().spliterator().estimateSize()); } @RepeatedTest(value = 3) void testSamples() { final UniformRandomProvider[] rngs = RandomAssert.createRNG(2); final LongSampler s1 = rngs[0]::nextLong; final LongSampler s2 = rngs[1]::nextLong; final int count = ThreadLocalRandom.current().nextInt(3, 13); Assertions.assertArrayEquals(createSamples(s1, count), s2.samples().limit(count).toArray()); } @ParameterizedTest @ValueSource(ints = {0, 1, 2, 5, 13}) void testSamples(int streamSize) { final UniformRandomProvider[] rngs = RandomAssert.createRNG(2); final LongSampler s1 = rngs[0]::nextLong; final LongSampler s2 = rngs[1]::nextLong; Assertions.assertArrayEquals(createSamples(s1, streamSize), s2.samples(streamSize).toArray()); } /** * Creates an array of samples. * * @param sampler Source of samples. * @param count Number of samples. * @return the samples */ private static long[] createSamples(LongSampler sampler, int count) { final long[] data = new long[count]; for (int i = 0; i < count; i++) { data[i] = sampler.sample(); } return data; } }
2,930
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/SmallMeanPoissonSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; /** * Test for the {@link SmallMeanPoissonSampler}. The tests hit edge cases for the sampler. */ class SmallMeanPoissonSamplerTest { /** * Test the constructor with a bad mean. */ @Test void testConstructorThrowsWithMeanThatSetsProbabilityP0ToZero() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final double p0 = Double.MIN_VALUE; // Note: p0 = Math.exp(-mean) => mean = -Math.log(p0). // Add to the limit on the mean to cause p0 to be zero. final double mean = -Math.log(p0) + 1; Assertions.assertThrows(IllegalArgumentException.class, () -> SmallMeanPoissonSampler.of(rng, mean)); } /** * Test the constructor with a bad mean. */ @Test void testConstructorThrowsWithZeroMean() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final double mean = 0; Assertions.assertThrows(IllegalArgumentException.class, () -> SmallMeanPoissonSampler.of(rng, mean)); } /** * Test the sample is bounded to 1000 * mean. */ @ParameterizedTest @ValueSource(doubles = {0.5, 1, 1.5, 2.2}) void testSampleUpperBounds(double mean) { // If the nextDouble() is always ~1 then the sample will hit the upper bounds. // nextLong() returns -1; nextDouble returns Math.nextDown(1.0). final UniformRandomProvider rng = () -> -1; final SharedStateDiscreteSampler sampler = SmallMeanPoissonSampler.of(rng, mean); final int expected = (int) Math.ceil(1000 * mean); Assertions.assertEquals(expected, sampler.sample()); } /** * Test the SharedStateSampler implementation. */ @Test void testSharedStateSampler() { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final double mean = 1.23; final SharedStateDiscreteSampler sampler1 = SmallMeanPoissonSampler.of(rng1, mean); final SharedStateDiscreteSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } }
2,931
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/InverseTransformDiscreteSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Test; /** * Test for the {@link InverseTransformDiscreteSampler}. */ class InverseTransformDiscreteSamplerTest { /** * Test the SharedStateSampler implementation. */ @Test void testSharedStateSampler() { DiscreteInverseCumulativeProbabilityFunction function = new DiscreteInverseCumulativeProbabilityFunction() { @Override public int inverseCumulativeProbability(double p) { return (int) Math.round(789 * p); } }; final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final SharedStateDiscreteSampler sampler1 = InverseTransformDiscreteSampler.of(rng1, function); final SharedStateDiscreteSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } }
2,932
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/KempSmallMeanPoissonSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.math3.distribution.PoissonDistribution; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test for the {@link KempSmallMeanPoissonSampler}. The tests hit edge cases for the * sampler and tests it functions at the supported upper bound on the mean. */ class KempSmallMeanPoissonSamplerTest { /** * The upper limit on the mean. * * <p>p0 = Math.exp(-mean) => mean = -Math.log(p0). When p0 is {@link Double#MIN_VALUE} the * mean is approximately 744.4.</p> */ private static final double SUPPORTED_UPPER_BOUND = -Math.log(Double.MIN_VALUE); /** The rng for construction tests. */ private final UniformRandomProvider dummyRng = new FixedRNG(0); /** * Test the constructor with a bad mean. */ @Test void testConstructorThrowsWithMeanLargerThanUpperBound() { final double mean = SUPPORTED_UPPER_BOUND + 1; Assertions.assertThrows(IllegalArgumentException.class, () -> KempSmallMeanPoissonSampler.of(dummyRng, mean)); } /** * Test the constructor with zero mean. */ @Test void testConstructorThrowsWithZeroMean() { final double mean = 0; Assertions.assertThrows(IllegalArgumentException.class, () -> KempSmallMeanPoissonSampler.of(dummyRng, mean)); } /** * Test the constructor with a negative mean. */ @Test void testConstructorThrowsWithNegativeMean() { final double mean = -1; Assertions.assertThrows(IllegalArgumentException.class, () -> KempSmallMeanPoissonSampler.of(dummyRng, mean)); } /** * Test the constructor with a NaN mean. */ @Test void testConstructorWithNaNMean() { final double mean = Double.NaN; Assertions.assertThrows(IllegalArgumentException.class, () -> KempSmallMeanPoissonSampler.of(dummyRng, mean)); } /** * Test the cumulative summation at the upper bound on the mean is close to zero when * starting from 1. */ @Test void testSummationFrom1AtUpperBound() { final double mean = SUPPORTED_UPPER_BOUND; double u = 1; int x = 0; double p = Math.exp(-mean); while (u > p && p != 0) { u -= p; x = x + 1; p = p * mean / x; } Assertions.assertEquals(0, u, 1e-3, "Summation is not zero"); Assertions.assertTrue(u > 0, "Summation is not greater than zero"); } /** * Test the cumulative summation at the upper bound on the mean is close to one when * starting from 0. */ @Test void testSummationTo1AtUpperBound() { final double mean = SUPPORTED_UPPER_BOUND; double u = 0; int x = 0; double p = Math.exp(-mean); while (p != 0) { u += p; x = x + 1; p = p * mean / x; } Assertions.assertEquals(1, u, 1e-3, "Summation is not one"); Assertions.assertTrue(u < 1, "Summation is not less than one"); } /** * Test the sampler functions at the upper bound on the mean. */ @Test void testSamplerAtUpperBounds() { final double mean = SUPPORTED_UPPER_BOUND; // Test some ranges for the cumulative probability final PoissonDistribution pd = new PoissonDistribution(null, mean, PoissonDistribution.DEFAULT_EPSILON, PoissonDistribution.DEFAULT_MAX_ITERATIONS); final FixedRNG rng = new FixedRNG(0); final SharedStateDiscreteSampler sampler = KempSmallMeanPoissonSampler.of(rng, mean); // Lower bound should be zero testSample(rng, sampler, 0, 0, 0); // Upper bound should exceed 99.99% of the range testSample(rng, sampler, 1, pd.inverseCumulativeProbability(0.9999), Integer.MAX_VALUE); // A sample from within the cumulative probability should be within the expected range for (int i = 1; i < 10; i++) { final double p = i * 0.1; final int lower = pd.inverseCumulativeProbability(p - 0.01); final int upper = pd.inverseCumulativeProbability(p + 0.01); testSample(rng, sampler, p, lower, upper); } } /** * Test the SharedStateSampler implementation. */ @Test void testSharedStateSampler() { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final double mean = 1.23; final SharedStateDiscreteSampler sampler1 = KempSmallMeanPoissonSampler.of(rng1, mean); final SharedStateDiscreteSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * Test a sample from the Poisson distribution at the given cumulative probability. * * @param rng the fixed random generator backing the sampler * @param sampler the sampler * @param cumulativeProbability the cumulative probability * @param lower the expected lower limit * @param upper the expected upper limit */ private static void testSample(FixedRNG rng, SharedStateDiscreteSampler sampler, double cumulativeProbability, int lower, int upper) { rng.setValue(cumulativeProbability); final int sample = sampler.sample(); Assertions.assertTrue(sample >= lower, () -> sample + " sample is not above realistic lower limit: " + lower); Assertions.assertTrue(sample <= upper, () -> sample + " sample is not below realistic upper limit: " + upper); } /** * A RNG returning a fixed value. */ private static class FixedRNG implements UniformRandomProvider { /** The value. */ private double value; /** * @param value the value */ FixedRNG(double value) { this.value = value; } @Override public double nextDouble() { return value; } /** * @param value the new value */ void setValue(double value) { this.value = value; } // CHECKSTYLE: stop all public long nextLong(long n) { return 0; } public long nextLong() { return 0; } public int nextInt(int n) { return 0; } public int nextInt() { return 0; } public float nextFloat() { return 0; } public void nextBytes(byte[] bytes, int start, int len) {} public void nextBytes(byte[] bytes) {} public boolean nextBoolean() { return false; } // CHECKSTYLE: resume all } }
2,933
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/LogNormalSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.apache.commons.rng.sampling.SharedStateSampler; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test for the {@link LogNormalSampler}. The tests hit edge cases for the sampler. */ class LogNormalSamplerTest { /** * Test the constructor with a bad standard deviation. */ @Test void testConstructorThrowsWithZeroShape() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final NormalizedGaussianSampler gauss = ZigguratSampler.NormalizedGaussian.of(rng); final double mu = 1; final double sigma = 0; Assertions.assertThrows(IllegalArgumentException.class, () -> LogNormalSampler.of(gauss, mu, sigma)); } /** * Test the SharedStateSampler implementation. */ @Test void testSharedStateSampler() { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final NormalizedGaussianSampler gauss = ZigguratSampler.NormalizedGaussian.of(rng1); // Test a negative mean is allowed (see RNG-166) final double mu = -1.23; final double sigma = 4.56; final SharedStateContinuousSampler sampler1 = LogNormalSampler.of(gauss, mu, sigma); final SharedStateContinuousSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * Test the SharedStateSampler implementation throws if the underlying sampler is * not a SharedStateSampler. */ @Test void testSharedStateSamplerThrowsIfUnderlyingSamplerDoesNotShareState() { final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final NormalizedGaussianSampler gauss = new NormalizedGaussianSampler() { @Override public double sample() { return 0; } }; final double mu = 1.23; final double sigma = 4.56; final SharedStateContinuousSampler sampler1 = LogNormalSampler.of(gauss, mu, sigma); Assertions.assertThrows(UnsupportedOperationException.class, () -> sampler1.withUniformRandomProvider(rng2)); } /** * Test the SharedStateSampler implementation throws if the underlying sampler is * a SharedStateSampler that returns an incorrect type. */ @Test void testSharedStateSamplerThrowsIfUnderlyingSamplerReturnsWrongSharedState() { final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final NormalizedGaussianSampler gauss = new BadSharedStateNormalizedGaussianSampler(); final double mu = 1.23; final double sigma = 4.56; final SharedStateContinuousSampler sampler1 = LogNormalSampler.of(gauss, mu, sigma); Assertions.assertThrows(UnsupportedOperationException.class, () -> sampler1.withUniformRandomProvider(rng2)); } /** * Test class to return an incorrect sampler from the SharedStateSampler method. * * <p>Note that due to type erasure the type returned by the SharedStateSampler is not * available at run-time and the LogNormalSampler has to assume it is the correct type.</p> */ private static class BadSharedStateNormalizedGaussianSampler implements NormalizedGaussianSampler, SharedStateSampler<Integer> { @Override public double sample() { return 0; } @Override public Integer withUniformRandomProvider(UniformRandomProvider rng) { // Something that is not a NormalizedGaussianSampler return Integer.valueOf(44); } } }
2,934
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/GeometricSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test for the {@link GeometricSampler}. The tests hit edge cases for the sampler. */ 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 void testProbabilityOfSuccessIsOneGeneratesZeroForSamples() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final SharedStateDiscreteSampler sampler = GeometricSampler.of(rng, 1); // All samples should be 0 for (int i = 0; i < 10; i++) { Assertions.assertEquals(0, sampler.sample(), "p=1 should have 0 for all samples"); } } /** * Test to demonstrate that any probability of success under one produces a valid * mean for the exponential distribution. */ @Test void testProbabilityOfSuccessUnderOneIsValid() { // The sampler explicitly handles probabilityOfSuccess == 1 as an edge case. // Anything under it should be valid for sampling from an ExponentialDistribution. final double probabilityOfSuccess = Math.nextDown(1); // Map to the mean final double exponentialMean = 1.0 / (-Math.log1p(-probabilityOfSuccess)); // As long as this is finite positive then the sampler is valid Assertions.assertTrue(exponentialMean > 0 && exponentialMean <= Double.MAX_VALUE); // The internal exponential sampler validates the mean so demonstrate creating a // geometric sampler does not throw. final UniformRandomProvider rng = RandomAssert.seededRNG(); GeometricSampler.of(rng, probabilityOfSuccess); } /** * 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 void testProbabilityOfSuccessIsOneSamplerToString() { final UniformRandomProvider unusedRng = RandomAssert.seededRNG(); final SharedStateDiscreteSampler sampler = GeometricSampler.of(unusedRng, 1); Assertions.assertTrue(sampler.toString().contains("Geometric"), "Missing 'Geometric' from toString"); } /** * 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 void testProbabilityOfSuccessIsAlmostZeroGeneratesMaxValueForSamples() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final SharedStateDiscreteSampler sampler = GeometricSampler.of(rng, Double.MIN_VALUE); // All samples should be max value for (int i = 0; i < 10; i++) { Assertions.assertEquals(Integer.MAX_VALUE, sampler.sample(), "p=(almost 0) should have Integer.MAX_VALUE for all samples"); } } /** * Test probability of success {@code >1} is not allowed. */ @Test void testProbabilityOfSuccessAboveOneThrows() { final UniformRandomProvider unusedRng = RandomAssert.seededRNG(); final double probabilityOfSuccess = Math.nextUp(1.0); Assertions.assertThrows(IllegalArgumentException.class, () -> GeometricSampler.of(unusedRng, probabilityOfSuccess)); } /** * Test probability of success {@code 0} is not allowed. */ @Test void testProbabilityOfSuccessIsZeroThrows() { final UniformRandomProvider unusedRng = RandomAssert.seededRNG(); final double probabilityOfSuccess = 0; Assertions.assertThrows(IllegalArgumentException.class, () -> GeometricSampler.of(unusedRng, probabilityOfSuccess)); } /** * Test the SharedStateSampler implementation. */ @Test void testSharedStateSampler() { testSharedStateSampler(0.5); } /** * Test the SharedStateSampler implementation with the edge case when the probability of * success is {@code 1.0}. */ @Test void testSharedStateSamplerWithProbabilityOfSuccessOne() { testSharedStateSampler(1.0); } /** * Test the SharedStateSampler implementation. * * @param probabilityOfSuccess Probability of success. */ private static void testSharedStateSampler(double probabilityOfSuccess) { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final SharedStateDiscreteSampler sampler1 = GeometricSampler.of(rng1, probabilityOfSuccess); final SharedStateDiscreteSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } }
2,935
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/InverseTransformContinuousSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Test; /** * Test for the {@link InverseTransformContinuousSampler}. */ class InverseTransformContinuousSamplerTest { /** * Test the SharedStateSampler implementation. */ @Test void testSharedStateSampler() { ContinuousInverseCumulativeProbabilityFunction function = new ContinuousInverseCumulativeProbabilityFunction() { @Override public double inverseCumulativeProbability(double p) { return 456.99 * p; } }; final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final SharedStateContinuousSampler sampler1 = InverseTransformContinuousSampler.of(rng1, function); final SharedStateContinuousSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } }
2,936
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/ContinuousSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import java.util.concurrent.ThreadLocalRandom; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; /** * Tests the default methods in the {@link ContinuousSampler} interface. */ class ContinuousSamplerTest { @Test void testSamplesUnlimitedSize() { final ContinuousSampler s = RandomAssert.createRNG()::nextDouble; Assertions.assertEquals(Long.MAX_VALUE, s.samples().spliterator().estimateSize()); } @RepeatedTest(value = 3) void testSamples() { final UniformRandomProvider[] rngs = RandomAssert.createRNG(2); final ContinuousSampler s1 = rngs[0]::nextDouble; final ContinuousSampler s2 = rngs[1]::nextDouble; final int count = ThreadLocalRandom.current().nextInt(3, 13); Assertions.assertArrayEquals(createSamples(s1, count), s2.samples().limit(count).toArray()); } @ParameterizedTest @ValueSource(ints = {0, 1, 2, 5, 13}) void testSamples(int streamSize) { final UniformRandomProvider[] rngs = RandomAssert.createRNG(2); final ContinuousSampler s1 = rngs[0]::nextDouble; final ContinuousSampler s2 = rngs[1]::nextDouble; Assertions.assertArrayEquals(createSamples(s1, streamSize), s2.samples(streamSize).toArray()); } /** * Creates an array of samples. * * @param sampler Source of samples. * @param count Number of samples. * @return the samples */ private static double[] createSamples(ContinuousSampler sampler, int count) { final double[] data = new double[count]; for (int i = 0; i < count; i++) { data[i] = sampler.sample(); } return data; } }
2,937
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/RejectionInversionZipfSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test for the {@link RejectionInversionZipfSampler}. The tests hit edge cases for the sampler. */ class RejectionInversionZipfSamplerTest { /** * Test the constructor with a bad number of elements. */ @Test void testConstructorThrowsWithZeroNumberOfElements() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final int numberOfElements = 0; final double exponent = 1; Assertions.assertThrows(IllegalArgumentException.class, () -> RejectionInversionZipfSampler.of(rng, numberOfElements, exponent)); } /** * Test the constructor with a bad exponent. */ @Test void testConstructorThrowsWithNegativeExponent() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final int numberOfElements = 1; final double exponent = Math.nextDown(0); Assertions.assertThrows(IllegalArgumentException.class, () -> RejectionInversionZipfSampler.of(rng, numberOfElements, exponent)); } /** * Test the SharedStateSampler implementation. */ @Test void testSharedStateSampler() { testSharedStateSampler(7, 1.23); } /** * Special case: Test the SharedStateSampler implementation with a zero exponent. */ @Test void testSharedStateSamplerWithZeroExponent() { testSharedStateSampler(7, 0); } /** * Test the SharedStateSampler implementation for the specified parameters. * * @param numberOfElements Number of elements * @param exponent Exponent */ private static void testSharedStateSampler(int numberOfElements, double exponent) { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); // Use instance constructor not factory constructor to exercise 1.X public API final RejectionInversionZipfSampler sampler1 = new RejectionInversionZipfSampler(rng1, numberOfElements, exponent); final SharedStateDiscreteSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * Test the toString method. This is added to ensure coverage as the factory constructor * used in other tests does not create an instance of the wrapper class. */ @Test void testToString() { final UniformRandomProvider rng = RandomAssert.seededRNG(); Assertions.assertTrue(new RejectionInversionZipfSampler(rng, 10, 2.0).toString() .toLowerCase().contains("zipf")); } }
2,938
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/DiscreteSamplerTestData.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import java.util.Arrays; /** * Data store for {@link DiscreteSamplerParametricTest}. */ class DiscreteSamplerTestData { private final DiscreteSampler sampler; private final int[] points; private final double[] probabilities; DiscreteSamplerTestData(DiscreteSampler sampler, int[] points, double[] probabilities) { this.sampler = sampler; this.points = points.clone(); this.probabilities = probabilities.clone(); } public DiscreteSampler getSampler() { return sampler; } public int[] getPoints() { return points.clone(); } public double[] getProbabilities() { return probabilities.clone(); } @Override public String toString() { final int len = points.length; final String[] p = new String[len]; for (int i = 0; i < len; i++) { p[i] = "p(" + points[i] + ")=" + probabilities[i]; } return sampler.toString() + ": " + Arrays.toString(p); } }
2,939
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/FastLoadedDiceRollerDiscreteSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import java.util.Arrays; import java.util.function.DoubleUnaryOperator; import java.util.stream.Stream; import org.apache.commons.math3.stat.descriptive.moment.Mean; import org.apache.commons.math3.stat.inference.ChiSquareTest; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; /** * Test for the {@link FastLoadedDiceRollerDiscreteSampler}. */ class FastLoadedDiceRollerDiscreteSamplerTest { /** * Creates the sampler. * * @param frequencies Observed frequencies. * @return the FLDR sampler */ private static SharedStateDiscreteSampler createSampler(long... frequencies) { final UniformRandomProvider rng = RandomAssert.createRNG(); return FastLoadedDiceRollerDiscreteSampler.of(rng, frequencies); } /** * Creates the sampler. * * @param weights Weights. * @return the FLDR sampler */ private static SharedStateDiscreteSampler createSampler(double... weights) { final UniformRandomProvider rng = RandomAssert.createRNG(); return FastLoadedDiceRollerDiscreteSampler.of(rng, weights); } /** * Return a stream of invalid frequencies for a discrete distribution. * * @return the stream of invalid frequencies */ static Stream<long[]> testFactoryConstructorFrequencies() { return Stream.of( // Null or empty (long[]) null, new long[0], // Negative new long[] {-1, 2, 3}, new long[] {1, -2, 3}, new long[] {1, 2, -3}, // Overflow of sum new long[] {Long.MAX_VALUE, Long.MAX_VALUE}, // x+x+2 == 0 new long[] {Long.MAX_VALUE, Long.MAX_VALUE, 2}, // x+x+x == x - 2 (i.e. positive) new long[] {Long.MAX_VALUE, Long.MAX_VALUE, Long.MAX_VALUE}, // Zero sum new long[1], new long[4] ); } @ParameterizedTest @MethodSource void testFactoryConstructorFrequencies(long[] frequencies) { Assertions.assertThrows(IllegalArgumentException.class, () -> createSampler(frequencies)); } /** * Return a stream of invalid weights for a discrete distribution. * * @return the stream of invalid weights */ static Stream<double[]> testFactoryConstructorWeights() { return Stream.of( // Null or empty (double[]) null, new double[0], // Negative, infinite or NaN new double[] {-1, 2, 3}, new double[] {1, -2, 3}, new double[] {1, 2, -3}, new double[] {Double.POSITIVE_INFINITY, 2, 3}, new double[] {1, Double.POSITIVE_INFINITY, 3}, new double[] {1, 2, Double.POSITIVE_INFINITY}, new double[] {Double.NaN, 2, 3}, new double[] {1, Double.NaN, 3}, new double[] {1, 2, Double.NaN}, // Zero sum new double[1], new double[4] ); } @ParameterizedTest @MethodSource void testFactoryConstructorWeights(double[] weights) { Assertions.assertThrows(IllegalArgumentException.class, () -> createSampler(weights)); } @Test void testToString() { for (final long[] observed : new long[][] {{42}, {1, 2, 3}}) { final SharedStateDiscreteSampler sampler = createSampler(observed); Assertions.assertTrue(sampler.toString().toLowerCase().contains("fast loaded dice roller")); } } @Test void testSingleCategory() { final int n = 13; final int[] expected = new int[n]; Assertions.assertArrayEquals(expected, createSampler(42).samples(n).toArray()); Assertions.assertArrayEquals(expected, createSampler(0.55).samples(n).toArray()); } @Test void testSingleFrequency() { final long[] frequencies = new long[5]; final int category = 2; frequencies[category] = 1; final SharedStateDiscreteSampler sampler = createSampler(frequencies); final int n = 7; final int[] expected = new int[n]; Arrays.fill(expected, category); Assertions.assertArrayEquals(expected, sampler.samples(n).toArray()); } @Test void testSingleWeight() { final double[] weights = new double[5]; final int category = 3; weights[category] = 1.5; final SharedStateDiscreteSampler sampler = createSampler(weights); final int n = 6; final int[] expected = new int[n]; Arrays.fill(expected, category); Assertions.assertArrayEquals(expected, sampler.samples(n).toArray()); } @Test void testIndexOfNonZero() { Assertions.assertThrows(IllegalStateException.class, () -> FastLoadedDiceRollerDiscreteSampler.indexOfNonZero(new long[3])); final long[] data = new long[3]; for (int i = 0; i < data.length; i++) { data[i] = 13; Assertions.assertEquals(i, FastLoadedDiceRollerDiscreteSampler.indexOfNonZero(data)); data[i] = 0; } } @ParameterizedTest @ValueSource(longs = {0, 1, -1, Integer.MAX_VALUE, 1L << 34}) void testCheckArraySize(long size) { // This is the same value as the sampler final int max = Integer.MAX_VALUE - 8; // Note: The method does not test for negatives. // This is not required when validating a positive int multiplied by another positive int. if (size > max) { Assertions.assertThrows(IllegalArgumentException.class, () -> FastLoadedDiceRollerDiscreteSampler.checkArraySize(size)); } else { Assertions.assertEquals((int) size, FastLoadedDiceRollerDiscreteSampler.checkArraySize(size)); } } /** * Return a stream of expected frequencies for a discrete distribution. * * @return the stream of expected frequencies */ static Stream<long[]> testSamplesFrequencies() { return Stream.of( // Single category new long[] {0, 0, 42, 0, 0}, // Sum to a power of 2 new long[] {1, 1, 2, 3, 1}, new long[] {0, 1, 1, 0, 2, 3, 1, 0}, // Do not sum to a power of 2 new long[] {1, 2, 3, 1, 3}, new long[] {1, 0, 2, 0, 3, 1, 3}, // Large frequencies new long[] {5126734627834L, 213267384684832L, 126781236718L, 71289979621378L} ); } /** * Check the distribution of samples match the expected probabilities. * * @param expectedFrequencies Expected frequencies. */ @ParameterizedTest @MethodSource void testSamplesFrequencies(long[] expectedFrequencies) { final SharedStateDiscreteSampler sampler = createSampler(expectedFrequencies); final int numberOfSamples = 10000; final long[] samples = new long[expectedFrequencies.length]; sampler.samples(numberOfSamples).forEach(x -> samples[x]++); // Handle a test with some zero-probability observations by mapping them out int mapSize = 0; double sum = 0; for (final double f : expectedFrequencies) { if (f != 0) { mapSize++; sum += f; } } // Single category will break the Chi-square test if (mapSize == 1) { int index = 0; while (index < expectedFrequencies.length) { if (expectedFrequencies[index] != 0) { break; } index++; } Assertions.assertEquals(numberOfSamples, samples[index], "Invalid single category samples"); return; } final double[] expected = new double[mapSize]; final long[] observed = new long[mapSize]; for (int i = 0; i < expectedFrequencies.length; i++) { if (expectedFrequencies[i] != 0) { --mapSize; expected[mapSize] = expectedFrequencies[i] / sum; observed[mapSize] = samples[i]; } else { Assertions.assertEquals(0, samples[i], "No samples expected from zero probability"); } } final ChiSquareTest chiSquareTest = new ChiSquareTest(); // Pass if we cannot reject null hypothesis that the distributions are the same. Assertions.assertFalse(chiSquareTest.chiSquareTest(expected, observed, 0.001)); } /** * Return a stream of expected weights for a discrete distribution. * * @return the stream of expected weights */ static Stream<double[]> testSamplesWeights() { return Stream.of( // Single category new double[] {0, 0, 0.523, 0, 0}, // Sum to a power of 2 new double[] {0.125, 0.125, 0.25, 0.375, 0.125}, new double[] {0, 0.125, 0.125, 0.25, 0, 0.375, 0.125, 0}, // Do not sum to a power of 2 new double[] {0.1, 0.2, 0.3, 0.1, 0.3}, new double[] {0.1, 0, 0.2, 0, 0.3, 0.1, 0.3}, // Sub-normal numbers new double[] {5 * Double.MIN_NORMAL, 2 * Double.MIN_NORMAL, 3 * Double.MIN_NORMAL, 9 * Double.MIN_NORMAL}, new double[] {2 * Double.MIN_NORMAL, Double.MIN_NORMAL, 0.5 * Double.MIN_NORMAL, 0.75 * Double.MIN_NORMAL}, new double[] {Double.MIN_VALUE, 2 * Double.MIN_VALUE, 3 * Double.MIN_VALUE, 7 * Double.MIN_VALUE}, // Large range of magnitude new double[] {1.0, 2.0, Math.scalb(3.0, -32), Math.scalb(4.0, -65), 5.0}, new double[] {Math.scalb(1.0, 35), Math.scalb(2.0, 35), Math.scalb(3.0, -32), Math.scalb(4.0, -65), Math.scalb(5.0, 35)}, // Sum to infinite new double[] {Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE / 2, Double.MAX_VALUE / 4} ); } /** * Check the distribution of samples match the expected weights. * * @param weights Category weights. */ @ParameterizedTest @MethodSource void testSamplesWeights(double[] weights) { final SharedStateDiscreteSampler sampler = createSampler(weights); final int numberOfSamples = 10000; final long[] samples = new long[weights.length]; sampler.samples(numberOfSamples).forEach(x -> samples[x]++); // Handle a test with some zero-probability observations by mapping them out int mapSize = 0; double sum = 0; // Handle infinite sum using a rolling mean for normalisation final Mean mean = new Mean(); for (final double w : weights) { if (w != 0) { mapSize++; sum += w; mean.increment(w); } } // Single category will break the Chi-square test if (mapSize == 1) { int index = 0; while (index < weights.length) { if (weights[index] != 0) { break; } index++; } Assertions.assertEquals(numberOfSamples, samples[index], "Invalid single category samples"); return; } final double mu = mean.getResult(); final int n = mapSize; final double s = sum; final DoubleUnaryOperator normalise = Double.isInfinite(sum) ? x -> (x / mu) * n : x -> x / s; final double[] expected = new double[mapSize]; final long[] observed = new long[mapSize]; for (int i = 0; i < weights.length; i++) { if (weights[i] != 0) { --mapSize; expected[mapSize] = normalise.applyAsDouble(weights[i]); observed[mapSize] = samples[i]; } else { Assertions.assertEquals(0, samples[i], "No samples expected from zero probability"); } } final ChiSquareTest chiSquareTest = new ChiSquareTest(); // Pass if we cannot reject null hypothesis that the distributions are the same. Assertions.assertFalse(chiSquareTest.chiSquareTest(expected, observed, 0.001)); } /** * Return a stream of expected frequencies for a discrete distribution where the frequencies * can be converted to a {@code double} without loss of precision. * * @return the stream of expected frequencies */ static Stream<long[]> testSamplesWeightsMatchesFrequencies() { // Reuse the same frequencies. // Those that cannot be converted to a double are ignored by the test. return testSamplesFrequencies(); } /** * Check the distribution of samples when the frequencies can be converted to weights without * loss of precision. * * @param frequencies Expected frequencies. */ @ParameterizedTest @MethodSource void testSamplesWeightsMatchesFrequencies(long[] frequencies) { final double[] weights = new double[frequencies.length]; for (int i = 0; i < frequencies.length; i++) { final double w = frequencies[i]; Assumptions.assumeTrue((long) w == frequencies[i]); // Ensure the exponent is set in the event of simple frequencies weights[i] = Math.scalb(w, -35); } final UniformRandomProvider[] rngs = RandomAssert.createRNG(2); final UniformRandomProvider rng1 = rngs[0]; final UniformRandomProvider rng2 = rngs[1]; final SharedStateDiscreteSampler sampler1 = FastLoadedDiceRollerDiscreteSampler.of(rng1, frequencies); final SharedStateDiscreteSampler sampler2 = FastLoadedDiceRollerDiscreteSampler.of(rng2, weights); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * Test scaled weights. The sampler uses the relative magnitude of weights and the * output should be invariant to scaling. The weights are sampled from the 2^53 dyadic * rationals in [0, 1). A scale factor of -1021 is the lower limit if a weight is * 2^-53 to maintain a non-zero weight. The upper limit is 1023 if a weight is 1 to avoid * infinite values. Note that it does not matter if the sum of weights is infinite; only * the individual weights must be finite. * * @param scaleFactor the scale factor */ @ParameterizedTest @ValueSource(ints = {1023, 67, 1, -59, -1020, -1021}) void testScaledWeights(int scaleFactor) { // Weights in [0, 1) final double[] w1 = RandomAssert.createRNG().doubles(10).toArray(); final double scale = Math.scalb(1.0, scaleFactor); final double[] w2 = Arrays.stream(w1).map(x -> x * scale).toArray(); final UniformRandomProvider[] rngs = RandomAssert.createRNG(2); final UniformRandomProvider rng1 = rngs[0]; final UniformRandomProvider rng2 = rngs[1]; final SharedStateDiscreteSampler sampler1 = FastLoadedDiceRollerDiscreteSampler.of(rng1, w1); final SharedStateDiscreteSampler sampler2 = FastLoadedDiceRollerDiscreteSampler.of(rng2, w2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * Test the alpha parameter removes small relative weights. * Weights should be removed if they are {@code 2^alpha} smaller than the largest * weight. * * @param alpha Alpha parameter */ @ParameterizedTest @ValueSource(ints = {13, 30, 53}) void testAlphaRemovesWeights(int alpha) { // The small weight must be > 2^alpha smaller so scale by (alpha + 1) final double small = Math.scalb(1.0, -(alpha + 1)); final double[] w1 = {1, 0.5, 0.5, 0}; final double[] w2 = {1, 0.5, 0.5, small}; final UniformRandomProvider[] rngs = RandomAssert.createRNG(3); final UniformRandomProvider rng1 = rngs[0]; final UniformRandomProvider rng2 = rngs[1]; final UniformRandomProvider rng3 = rngs[2]; final int n = 10; final int[] s1 = FastLoadedDiceRollerDiscreteSampler.of(rng1, w1).samples(n).toArray(); final int[] s2 = FastLoadedDiceRollerDiscreteSampler.of(rng2, w2, alpha).samples(n).toArray(); final int[] s3 = FastLoadedDiceRollerDiscreteSampler.of(rng3, w2, alpha + 1).samples(n).toArray(); Assertions.assertArrayEquals(s1, s2, "alpha parameter should ignore the small weight"); Assertions.assertFalse(Arrays.equals(s1, s3), "alpha+1 parameter should not ignore the small weight"); } static Stream<long[]> testSharedStateSampler() { return Stream.of( new long[] {42}, new long[] {1, 1, 2, 3, 1} ); } @ParameterizedTest @MethodSource void testSharedStateSampler(long[] frequencies) { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final SharedStateDiscreteSampler sampler1 = FastLoadedDiceRollerDiscreteSampler.of(rng1, frequencies); final SharedStateDiscreteSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } }
2,940
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/TSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; /** * Test for the {@link TSampler}. */ class TSamplerTest { /** * Test the constructor with an invalid degrees of freedom. */ @ParameterizedTest @ValueSource(doubles = {0, -1, Double.NaN}) void testConstructorThrowsWithBadDegreesOfFreedom(double degreesOfFreedom) { final UniformRandomProvider rng = RandomAssert.seededRNG(); Assertions.assertThrows(IllegalArgumentException.class, () -> TSampler.of(rng, degreesOfFreedom)); } /** * Test the SharedStateSampler implementation. */ @ParameterizedTest @ValueSource(doubles = {4.56, 1e16}) void testSharedStateSampler(double degreesOfFreedom) { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final TSampler sampler1 = TSampler.of(rng1, degreesOfFreedom); final TSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * Test extremely large degrees of freedom is approximated using a normal distribution. */ @Test void testExtremelyLargeDegreesOfFreedom() { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final double degreesOfFreedom = 1e16; final ContinuousSampler sampler1 = TSampler.of(rng1, degreesOfFreedom); final ContinuousSampler sampler2 = ZigguratSampler.NormalizedGaussian.of(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } }
2,941
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/ZigguratSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import java.util.Arrays; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Stream; import org.apache.commons.math3.distribution.AbstractRealDistribution; import org.apache.commons.math3.distribution.ExponentialDistribution; import org.apache.commons.math3.distribution.NormalDistribution; import org.apache.commons.math3.stat.inference.ChiSquareTest; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.core.source64.SplitMix64; import org.apache.commons.rng.sampling.RandomAssert; import org.apache.commons.rng.simple.RandomSource; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; /** * Test for {@link ZigguratSampler}. */ class ZigguratSamplerTest { /** * The seed for the RNG used in the distribution sampling tests. * * <p>This has been chosen to allow the test to pass with all generators. * Set to null test with a random seed. */ private static final Long SEED = 0xabcdefL; /** * Test the exponential constructor with a bad mean. */ @Test void testExponentialConstructorThrowsWithZeroMean() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final double mean = 0; Assertions.assertThrows(IllegalArgumentException.class, () -> ZigguratSampler.Exponential.of(rng, mean)); } /** * Test the exponential SharedStateSampler implementation. */ @Test void testExponentialSharedStateSampler() { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final ZigguratSampler.Exponential sampler1 = ZigguratSampler.Exponential.of(rng1); final ZigguratSampler.Exponential sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * Test the exponential SharedStateSampler implementation with a mean. */ @Test void testExponentialSharedStateSamplerWithMean() { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final double mean = 1.23; final ZigguratSampler.Exponential sampler1 = ZigguratSampler.Exponential.of(rng1, mean); final ZigguratSampler.Exponential sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * Test the Gaussian SharedStateSampler implementation. */ @Test void testGaussianSharedStateSampler() { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final ZigguratSampler.NormalizedGaussian sampler1 = ZigguratSampler.NormalizedGaussian.of(rng1); final ZigguratSampler.NormalizedGaussian sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * Test the recursion in the exponential distribution. */ @Test void testExponentialRecursion() { // The exponential distribution will enter the edge of the ziggurat if the RNG // outputs -1 (all bits). This performs alias sampling using a long value. // The tail will be selected if the next output is -1. // Thus two -1 values enter recursion where a new exponential sample is added // to the tail value: final double tailValue = 7.569274694148063; // Alias sampling assigns the ziggurat layer using the lower 8 bits. // The rest determine if the layer or the alias are used. We do not control this // and leave it to a seeded RNG to select different layers. // A value of zero will create a sample of zero (42 is the seed) Assertions.assertEquals(0.0, expSample(42, 0)); Assertions.assertEquals(tailValue, expSample(42, -1, -1, 0)); // Use different seeds to test different layers from the edge of the ziggurat. for (final long seed : new long[] {42, -2136612838, 2340923842L, -1263746817818681L}) { // Base value final double x0 = expSample(seed); // Edge value final double x1 = expSample(seed, -1); // Recursion Assertions.assertEquals(x0 + tailValue, expSample(seed, -1, -1)); Assertions.assertEquals(x1 + tailValue, expSample(seed, -1, -1, -1)); // Double recursion // Note the order of additions is important as the final sample is added to // a summation of the tail value. Assertions.assertEquals(tailValue + tailValue + x0, expSample(seed, -1, -1, -1, -1)); Assertions.assertEquals(tailValue + tailValue + x1, expSample(seed, -1, -1, -1, -1, -1)); } } /** * Create an exponential sample from the sequence of longs, then revert to a seed RNG. * * @param seed the seed * @param longs the longs * @return the sample */ private static double expSample(long seed, final long... longs) { final SplitMix64 rng = new SplitMix64(seed) { private int i; @Override public long next() { if (i == longs.length) { // Revert to seeded RNG return super.next(); } return longs[i++]; } }; return ZigguratSampler.Exponential.of(rng).sample(); } // Note: // The sampler samples within the box regions of the ziggurat > 98.5% of the time. // The rest of the time a sample is taken from an overhang region or the tail. The proportion // of samples from each of the overhangs and tail is related to the volume of those // regions. The sampling within a region must fit the PDF curve of the region. // We must test two items: (1) if the sampling is biased to certain overhangs; // and (2) if the sampling is biased within a single overhang. // // The following tests check if the overall shape of the PDF is correct. Then small // regions are sampled that target specific parts of the ziggurat: the overhangs and the tail. // For the exponential distribution all overhangs are concave so any region can be tested. // For the normal distribution the overhangs switch from convex to concave at the inflection // point which is x=1. The test targets regions specifically above and below the inflection // point. // // Testing the distribution within an overhang requires a histogram with widths smaller // than the width differences in the ziggurat. // // For the normal distribution the widths at each end and around the inflection point are: // [3.6360066255009458, 3.431550493837111, 3.3044597575834205, 3.2104230299359244] // [1.0113527773194309, 1.003307168714496, 0.9951964183341382, 0.9870178156137862] // [0.3881084509554052, 0.34703847379449715, 0.29172225078072095, 0.0] // // For the exponential: // [7.569274694148063, 6.822872544335941, 6.376422694249821, 6.05490013642656] // [0.18840300957360784, 0.15921172977030051, 0.12250380599214447, 0.0] // // Two tests are performed: // (1) The bins are spaced using the quantiles of the distribution. // The histogram should be uniform in frequency across all bins. // (2) The bins are spaced uniformly. The frequencies should match the CDF of the function // for that region. In this test the number of bins is chosen to ensure that there are multiple // bins covering even the smallest gaps between ziggurat layers. Thus the bins will partition // samples within a single overhang layer. // // Note: // These tests could be improved as not all minor errors in the samplers are detected. // The test does detect all the bugs that were eliminated from the algorithm during // development if they are reintroduced. // // Bugs that cannot be detected: // 1. Changing the J_INFLECTION point in the Gaussian sampler to the extremes of 1 or 253 // does not fail. Thus the test cannot detect incorrect triangle sampling for // convex/concave regions. A sample that is a uniform lower-left triangle sample // for any concave region is missed by the test. // 2. Changing the E_MAX threshold in the exponential sampler to 0 does not fail. // Thus the test cannot detect the difference between a uniform lower-left triangle // sample and a uniform convex region sample. // This may require more samples in the histogram or a different test strategy. An example // would be to force the RNG to sample outside the ziggurat boxes. The expected counts would // have to be constructed using prior knowledge of the ziggurat box sizes. Thus the CDF can // be computed for each overhang minus the ziggurat region underneath. No distribution // exists to support this in Commons Math. A custom implementation should support computing // the CDF of the ziggurat boxes from x0 to x1. /** * Create a stream of constructors of a Gaussian sampler. * * <p>Note: This method exists to allow this test to be duplicated in the examples JMH * module where many implementations are tested. * * @return the stream of constructors */ private static Stream<Arguments> gaussianSamplers() { final Function<UniformRandomProvider, ContinuousSampler> factory = ZigguratSampler.NormalizedGaussian::of; return Stream.of(Arguments.of("NormalizedGaussian", factory)); } /** * Create a stream of constructors of an exponential sampler. * * <p>Note: This method exists to allow this test to be duplicated in the examples JMH * module where many implementations are tested. * * @return the stream of constructors */ private static Stream<Arguments> exponentialSamplers() { final Function<UniformRandomProvider, ContinuousSampler> factory = ZigguratSampler.Exponential::of; return Stream.of(Arguments.of("Exponential", factory)); } /** * Creates the gaussian distribution. * * @return the distribution */ private static AbstractRealDistribution createGaussianDistribution() { return new NormalDistribution(null, 0.0, 1.0); } /** * Creates the exponential distribution. * * @return the distribution */ private static AbstractRealDistribution createExponentialDistribution() { return new ExponentialDistribution(null, 1.0); } /** * Test Gaussian samples using a large number of bins based on uniformly spaced * quantiles. Added for RNG-159. * * @param name Name of the sampler * @param factory Factory to create the sampler */ @ParameterizedTest(name = "{index} => {0}") @MethodSource("gaussianSamplers") void testGaussianSamplesWithQuantiles(String name, Function<UniformRandomProvider, ContinuousSampler> factory) { final int bins = 2000; final AbstractRealDistribution dist = createGaussianDistribution(); final double[] quantiles = new double[bins]; for (int i = 0; i < bins; i++) { quantiles[i] = dist.inverseCumulativeProbability((i + 1.0) / bins); } testSamples(quantiles, factory, ZigguratSamplerTest::createGaussianDistribution, // Test positive and negative ranges to check symmetry. // Smallest layer is 0.292 (convex region) new double[] {0, 0.2}, new double[] {-0.35, -0.1}, // Around the mean new double[] {-0.1, 0.1}, new double[] {-0.4, 0.6}, // Inflection point at x=1 new double[] {-1.1, -0.9}, // A concave region new double[] {2.1, 2.5}, // Tail = 3.64 new double[] {2.5, 8}); } /** * Test Gaussian samples using a large number of bins uniformly spaced in a range. * Added for RNG-159. * * @param name Name of the sampler * @param factory Factory to create the sampler */ @ParameterizedTest(name = "{index} => {0}") @MethodSource("gaussianSamplers") void testGaussianSamplesWithUniformValues(String name, Function<UniformRandomProvider, ContinuousSampler> factory) { final int bins = 2000; final double[] values = new double[bins]; final double minx = -8; final double maxx = 8; // Bin width = 16 / 2000 = 0.008 for (int i = 0; i < bins; i++) { values[i] = minx + (maxx - minx) * (i + 1.0) / bins; } // Ensure upper bound is the support limit values[bins - 1] = Double.POSITIVE_INFINITY; testSamples(values, factory, ZigguratSamplerTest::createGaussianDistribution, // Test positive and negative ranges to check symmetry. // Smallest layer is 0.292 (convex region) new double[] {0, 0.2}, new double[] {-0.35, -0.1}, // Around the mean new double[] {-0.1, 0.1}, new double[] {-0.4, 0.6}, // Inflection point at x=1 new double[] {-1.01, -0.99}, new double[] {0.98, 1.03}, // A concave region new double[] {1.03, 1.05}, // Tail = 3.64 new double[] {3.6, 3.8}, new double[] {3.7, 8}); } /** * Test exponential samples using a large number of bins based on uniformly spaced quantiles. * * @param name Name of the sampler * @param factory Factory to create the sampler */ @ParameterizedTest(name = "{index} => {0}") @MethodSource("exponentialSamplers") void testExponentialSamplesWithQuantiles(String name, Function<UniformRandomProvider, ContinuousSampler> factory) { final int bins = 2000; final AbstractRealDistribution dist = createExponentialDistribution(); final double[] quantiles = new double[bins]; for (int i = 0; i < bins; i++) { quantiles[i] = dist.inverseCumulativeProbability((i + 1.0) / bins); } testSamples(quantiles, factory, ZigguratSamplerTest::createExponentialDistribution, // Smallest layer is 0.122 new double[] {0, 0.1}, new double[] {0.05, 0.15}, // Around the mean new double[] {0.9, 1.1}, // Tail = 7.57 new double[] {1.5, 12}); } /** * Test exponential samples using a large number of bins uniformly spaced in a range. * * @param name Name of the sampler * @param factory Factory to create the sampler */ @ParameterizedTest(name = "{index} => {0}") @MethodSource("exponentialSamplers") void testExponentialSamplesWithUniformValues(String name, Function<UniformRandomProvider, ContinuousSampler> factory) { final int bins = 2000; final double[] values = new double[bins]; final double minx = 0; // Enter the tail of the distribution final double maxx = 12; // Bin width = 12 / 2000 = 0.006 for (int i = 0; i < bins; i++) { values[i] = minx + (maxx - minx) * (i + 1.0) / bins; } // Ensure upper bound is the support limit values[bins - 1] = Double.POSITIVE_INFINITY; testSamples(values, factory, ZigguratSamplerTest::createExponentialDistribution, // Smallest layer is 0.122 new double[] {0, 0.1}, new double[] {0.05, 0.15}, // Around the mean new double[] {0.9, 1.1}, // Tail = 7.57 new double[] {7.5, 7.7}, new double[] {7.7, 12}); } /** * Test samples using the provided bins. Values correspond to the bin upper * limit. It is assumed the values span most of the distribution. Additional * tests are performed using a region of the distribution sampled. * * @param values Bin upper limits * @param factory Factory to create the sampler * @param distribution The distribution under test * @param ranges Ranges of the distribution to test */ private static void testSamples(double[] values, Function<UniformRandomProvider, ContinuousSampler> factory, Supplier<AbstractRealDistribution> distribution, double[]... ranges) { final int bins = values.length; final int samples = 10000000; final long[] observed = new long[bins]; final UniformRandomProvider rng = RandomSource.XO_SHI_RO_128_PP.create(SEED); final ContinuousSampler sampler = factory.apply(rng); for (int i = 0; i < samples; i++) { final double x = sampler.sample(); final int index = findIndex(values, x); observed[index]++; } // Compute expected final AbstractRealDistribution dist = distribution.get(); final double[] expected = new double[bins]; double x0 = Double.NEGATIVE_INFINITY; for (int i = 0; i < bins; i++) { final double x1 = values[i]; expected[i] = dist.probability(x0, x1); x0 = x1; } final double significanceLevel = 0.001; final double lowerBound = dist.getSupportLowerBound(); final ChiSquareTest chiSquareTest = new ChiSquareTest(); // Pass if we cannot reject null hypothesis that the distributions are the same. final double pValue = chiSquareTest.chiSquareTest(expected, observed); Assertions.assertFalse(pValue < 0.001, () -> String.format("(%s <= x < %s) Chi-square p-value = %s", lowerBound, values[bins - 1], pValue)); // Test regions of the ziggurat. for (final double[] range : ranges) { final int min = findIndex(values, range[0]); final int max = findIndex(values, range[1]); // Must have a range of 2 if (max - min + 1 < 2) { // This will probably occur if the quantiles test uses too small a range // for the tail. The tail is so far into the CDF that a single bin is // often used to represent it. Assertions.fail("Invalid range: " + Arrays.toString(range)); } final long[] observed2 = Arrays.copyOfRange(observed, min, max + 1); final double[] expected2 = Arrays.copyOfRange(expected, min, max + 1); final double pValueB = chiSquareTest.chiSquareTest(expected2, observed2); Assertions.assertFalse(pValueB < significanceLevel, () -> String.format("(%s <= x < %s) Chi-square p-value = %s", min == 0 ? lowerBound : values[min - 1], values[max], pValueB)); } } /** * Find the index of the value in the data such that: * <pre> * data[index - 1] <= x < data[index] * </pre> * * <p>This is a specialised binary search that assumes the bounds of the data are the * extremes of the support, and the upper support is infinite. Thus an index cannot * be returned as equal to the data length. * * @param data the data * @param x the value * @return the index */ private static int findIndex(double[] data, double x) { int low = 0; int high = data.length - 1; // Bracket so that low is just above the value x while (low <= high) { final int mid = (low + high) >>> 1; final double midVal = data[mid]; if (x < midVal) { // Reduce search range high = mid - 1; } else { // Set data[low] above the value low = mid + 1; } } // Verify the index is correct Assertions.assertTrue(x < data[low]); if (low != 0) { Assertions.assertTrue(x >= data[low - 1]); } return low; } }
2,942
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/DiscreteSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import java.util.concurrent.ThreadLocalRandom; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; /** * Tests the default methods in the {@link DiscreteSampler} interface. */ class DiscreteSamplerTest { @Test void testSamplesUnlimitedSize() { final DiscreteSampler s = RandomAssert.createRNG()::nextInt; Assertions.assertEquals(Long.MAX_VALUE, s.samples().spliterator().estimateSize()); } @RepeatedTest(value = 3) void testSamples() { final UniformRandomProvider[] rngs = RandomAssert.createRNG(2); final DiscreteSampler s1 = rngs[0]::nextInt; final DiscreteSampler s2 = rngs[1]::nextInt; final int count = ThreadLocalRandom.current().nextInt(3, 13); Assertions.assertArrayEquals(createSamples(s1, count), s2.samples().limit(count).toArray()); } @ParameterizedTest @ValueSource(ints = {0, 1, 2, 5, 13}) void testSamples(int streamSize) { final UniformRandomProvider[] rngs = RandomAssert.createRNG(2); final DiscreteSampler s1 = rngs[0]::nextInt; final DiscreteSampler s2 = rngs[1]::nextInt; Assertions.assertArrayEquals(createSamples(s1, streamSize), s2.samples(streamSize).toArray()); } /** * Creates an array of samples. * * @param sampler Source of samples. * @param count Number of samples. * @return the samples */ private static int[] createSamples(DiscreteSampler sampler, int count) { final int[] data = new int[count]; for (int i = 0; i < count; i++) { data[i] = sampler.sample(); } return data; } }
2,943
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/MarsagliaTsangWangDiscreteSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.math3.stat.inference.ChiSquareTest; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.core.source32.IntProvider; import org.apache.commons.rng.core.source64.SplitMix64; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test for the {@link MarsagliaTsangWangDiscreteSampler}. The tests hit edge cases for * the sampler factory methods that build the normalised probability distribution. * * <p>Statistical testing of the sampler is performed using entries in {@link DiscreteSamplersList}.</p> */ class MarsagliaTsangWangDiscreteSamplerTest { @Test void testCreateDiscreteDistributionThrowsWithNullProbabilites() { assertEnumeratedSamplerConstructorThrows(null); } @Test void testCreateDiscreteDistributionThrowsWithZeroLengthProbabilites() { assertEnumeratedSamplerConstructorThrows(new double[0]); } @Test void testCreateDiscreteDistributionThrowsWithNegativeProbabilites() { assertEnumeratedSamplerConstructorThrows(new double[] {-1, 0.1, 0.2}); } @Test void testCreateDiscreteDistributionThrowsWithNaNProbabilites() { assertEnumeratedSamplerConstructorThrows(new double[] {0.1, Double.NaN, 0.2}); } @Test void testCreateDiscreteDistributionThrowsWithInfiniteProbabilites() { assertEnumeratedSamplerConstructorThrows(new double[] {0.1, Double.POSITIVE_INFINITY, 0.2}); } @Test void testCreateDiscreteDistributionThrowsWithInfiniteSumProbabilites() { assertEnumeratedSamplerConstructorThrows(new double[] {Double.MAX_VALUE, Double.MAX_VALUE}); } @Test void testCreateDiscreteDistributionThrowsWithZeroSumProbabilites() { assertEnumeratedSamplerConstructorThrows(new double[4]); } /** * Assert the enumerated sampler factory constructor throws an {@link IllegalArgumentException}. * * @param probabilities Probabilities. */ private static void assertEnumeratedSamplerConstructorThrows(double[] probabilities) { final UniformRandomProvider rng = new SplitMix64(0L); Assertions.assertThrows(IllegalArgumentException.class, () -> MarsagliaTsangWangDiscreteSampler.Enumerated.of(rng, probabilities)); } /** * Test the {@link Object#toString()} method contains the algorithm author names. */ @Test void testToString() { final UniformRandomProvider rng = new SplitMix64(0L); final DiscreteSampler sampler = MarsagliaTsangWangDiscreteSampler.Enumerated.of(rng, new double[] {0.5, 0.5}); String text = sampler.toString(); for (String item : new String[] {"Marsaglia", "Tsang", "Wang"}) { Assertions.assertTrue(text.contains(item), () -> "toString missing: " + item); } } // Sampling tests /** * Test offset samples. This test hits all code paths in the sampler for 8, 16, and 32-bit * storage using different offsets to control the maximum sample value. */ @Test void testOffsetSamples() { // This is filled with probabilities to hit all edge cases in the fill procedure. // The probabilities must have a digit from each of the 5 possible. final int[] prob = new int[6]; prob[0] = 1; prob[1] = 1 + 1 << 6; prob[2] = 1 + 1 << 12; prob[3] = 1 + 1 << 18; prob[4] = 1 + 1 << 24; // Ensure probabilities sum to 2^30 prob[5] = (1 << 30) - (prob[0] + prob[1] + prob[2] + prob[3] + prob[4]); // To hit all samples requires integers that are under the look-up table limits. // So compute the limits here. int n1 = 0; int n2 = 0; int n3 = 0; int n4 = 0; for (final int m : prob) { n1 += getBase64Digit(m, 1); n2 += getBase64Digit(m, 2); n3 += getBase64Digit(m, 3); n4 += getBase64Digit(m, 4); } final int t1 = n1 << 24; final int t2 = t1 + (n2 << 18); final int t3 = t2 + (n3 << 12); final int t4 = t3 + (n4 << 6); // Create values under the limits and bit shift by 2 to reverse what the sampler does. final int[] values = new int[] {0, t1, t2, t3, t4, 0xffffffff}; for (int i = 0; i < values.length; i++) { values[i] <<= 2; } final UniformRandomProvider rng1 = new FixedSequenceIntProvider(values); final UniformRandomProvider rng2 = new FixedSequenceIntProvider(values); final UniformRandomProvider rng3 = new FixedSequenceIntProvider(values); // Create offsets to force storage as 8, 16, or 32-bit final int offset1 = 1; final int offset2 = 1 << 8; final int offset3 = 1 << 16; final double[] p1 = createProbabilities(offset1, prob); final double[] p2 = createProbabilities(offset2, prob); final double[] p3 = createProbabilities(offset3, prob); final SharedStateDiscreteSampler sampler1 = MarsagliaTsangWangDiscreteSampler.Enumerated.of(rng1, p1); final SharedStateDiscreteSampler sampler2 = MarsagliaTsangWangDiscreteSampler.Enumerated.of(rng2, p2); final SharedStateDiscreteSampler sampler3 = MarsagliaTsangWangDiscreteSampler.Enumerated.of(rng3, p3); for (int i = 0; i < values.length; i++) { // Remove offsets final int s1 = sampler1.sample() - offset1; final int s2 = sampler2.sample() - offset2; final int s3 = sampler3.sample() - offset3; Assertions.assertEquals(s1, s2, "Offset sample 1 and 2 do not match"); Assertions.assertEquals(s1, s3, "Offset Sample 1 and 3 do not match"); } } /** * Creates the probabilities using zero padding below the values. * * @param offset Offset for first given probability (i.e. the zero padding size). * @param prob Probability values. * @return the zero-padded probabilities */ private static double[] createProbabilities(int offset, int[] prob) { double[] probabilities = new double[offset + prob.length]; for (int i = 0; i < prob.length; i++) { probabilities[i + offset] = prob[i]; } return probabilities; } /** * Test samples from a distribution expressed using {@code double} probabilities. */ @Test void testRealProbabilityDistributionSamples() { // These do not have to sum to 1 final double[] probabilities = new double[11]; final UniformRandomProvider rng = RandomAssert.createRNG(); for (int i = 0; i < probabilities.length; i++) { probabilities[i] = rng.nextDouble(); } // First test the table is completely filled to 2^30 final UniformRandomProvider dummyRng = new FixedSequenceIntProvider(new int[] {0xffffffff}); final SharedStateDiscreteSampler dummySampler = MarsagliaTsangWangDiscreteSampler.Enumerated.of(dummyRng, probabilities); // This will throw if the table is incomplete as it hits the upper limit dummySampler.sample(); // Do a test of the actual sampler final SharedStateDiscreteSampler sampler = MarsagliaTsangWangDiscreteSampler.Enumerated.of(rng, probabilities); final int numberOfSamples = 10000; final long[] samples = new long[probabilities.length]; for (int i = 0; i < numberOfSamples; i++) { samples[sampler.sample()]++; } final ChiSquareTest chiSquareTest = new ChiSquareTest(); // Pass if we cannot reject null hypothesis that the distributions are the same. Assertions.assertFalse(chiSquareTest.chiSquareTest(probabilities, samples, 0.001)); } /** * Test the storage requirements for a worst case set of 2^8 probabilities. This tests the * limits described in the class Javadoc is correct. */ @Test void testStorageRequirements8() { // Max digits from 2^22: // (2^4 + 2^6 + 2^6 + 2^6) // Storage in bytes // = (15 + 3 * 63) * 2^8 // = 52224 B // = 0.0522 MB checkStorageRequirements(8, 0.06); } /** * Test the storage requirements for a worst case set of 2^16 probabilities. This tests the * limits described in the class Javadoc is correct. */ @Test void testStorageRequirements16() { // Max digits from 2^14: // (2^2 + 2^6 + 2^6) // Storage in bytes // = 2 * (3 + 2 * 63) * 2^16 // = 16908288 B // = 16.91 MB checkStorageRequirements(16, 17.0); } /** * Test the storage requirements for a worst case set of 2^k probabilities. This * tests the limits described in the class Javadoc is correct. * * @param k Base is 2^k. * @param expectedLimitMB Expected limit in MB. */ private static void checkStorageRequirements(int k, double expectedLimitMB) { // Worst case scenario is a uniform distribution of 2^k samples each with the highest // mask set for base 64 digits. // The max number of samples: 2^k final int maxSamples = 1 << k; // The highest value for each sample: // 2^30 / 2^k = 2^(30-k) // The highest mask is all bits set final int m = (1 << (30 - k)) - 1; // Check the sum is less than 2^30 final long sum = (long) maxSamples * m; final int total = 1 << 30; Assertions.assertTrue(sum < total, "Worst case uniform distribution is above 2^30"); // Get the digits as per the sampler and compute storage final int d1 = getBase64Digit(m, 1); final int d2 = getBase64Digit(m, 2); final int d3 = getBase64Digit(m, 3); final int d4 = getBase64Digit(m, 4); final int d5 = getBase64Digit(m, 5); // Compute storage in MB assuming 2 byte storage int bytes; if (k <= 8) { bytes = 1; } else if (k <= 16) { bytes = 2; } else { bytes = 4; } final double storageMB = bytes * 1e-6 * (d1 + d2 + d3 + d4 + d5) * maxSamples; Assertions.assertTrue(storageMB < expectedLimitMB, () -> "Worst case uniform distribution storage " + storageMB + "MB is above expected limit: " + expectedLimitMB); } /** * Gets the k<sup>th</sup> base 64 digit of {@code m}. * * @param m Value m. * @param k Digit. * @return the base 64 digit */ private static int getBase64Digit(int m, int k) { return (m >>> (30 - 6 * k)) & 63; } /** * Test the Poisson distribution with a bad mean that is above the supported range. */ @Test void testCreatePoissonDistributionThrowsWithMeanLargerThanUpperBound() { final UniformRandomProvider rng = new FixedRNG(); final double mean = 1025; Assertions.assertThrows(IllegalArgumentException.class, () -> MarsagliaTsangWangDiscreteSampler.Poisson.of(rng, mean)); } /** * Test the Poisson distribution with a bad mean that is below the supported range. */ @Test void testCreatePoissonDistributionThrowsWithZeroMean() { final UniformRandomProvider rng = new FixedRNG(); final double mean = 0; Assertions.assertThrows(IllegalArgumentException.class, () -> MarsagliaTsangWangDiscreteSampler.Poisson.of(rng, mean)); } /** * Test the Poisson distribution with the maximum mean. */ @Test void testCreatePoissonDistributionWithMaximumMean() { final UniformRandomProvider rng = new FixedRNG(); final double mean = 1024; final DiscreteSampler sampler = MarsagliaTsangWangDiscreteSampler.Poisson.of(rng, mean); // Note: No assertions. This will throw if the table does not sum to 2^30 // as the RNG outputs the maximum index into the look-up tables. sampler.sample(); } /** * Test the Poisson distribution with a small mean that hits the edge case where the * probability sum is not 2^30. */ @Test void testCreatePoissonDistributionWithSmallMean() { final UniformRandomProvider rng = new FixedRNG(); final double mean = 0.25; final DiscreteSampler sampler = MarsagliaTsangWangDiscreteSampler.Poisson.of(rng, mean); // Note: No assertions. This will throw if the table does not sum to 2^30 // as the RNG outputs the maximum index into the look-up tables. sampler.sample(); } /** * Test the Poisson distribution with a medium mean that is at the switch point * for how the probability distribution is computed. This hits the edge case * where the loop from the mean decrements to reach zero. */ @Test void testCreatePoissonDistributionWithMediumMean() { final UniformRandomProvider rng = new FixedRNG(); final double mean = 21.4; final DiscreteSampler sampler = MarsagliaTsangWangDiscreteSampler.Poisson.of(rng, mean); // Note: No assertions. This will throw if the table does not sum to 2^30 // as the RNG outputs the maximum index into the look-up tables. sampler.sample(); } /** * Test the Binomial distribution with a bad number of trials. */ @Test void testCreateBinomialDistributionThrowsWithTrialsBelow0() { final UniformRandomProvider rng = new FixedRNG(); final int trials = -1; final double p = 0.5; Assertions.assertThrows(IllegalArgumentException.class, () -> MarsagliaTsangWangDiscreteSampler.Binomial.of(rng, trials, p)); } /** * Test the Binomial distribution with an unsupported number of trials. */ @Test void testCreateBinomialDistributionThrowsWithTrialsAboveMax() { final UniformRandomProvider rng = new FixedRNG(); final int trials = 1 << 16; // 2^16 final double p = 0.5; Assertions.assertThrows(IllegalArgumentException.class, () -> MarsagliaTsangWangDiscreteSampler.Binomial.of(rng, trials, p)); } /** * Test the Binomial distribution with probability {@code < 0}. */ @Test void testCreateBinomialDistributionThrowsWithProbabilityBelow0() { final UniformRandomProvider rng = new FixedRNG(); final int trials = 1; final double p = -0.5; Assertions.assertThrows(IllegalArgumentException.class, () -> MarsagliaTsangWangDiscreteSampler.Binomial.of(rng, trials, p)); } /** * Test the Binomial distribution with probability {@code > 1}. */ @Test void testCreateBinomialDistributionThrowsWithProbabilityAbove1() { final UniformRandomProvider rng = new FixedRNG(); final int trials = 1; final double p = 1.5; Assertions.assertThrows(IllegalArgumentException.class, () -> MarsagliaTsangWangDiscreteSampler.Binomial.of(rng, trials, p)); } /** * Test the Binomial distribution with distribution parameters that create a very small p(0) * with a high probability of success. */ @Test void testCreateBinomialDistributionWithSmallestP0ValueAndHighestProbabilityOfSuccess() { final UniformRandomProvider rng = new FixedRNG(); // p(0) = Math.exp(trials * Math.log(1-p)) // p(0) will be smaller as Math.log(1-p) is more negative, which occurs when p is // larger. // Since the sampler uses inversion the largest value for p is 0.5. // At the extreme for p = 0.5: // trials = Math.log(p(0)) / Math.log(1-p) // = Math.log(Double.MIN_VALUE) / Math.log(0.5) // = 1074 final int trials = (int) Math.floor(Math.log(Double.MIN_VALUE) / Math.log(0.5)); final double p = 0.5; // Validate set-up Assertions.assertEquals(Double.MIN_VALUE, getBinomialP0(trials, p), 0, "Invalid test set-up for p(0)"); Assertions.assertEquals(0, getBinomialP0(trials + 1, p), 0, "Invalid test set-up for p(0)"); // This will throw if the table does not sum to 2^30 final DiscreteSampler sampler = MarsagliaTsangWangDiscreteSampler.Binomial.of(rng, trials, p); sampler.sample(); } /** * Test the Binomial distribution with distribution parameters that create a p(0) * that is zero (thus the distribution cannot be computed). */ @Test void testCreateBinomialDistributionThrowsWhenP0IsZero() { final UniformRandomProvider rng = new FixedRNG(); // As above but increase the trials so p(0) should be zero final int trials = 1 + (int) Math.floor(Math.log(Double.MIN_VALUE) / Math.log(0.5)); final double p = 0.5; // Validate set-up Assertions.assertEquals(0, getBinomialP0(trials, p), 0, "Invalid test set-up for p(0)"); Assertions.assertThrows(IllegalArgumentException.class, () -> MarsagliaTsangWangDiscreteSampler.Binomial.of(rng, trials, p)); } /** * Test the Binomial distribution with distribution parameters that create a very small p(0) * with a high number of trials. */ @Test void testCreateBinomialDistributionWithLargestTrialsAndSmallestProbabilityOfSuccess() { final UniformRandomProvider rng = new FixedRNG(); // p(0) = Math.exp(trials * Math.log(1-p)) // p(0) will be smaller as Math.log(1-p) is more negative, which occurs when p is // larger. // Since the sampler uses inversion the largest value for p is 0.5. // At the extreme for trials = 2^16-1: // p = 1 - Math.exp(Math.log(p(0)) / trials) // = 1 - Math.exp(Math.log(Double.MIN_VALUE) / trials) // = 0.011295152668039599 final int trials = (1 << 16) - 1; double p = 1 - Math.exp(Math.log(Double.MIN_VALUE) / trials); // Validate set-up Assertions.assertEquals(Double.MIN_VALUE, getBinomialP0(trials, p), 0, "Invalid test set-up for p(0)"); // Search for larger p until Math.nextUp(p) produces 0 double upper = p * 2; Assertions.assertEquals(0, getBinomialP0(trials, upper), 0, "Invalid test set-up for p(0)"); double lower = p; while (Double.doubleToRawLongBits(lower) + 1 < Double.doubleToRawLongBits(upper)) { final double mid = (upper + lower) / 2; if (getBinomialP0(trials, mid) == 0) { upper = mid; } else { lower = mid; } } p = lower; // Re-validate Assertions.assertEquals(Double.MIN_VALUE, getBinomialP0(trials, p), 0, "Invalid test set-up for p(0)"); Assertions.assertEquals(0, getBinomialP0(trials, Math.nextUp(p)), 0, "Invalid test set-up for p(0)"); final DiscreteSampler sampler = MarsagliaTsangWangDiscreteSampler.Binomial.of(rng, trials, p); // This will throw if the table does not sum to 2^30 sampler.sample(); } /** * Gets the p(0) value for the Binomial distribution. * * @param trials Number of trials. * @param probabilityOfSuccess Probability of success. * @return the p(0) value */ private static double getBinomialP0(int trials, double probabilityOfSuccess) { return Math.exp(trials * Math.log(1 - probabilityOfSuccess)); } /** * Test the Binomial distribution with a probability of 0 where the sampler should equal 0. */ @Test void testCreateBinomialDistributionWithProbability0() { final UniformRandomProvider rng = new FixedRNG(); final int trials = 1000000; final double p = 0; final DiscreteSampler sampler = MarsagliaTsangWangDiscreteSampler.Binomial.of(rng, trials, p); for (int i = 0; i < 5; i++) { Assertions.assertEquals(0, sampler.sample()); } // Hit the toString() method Assertions.assertTrue(sampler.toString().contains("Binomial")); } /** * Test the Binomial distribution with a probability of 1 where the sampler should equal * the number of trials. */ @Test void testCreateBinomialDistributionWithProbability1() { final UniformRandomProvider rng = new FixedRNG(); final int trials = 1000000; final double p = 1; final DiscreteSampler sampler = MarsagliaTsangWangDiscreteSampler.Binomial.of(rng, trials, p); for (int i = 0; i < 5; i++) { Assertions.assertEquals(trials, sampler.sample()); } // Hit the toString() method Assertions.assertTrue(sampler.toString().contains("Binomial")); } /** * Test the sampler with a large number of trials. This tests the sampler can create the * Binomial distribution for a large size when a limiting distribution (e.g. the Normal distribution) * could be used instead. */ @Test void testCreateBinomialDistributionWithLargeNumberOfTrials() { final UniformRandomProvider rng = new FixedRNG(); final int trials = 65000; final double p = 0.01; final DiscreteSampler sampler = MarsagliaTsangWangDiscreteSampler.Binomial.of(rng, trials, p); // Note: No assertions. This will throw if the table does not sum to 2^30 // as the RNG outputs the maximum index into the look-up tables. sampler.sample(); } /** * Test the sampler with a probability of 0.5. This should hit the edge case in the loop to * search for the last probability of the Binomial distribution. */ @Test void testCreateBinomialDistributionWithProbability50Percent() { final UniformRandomProvider rng = new FixedRNG(); final int trials = 10; final double p = 0.5; final DiscreteSampler sampler = MarsagliaTsangWangDiscreteSampler.Binomial.of(rng, trials, p); // Note: No assertions. This will throw if the table does not sum to 2^30 // as the RNG outputs the maximum index into the look-up tables. sampler.sample(); } /** * Test the sampler with a probability that requires inversion has the same name for * {@link Object#toString()}. */ @Test void testBinomialSamplerToString() { final UniformRandomProvider rng = new FixedRNG(); final int trials = 10; final double p1 = 0.4; final double p2 = 1 - p1; final DiscreteSampler sampler1 = MarsagliaTsangWangDiscreteSampler.Binomial.of(rng, trials, p1); final DiscreteSampler sampler2 = MarsagliaTsangWangDiscreteSampler.Binomial.of(rng, trials, p2); Assertions.assertEquals(sampler1.toString(), sampler2.toString()); } /** * Test the SharedStateSampler implementation with the 8-bit storage implementation. */ @Test void testSharedStateSamplerWith8bitStorage() { testSharedStateSampler(0, new int[] {1, 2, 3, 4, 5}); } /** * Test the SharedStateSampler implementation with the 16-bit storage implementation. */ @Test void testSharedStateSamplerWith16bitStorage() { testSharedStateSampler(1 << 8, new int[] {1, 2, 3, 4, 5}); } /** * Test the SharedStateSampler implementation with the 32-bit storage implementation. */ @Test void testSharedStateSamplerWith32bitStorage() { testSharedStateSampler(1 << 16, new int[] {1, 2, 3, 4, 5}); } /** * Test the SharedStateSampler implementation using zero padded probabilities to force * different storage implementations. * * @param offset Offset for first given probability (i.e. the zero padding size). * @param prob Probability values. */ private static void testSharedStateSampler(int offset, int[] prob) { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); double[] probabilities = createProbabilities(offset, prob); final SharedStateDiscreteSampler sampler1 = MarsagliaTsangWangDiscreteSampler.Enumerated.of(rng1, probabilities); final SharedStateDiscreteSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * Test the SharedStateSampler implementation with a Binomial distribution with a fixed result. */ @Test void testSharedStateSamplerWithFixedBinomialDistribution() { testSharedStateSampler(10, 1.0); } /** * Test the SharedStateSampler implementation with a Binomial distribution that requires * inversion (probability of success > 0.5). */ @Test void testSharedStateSamplerWithInvertedBinomialDistribution() { testSharedStateSampler(10, 0.999); } /** * Test the SharedStateSampler implementation using a binomial distribution to exercise * special implementations. * * @param trials Number of trials. * @param probabilityOfSuccess Probability of success. */ private static void testSharedStateSampler(int trials, double probabilityOfSuccess) { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final SharedStateDiscreteSampler sampler1 = MarsagliaTsangWangDiscreteSampler.Binomial.of(rng1, trials, probabilityOfSuccess); final SharedStateDiscreteSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * Return a fixed sequence of {@code int} output. */ private static class FixedSequenceIntProvider extends IntProvider { /** The count of values output. */ private int count; /** The values. */ private final int[] values; /** * Instantiates a new fixed sequence int provider. * * @param values Values. */ FixedSequenceIntProvider(int[] values) { this.values = values; } @Override public int next() { // This should not be called enough to overflow count return values[count++ % values.length]; } } /** * A RNG returning a fixed {@code int} value with all the bits set. */ private static class FixedRNG extends IntProvider { @Override public int next() { return 0xffffffff; } } }
2,944
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/LevySamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.core.source64.SplitMix64; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test for the {@link LevySampler}. */ class LevySamplerTest { /** * Test the constructor with a negative scale. */ @Test void testConstructorThrowsWithNegativeScale() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final double location = 1; final double scale = -1e-6; Assertions.assertThrows(IllegalArgumentException.class, () -> LevySampler.of(rng, location, scale)); } /** * Test the constructor with a zero scale. */ @Test void testConstructorThrowsWithZeroScale() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final double location = 1; final double scale = 0; Assertions.assertThrows(IllegalArgumentException.class, () -> LevySampler.of(rng, location, scale)); } /** * Test the SharedStateSampler implementation. */ @Test void testSharedStateSampler() { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final double location = 4.56; final double scale = 1.23; final LevySampler sampler1 = LevySampler.of(rng1, location, scale); final LevySampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * Test the support of the standard distribution is {@code [0, inf)}. */ @Test void testSupport() { final double location = 0.0; final double scale = 1.0; // Force the underlying ZigguratSampler.NormalizedGaussian to create 0 final LevySampler s1 = LevySampler.of( new SplitMix64(0L) { @Override public long next() { return 0L; } }, location, scale); Assertions.assertEquals(Double.POSITIVE_INFINITY, s1.sample()); // Force the underlying ZigguratSampler.NormalizedGaussian to create a large // sample in the tail of the distribution. // The first two -1,-1 values enters the tail of the distribution. // Here an exponential is added to 3.6360066255009455861. // The exponential also requires -1,-1 to recurse. Each recursion adds 7.569274694148063 // to the exponential. A value of 0 stops recursion with a sample of 0. // Two exponentials are required: x and y. // The exponential is multiplied by 0.27502700159745347 to create x. // The condition 2y >= x^x must be true to return x. // Create x = 4 * 7.57 and y = 16 * 7.57 final long[] sequence = { // Sample the Gaussian tail -1, -1, // Exponential x = 4 * 7.57... * 0.275027001597525 -1, -1, -1, -1, -1, -1, -1, -1, 0, // Exponential y = 16 * 7.57... -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, }; final LevySampler s2 = LevySampler.of( new SplitMix64(0L) { private int i; @Override public long next() { if (i++ < sequence.length) { return sequence[i - 1]; } return super.next(); } }, location, scale); // The tail of the zigguart should be approximately s=11.963 final double s = 4 * 7.569274694148063 * 0.27502700159745347 + 3.6360066255009455861; // expected is 1/s^2 = 0.006987 // So the sampler never achieves the lower bound of zero. // It requires an extreme deviate from the Gaussian. final double expected = 1 / (s * s); Assertions.assertEquals(expected, s2.sample()); } }
2,945
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/GaussianSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.apache.commons.rng.sampling.SharedStateSampler; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test for the {@link GaussianSampler}. The tests hit edge cases for the sampler. */ class GaussianSamplerTest { /** * Test the constructor with a zero standard deviation. */ @Test void testConstructorThrowsWithZeroStandardDeviation() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final NormalizedGaussianSampler gauss = ZigguratSampler.NormalizedGaussian.of(rng); final double mean = 1; final double standardDeviation = 0; Assertions.assertThrows(IllegalArgumentException.class, () -> GaussianSampler.of(gauss, mean, standardDeviation)); } /** * Test the constructor with an infinite standard deviation. */ @Test void testConstructorThrowsWithInfiniteStandardDeviation() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final NormalizedGaussianSampler gauss = new ZigguratNormalizedGaussianSampler(rng); final double mean = 1; final double standardDeviation = Double.POSITIVE_INFINITY; Assertions.assertThrows(IllegalArgumentException.class, () -> GaussianSampler.of(gauss, mean, standardDeviation)); } /** * Test the constructor with a NaN standard deviation. */ @Test void testConstructorThrowsWithNaNStandardDeviation() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final NormalizedGaussianSampler gauss = new ZigguratNormalizedGaussianSampler(rng); final double mean = 1; final double standardDeviation = Double.NaN; Assertions.assertThrows(IllegalArgumentException.class, () -> GaussianSampler.of(gauss, mean, standardDeviation)); } /** * Test the constructor with an infinite mean. */ @Test void testConstructorThrowsWithInfiniteMean() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final NormalizedGaussianSampler gauss = new ZigguratNormalizedGaussianSampler(rng); final double mean = Double.POSITIVE_INFINITY; final double standardDeviation = 1; Assertions.assertThrows(IllegalArgumentException.class, () -> GaussianSampler.of(gauss, mean, standardDeviation)); } /** * Test the constructor with a NaN mean. */ @Test void testConstructorThrowsWithNaNMean() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final NormalizedGaussianSampler gauss = new ZigguratNormalizedGaussianSampler(rng); final double mean = Double.NaN; final double standardDeviation = 1; Assertions.assertThrows(IllegalArgumentException.class, () -> GaussianSampler.of(gauss, mean, standardDeviation)); } /** * Test the SharedStateSampler implementation. */ @Test void testSharedStateSampler() { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final NormalizedGaussianSampler gauss = ZigguratSampler.NormalizedGaussian.of(rng1); final double mean = 1.23; final double standardDeviation = 4.56; final SharedStateContinuousSampler sampler1 = GaussianSampler.of(gauss, mean, standardDeviation); final SharedStateContinuousSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * Test the SharedStateSampler implementation throws if the underlying sampler is * not a SharedStateSampler. */ @Test void testSharedStateSamplerThrowsIfUnderlyingSamplerDoesNotShareState() { final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final NormalizedGaussianSampler gauss = new NormalizedGaussianSampler() { @Override public double sample() { return 0; } }; final double mean = 1.23; final double standardDeviation = 4.56; final SharedStateContinuousSampler sampler1 = GaussianSampler.of(gauss, mean, standardDeviation); Assertions.assertThrows(UnsupportedOperationException.class, () -> sampler1.withUniformRandomProvider(rng2)); } /** * Test the SharedStateSampler implementation throws if the underlying sampler is * a SharedStateSampler that returns an incorrect type. */ @Test void testSharedStateSamplerThrowsIfUnderlyingSamplerReturnsWrongSharedState() { final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final NormalizedGaussianSampler gauss = new BadSharedStateNormalizedGaussianSampler(); final double mean = 1.23; final double standardDeviation = 4.56; final SharedStateContinuousSampler sampler1 = GaussianSampler.of(gauss, mean, standardDeviation); Assertions.assertThrows(UnsupportedOperationException.class, () -> sampler1.withUniformRandomProvider(rng2)); } /** * Test class to return an incorrect sampler from the SharedStateSampler method. * * <p>Note that due to type erasure the type returned by the SharedStateSampler is not * available at run-time and the GaussianSampler has to assume it is the correct type.</p> */ private static class BadSharedStateNormalizedGaussianSampler implements NormalizedGaussianSampler, SharedStateSampler<Integer> { @Override public double sample() { return 0; } @Override public Integer withUniformRandomProvider(UniformRandomProvider rng) { // Something that is not a NormalizedGaussianSampler return Integer.valueOf(44); } } }
2,946
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/ChengBetaSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test for the {@link ChengBetaSampler}. The tests hit edge cases for the sampler. */ class ChengBetaSamplerTest { /** * Test the constructor with a bad alpha. */ @Test void testConstructorThrowsWithZeroAlpha() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final double alpha = 0; final double beta = 1; Assertions.assertThrows(IllegalArgumentException.class, () -> ChengBetaSampler.of(rng, alpha, beta)); } /** * Test the constructor with a bad beta. */ @Test void testConstructorThrowsWithZeroBeta() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final double alpha = 1; final double beta = 0; Assertions.assertThrows(IllegalArgumentException.class, () -> ChengBetaSampler.of(rng, alpha, beta)); } /** * Test the SharedStateSampler implementation. */ @Test void testSharedStateSamplerWithAlphaAndBetaAbove1AndAlphaBelowBeta() { testSharedStateSampler(1.23, 4.56); } /** * Test the SharedStateSampler implementation. */ @Test void testSharedStateSamplerWithAlphaAndBetaAbove1AndAlphaAboveBeta() { testSharedStateSampler(4.56, 1.23); } /** * Test the SharedStateSampler implementation. */ @Test void testSharedStateSamplerWithAlphaOrBetaBelow1AndAlphaBelowBeta() { testSharedStateSampler(0.23, 4.56); } /** * Test the SharedStateSampler implementation. */ @Test void testSharedStateSamplerWithAlphaOrBetaBelow1AndAlphaAboveBeta() { testSharedStateSampler(4.56, 0.23); } /** * Test the SharedStateSampler implementation. * * @param alpha Alpha. * @param beta Beta. */ private static void testSharedStateSampler(double alpha, double beta) { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); // Use instance constructor not factory constructor to exercise 1.X public API final SharedStateContinuousSampler sampler1 = new ChengBetaSampler(rng1, alpha, beta); final SharedStateContinuousSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * Test the toString method. This is added to ensure coverage as the factory constructor * used in other tests does not create an instance of the wrapper class. */ @Test void testToString() { final UniformRandomProvider rng = RandomAssert.seededRNG(); Assertions.assertTrue(new ChengBetaSampler(rng, 1.0, 2.0).toString() .toLowerCase().contains("beta")); } }
2,947
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/DiscreteSamplerParametricTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.math3.stat.inference.ChiSquareTest; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; /** * Tests for random deviates generators. */ class DiscreteSamplerParametricTest { private static Iterable<DiscreteSamplerTestData> getSamplerTestData() { return DiscreteSamplersList.list(); } @ParameterizedTest @MethodSource("getSamplerTestData") void testSampling(DiscreteSamplerTestData data) { final int sampleSize = 10000; // Probabilities are normalised by the chi-square test check(sampleSize, data.getSampler(), data.getPoints(), data.getProbabilities()); } /** * Performs a chi-square test of homogeneity of the observed * distribution with the expected distribution. * An average failure rate higher than 5% causes the test case * to fail. * * @param sampler Sampler. * @param sampleSize Number of random values to generate. * @param points Outcomes. * @param expected Expected counts of the given outcomes. */ private static void check(long sampleSize, DiscreteSampler sampler, int[] points, double[] expected) { final ChiSquareTest chiSquareTest = new ChiSquareTest(); final int numTests = 50; // Run the tests. int numFailures = 0; final int numBins = points.length; final long[] observed = new long[numBins]; // For storing chi2 larger than the critical value. final List<Double> failedStat = new ArrayList<>(); try { for (int i = 0; i < numTests; i++) { Arrays.fill(observed, 0); SAMPLE: for (long j = 0; j < sampleSize; j++) { final int value = sampler.sample(); for (int k = 0; k < numBins; k++) { if (value == points[k]) { ++observed[k]; continue SAMPLE; } } } final double p = chiSquareTest.chiSquareTest(expected, observed); if (p < 0.01) { failedStat.add(p); ++numFailures; } } } catch (Exception e) { // Should never happen. throw new RuntimeException("Unexpected", e); } // The expected number of failed tests can be modelled as a Binomial distribution // B(n, p) with n=50, p=0.01 (50 tests with a 1% significance level). // The cumulative probability of the number of failed tests (X) is: // x P(X>x) // 1 0.0894 // 2 0.0138 // 3 0.0016 if (numFailures > 3) { // Test will fail with 0.16% probability Assertions.fail(String.format( "%s: Too many failures for sample size = %d " + " (%d out of %d tests failed, chi2=%s", sampler, sampleSize, numFailures, numTests, Arrays.toString(failedStat.toArray(new Double[0])))); } } }
2,948
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/AhrensDieterExponentialSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import java.time.Duration; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.core.source64.SplitMix64; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test for the {@link AhrensDieterExponentialSampler}. The tests hit edge cases for the sampler. */ class AhrensDieterExponentialSamplerTest { /** * Test the constructor with a bad mean. */ @Test void testConstructorThrowsWithZeroMean() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final double mean = 0; Assertions.assertThrows(IllegalArgumentException.class, () -> AhrensDieterExponentialSampler.of(rng, mean)); } /** * Test the SharedStateSampler implementation. */ @Test void testSharedStateSampler() { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final double mean = 1.23; final SharedStateContinuousSampler sampler1 = AhrensDieterExponentialSampler.of(rng1, mean); final SharedStateContinuousSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * Test the sampler is robust to a generator that outputs zeros. * See RNG-144. */ @Test void testSamplerWithZeroFromRandomGenerator() { // A broken generator that returns zero. final UniformRandomProvider rng = new SplitMix64(0) { @Override public long nextLong() { return 0L; } }; final SharedStateContinuousSampler sampler = AhrensDieterExponentialSampler.of(rng, 1); // This should not infinite loop final double[] x = {-1}; Assertions.assertTimeout(Duration.ofMillis(50), () -> { x[0] = sampler.sample(); }); Assertions.assertTrue(x[0] >= 0); } /** * Test the sampler is robust to a generator that outputs full bits. The uniform random * double will be at the top of the range {@code [0, 1]}. */ @Test void testSamplerWithOneFromRandomGenerator() { // A broken generator that returns all the bits set. final UniformRandomProvider rng = new SplitMix64(0) { @Override public long nextLong() { // All the bits set return -1; } }; final SharedStateContinuousSampler sampler = AhrensDieterExponentialSampler.of(rng, 1); final double x = sampler.sample(); Assertions.assertTrue(x >= 0); } }
2,949
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/SamplerBaseTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test for the {@link SamplerBase}. The class is deprecated but is public. The methods * should be tested to ensure correct functionality. */ @SuppressWarnings("deprecation") class SamplerBaseTest { @Test void testNextMethods() { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final SamplerBase sampler = new SamplerBase(rng2); final int n = 256; for (int i = 0; i < 3; i++) { Assertions.assertEquals(rng1.nextDouble(), sampler.nextDouble()); Assertions.assertEquals(rng1.nextInt(), sampler.nextInt()); Assertions.assertEquals(rng1.nextInt(n), sampler.nextInt(n)); Assertions.assertEquals(rng1.nextLong(), sampler.nextLong()); } } @Test void testToString() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final SamplerBase sampler = new SamplerBase(rng); Assertions.assertTrue(sampler.toString().contains("rng")); } }
2,950
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/BoxMullerLogNormalSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test for the {@link BoxMullerLogNormalSampler}. The tests hit edge cases for the sampler. */ class BoxMullerLogNormalSamplerTest { /** * Test the constructor with a bad standard deviation. */ @SuppressWarnings({"deprecation"}) @Test void testConstructorThrowsWithZeroShape() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final double mu = 1; final double sigma = 0; Assertions.assertThrows(IllegalArgumentException.class, () -> new BoxMullerLogNormalSampler(rng, mu, sigma)); } }
2,951
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/ContinuousSamplersList.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; /** * List of samplers. */ public final class ContinuousSamplersList { /** List of all RNGs implemented in the library. */ private static final List<ContinuousSamplerTestData> LIST = new ArrayList<>(); static { try { // This test uses reference distributions from commons-math3 to compute the expected // PMF. These distributions have a dual functionality to compute the PMF and perform // sampling. When no sampling is needed for the created distribution, it is advised // to pass null as the random generator via the appropriate constructors to avoid the // additional initialisation overhead. org.apache.commons.math3.random.RandomGenerator unusedRng = null; // List of distributions to test. // Gaussian ("inverse method"). final double meanNormal = -123.45; final double sigmaNormal = 6.789; add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, meanNormal, sigmaNormal), RandomAssert.createRNG()); // Gaussian (DEPRECATED "Box-Muller"). add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, meanNormal, sigmaNormal), new BoxMullerGaussianSampler(RandomAssert.createRNG(), meanNormal, sigmaNormal)); // Gaussian ("Box-Muller"). add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, meanNormal, sigmaNormal), GaussianSampler.of(new BoxMullerNormalizedGaussianSampler(RandomAssert.createRNG()), meanNormal, sigmaNormal)); // Gaussian ("Marsaglia"). add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, meanNormal, sigmaNormal), GaussianSampler.of(new MarsagliaNormalizedGaussianSampler(RandomAssert.createRNG()), meanNormal, sigmaNormal)); // Gaussian ("Ziggurat"). add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, meanNormal, sigmaNormal), GaussianSampler.of(new ZigguratNormalizedGaussianSampler(RandomAssert.createRNG()), meanNormal, sigmaNormal)); // Gaussian ("Modified ziggurat"). add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, meanNormal, sigmaNormal), GaussianSampler.of(ZigguratSampler.NormalizedGaussian.of(RandomAssert.createRNG()), meanNormal, sigmaNormal)); // Beta ("inverse method"). final double alphaBeta = 4.3; final double betaBeta = 2.1; add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(unusedRng, alphaBeta, betaBeta), RandomAssert.createRNG()); // Beta ("Cheng"). add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(unusedRng, alphaBeta, betaBeta), ChengBetaSampler.of(RandomAssert.createRNG(), alphaBeta, betaBeta)); add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(unusedRng, betaBeta, alphaBeta), ChengBetaSampler.of(RandomAssert.createRNG(), betaBeta, alphaBeta)); // Beta ("Cheng", alternate algorithm). final double alphaBetaAlt = 0.5678; final double betaBetaAlt = 0.1234; add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(unusedRng, alphaBetaAlt, betaBetaAlt), ChengBetaSampler.of(RandomAssert.createRNG(), alphaBetaAlt, betaBetaAlt)); add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(unusedRng, betaBetaAlt, alphaBetaAlt), ChengBetaSampler.of(RandomAssert.createRNG(), betaBetaAlt, alphaBetaAlt)); // Cauchy ("inverse method"). final double medianCauchy = 0.123; final double scaleCauchy = 4.5; add(LIST, new org.apache.commons.math3.distribution.CauchyDistribution(unusedRng, medianCauchy, scaleCauchy), RandomAssert.createRNG()); // Chi-square ("inverse method"). final int dofChi2 = 12; add(LIST, new org.apache.commons.math3.distribution.ChiSquaredDistribution(unusedRng, dofChi2), RandomAssert.createRNG()); // Exponential ("inverse method"). final double meanExp = 3.45; add(LIST, new org.apache.commons.math3.distribution.ExponentialDistribution(unusedRng, meanExp), RandomAssert.createRNG()); // Exponential. add(LIST, new org.apache.commons.math3.distribution.ExponentialDistribution(unusedRng, meanExp), AhrensDieterExponentialSampler.of(RandomAssert.createRNG(), meanExp)); // Exponential ("Modified ziggurat"). add(LIST, new org.apache.commons.math3.distribution.ExponentialDistribution(unusedRng, meanExp), ZigguratSampler.Exponential.of(RandomAssert.createRNG(), meanExp)); // F ("inverse method"). final int numDofF = 4; final int denomDofF = 7; add(LIST, new org.apache.commons.math3.distribution.FDistribution(unusedRng, numDofF, denomDofF), RandomAssert.createRNG()); // Gamma ("inverse method"). final double alphaGammaSmallerThanOne = 0.1234; final double alphaGammaLargerThanOne = 2.345; final double thetaGamma = 3.456; add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(unusedRng, alphaGammaLargerThanOne, thetaGamma), RandomAssert.createRNG()); // Gamma (alpha < 1). add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(unusedRng, alphaGammaSmallerThanOne, thetaGamma), AhrensDieterMarsagliaTsangGammaSampler.of(RandomAssert.createRNG(), alphaGammaSmallerThanOne, thetaGamma)); // Gamma (alpha > 1). add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(unusedRng, alphaGammaLargerThanOne, thetaGamma), AhrensDieterMarsagliaTsangGammaSampler.of(RandomAssert.createRNG(), alphaGammaLargerThanOne, thetaGamma)); // Gumbel ("inverse method"). final double muGumbel = -4.56; final double betaGumbel = 0.123; add(LIST, new org.apache.commons.math3.distribution.GumbelDistribution(unusedRng, muGumbel, betaGumbel), RandomAssert.createRNG()); // Laplace ("inverse method"). final double muLaplace = 12.3; final double betaLaplace = 5.6; add(LIST, new org.apache.commons.math3.distribution.LaplaceDistribution(unusedRng, muLaplace, betaLaplace), RandomAssert.createRNG()); // Levy ("inverse method"). final double muLevy = -1.098; final double cLevy = 0.76; add(LIST, new org.apache.commons.math3.distribution.LevyDistribution(unusedRng, muLevy, cLevy), RandomAssert.createRNG()); // Levy sampler add(LIST, new org.apache.commons.math3.distribution.LevyDistribution(unusedRng, muLevy, cLevy), LevySampler.of(RandomAssert.createRNG(), muLevy, cLevy)); add(LIST, new org.apache.commons.math3.distribution.LevyDistribution(unusedRng, 0.0, 1.0), LevySampler.of(RandomAssert.createRNG(), 0.0, 1.0)); // Log normal ("inverse method"). final double muLogNormal = 2.345; final double sigmaLogNormal = 0.1234; add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(unusedRng, muLogNormal, sigmaLogNormal), RandomAssert.createRNG()); // Log-normal (DEPRECATED "Box-Muller"). add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(unusedRng, muLogNormal, sigmaLogNormal), new BoxMullerLogNormalSampler(RandomAssert.createRNG(), muLogNormal, sigmaLogNormal)); // Log-normal ("Box-Muller"). add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(unusedRng, muLogNormal, sigmaLogNormal), LogNormalSampler.of(new BoxMullerNormalizedGaussianSampler(RandomAssert.createRNG()), muLogNormal, sigmaLogNormal)); // Log-normal ("Marsaglia"). add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(unusedRng, muLogNormal, sigmaLogNormal), LogNormalSampler.of(new MarsagliaNormalizedGaussianSampler(RandomAssert.createRNG()), muLogNormal, sigmaLogNormal)); // Log-normal ("Ziggurat"). add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(unusedRng, muLogNormal, sigmaLogNormal), LogNormalSampler.of(new ZigguratNormalizedGaussianSampler(RandomAssert.createRNG()), muLogNormal, sigmaLogNormal)); // Log-normal negative mean final double muLogNormal2 = -1.1; final double sigmaLogNormal2 = 2.3; add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(unusedRng, muLogNormal2, sigmaLogNormal2), LogNormalSampler.of(new ZigguratNormalizedGaussianSampler(RandomAssert.createRNG()), muLogNormal2, sigmaLogNormal2)); // Logistic ("inverse method"). final double muLogistic = -123.456; final double sLogistic = 7.89; add(LIST, new org.apache.commons.math3.distribution.LogisticDistribution(unusedRng, muLogistic, sLogistic), RandomAssert.createRNG()); // Nakagami ("inverse method"). final double muNakagami = 78.9; final double omegaNakagami = 23.4; final double inverseAbsoluteAccuracyNakagami = org.apache.commons.math3.distribution.NakagamiDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY; add(LIST, new org.apache.commons.math3.distribution.NakagamiDistribution(unusedRng, muNakagami, omegaNakagami, inverseAbsoluteAccuracyNakagami), RandomAssert.createRNG()); // Pareto ("inverse method"). final double scalePareto = 23.45; final double shapePareto = 0.1234; add(LIST, new org.apache.commons.math3.distribution.ParetoDistribution(unusedRng, scalePareto, shapePareto), RandomAssert.createRNG()); // Pareto. add(LIST, new org.apache.commons.math3.distribution.ParetoDistribution(unusedRng, scalePareto, shapePareto), InverseTransformParetoSampler.of(RandomAssert.createRNG(), scalePareto, shapePareto)); // Large shape final double shapePareto2 = 12.34; add(LIST, new org.apache.commons.math3.distribution.ParetoDistribution(unusedRng, scalePareto, shapePareto2), InverseTransformParetoSampler.of(RandomAssert.createRNG(), scalePareto, shapePareto2)); // Stable distributions. // Gaussian case: alpha=2 add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, 0, Math.sqrt(2)), StableSampler.of(RandomAssert.createRNG(), 2, 0)); add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, 3.4, 0.75 * Math.sqrt(2)), StableSampler.of(RandomAssert.createRNG(), 2, 0, 0.75, 3.4)); // Cauchy case: alpha=1, beta=0, gamma=2.73, delta=0.87 add(LIST, new org.apache.commons.math3.distribution.CauchyDistribution(unusedRng, 0.87, 2.73), StableSampler.of(RandomAssert.createRNG(), 1, 0, 2.73, 0.87)); // Levy case: alpha=0.5, beta=0, gamma=5.7, delta=-1.23 // The 0-parameterization requires the reference distribution (1-parameterization) is shifted: // S0(Z) = S1(Z) + gamma * beta * tan(pi * alpha / 2); gamma = 5.7, beta = -1, alpha = 0.5 // = gamma * -1 * tan(pi/4) = -gamma add(LIST, new org.apache.commons.math3.distribution.LevyDistribution(unusedRng, -1.23 - 5.7, 5.7), StableSampler.of(RandomAssert.createRNG(), 0.5, 1.0, 5.7, -1.23)); // Levy case: alpha=0.5, beta=0. // The 0-parameterization requires the reference distribution is shifted by -tan(pi/4) = -1 add(LIST, new org.apache.commons.math3.distribution.LevyDistribution(unusedRng, -1.0, 1.0), StableSampler.of(RandomAssert.createRNG(), 0.5, 1.0, 1.0, 0.0)); // No Stable distribution in Commons Math: Deciles computed using Nolan's STABLE program: // https://edspace.american.edu/jpnolan/stable/ // General case (alpha > 1): alpha=1.3, beta=0.4, gamma=1.5, delta=-6.4 add(LIST, new double[] {-8.95069776039550, -7.89186827865320, -7.25070352695719, -6.71497820795024, -6.19542020516881, -5.63245847779003, -4.94643432673952, -3.95462242999135, -1.90020994991840, Double.POSITIVE_INFINITY}, StableSampler.of(RandomAssert.createRNG(), 1.3, 0.4, 1.5, -6.4)); // General case (alpha < 1): alpha=0.8, beta=-0.3, gamma=0.75, delta=3.25 add(LIST, new double[] {-1.60557902637291, 1.45715153372767, 2.39577970333297, 2.86274746879986, 3.15907259287483, 3.38633464572309, 3.60858199662215, 3.96001854555454, 5.16261950198042, Double.POSITIVE_INFINITY}, StableSampler.of(RandomAssert.createRNG(), 0.8, -0.3, 0.75, 3.25)); // Alpha 1 case: alpha=1.0, beta=0.3 add(LIST, new double[] {-2.08189340389400, -0.990511737972781, -0.539025554211755, -0.204710171216492, 0.120388569770401, 0.497197960523146, 1.01228394387185, 1.89061920660563, 4.20559140293206, Double.POSITIVE_INFINITY}, StableSampler.of(RandomAssert.createRNG(), 1.0, 0.3)); // Symmetric case (beta=0): alpha=1.3, beta=0.0 add(LIST, new double[] {-2.29713832179280, -1.26781259700375, -0.739212223404616, -0.346771353386198, 0.00000000000000, 0.346771353386198, 0.739212223404616, 1.26781259700376, 2.29713832179280, Double.POSITIVE_INFINITY}, StableSampler.of(RandomAssert.createRNG(), 1.3, 0.0)); // This is the smallest alpha where the CDF can be reliably computed. // Small alpha case: alpha=0.1, beta=-0.2 add(LIST, new double[] {-14345498.0855558, -4841.68845914421, -22.6430159400915, -0.194461655962062, 0.299822962206354E-1, 0.316768853375197E-1, 0.519382255860847E-1, 21.8595769961580, 147637.033822552, Double.POSITIVE_INFINITY}, StableSampler.of(RandomAssert.createRNG(), 0.1, -0.2)); // T ("inverse method"). final double dofT = 0.76543; add(LIST, new org.apache.commons.math3.distribution.TDistribution(unusedRng, dofT), RandomAssert.createRNG()); // T. add(LIST, new org.apache.commons.math3.distribution.TDistribution(unusedRng, dofT), TSampler.of(RandomAssert.createRNG(), dofT)); // T with 'large' degrees of freedom. final double dofTlarge = 30; add(LIST, new org.apache.commons.math3.distribution.TDistribution(unusedRng, dofTlarge), TSampler.of(RandomAssert.createRNG(), dofTlarge)); // T with 'huge' degrees of freedom (approaches a normal distribution). // Deciles are computed incorrectly using Commons Math; values computed using Matlab. // Note: DF is below the switch to using a normal distribution. final double dofTHuge = 1e15; add(LIST, new double[] {-1.2815515655446015, -0.84162123357291463, -0.52440051270804089, -0.25334710313579983, 0, 0.25334710313579983, 0.52440051270804089, 0.84162123357291474, 1.2815515655446015, Double.POSITIVE_INFINITY}, TSampler.of(RandomAssert.createRNG(), dofTHuge)); // Triangular ("inverse method"). final double aTriangle = -0.76543; final double cTriangle = -0.65432; final double bTriangle = -0.54321; add(LIST, new org.apache.commons.math3.distribution.TriangularDistribution(unusedRng, aTriangle, cTriangle, bTriangle), RandomAssert.createRNG()); // Uniform ("inverse method"). final double loUniform = -1.098; final double hiUniform = 0.76; add(LIST, new org.apache.commons.math3.distribution.UniformRealDistribution(unusedRng, loUniform, hiUniform), RandomAssert.createRNG()); // Uniform. add(LIST, new org.apache.commons.math3.distribution.UniformRealDistribution(unusedRng, loUniform, hiUniform), ContinuousUniformSampler.of(RandomAssert.createRNG(), loUniform, hiUniform)); // Weibull ("inverse method"). final double alphaWeibull = 678.9; final double betaWeibull = 98.76; add(LIST, new org.apache.commons.math3.distribution.WeibullDistribution(unusedRng, alphaWeibull, betaWeibull), RandomAssert.createRNG()); } catch (Exception e) { // CHECKSTYLE: stop Regexp System.err.println("Unexpected exception while creating the list of samplers: " + e); e.printStackTrace(System.err); // CHECKSTYLE: resume Regexp throw new RuntimeException(e); } } /** * Class contains only static methods. */ private ContinuousSamplersList() {} /** * @param list List of data (one the "parameters" tested by the Junit parametric test). * @param dist Distribution to which the samples are supposed to conform. * @param rng Generator of uniformly distributed sequences. */ private static void add(List<ContinuousSamplerTestData> list, final org.apache.commons.math3.distribution.RealDistribution dist, UniformRandomProvider rng) { final ContinuousSampler inverseMethodSampler = InverseTransformContinuousSampler.of(rng, new ContinuousInverseCumulativeProbabilityFunction() { @Override public double inverseCumulativeProbability(double p) { return dist.inverseCumulativeProbability(p); } @Override public String toString() { return dist.toString(); } }); list.add(new ContinuousSamplerTestData(inverseMethodSampler, getDeciles(dist))); } /** * @param list List of data (one the "parameters" tested by the Junit parametric test). * @param dist Distribution to which the samples are supposed to conform. * @param sampler Sampler. */ private static void add(List<ContinuousSamplerTestData> list, final org.apache.commons.math3.distribution.RealDistribution dist, final ContinuousSampler sampler) { list.add(new ContinuousSamplerTestData(sampler, getDeciles(dist))); } /** * @param list List of data (one the "parameters" tested by the Junit parametric test). * @param deciles Deciles of the given distribution. * @param sampler Sampler. */ private static void add(List<ContinuousSamplerTestData> list, final double[] deciles, final ContinuousSampler sampler) { list.add(new ContinuousSamplerTestData(sampler, deciles)); } /** * Subclasses that are "parametric" tests can forward the call to * the "@Parameters"-annotated method to this method. * * @return the list of all generators. */ public static Iterable<ContinuousSamplerTestData> list() { return Collections.unmodifiableList(LIST); } /** * @param dist Distribution. * @return the deciles of the given distribution. */ private static double[] getDeciles(org.apache.commons.math3.distribution.RealDistribution dist) { final int last = 9; final double[] deciles = new double[last]; final double ten = 10; for (int i = 0; i < last; i++) { deciles[i] = dist.inverseCumulativeProbability((i + 1) / ten); } return deciles; } }
2,952
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/ContinuousUniformSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.core.source64.SplitMix64; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test for the {@link ContinuousUniformSampler}. */ class ContinuousUniformSamplerTest { /** * Test that the sampler algorithm does not require high to be above low. */ @Test void testNoRestrictionOnOrderOfLowAndHighParameters() { final double low = 3.18; final double high = 5.23; final UniformRandomProvider rng = RandomAssert.createRNG(); testSampleInRange(rng, low, high); testSampleInRange(rng, high, low); } private static void testSampleInRange(UniformRandomProvider rng, double low, double high) { final SharedStateContinuousSampler sampler = ContinuousUniformSampler.of(rng, low, high); final double min = Math.min(low, high); final double max = Math.max(low, high); for (int i = 0; i < 10; i++) { final double value = sampler.sample(); Assertions.assertTrue(value >= min && value <= max, () -> "Value not in range: " + value); } } /** * Test the sampler excludes the bounds when the underlying generator returns long values * that produce the limit of the uniform double output. */ @Test void testExcludeBounds() { // A broken RNG that will return in an alternating sequence from 0 up or -1 down. // This is either zero bits or all the bits final UniformRandomProvider rng = new SplitMix64(0L) { private long l1; private long l2; @Override public long nextLong() { long x; if (l1 > l2) { l2++; // Descending sequence: -1, -2, -3, ... x = -l2; } else { // Ascending sequence: 0, 1, 2, ... x = l1++; } // Shift by 11 bits to reverse the shift performed when computing the next // double from a long. return x << 11; } }; final double low = 3.18; final double high = 5.23; final SharedStateContinuousSampler sampler = ContinuousUniformSampler.of(rng, low, high, true); // Test the sampler excludes the end points for (int i = 0; i < 10; i++) { final double value = sampler.sample(); Assertions.assertTrue(value > low && value < high, () -> "Value not in range: " + value); } } /** * Test open intervals {@code (lower,upper)} where there are not enough double values * between the limits. */ @Test void testInvalidOpenIntervalThrows() { final UniformRandomProvider rng = RandomAssert.seededRNG(); for (final double[] interval : new double[][] { // Opposite signs. Require two doubles inside the range. {-0.0, 0.0}, {-0.0, Double.MIN_VALUE}, {-0.0, Double.MIN_VALUE * 2}, {-Double.MIN_VALUE, 0.0}, {-Double.MIN_VALUE * 2, 0.0}, {-Double.MIN_VALUE, Double.MIN_VALUE}, // Same signs. Requires one double inside the range. // Same exponent {1.23, Math.nextUp(1.23)}, {1.23, Math.nextUp(1.23)}, // Different exponent {2.0, Math.nextDown(2.0)}, }) { final double low = interval[0]; final double high = interval[1]; Assertions.assertThrows(IllegalArgumentException.class, () -> ContinuousUniformSampler.of(rng, low, high, true), () -> "(" + low + "," + high + ")"); Assertions.assertThrows(IllegalArgumentException.class, () -> ContinuousUniformSampler.of(rng, high, low, true), () -> "(" + high + "," + low + ")"); } // Valid. This will overflow if the raw long bits are extracted and // subtracted to obtain a ULP difference. ContinuousUniformSampler.of(rng, Double.MAX_VALUE, -Double.MAX_VALUE, true); } /** * Test open intervals {@code (lower,upper)} where there is only the minimum number of * double values between the limits. */ @Test void testTinyOpenIntervalSample() { final UniformRandomProvider rng = RandomAssert.seededRNG(); // Test sub-normal ranges final double x = Double.MIN_VALUE; for (final double expected : new double[] { 1.23, 2, 56787.7893, 3 * x, 2 * x, x }) { final double low = Math.nextUp(expected); final double high = Math.nextDown(expected); Assertions.assertEquals(expected, ContinuousUniformSampler.of(rng, low, high, true).sample()); Assertions.assertEquals(expected, ContinuousUniformSampler.of(rng, high, low, true).sample()); Assertions.assertEquals(-expected, ContinuousUniformSampler.of(rng, -low, -high, true).sample()); Assertions.assertEquals(-expected, ContinuousUniformSampler.of(rng, -high, -low, true).sample()); } // Special case of sampling around zero. // Requires 2 doubles inside the range. final double y = ContinuousUniformSampler.of(rng, -x, 2 * x, true).sample(); Assertions.assertTrue(-x < y && y < 2 * x); final double z = ContinuousUniformSampler.of(rng, -2 * x, x, true).sample(); Assertions.assertTrue(-2 * x < z && z < x); } /** * Test the SharedStateSampler implementation. */ @Test void testSharedStateSampler() { testSharedStateSampler(false); testSharedStateSampler(true); } /** * Test the SharedStateSampler implementation. * * @param excludedBounds Set to true to exclude the bounds. */ private static void testSharedStateSampler(boolean excludedBounds) { // Create RNGs that will generate a sample at the limits. // This tests the bounds excluded sampler correctly shares state. // Do this using a RNG that outputs 0 for the first nextDouble(). final UniformRandomProvider rng1 = new SplitMix64(0L) { private double x; @Override public double nextDouble() { final double y = x; x = super.nextDouble(); return y; } }; final UniformRandomProvider rng2 = new SplitMix64(0L) { private double x; @Override public double nextDouble() { final double y = x; x = super.nextDouble(); return y; } }; final double low = 1.23; final double high = 4.56; final SharedStateContinuousSampler sampler1 = ContinuousUniformSampler.of(rng1, low, high, excludedBounds); final SharedStateContinuousSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * Test the sampler implementation with bounds excluded matches that with bounds included * when the generator does not produce the limit of the uniform double output. */ @Test void testSamplerWithBoundsExcluded() { // SplitMix64 only returns zero once in the output. Seeded with zero it outputs zero // at the end of the period. final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final double low = 1.23; final double high = 4.56; final SharedStateContinuousSampler sampler1 = ContinuousUniformSampler.of(rng1, low, high, false); final SharedStateContinuousSampler sampler2 = ContinuousUniformSampler.of(rng2, low, high, true); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } }
2,953
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/AliasMethodDiscreteSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import java.util.Arrays; import org.apache.commons.math3.distribution.BinomialDistribution; import org.apache.commons.math3.distribution.PoissonDistribution; import org.apache.commons.math3.stat.inference.ChiSquareTest; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test for the {@link AliasMethodDiscreteSampler}. */ class AliasMethodDiscreteSamplerTest { @Test void testConstructorThrowsWithNullProbabilities() { Assertions.assertThrows(IllegalArgumentException.class, () -> createSampler(null)); } @Test void testConstructorThrowsWithZeroLengthProbabilities() { Assertions.assertThrows(IllegalArgumentException.class, () -> createSampler(new double[0])); } @Test void testConstructorThrowsWithNegativeProbabilities() { Assertions.assertThrows(IllegalArgumentException.class, () -> createSampler(new double[] {-1, 0.1, 0.2})); } @Test void testConstructorThrowsWithNaNProbabilities() { Assertions.assertThrows(IllegalArgumentException.class, () -> createSampler(new double[] {0.1, Double.NaN, 0.2})); } @Test void testConstructorThrowsWithInfiniteProbabilities() { Assertions.assertThrows(IllegalArgumentException.class, () -> createSampler(new double[] {0.1, Double.POSITIVE_INFINITY, 0.2})); } @Test void testConstructorThrowsWithInfiniteSumProbabilities() { Assertions.assertThrows(IllegalArgumentException.class, () -> createSampler(new double[] {Double.MAX_VALUE, Double.MAX_VALUE})); } @Test void testConstructorThrowsWithZeroSumProbabilities() { Assertions.assertThrows(IllegalArgumentException.class, () -> createSampler(new double[4])); } @Test void testToString() { final SharedStateDiscreteSampler sampler = createSampler(new double[] {0.5, 0.5}); Assertions.assertTrue(sampler.toString().toLowerCase().contains("alias method")); } /** * Creates the sampler without zero-padding enabled. * * @param probabilities the probabilities * @return the alias method discrete sampler */ private static SharedStateDiscreteSampler createSampler(double[] probabilities) { final UniformRandomProvider rng = RandomAssert.createRNG(); return AliasMethodDiscreteSampler.of(rng, probabilities, -1); } /** * Test sampling from a binomial distribution. */ @Test void testBinomialSamples() { final int trials = 67; final double probabilityOfSuccess = 0.345; final BinomialDistribution dist = new BinomialDistribution(trials, probabilityOfSuccess); final double[] expected = new double[trials + 1]; for (int i = 0; i < expected.length; i++) { expected[i] = dist.probability(i); } checkSamples(expected); } /** * Test sampling from a Poisson distribution. */ @Test void testPoissonSamples() { final double mean = 3.14; final PoissonDistribution dist = new PoissonDistribution(null, mean, PoissonDistribution.DEFAULT_EPSILON, PoissonDistribution.DEFAULT_MAX_ITERATIONS); final int maxN = dist.inverseCumulativeProbability(1 - 1e-6); double[] expected = new double[maxN]; for (int i = 0; i < expected.length; i++) { expected[i] = dist.probability(i); } checkSamples(expected); } /** * Test sampling from a non-uniform distribution of probabilities (these sum to 1). */ @Test void testNonUniformSamplesWithProbabilities() { final double[] expected = {0.1, 0.2, 0.3, 0.1, 0.3}; checkSamples(expected); } /** * Test sampling from a non-uniform distribution using the factory constructor to zero pad * the input probabilities. */ @Test void testNonUniformSamplesWithProbabilitiesWithDefaultFactoryConstructor() { final double[] expected = {0.1, 0.2, 0.3, 0.1, 0.3}; checkSamples(AliasMethodDiscreteSampler.of(RandomAssert.createRNG(), expected), expected); } /** * Test sampling from a non-uniform distribution of observations (i.e. the sum is not 1 as per * probabilities). */ @Test void testNonUniformSamplesWithObservations() { final double[] expected = {1, 2, 3, 1, 3}; checkSamples(expected); } /** * Test sampling from a non-uniform distribution of probabilities (these sum to 1). * Extra zero-values are added to make the table size a power of 2. */ @Test void testNonUniformSamplesWithProbabilitiesPaddedToPowerOf2() { final double[] expected = {0.1, 0, 0.2, 0.3, 0.1, 0.3, 0, 0}; checkSamples(expected); } /** * Test sampling from a non-uniform distribution of observations (i.e. the sum is not 1 as per * probabilities). Extra zero-values are added to make the table size a power of 2. */ @Test void testNonUniformSamplesWithObservationsPaddedToPowerOf2() { final double[] expected = {1, 2, 3, 0, 1, 3, 0, 0}; checkSamples(expected); } /** * Test sampling from a non-uniform distribution of probabilities (these sum to 1). * Extra zero-values are added. */ @Test void testNonUniformSamplesWithZeroProbabilities() { final double[] expected = {0.1, 0, 0.2, 0.3, 0.1, 0.3, 0}; checkSamples(expected); } /** * Test sampling from a non-uniform distribution of observations (i.e. the sum is not 1 as per * probabilities). Extra zero-values are added. */ @Test void testNonUniformSamplesWithZeroObservations() { final double[] expected = {1, 2, 3, 0, 1, 3, 0}; checkSamples(expected); } /** * Test sampling from a uniform distribution. This is an edge case where there * are no probabilities less than the mean. */ @Test void testUniformSamplesWithNoObservationLessThanTheMean() { final double[] expected = {2, 2, 2, 2, 2, 2}; checkSamples(expected); } /** * Test sampling from a non-uniform distribution which is zero-padded to a large size. */ @Test void testLargeTableSize() { double[] expected = {0.1, 0.2, 0.3, 0.1, 0.3}; // Pad to a large table size not supported for fast sampling (anything > 2^11) expected = Arrays.copyOf(expected, 1 << 12); checkSamples(expected); } /** * Check the distribution of samples match the expected probabilities. * * @param expected the expected probabilities */ private static void checkSamples(double[] probabilities) { checkSamples(createSampler(probabilities), probabilities); } /** * Check the distribution of samples match the expected probabilities. * * @param expected the expected probabilities */ private static void checkSamples(SharedStateDiscreteSampler sampler, double[] probabilities) { final int numberOfSamples = 10000; final long[] samples = new long[probabilities.length]; for (int i = 0; i < numberOfSamples; i++) { samples[sampler.sample()]++; } // Handle a test with some zero-probability observations by mapping them out int mapSize = 0; for (int i = 0; i < probabilities.length; i++) { if (probabilities[i] != 0) { mapSize++; } } double[] expected = new double[mapSize]; long[] observed = new long[mapSize]; for (int i = 0; i < probabilities.length; i++) { if (probabilities[i] != 0) { --mapSize; expected[mapSize] = probabilities[i]; observed[mapSize] = samples[i]; } else { Assertions.assertEquals(0, samples[i], "No samples expected from zero probability"); } } final ChiSquareTest chiSquareTest = new ChiSquareTest(); // Pass if we cannot reject null hypothesis that the distributions are the same. Assertions.assertFalse(chiSquareTest.chiSquareTest(expected, observed, 0.001)); } /** * Test the SharedStateSampler implementation for the specialised power-of-2 table size. */ @Test void testSharedStateSamplerWithPowerOf2TableSize() { testSharedStateSampler(new double[] {0.1, 0.2, 0.3, 0.4}); } /** * Test the SharedStateSampler implementation for the generic non power-of-2 table size. */ @Test void testSharedStateSamplerWithNonPowerOf2TableSize() { testSharedStateSampler(new double[] {0.1, 0.2, 0.3}); } /** * Test the SharedStateSampler implementation. * * @param probabilities The probabilities */ private static void testSharedStateSampler(double[] probabilities) { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); // Use negative alpha to disable padding final SharedStateDiscreteSampler sampler1 = AliasMethodDiscreteSampler.of(rng1, probabilities, -1); final SharedStateDiscreteSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } }
2,954
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/DiscreteSamplersList.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.commons.math3.util.MathArrays; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; /** * List of samplers. */ public final class DiscreteSamplersList { /** List of all RNGs implemented in the library. */ private static final List<DiscreteSamplerTestData> LIST = new ArrayList<>(); static { try { // This test uses reference distributions from commons-math3 to compute the expected // PMF. These distributions have a dual functionality to compute the PMF and perform // sampling. When no sampling is needed for the created distribution, it is advised // to pass null as the random generator via the appropriate constructors to avoid the // additional initialisation overhead. org.apache.commons.math3.random.RandomGenerator unusedRng = null; // List of distributions to test. // Binomial ("inverse method"). final int trialsBinomial = 20; final double probSuccessBinomial = 0.67; add(LIST, new org.apache.commons.math3.distribution.BinomialDistribution(unusedRng, trialsBinomial, probSuccessBinomial), MathArrays.sequence(8, 9, 1), RandomAssert.createRNG()); add(LIST, new org.apache.commons.math3.distribution.BinomialDistribution(unusedRng, trialsBinomial, probSuccessBinomial), // range [9,16] MathArrays.sequence(8, 9, 1), MarsagliaTsangWangDiscreteSampler.Binomial.of(RandomAssert.createRNG(), trialsBinomial, probSuccessBinomial)); // Inverted add(LIST, new org.apache.commons.math3.distribution.BinomialDistribution(unusedRng, trialsBinomial, 1 - probSuccessBinomial), // range [4,11] = [20-16, 20-9] MathArrays.sequence(8, 4, 1), MarsagliaTsangWangDiscreteSampler.Binomial.of(RandomAssert.createRNG(), trialsBinomial, 1 - probSuccessBinomial)); // Geometric ("inverse method"). final double probSuccessGeometric = 0.21; add(LIST, new org.apache.commons.math3.distribution.GeometricDistribution(unusedRng, probSuccessGeometric), MathArrays.sequence(10, 0, 1), RandomAssert.createRNG()); // Geometric. add(LIST, new org.apache.commons.math3.distribution.GeometricDistribution(unusedRng, probSuccessGeometric), MathArrays.sequence(10, 0, 1), GeometricSampler.of(RandomAssert.createRNG(), probSuccessGeometric)); // Hypergeometric ("inverse method"). final int popSizeHyper = 34; final int numSuccessesHyper = 11; final int sampleSizeHyper = 12; add(LIST, new org.apache.commons.math3.distribution.HypergeometricDistribution(unusedRng, popSizeHyper, numSuccessesHyper, sampleSizeHyper), MathArrays.sequence(10, 0, 1), RandomAssert.createRNG()); // Pascal ("inverse method"). final int numSuccessesPascal = 6; final double probSuccessPascal = 0.2; add(LIST, new org.apache.commons.math3.distribution.PascalDistribution(unusedRng, numSuccessesPascal, probSuccessPascal), MathArrays.sequence(18, 1, 1), RandomAssert.createRNG()); // Uniform ("inverse method"). final int loUniform = -3; final int hiUniform = 4; add(LIST, new org.apache.commons.math3.distribution.UniformIntegerDistribution(unusedRng, loUniform, hiUniform), MathArrays.sequence(8, -3, 1), RandomAssert.createRNG()); // Uniform (power of 2 range). add(LIST, new org.apache.commons.math3.distribution.UniformIntegerDistribution(unusedRng, loUniform, hiUniform), MathArrays.sequence(8, -3, 1), DiscreteUniformSampler.of(RandomAssert.createRNG(), loUniform, hiUniform)); // Uniform (large range). final int halfMax = Integer.MAX_VALUE / 2; final int hiLargeUniform = halfMax + 10; final int loLargeUniform = -hiLargeUniform; add(LIST, new org.apache.commons.math3.distribution.UniformIntegerDistribution(unusedRng, loLargeUniform, hiLargeUniform), MathArrays.sequence(20, -halfMax, halfMax / 10), DiscreteUniformSampler.of(RandomAssert.createRNG(), loLargeUniform, hiLargeUniform)); // Uniform (non-power of 2 range). final int rangeNonPowerOf2Uniform = 11; final int hiNonPowerOf2Uniform = loUniform + rangeNonPowerOf2Uniform; add(LIST, new org.apache.commons.math3.distribution.UniformIntegerDistribution(unusedRng, loUniform, hiNonPowerOf2Uniform), MathArrays.sequence(rangeNonPowerOf2Uniform, -3, 1), DiscreteUniformSampler.of(RandomAssert.createRNG(), loUniform, hiNonPowerOf2Uniform)); // Zipf ("inverse method"). final int numElementsZipf = 5; final double exponentZipf = 2.345; add(LIST, new org.apache.commons.math3.distribution.ZipfDistribution(unusedRng, numElementsZipf, exponentZipf), MathArrays.sequence(5, 1, 1), RandomAssert.createRNG()); // Zipf. add(LIST, new org.apache.commons.math3.distribution.ZipfDistribution(unusedRng, numElementsZipf, exponentZipf), MathArrays.sequence(5, 1, 1), RejectionInversionZipfSampler.of(RandomAssert.createRNG(), numElementsZipf, exponentZipf)); // Zipf (exponent close to 1). final double exponentCloseToOneZipf = 1 - 1e-10; add(LIST, new org.apache.commons.math3.distribution.ZipfDistribution(unusedRng, numElementsZipf, exponentCloseToOneZipf), MathArrays.sequence(5, 1, 1), RejectionInversionZipfSampler.of(RandomAssert.createRNG(), numElementsZipf, exponentCloseToOneZipf)); // Zipf (exponent = 0). add(LIST, MathArrays.sequence(5, 1, 1), new double[] {0.2, 0.2, 0.2, 0.2, 0.2}, RejectionInversionZipfSampler.of(RandomAssert.createRNG(), numElementsZipf, 0.0)); // Poisson ("inverse method"). final double epsilonPoisson = org.apache.commons.math3.distribution.PoissonDistribution.DEFAULT_EPSILON; final int maxIterationsPoisson = org.apache.commons.math3.distribution.PoissonDistribution.DEFAULT_MAX_ITERATIONS; final double meanPoisson = 3.21; add(LIST, new org.apache.commons.math3.distribution.PoissonDistribution(unusedRng, meanPoisson, epsilonPoisson, maxIterationsPoisson), MathArrays.sequence(10, 0, 1), RandomAssert.createRNG()); // Poisson. add(LIST, new org.apache.commons.math3.distribution.PoissonDistribution(unusedRng, meanPoisson, epsilonPoisson, maxIterationsPoisson), MathArrays.sequence(10, 0, 1), PoissonSampler.of(RandomAssert.createRNG(), meanPoisson)); // Dedicated small mean poisson samplers add(LIST, new org.apache.commons.math3.distribution.PoissonDistribution(unusedRng, meanPoisson, epsilonPoisson, maxIterationsPoisson), MathArrays.sequence(10, 0, 1), SmallMeanPoissonSampler.of(RandomAssert.createRNG(), meanPoisson)); add(LIST, new org.apache.commons.math3.distribution.PoissonDistribution(unusedRng, meanPoisson, epsilonPoisson, maxIterationsPoisson), MathArrays.sequence(10, 0, 1), KempSmallMeanPoissonSampler.of(RandomAssert.createRNG(), meanPoisson)); add(LIST, new org.apache.commons.math3.distribution.PoissonDistribution(unusedRng, meanPoisson, epsilonPoisson, maxIterationsPoisson), MathArrays.sequence(10, 0, 1), MarsagliaTsangWangDiscreteSampler.Poisson.of(RandomAssert.createRNG(), meanPoisson)); // LargeMeanPoissonSampler should work at small mean. // Note: This hits a code path where the sample from the normal distribution is rejected. add(LIST, new org.apache.commons.math3.distribution.PoissonDistribution(unusedRng, meanPoisson, epsilonPoisson, maxIterationsPoisson), MathArrays.sequence(10, 0, 1), LargeMeanPoissonSampler.of(RandomAssert.createRNG(), meanPoisson)); // Poisson (40 < mean < 80). final double largeMeanPoisson = 67.89; add(LIST, new org.apache.commons.math3.distribution.PoissonDistribution(unusedRng, largeMeanPoisson, epsilonPoisson, maxIterationsPoisson), MathArrays.sequence(50, (int) (largeMeanPoisson - 25), 1), PoissonSampler.of(RandomAssert.createRNG(), largeMeanPoisson)); // Dedicated large mean poisson sampler add(LIST, new org.apache.commons.math3.distribution.PoissonDistribution(unusedRng, largeMeanPoisson, epsilonPoisson, maxIterationsPoisson), MathArrays.sequence(50, (int) (largeMeanPoisson - 25), 1), LargeMeanPoissonSampler.of(RandomAssert.createRNG(), largeMeanPoisson)); add(LIST, new org.apache.commons.math3.distribution.PoissonDistribution(unusedRng, largeMeanPoisson, epsilonPoisson, maxIterationsPoisson), MathArrays.sequence(50, (int) (largeMeanPoisson - 25), 1), MarsagliaTsangWangDiscreteSampler.Poisson.of(RandomAssert.createRNG(), largeMeanPoisson)); // Poisson (mean >> 40). final double veryLargeMeanPoisson = 543.21; add(LIST, new org.apache.commons.math3.distribution.PoissonDistribution(unusedRng, veryLargeMeanPoisson, epsilonPoisson, maxIterationsPoisson), MathArrays.sequence(100, (int) (veryLargeMeanPoisson - 50), 1), PoissonSampler.of(RandomAssert.createRNG(), veryLargeMeanPoisson)); // Dedicated large mean poisson sampler add(LIST, new org.apache.commons.math3.distribution.PoissonDistribution(unusedRng, veryLargeMeanPoisson, epsilonPoisson, maxIterationsPoisson), MathArrays.sequence(100, (int) (veryLargeMeanPoisson - 50), 1), LargeMeanPoissonSampler.of(RandomAssert.createRNG(), veryLargeMeanPoisson)); add(LIST, new org.apache.commons.math3.distribution.PoissonDistribution(unusedRng, veryLargeMeanPoisson, epsilonPoisson, maxIterationsPoisson), MathArrays.sequence(100, (int) (veryLargeMeanPoisson - 50), 1), MarsagliaTsangWangDiscreteSampler.Poisson.of(RandomAssert.createRNG(), veryLargeMeanPoisson)); // Any discrete distribution final int[] discretePoints = {0, 1, 2, 3, 4}; final double[] discreteProbabilities = {0.1, 0.2, 0.3, 0.4, 0.5}; final long[] discreteFrequencies = {1, 2, 3, 4, 5}; add(LIST, discretePoints, discreteProbabilities, MarsagliaTsangWangDiscreteSampler.Enumerated.of(RandomAssert.createRNG(), discreteProbabilities)); add(LIST, discretePoints, discreteProbabilities, GuideTableDiscreteSampler.of(RandomAssert.createRNG(), discreteProbabilities)); add(LIST, discretePoints, discreteProbabilities, AliasMethodDiscreteSampler.of(RandomAssert.createRNG(), discreteProbabilities)); add(LIST, discretePoints, discreteProbabilities, FastLoadedDiceRollerDiscreteSampler.of(RandomAssert.createRNG(), discreteFrequencies)); add(LIST, discretePoints, discreteProbabilities, FastLoadedDiceRollerDiscreteSampler.of(RandomAssert.createRNG(), discreteProbabilities)); } catch (Exception e) { // CHECKSTYLE: stop Regexp System.err.println("Unexpected exception while creating the list of samplers: " + e); e.printStackTrace(System.err); // CHECKSTYLE: resume Regexp throw new RuntimeException(e); } } /** * Class contains only static methods. */ private DiscreteSamplersList() {} /** * @param list List of data (one the "parameters" tested by the Junit parametric test). * @param dist Distribution to which the samples are supposed to conform. * @param points Outcomes selection. * @param rng Generator of uniformly distributed sequences. */ private static void add(List<DiscreteSamplerTestData> list, final org.apache.commons.math3.distribution.IntegerDistribution dist, int[] points, UniformRandomProvider rng) { final DiscreteSampler inverseMethodSampler = InverseTransformDiscreteSampler.of(rng, new DiscreteInverseCumulativeProbabilityFunction() { @Override public int inverseCumulativeProbability(double p) { return dist.inverseCumulativeProbability(p); } @Override public String toString() { return dist.toString(); } }); list.add(new DiscreteSamplerTestData(inverseMethodSampler, points, getProbabilities(dist, points))); } /** * @param list List of data (one the "parameters" tested by the Junit parametric test). * @param dist Distribution to which the samples are supposed to conform. * @param points Outcomes selection. * @param sampler Sampler. */ private static void add(List<DiscreteSamplerTestData> list, final org.apache.commons.math3.distribution.IntegerDistribution dist, int[] points, final DiscreteSampler sampler) { list.add(new DiscreteSamplerTestData(sampler, points, getProbabilities(dist, points))); } /** * @param list List of data (one the "parameters" tested by the Junit parametric test). * @param points Outcomes selection. * @param probabilities Probability distribution to which the samples are supposed to conform. * @param sampler Sampler. */ private static void add(List<DiscreteSamplerTestData> list, int[] points, final double[] probabilities, final DiscreteSampler sampler) { list.add(new DiscreteSamplerTestData(sampler, points, probabilities)); } /** * Subclasses that are "parametric" tests can forward the call to * the "@Parameters"-annotated method to this method. * * @return the list of all generators. */ public static Iterable<DiscreteSamplerTestData> list() { return Collections.unmodifiableList(LIST); } /** * @param dist Distribution. * @param points Points. * @return the probabilities of the given points according to the distribution. */ private static double[] getProbabilities(org.apache.commons.math3.distribution.IntegerDistribution dist, int[] points) { final int len = points.length; final double[] prob = new double[len]; for (int i = 0; i < len; i++) { prob[i] = dist instanceof org.apache.commons.math3.distribution.UniformIntegerDistribution ? // XXX Workaround. getProbability((org.apache.commons.math3.distribution.UniformIntegerDistribution) dist) : dist.probability(points[i]); if (prob[i] < 0) { throw new IllegalStateException(dist + ": p < 0 (at " + points[i] + ", p=" + prob[i]); } } return prob; } /** * Workaround bugs in Commons Math's "UniformIntegerDistribution" (cf. MATH-1396). */ private static double getProbability(org.apache.commons.math3.distribution.UniformIntegerDistribution dist) { return 1 / ((double) dist.getSupportUpperBound() - (double) dist.getSupportLowerBound() + 1); } }
2,955
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/StableSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import java.util.function.Supplier; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.core.source64.SplitMix64; import org.apache.commons.rng.sampling.RandomAssert; import org.apache.commons.rng.sampling.distribution.StableSampler.Beta0CMSStableSampler; import org.apache.commons.rng.sampling.distribution.StableSampler.Beta0WeronStableSampler; import org.apache.commons.rng.sampling.distribution.StableSampler.CMSStableSampler; import org.apache.commons.rng.sampling.distribution.StableSampler.SpecialMath; import org.apache.commons.rng.sampling.distribution.StableSampler.WeronStableSampler; import org.apache.commons.rng.simple.RandomSource; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Tests for the class {@link StableSampler}. * * <p>Note: Samples from the stable distribution are tested in * {@link ContinuousSamplerParametricTest}. * * <p>This contains tests for the assumptions made by the {@link StableSampler} implementation * of the Chambers-Mallows-Stuck (CMS) method as described in * Chambers, Mallows &amp; Stuck (1976) "A Method for Simulating Stable Random Variables". * Journal of the American Statistical Association. 71 (354): 340–344. * * <p>The test class contains copy implementations of the routines in the {@link StableSampler} * to test the algorithms with various parameters. This avoids excess manipulation * of the RNG provided to the stable sampler to test edge cases and also allows * calling the algorithm with values that are eliminated by the sampler (e.g. u=0). * * <p>Some tests of the sampler are performed that manipulate the underlying RNG to create * extreme values for the random deviates. This hits edges cases where the computation has * to be corrected. */ class StableSamplerTest { /** pi / 2. */ private static final double PI_2 = Math.PI / 2; /** pi / 4. */ private static final double PI_4 = Math.PI / 4; /** pi/4 scaled by 2^-53. */ private static final double PI_4_SCALED = 0x1.0p-55 * Math.PI; /** The interval between successive values of a uniform variate u. * This is the gap between the 2^53 dyadic rationals in [0, 1). */ private static final double DU = 0x1.0p-53; /** The smallest non-zero sample from the ZigguratSampler.Exponential sampler. */ private static final double SMALL_W = 6.564735882096453E-19; /** A tail sample from the ZigguratSampler.Exponential after 1 recursions of the sample method. */ private static final double TAIL_W = 7.569274694148063; /** A largest sample from the ZigguratSampler.Exponential after 4 recursions of the sample method. */ private static final double LARGE_W = 4 * TAIL_W; /** The smallest value for alpha where 1 - (1-alpha) = alpha. */ private static final double SMALLEST_ALPHA = 1.0 - Math.nextDown(1.0); private static final double VALID_ALPHA = 1.23; private static final double VALID_BETA = 0.23; private static final double VALID_GAMMA = 2.34; private static final double VALID_DELTA = 3.45; @Test void testAlphaZeroThrows() { assertConstructorThrows(0.0, VALID_BETA, VALID_GAMMA, VALID_DELTA); } @Test void testAlphaBelowZeroThrows() { assertConstructorThrows(Math.nextDown(0.0), VALID_BETA, VALID_GAMMA, VALID_DELTA); } @Test void testAlphaTooCloseToZeroThrows() { // The realistic range for alpha is not Double.MIN_VALUE. // The number 1 - alpha must not be 1. // This is valid final UniformRandomProvider rng = new SplitMix64(0L); StableSampler s = StableSampler.of(rng, SMALLEST_ALPHA, VALID_BETA, VALID_GAMMA, VALID_DELTA); Assertions.assertNotNull(s); // Smaller than this is still above zero but 1 - alpha == 1 final double alphaTooSmall = SMALLEST_ALPHA / 2; Assertions.assertNotEquals(0.0, alphaTooSmall, "Expected alpha to be positive"); Assertions.assertEquals(1.0, 1 - alphaTooSmall, "Expected rounding to 1"); // Because alpha is effectively zero this will throw assertConstructorThrows(alphaTooSmall, VALID_BETA, VALID_GAMMA, VALID_DELTA); } @Test void testAlphaAboveTwoThrows() { assertConstructorThrows(Math.nextUp(2.0), VALID_BETA, VALID_GAMMA, VALID_DELTA); } @Test void testAlphaNaNThrows() { assertConstructorThrows(Double.NaN, VALID_BETA, VALID_GAMMA, VALID_DELTA); } @Test void testBetaBelowMinusOneThrows() { assertConstructorThrows(VALID_ALPHA, Math.nextDown(-1.0), VALID_GAMMA, VALID_DELTA); } @Test void testBetaAboveOneThrows() { assertConstructorThrows(VALID_ALPHA, Math.nextUp(1.0), VALID_GAMMA, VALID_DELTA); } @Test void testBetaNaNThrows() { assertConstructorThrows(VALID_ALPHA, Double.NaN, VALID_GAMMA, VALID_DELTA); } @Test void testGammaNotStrictlyPositiveThrows() { assertConstructorThrows(VALID_ALPHA, VALID_BETA, 0.0, VALID_DELTA); } @Test void testGammaInfThrows() { assertConstructorThrows(VALID_ALPHA, VALID_BETA, Double.POSITIVE_INFINITY, VALID_DELTA); } @Test void testGammaNaNThrows() { assertConstructorThrows(VALID_ALPHA, VALID_BETA, Double.NaN, VALID_DELTA); } @Test void testDeltaInfThrows() { assertConstructorThrows(VALID_ALPHA, VALID_BETA, VALID_GAMMA, Double.POSITIVE_INFINITY); } @Test void testDeltaNegInfThrows() { assertConstructorThrows(VALID_ALPHA, VALID_BETA, VALID_GAMMA, Double.NEGATIVE_INFINITY); } @Test void testDeltaNaNThrows() { assertConstructorThrows(VALID_ALPHA, VALID_BETA, VALID_GAMMA, Double.NaN); } /** * Asserts the stable sampler factory constructor throws an {@link IllegalArgumentException}. * * @param alpha Stability parameter. Must be in range {@code (0, 2]}. * @param beta Skewness parameter. Must be in range {@code [-1, 1]}. * @param gamma Scale parameter. Must be strictly positive and finite. * @param delta Location parameter. Must be finite. */ private static void assertConstructorThrows(double alpha, double beta, double gamma, double delta) { final UniformRandomProvider rng = new SplitMix64(0L); Assertions.assertThrows(IllegalArgumentException.class, () -> StableSampler.of(rng, alpha, beta, gamma, delta)); } /** * Assumption test: * Test the limits of the value {@code tau} at the extreme limits of {@code alpha}. * The expression is evaluated against the original CMS algorithm. The method * has been updated to ensure symmetry around zero. * * <p>The test demonstrates that tau can be zero even when beta is not zero. Thus * the choice of a beta=0 sampler must check tau and not beta. */ @Test void testTauLimits() { // At the limit of beta, tau ranges from 2/pi to 0 as alpha moves away from 1. final double beta = 1; // alpha -> 2: tau -> 0 // alpha -> 0: tau -> 0 Assertions.assertEquals(0.0, CMSStableSampler.getTau(2, beta)); Assertions.assertEquals(0.0, CMSStableSampler.getTau(0, beta)); // Full range over 0 to 2. for (int i = 0; i <= 512; i++) { // This is a power of 2 so the symmetric test uses an exact mirror final double alpha = (double) i / 256; final double tau = CMSStableSampler.getTau(alpha, beta); final double expected = getTauOriginal(alpha, beta); Assertions.assertEquals(expected, tau, 1e-15); // Symmetric Assertions.assertEquals(tau, CMSStableSampler.getTau(2 - alpha, beta)); } // alpha -> 1: tau -> beta / (pi / 2) = 0.6366 final double limit = beta / PI_2; Assertions.assertEquals(limit, CMSStableSampler.getTau(1, beta)); for (double alpha : new double[] {1.01, 1 + 1e-6, 1, 1 - 1e-6, 0.99}) { final double tau = CMSStableSampler.getTau(alpha, beta); final double expected = getTauOriginal(alpha, beta); Assertions.assertEquals(expected, tau, 1e-15); // Approach the limit Assertions.assertEquals(limit, tau, Math.abs(1 - alpha) + 1e-15); } // It can be zero if beta is zero or close to zero when alpha != 1. // This requires we check tau==0 instead of beta==0 to switch to // a beta = 0 sampler. Assertions.assertEquals(0.0, CMSStableSampler.getTau(1.3, 0.0)); Assertions.assertEquals(0.0, CMSStableSampler.getTau(1.5, Double.MIN_VALUE)); Assertions.assertNotEquals(0.0, CMSStableSampler.getTau(1.0, Double.MIN_VALUE)); // The sign of beta determines the sign of tau. Assertions.assertEquals(0.5, CMSStableSampler.getTau(1.5, beta)); Assertions.assertEquals(0.5, CMSStableSampler.getTau(0.5, beta)); Assertions.assertEquals(-0.5, CMSStableSampler.getTau(1.5, -beta)); Assertions.assertEquals(-0.5, CMSStableSampler.getTau(0.5, -beta)); // Check monototic at the transition point to switch to a different computation. final double tau1 = CMSStableSampler.getTau(Math.nextDown(1.5), 1); final double tau2 = CMSStableSampler.getTau(1.5, 1); final double tau3 = CMSStableSampler.getTau(Math.nextUp(1.5), 1); Assertions.assertTrue(tau1 > tau2); Assertions.assertTrue(tau2 > tau3); // Test symmetry at the transition Assertions.assertEquals(tau1, CMSStableSampler.getTau(2 - Math.nextDown(1.5), 1)); Assertions.assertEquals(tau2, CMSStableSampler.getTau(0.5, 1)); Assertions.assertEquals(tau3, CMSStableSampler.getTau(2 - Math.nextUp(1.5), 1)); } /** * Gets tau using the original method from the CMS algorithm implemented in the * program RSTAB. This does not use {@link SpecialMath#tan2(double)} but uses * {@link Math#tan(double)} to implement {@code tan(x) / x}. * * @param alpha alpha * @param beta the beta * @return tau */ private static double getTauOriginal(double alpha, double beta) { final double eps = 1 - alpha; // Compute RSTAB prefactor double tau; // Use the method from Chambers et al (1976). // TAN2(x) = tan(x) / x // PIBY2 = pi / 2 // Comments are the FORTRAN code from the RSTAB routine. if (eps > -0.99) { // TAU = BPRIME / (TAN2(EPS * PIBY2) * PIBY2) final double tan2 = eps == 0 ? 1 : Math.tan(eps * PI_2) / (eps * PI_2); tau = beta / (tan2 * PI_2); } else { // TAU = BPRIME * PIBY2 * EPS * (1.-EPS) * TAN2 ((1. -EPS) * PIBY2) final double meps1 = 1 - eps; final double tan2 = Math.tan(meps1 * PI_2) / (meps1 * PI_2); tau = beta * PI_2 * eps * meps1 * tan2; } return tau; } /** * Assumption test: * Test the value {@code a2} is not zero. Knowing {@code a2} is not zero simplifies * correction of non-finite results from the CMS algorithm. */ @Test void testA2IsNotZero() { // The extreme limit of the angle phiby2. This is ignored by the sampler // as it can result in cancellation of terms and invalid results. final double p0 = getU(Long.MIN_VALUE); Assertions.assertEquals(-PI_4, p0); // These are the limits to generate (-pi/4, pi/4) final double p1 = getU(Long.MIN_VALUE + (1 << 10)); final double p2 = getU(Long.MAX_VALUE); Assertions.assertNotEquals(-PI_4, p1); Assertions.assertNotEquals(PI_4, p2); Assertions.assertEquals(-PI_4 + PI_4 * DU, p1); Assertions.assertEquals(PI_4 - PI_4 * DU, p2); for (double phiby2 : new double[] {p1, p2}) { // phiby2 in (-pi/4, pi/4) // a in (-1, 1) final double a = phiby2 * SpecialMath.tan2(phiby2); Assertions.assertEquals(Math.copySign(Math.nextDown(1.0), phiby2), a); final double da = a * a; final double a2 = 1 - da; // The number is close to but not equal to zero Assertions.assertNotEquals(0.0, a2); // The minimum value of a2 is 2.220E-16 = 2^-52 Assertions.assertEquals(0x1.0p-52, a2); } } /** * Assumption test: * Test the value of the numerator used to compute z. If this is negative then * computation of log(z) creates a NaN. This effect occurs when the uniform * random deviate u is either 0 or 1 and beta is -1 or 1. The effect is reduced * when u is in the range {@code (0, 1)} but not eliminated. The test * demonstrates: (a) the requirement to check z during the sample method when * {@code alpha!=1}; and (b) when {@code alpha=1} then z cannot be zero when u * is in the open interval {@code (0, 1)}. */ @Test void testZIsNotAlwaysAboveZero() { // A long is used to create phi/2: // The next to limit values for the phi/2 final long x00 = Long.MIN_VALUE; final long x0 = Long.MIN_VALUE + (1 << 10); final long x1 = Long.MAX_VALUE; Assertions.assertEquals(-PI_4, getU(x00)); Assertions.assertEquals(-PI_4 + DU * PI_4, getU(x0)); Assertions.assertEquals(PI_4 - DU * PI_4, getU(x1)); // General case numerator: // b2 + 2 * phiby2 * bb * tau // To generate 0 numerator requires: // b2 == -2 * phiby2 * bb * tau // // The expansion of the terms is: // 1 - tan^2(eps * phi/2) // == -phi * tan2(eps * phi/2) * beta // ----------------------- // tan2(eps * pi/2) * pi/2 // // == -2 * phi * tan2(eps * phi/2) * beta // ----------------------------------- // pi * tan2(eps * pi/2) // // == -2 * phi * tan(eps * phi/2) / (eps * phi/2) * beta // -------------------------------------------------- // pi * tan(eps * pi/2) / (eps * pi/2) // // if phi/2 = pi/4, x = eps * phi/2: // == -2 * pi/4 * tan(x) / (x) * beta // --------------------------------- // pi * tan(2x) / (2x) // // This is a known double-angle identity for tan: // 1 - tan^2(x) == -2 tan(x) * beta // --------- // tan(2x) // Thus if |beta|=1 with opposite sign to phi, and |phi|=pi/2 // the numerator is zero for all alpha. // This is not true due to floating-point // error but the following cases are known to exhibit the result. Assertions.assertEquals(0.0, computeNumerator(0.859375, 1, x00)); // Even worse to have negative as the log(-ve) = nan Assertions.assertTrue(0.0 > computeNumerator(0.9375, 1, x00)); Assertions.assertTrue(0.0 > computeNumerator(1.90625, 1, x00)); // As phi reduces in magnitude the equality fails. // The numerator=0 can often be corrected // with the next random variate from the range limit. Assertions.assertTrue(0.0 < computeNumerator(0.859375, 1, x0)); Assertions.assertTrue(0.0 < computeNumerator(0.9375, 1, x0)); Assertions.assertTrue(0.0 < computeNumerator(1.90625, 1, x0)); // WARNING: // Even when u is not at the limit floating point error can still create // a bad numerator. This is rare but shows we must still detect this edge // case. Assertions.assertTrue(0.0 > computeNumerator(0.828125, 1, x0)); Assertions.assertTrue(0.0 > computeNumerator(1.291015625, -1, x1)); // beta=0 case the numerator reduces to b2: // b2 = 1 - tan^2((1-alpha) * phi/2) // requires tan(x)=1; x=pi/4. // Note: tan(x) = x * SpecialMath.tan2(x) returns +/-1 for u = +/-pi/4. Assertions.assertEquals(-1, SpecialMath.tan2(getU(x00)) * getU(x00)); // Using the next value in the range this is not an issue. // The beta=0 sampler does not have to check for z=0. Assertions.assertTrue(-1 < SpecialMath.tan2(getU(x0)) * getU(x0)); Assertions.assertTrue(1 > SpecialMath.tan2(getU(x1)) * getU(x1)); // Use alpha=2 so 1-alpha (eps) is at the limit final double beta = 0; Assertions.assertEquals(0.0, computeNumerator(2, beta, x00)); Assertions.assertTrue(0.0 < computeNumerator(2, beta, x0)); Assertions.assertTrue(0.0 < computeNumerator(2, beta, x1)); Assertions.assertTrue(0.0 < computeNumerator(Math.nextDown(2), beta, x0)); Assertions.assertTrue(0.0 < computeNumerator(Math.nextDown(2), beta, x1)); // alpha=1 case the numerator reduces to: // 1 + 2 * phi/2 * tau // A zero numerator requires: // 2 * phiby2 * tau = -1 // // tau = 2 * beta / pi // phiby2 = -pi / (2 * 2 * beta) // beta = 1 => phiby2 = -pi/4 // beta = -1 => phiby2 = pi/4 // The alpha=1 sampler does not have to check for z=0 if phiby2 excludes -pi/4. final double alpha = 1; Assertions.assertEquals(0.0, computeNumerator(alpha, 1, x00)); // Next value of u computes above zero Assertions.assertTrue(0.0 < computeNumerator(alpha, 1, x0)); Assertions.assertTrue(0.0 < computeNumerator(alpha, -1, x1)); // beta < 1 => u < 0 // beta > -1 => u > 1 // z=0 not possible with any other beta Assertions.assertTrue(0.0 < computeNumerator(alpha, Math.nextUp(-1), x00)); } /** * Compute the numerator value for the z coefficient in the CMS algorithm. * * @param alpha Stability parameter. Must be in range {@code (0, 2]}. * @param beta Skewness parameter. Must be in range {@code [-1, 1]}. * @param x The random long used to generate the uniform deviate in the range {@code [-pi/4, pi/4)}. * @return numerator */ private static double computeNumerator(double alpha, double beta, long x) { final double phiby2 = getU(x); final double eps = 1 - alpha; final double tau = CMSStableSampler.getTau(alpha, beta); final double bb = SpecialMath.tan2(eps * phiby2); final double b = eps * phiby2 * bb; // Compute some necessary subexpressions final double db = b * b; final double b2 = 1 - db; // Compute z coefficient numerator. return b2 + 2 * phiby2 * bb * tau; } /** * Assumption test: * Test the CMS algorithm can compute the value {@code d} without creating a NaN * when {@code z} is any non-zero finite value. When the value {@code z} is zero or infinite * the computation may multiply infinity by zero and create NaN. */ @Test void testComputeDWhenZIsFiniteNonZero() { final double[] zs = {Double.MIN_VALUE, Double.MAX_VALUE}; final double[] alphas = {2, 1.5, 1 + 1e-6, 1, 1 - 1e-6, 0.5, 0.01, 1e-10, SMALLEST_ALPHA}; for (final double alpha : alphas) { // Finite z for (final double z : zs) { // The result may be infinite, but not NaN Assertions.assertNotEquals(Double.NaN, computeD(alpha, z)); } // May be invalid with z=0 or z=inf as some combinations multiply the // infinity by 0 to create NaN. // When z=0, log(z) = -inf, d = d2(sign(1-alpha) * -inf) * -inf final double d0 = computeD(alpha, 0); if (alpha < 1) { // d2(-inf) * -inf = 0 * -inf = NaN Assertions.assertEquals(Double.NaN, d0); } else if (alpha == 1) { // d2(0 * -inf) -> NaN Assertions.assertEquals(Double.NaN, d0); } else { // alpha > 1 // d2(inf) * -inf = -inf Assertions.assertEquals(Double.NEGATIVE_INFINITY, d0); } // When z=inf, log(z) = inf, d = d2(sign(1-alpha) * inf) * inf final double di = computeD(alpha, Double.POSITIVE_INFINITY); if (alpha < 1) { // d2(inf) * inf = inf Assertions.assertEquals(Double.POSITIVE_INFINITY, di); } else if (alpha == 1) { // d2(0 * inf) -> NaN Assertions.assertEquals(Double.NaN, di); } else { // alpha > 1 // d2(-inf) * inf = 0 * inf = NaN Assertions.assertEquals(Double.NaN, di); } } } /** * Compute the {@code d} value in the CMS algorithm. * * @param alpha alpha * @param z z * @return d */ private static double computeD(double alpha, double z) { final double alogz = Math.log(z); final double eps = 1 - alpha; final double meps1 = 1 - eps; return SpecialMath.d2(eps * alogz / meps1) * (alogz / meps1); } /** * Assumption test: * Test the sin(alpha * phi + atan(-zeta)) term can be zero. * This applies to the Weron formula. */ @Test void testSinAlphaPhiMinusAtanZeta() { // Note sin(alpha * phi + atan(-zeta)) is zero when: // alpha * phi = -atan(-zeta) // tan(-alpha * phi) = -zeta // = beta * tan(alpha * pi / 2) // beta = tan(-alpha * phi) / tan(alpha * pi / 2) // Find a case where the result is zero... for (double alpha : new double[] {0.25, 0.125}) { for (double phi : new double[] {PI_4, PI_4 / 2}) { double beta = Math.tan(-alpha * phi) / Math.tan(alpha * PI_2); double zeta = -beta * Math.tan(alpha * PI_2); double atanZeta = Math.atan(-zeta); Assertions.assertEquals(0.0, alpha * phi + atanZeta); } } } /** * Assumption test: * Test the cos(phi - alpha * (phi + xi)) term is positive. * This applies to the Weron formula. */ @Test void testCosPhiMinusAlphaPhiXi() { // This is the extreme of cos(x) that should be used final double cosPi2 = Math.cos(PI_2); // The function is symmetric Assertions.assertEquals(cosPi2, Math.cos(-PI_2)); // As pi is an approximation then the cos value is not exactly 0 Assertions.assertTrue(cosPi2 > 0); final UniformRandomProvider rng = RandomAssert.createRNG(); // The term is mirrored around 1 so use extremes between 1 and 0 final double[] alphas = {1, Math.nextDown(1), 0.99, 0.5, 0.1, 0.05, 0.01, DU}; // Longs to generate extremes for the angle phi. This is mirrored // by negation is the assert method so use values to create phi in [0, pi/2). final long[] xs = {0, 1 << 10, Long.MIN_VALUE >>> 1, Long.MAX_VALUE}; for (final double alpha : alphas) { for (final long x : xs) { assertCosPhiMinusAlphaPhiXi(alpha, x); assertCosPhiMinusAlphaPhiXi(2 - alpha, x); } for (int j = 0; j < 1000; j++) { final long x = rng.nextLong(); assertCosPhiMinusAlphaPhiXi(alpha, x); assertCosPhiMinusAlphaPhiXi(2 - alpha, x); } } // Random alpha for (int i = 0; i < 1000; i++) { final double alpha = rng.nextDouble(); for (final long x : xs) { assertCosPhiMinusAlphaPhiXi(alpha, x); assertCosPhiMinusAlphaPhiXi(2 - alpha, x); } for (int j = 0; j < 1000; j++) { final long x = rng.nextLong(); assertCosPhiMinusAlphaPhiXi(alpha, x); assertCosPhiMinusAlphaPhiXi(2 - alpha, x); } } // Enumerate alpha for (int i = 0; i <= 1023; i++) { final double alpha = (double) i / 1023; for (final long x : xs) { assertCosPhiMinusAlphaPhiXi(alpha, x); assertCosPhiMinusAlphaPhiXi(2 - alpha, x); } } } /** * Assert the cos(phi - alpha * (phi + xi)) term is positive. * This asserts the term (phi - alpha * (phi + xi)) is in the interval (-pi/2, pi/2) when * beta is the extreme of +/-1. * * @param alpha alpha * @param x the long used to create the uniform deviate */ private static void assertCosPhiMinusAlphaPhiXi(double alpha, long x) { // Update for symmetry around alpha = 1 final double eps = 1 - alpha; final double meps1 = 1 - eps; // zeta = -beta * tan(alpha * pi / 2) // xi = atan(-zeta) / alpha // Compute phi - alpha * (phi + xi). // This value must be in (-pi/2, pi/2). // The term expands to: // phi - alpha * (phi + xi) // = phi - alpha * phi - atan(-zeta) // = (1-alpha) * phi - atan(-zeta) // When beta = +/-1, // atanZeta = +/-alpha * pi/2 if alpha < 1 // atanZeta = +/-(2-alpha) * pi/2 if alpha > 1 // alpha=1 => always +/-pi/2 // alpha=0,2 => always +/-phi // Values in between use the addition: // (1-alpha) * phi +/- alpha * pi/2 // Since (1-alpha) is exact and alpha = 1 - (1-alpha) the addition // cannot exceed pi/2. // Avoid the round trip using tan and arctan when beta is +/- 1 // zeta = -beta * Math.tan(alpha * pi / 2); // atan(-zeta) = alpha * pi / 2 final double alphaPi2; if (meps1 > 1) { // Avoid calling tan outside the domain limit [-pi/2, pi/2]. alphaPi2 = -(2 - meps1) * PI_2; } else { alphaPi2 = meps1 * PI_2; } // Compute eps * phi +/- alpha * pi / 2 // Test it is in the interval (-pi/2, pi/2) double phi = getU(x) * 2; double value = eps * phi + alphaPi2; Assertions.assertTrue(value <= PI_2); Assertions.assertTrue(value >= -PI_2); value = eps * phi - alphaPi2; Assertions.assertTrue(value <= PI_2); Assertions.assertTrue(value >= -PI_2); // Mirror the deviate phi = -phi; value = eps * phi + alphaPi2; Assertions.assertTrue(value <= PI_2); Assertions.assertTrue(value >= -PI_2); value = eps * phi - alphaPi2; Assertions.assertTrue(value <= PI_2); Assertions.assertTrue(value >= -PI_2); } /** * Assumption test: * Test the sin(alpha * phi) term is only zero when phi is zero. * This applies to the Weron formula when {@code beta = 0}. */ @Test void testSinAlphaPhi() { // Smallest non-zero phi. // getU creates in the domain (-pi/4, pi/4) so double the angle. for (final double phi : new double[] {getU(-1) * 2, getU(1 << 10) * 2}) { final double x = Math.sin(SMALLEST_ALPHA * phi); Assertions.assertNotEquals(0.0, x); // Value is actually: Assertions.assertEquals(1.9361559566769725E-32, Math.abs(x)); } } /** * Assumption test: * Test functions to compute {@code (exp(x) - 1) / x}. This tests the use of * {@link Math#expm1(double)} and {@link Math#exp(double)} to determine if the switch * point to the high precision version is monotonic. */ @Test void testExpM1() { // Test monotonic at the switch point Assertions.assertEquals(d2(0.5), d2b(0.5)); // When positive x -> 0 the value smaller bigger. Assertions.assertTrue(d2(Math.nextDown(0.5)) <= d2b(0.5)); Assertions.assertEquals(d2(-0.5), d2b(-0.5)); // When negative x -> 0 the value gets bigger. Assertions.assertTrue(d2(-Math.nextDown(0.5)) >= d2b(-0.5)); // Potentially the next power of 2 could be used based on ULP errors but // the switch is not monotonic. Assertions.assertFalse(d2(Math.nextDown(0.25)) <= d2b(0.25)); } /** * This is not a test. * * <p>This outputs a report of the mean ULP difference between * using {@link Math#expm1(double)} and {@link Math#exp(double)} to evaluate * {@code (exp(x) - 1) / x}. This helps choose the switch point to avoid the computationally * expensive expm1 function. */ //@Test void expm1ULPReport() { // Create random doubles with a given exponent. Compute the mean and max ULP difference. final UniformRandomProvider rng = RandomAssert.createRNG(); // For a quicker report set to <= 2^20. final int size = 1 << 30; // Create random doubles using random bits in the 52-bit mantissa. final long mask = (1L << 52) - 1; // Note: // The point at which there *should* be no difference between the two is when // exp(x) - 1 == exp(x). This will occur at exp(x)=2^54, x = ln(2^54) = 37.43. Assertions.assertEquals(((double) (1L << 54)) - 1, (double) (1L << 54)); // However since expm1 and exp are only within 1 ULP of the exact result differences // still occur above this threshold. // 2^6 = 64; 2^-4 = 0.0625 for (int signedExp = 6; signedExp >= -4; signedExp--) { // The exponent must be unsigned so + 1023 to the signed exponent final long exp = (signedExp + 1023L) << 52; // Test we are creating the correct numbers Assertions.assertEquals(signedExp, Math.getExponent(Double.longBitsToDouble(exp))); Assertions.assertEquals(signedExp, Math.getExponent(Double.longBitsToDouble((-1 & mask) | exp))); // Get the average and max ulp long sum1 = 0; long sum2 = 0; long max1 = 0; long max2 = 0; for (int i = size; i-- > 0;) { final long bits = rng.nextLong() & mask; final double x = Double.longBitsToDouble(bits | exp); final double x1 = d2(x); final double x2 = d2b(x); final double x1b = d2(-x); final double x2b = d2b(-x); final long ulp1 = Math.abs(Double.doubleToRawLongBits(x1) - Double.doubleToRawLongBits(x2)); final long ulp2 = Math.abs(Double.doubleToRawLongBits(x1b) - Double.doubleToRawLongBits(x2b)); sum1 += ulp1; sum2 += ulp2; if (max1 < ulp1) { max1 = ulp1; } if (max2 < ulp2) { max2 = ulp2; } } // CHECKSTYLE: stop Regexp System.out.printf("%-6s %2d %-24s (%d) %-24s (%d)%n", Double.longBitsToDouble(exp), signedExp, (double) sum1 / size, max1, (double) sum2 / size, max2); // CHECKSTYLE: resume Regexp } } /** * Evaluate {@code (exp(x) - 1) / x} using {@link Math#expm1(double)}. * For {@code x} in the range {@code [-inf, inf]} returns * a result in {@code [0, inf]}. * * <ul> * <li>For {@code x=-inf} this returns {@code 0}. * <li>For {@code x=0} this returns {@code 1}. * <li>For {@code x=inf} this returns {@code inf}. * </ul> * * <p> This corrects {@code 0 / 0} and {@code inf / inf} division from * {@code NaN} to either {@code 1} or the upper bound respectively. * * @param x value to evaluate * @return {@code (exp(x) - 1) / x}. */ private static double d2(double x) { // Here we use a conditional to detect both edge cases, which are then corrected. final double d2 = Math.expm1(x) / x; if (Double.isNaN(d2)) { // Correct edge cases. if (x == 0) { return 1.0; } // x must have been +infinite or NaN return x; } return d2; } /** * Evaluate {@code (exp(x) - 1) / x} using {@link Math#exp(double)}. * For {@code x} in the range {@code [-inf, inf]} returns * a result in {@code [0, inf]}. * * <ul> * <li>For {@code x=-inf} this returns {@code 0}. * <li>For {@code x=0} this returns {@code 1}. * <li>For {@code x=inf} this returns {@code inf}. * </ul> * * <p> This corrects {@code 0 / 0} and {@code inf / inf} division from * {@code NaN} to either {@code 1} or the upper bound respectively. * * @param x value to evaluate * @return {@code (exp(x) - 1) / x}. */ private static double d2b(double x) { // Here we use a conditional to detect both edge cases, which are then corrected. final double d2 = (Math.exp(x) - 1) / x; if (Double.isNaN(d2)) { // Correct edge cases. if (x == 0) { return 1.0; } // x must have been +infinite or NaN return x; } return d2; } /** * Test the special d2 function returns {@code (exp(x) - 1) / x}. * The limits of the function are {@code [0, inf]} and it should return 1 when x=0. */ @Test void testD2() { for (final double x : new double[] {Double.MAX_VALUE, Math.log(Double.MAX_VALUE), 10, 5, 1, 0.5, 0.1, 0.05, 0.01}) { Assertions.assertEquals(Math.expm1(x) / x, SpecialMath.d2(x), 1e-15); Assertions.assertEquals(Math.expm1(-x) / -x, SpecialMath.d2(-x), 1e-15); } // Negative infinity computes without correction Assertions.assertEquals(0.0, Math.expm1(Double.NEGATIVE_INFINITY) / Double.NEGATIVE_INFINITY); Assertions.assertEquals(0.0, SpecialMath.d2(Double.NEGATIVE_INFINITY)); // NaN is returned (i.e. no correction) Assertions.assertEquals(Double.NaN, SpecialMath.d2(Double.NaN)); // Edge cases for z=0 or z==inf require correction Assertions.assertEquals(Double.NaN, Math.expm1(0) / 0.0); Assertions.assertEquals(Double.NaN, Math.expm1(Double.POSITIVE_INFINITY) / Double.POSITIVE_INFINITY); // Corrected in the special function Assertions.assertEquals(1.0, SpecialMath.d2(0.0)); Assertions.assertEquals(Double.POSITIVE_INFINITY, SpecialMath.d2(Double.POSITIVE_INFINITY)); } /** * Test the tan2 function returns {@code tan(x) / x}. */ @Test void testTan2() { // Test the value of tan(x) when the angle is generated in the open interval (-pi/4, pi/4) for (final long x : new long[] {Long.MIN_VALUE + (1 << 10), Long.MAX_VALUE}) { final double phiby2 = getU(x); Assertions.assertEquals(PI_4 - DU * PI_4, Math.abs(phiby2)); final double a = phiby2 * SpecialMath.tan2(phiby2); // Check this is not 1 Assertions.assertNotEquals(1, Math.abs(a)); Assertions.assertTrue(Math.abs(a) < 1.0); } // At pi/4 the function reverts to Math.tan(x) / x. Test through the transition. final double pi = Math.PI; for (final double x : new double[] {pi, pi / 2, pi / 3.99, pi / 4, pi / 4.01, pi / 8, pi / 16}) { final double y = Math.tan(x) / x; Assertions.assertEquals(y, SpecialMath.tan2(x), Math.ulp(y)); } // Test this closely matches the JDK tan function. // Test uniformly between 0 and pi / 4. // Count the errors with the ULP difference. // Get max ULP and mean ULP. Do this for both tan(x) and tan(x)/x functions. final UniformRandomProvider rng = RandomSource.XO_RO_SHI_RO_128_PP.create(0x1647816481684L); int count = 0; long ulp = 0; long max = 0; long ulp2 = 0; long max2 = 0; for (int i = 0; i < 1000; i++) { final double x = rng.nextDouble() * PI_4; count++; final double tanx = Math.tan(x); final double tan2x = SpecialMath.tan2(x); // Test tan(x) double y = x * tan2x; if (y != tanx) { final long u = Math.abs(Double.doubleToRawLongBits(tanx) - Double.doubleToRawLongBits(y)); if (max < u) { max = u; } ulp += u; // Within 4 ulp. Note tan(x) is within 1 ulp of the result. So this // is max 5 ulp from the result. Assertions.assertEquals(tanx, y, 4 * Math.ulp(tanx)); } // Test tan(x) / x y = tanx / x; if (y != tan2x) { final long u = Math.abs(Double.doubleToRawLongBits(tan2x) - Double.doubleToRawLongBits(y)); if (max2 < u) { max2 = u; } ulp2 += u; // Within 3 ulp. Assertions.assertEquals(y, tan2x, 3 * Math.ulp(y)); } } // Mean (max) ULP is very low // 2^30 random samples in [0, pi / 4) // tan(x) tan(x) / x // tan4283 93436.25534446817 201185 : 68313.16171793547 128079 // tan4288c 0.5905972588807344 4 : 0.4047176940366626 3 Assertions.assertTrue((double) ulp / count < 0.6, "Mean ULP to tan(x) is too high"); Assertions.assertTrue((double) ulp2 / count < 0.45, "Mean ULP to tan(x) / x is too high"); // If the value is under 1 then the sampler will break due to cancellation errors. Assertions.assertEquals(1.0, SpecialMath.tan2(0.0), "Must be exact tan(x) / x at x=0"); Assertions.assertEquals(4 / Math.PI, SpecialMath.tan2(PI_4), Math.ulp(4 / Math.PI)); Assertions.assertEquals(1.0, PI_4 * SpecialMath.tan2(PI_4), Math.ulp(1.0)); // If this is above 1 then the sampler will break. Test at the switch point pi/4. Assertions.assertTrue(1.0 >= PI_4 * SpecialMath.tan2(PI_4)); Assertions.assertTrue(1.0 >= PI_4 * SpecialMath.tan2(Math.nextDown(PI_4))); // Monotonic function at the transition Assertions.assertTrue(SpecialMath.tan2(Math.nextUp(PI_4)) >= SpecialMath.tan2(PI_4)); } /** * Assumption test: * Demonstrate the CMS algorithm matches the Weron formula when {@code alpha != 1}. * This shows the two are equivalent; they should match as the formulas are rearrangements. */ @Test void testSamplesWithAlphaNot1() { // Use non-extreme parameters. beta and u are negated so use non-redundant values final double[] alphas = {0.3, 0.9, 1.1, 1.5}; final double[] betas = {-1, -0.5, -0.3, 0}; final double[] ws = {0.1, 1, 3}; final double[] us = {0.1, 0.25, 0.5, 0.8}; final double relative = 1e-5; final double absolute = 1e-10; for (final double alpha : alphas) { for (final double beta : betas) { for (final double w : ws) { for (final double u : us) { final double x = sampleCMS(alpha, beta, w, u); final double y = sampleWeronAlphaNot1(alpha, beta, w, u); Assertions.assertEquals(x, y, Math.max(absolute, Math.abs(x) * relative)); // Test symmetry final double z = sampleCMS(alpha, -beta, w, 1 - u); Assertions.assertEquals(x, -z, 0.0); } } } } } /** * Assumption test: * Demonstrate the CMS algorithm matches the Weron formula when {@code alpha == 1}. * This shows the two are equivalent; they should match as the formulas are rearrangements. */ @Test void testSamplesWithAlpha1() { // Use non-extreme parameters. beta and u are negated so use non-redundant values final double[] betas = {-1, -0.5, -0.3, 0}; final double[] ws = {0.1, 1, 3}; final double[] us = {0.1, 0.25, 0.5, 0.8}; final double relative = 1e-5; final double absolute = 1e-10; final double alpha = 1; for (final double beta : betas) { for (final double w : ws) { for (final double u : us) { final double x = sampleCMS(alpha, beta, w, u); final double y = sampleWeronAlpha1(beta, w, u); Assertions.assertEquals(x, y, Math.max(absolute, Math.abs(x) * relative)); // Test symmetry final double z = sampleCMS(alpha, -beta, w, 1 - u); Assertions.assertEquals(x, -z, 0.0); } } } } /** * Assumption test: * Demonstrate the CMS formula is continuous as {@code alpha -> 1}. * Demonstrate the Weron formula is not continuous as {@code alpha -> 1}. */ @Test void testConvergenceWithAlphaCloseTo1() { final double[] betas = {-1, -0.5, 0, 0.3, 1}; final double[] ws = {0.1, 1, 10}; final double[] us = {0.1, 0.25, 0.5, 0.8}; final int steps = 30; // Start with alpha not close to 0. The value 0.0625 is a power of 2 so is scaled // exactly by dividing by 2. With 30 steps this ranges from 2^-4 to 2^-34 leaving alpha: // 1.0625 -> 1.0000000000582077 or // 0.9375 -> 0.9999999999417923. for (double deltaStart : new double[] {-0.0625, 0.0625}) { // As alpha approaches 1 the value should approach the value when alpha=0. // Count the number of times it get further away with a change of alpha. int cmsCount = 0; int weronCount = 0; for (final double beta : betas) { for (final double w : ws) { for (final double u : us) { // CMS formulas double x0 = sampleCMS(1, beta, w, u); Assertions.assertTrue(Double.isFinite(x0), "Target must be finite"); // Sample should approach x0 as alpha approaches 1 double delta = deltaStart; double dx = Math.abs(x0 - sampleCMS(1 + delta, beta, w, u)); for (int i = 0; i < steps; i++) { delta /= 2; final double dx2 = Math.abs(x0 - sampleCMS(1 + delta, beta, w, u)); if (dx2 > dx) { cmsCount++; } dx = dx2; } // Weron formulas x0 = sampleWeronAlpha1(beta, w, u); Assertions.assertTrue(Double.isFinite(x0), "Target must be finite"); // Sample should approach x0 as alpha approaches 1 delta = deltaStart; dx = Math.abs(x0 - sampleWeronAlphaNot1(1 + delta, beta, w, u)); for (int i = 0; i < steps; i++) { delta /= 2; final double dx2 = Math.abs(x0 - sampleWeronAlphaNot1(1 + delta, beta, w, u)); if (dx2 > dx) { weronCount++; } dx = dx2; } } } } // The CMS formala monotonically converges Assertions.assertEquals(0, cmsCount); // The weron formula does not monotonically converge // (difference to the target can be bigger when alpha moves closer to 1). Assertions.assertTrue(weronCount > 200); } } /** * Test extreme inputs to the CMS algorithm where {@code alpha != 1} and/or * {@code beta != 0}. These demonstrate cases where the parameters and the * random variates will create non-finite samples. The test checks that the Weron * formula can create an appropriate sample for all cases where the CMS formula fails. */ @Test void testExtremeInputsToSample() { // Demonstrate instability when w = 0 Assertions.assertEquals(Double.NaN, sampleCMS(1.3, 0.7, 0, 0.25)); Assertions.assertTrue(Double.isFinite(sampleCMS(1.3, 0.7, SMALL_W, 0.25))); // Demonstrate instability when u -> 0 or 1, and |beta| = 1 Assertions.assertEquals(Double.NaN, sampleCMS(1.1, 1.0, 0.1, 0)); Assertions.assertTrue(Double.isFinite(sampleCMS(1.1, 1.0, 0.1, DU))); // Demonstrate instability when alpha -> 0 // Small alpha does not tolerate very small w. Assertions.assertEquals(Double.NaN, sampleCMS(0.01, 0.7, SMALL_W, 0.5)); // Very small alpha does not tolerate u approaching 0 or 1 (depending on the // skew) Assertions.assertEquals(Double.NaN, sampleCMS(1e-5, 0.7, 1.0, 1e-4)); Assertions.assertEquals(Double.NaN, sampleCMS(1e-5, -0.7, 1.0, 1 - 1e-4)); final double[] alphas = {Math.nextDown(2), 1.3, 1.1, Math.nextUp(1), 1, Math.nextDown(1), 0.7, 0.1, 0.05, 0.01, 0x1.0p-16}; final double[] betas = {1, 0.9, 0.001, 0}; // Avoid zero for the exponential sample. // Test the smallest non-zero sample from the ArhensDieter exponential sampler, // and the largest sample. final double[] ws = {0, SMALL_W, 0.001, 1, 10, LARGE_W}; // The algorithm requires a uniform deviate in (0, 1). // Use extremes of the 2^53 dyadic rationals in (0, 1) up to the symmetry limit // (i.e. 0.5). final double[] us = {DU, 2 * DU, 0.0001, 0.5 - DU, 0.5}; int nan1 = 0; for (final double alpha : alphas) { for (final double beta : betas) { if (alpha == 1 && beta == 0) { // Ignore the Cauchy case continue; } // Get the support of the distribution. This is not -> +/-infinity // when alpha < 1 and beta = +/-1. final double[] support = getSupport(alpha, beta); final double lower = support[0]; final double upper = support[1]; for (final double w : ws) { for (final double u : us) { final double x1 = sampleCMS(alpha, beta, w, u); final double x2 = sampleWeron(alpha, beta, w, u); if (Double.isNaN(x1)) { nan1++; } // The edge-case corrected Weron formula should not fail Assertions.assertNotEquals(Double.NaN, x2); // Check symmetry of each formula. // Use a delta of zero to allow equality of 0.0 and -0.0. Assertions.assertEquals(x1, 0.0 - sampleCMS(alpha, -beta, w, 1 - u), 0.0); Assertions.assertEquals(x2, 0.0 - sampleWeron(alpha, -beta, w, 1 - u), 0.0); if (Double.isInfinite(x1) && x1 != x2) { // Check the Weron correction for extreme samples. // The result should be at the correct *finite* support bounds. // Note: This applies when alpha < 1 and beta = +/-1. Assertions.assertTrue(lower <= x2 && x2 <= upper); } } } } } // The CMS algorithm is expected to fail some cases Assertions.assertNotEquals(0, nan1); } /** * Create a sample from a stable distribution. This is an implementation of the CMS * algorithm to allow exploration of various input values. The algorithm matches that * in the {@link CMSStableSampler} with the exception that the uniform variate * is provided in {@code (0, 1)}, not{@code (-pi/4, pi/4)}. * * @param alpha Stability parameter. Must be in the interval {@code (0, 2]}. * @param beta Skewness parameter. Must be in the interval {@code [-1, 1]}. * @param w Exponential variate * @param u Uniform variate * @return the sample */ private static double sampleCMS(double alpha, double beta, double w, double u) { final double phiby2 = PI_2 * (u - 0.5); final double eps = 1 - alpha; // Do not use alpha in place of 1 - eps. When alpha < 0.5, 1 - eps == alpha is not // always true as the reverse is not exact. final double meps1 = 1 - eps; // Compute RSTAB prefactor final double tau = CMSStableSampler.getTau(alpha, beta); // Generic stable distribution that is continuous as alpha -> 1. // This is a trigonomic rearrangement of equation 4.1 from Chambers et al (1976) // as implemented in the Fortran program RSTAB. // Uses the special functions: // tan2 = tan(x) / x // d2 = (exp(x) - 1) / x // Here tan2 is implemented using an high precision approximation. // Compute some tangents // Limits for |phi/2| < pi/4 // a in (-1, 1) final double a = phiby2 * SpecialMath.tan2(phiby2); // bb in [1, 4/pi) final double bb = SpecialMath.tan2(eps * phiby2); // b in (-1, 1) final double b = eps * phiby2 * bb; // Compute some necessary subexpressions final double da = a * a; final double db = b * b; // a2 in (0, 1] final double a2 = 1 - da; // a2p in [1, 2) final double a2p = 1 + da; // b2 in (0, 1] final double b2 = 1 - db; // b2p in [1, 2) final double b2p = 1 + db; // Compute coefficient. // Note: // Avoid z <= 0 to avoid log(z) as negative infinity or nan. // This occurs when |phiby2| -> +/-pi/4 and |beta| -> 1. // Problems: // numerator=0 => z=0 // denominator=0 => z=inf // numerator=denominator=0 => z=nan // 1. w or a2 are zero so the denominator is zero. w can be a rare exponential sample. // a2 -> zero if the uniform deviate is 0 or 1 and angle is |pi/4|. // If w -> 0 and |u-0.5| -> 0.5 then the product of w * a2 can be zero. // 2. |eps|=1, phiby2=|pi/4| => bb=4/pi, b=1, b2=0; if tau=0 then the numerator is zero. // This requires beta=0. final double z = a2p * (b2 + 2 * phiby2 * bb * tau) / (w * a2 * b2p); // Compute the exponential-type expression final double alogz = Math.log(z); final double d = SpecialMath.d2(eps * alogz / meps1) * (alogz / meps1); // Compute stable return (1 + eps * d) * (2 * ((a - b) * (1 + a * b) - phiby2 * tau * bb * (b * a2 - 2 * a))) / (a2 * b2p) + tau * d; } /** * Create a sample from a stable distribution. This is an implementation of the Weron formula. * The formula has been modified when alpha != 1 to return the 0-parameterization result and * correct extreme samples to +/-infinity. * * @param alpha Stability parameter. Must be in the interval {@code (0, 2]}. * @param beta Skewness parameter. Must be in the interval {@code [-1, 1]}. * @param w Exponential variate * @param u Uniform variate * @return the sample * @see <a href="https://doi.org/10.1016%2F0167-7152%2895%2900113-1">Weron, R (1996). * "On the Chambers-Mallows-Stuck method for simulating skewed stable random variables". * Statistics &amp; Probability Letters. 28 (2): 165–171.</a> */ private static double sampleWeron(double alpha, double beta, double w, double u) { return alpha == 1 ? sampleWeronAlpha1(beta, w, u) : sampleWeronAlphaNot1(alpha, beta, w, u); } /** * Create a sample from a stable distribution. This is an implementation of the * Weron {@code alpha != 1} formula. The formula has been modified to return the * 0-parameterization result and correct extreme samples to +/-infinity. The * algorithm matches that in the {@link WeronStableSampler} with the exception that * the uniform variate is provided in {@code (0, 1)}, not{@code (-pi/2, pi/2)}. * * <p>Due to the increasingly large shift (up to 1e16) as {@code alpha -> 1} * that is used to move the result to the 0-parameterization the samples around * the mode of the distribution have large cancellation and a reduced number of * bits in the sample value. * * @param alpha Stability parameter. Must be in the interval {@code (0, 2]}. * @param beta Skewness parameter. Must be in the interval {@code [-1, 1]}. * @param w Exponential variate * @param u Uniform variate * @return the sample * @see <a href="https://doi.org/10.1016%2F0167-7152%2895%2900113-1">Weron, R * (1996). * "On the Chambers-Mallows-Stuck method for simulating skewed stable random variables". * Statistics &amp; Probability Letters. 28 (2): 165–171.</a> */ private static double sampleWeronAlphaNot1(double alpha, double beta, double w, double u) { // Update for symmetry around alpha = 1 final double eps = 1 - alpha; final double meps1 = 1 - eps; double zeta; if (meps1 > 1) { zeta = beta * Math.tan((2 - meps1) * PI_2); } else { zeta = -beta * Math.tan(meps1 * PI_2); } final double scale = Math.pow(1 + zeta * zeta, 0.5 / meps1); final double invAlpha = 1.0 / meps1; final double invAlphaM1 = invAlpha - 1; final double phi = Math.PI * (u - 0.5); // Generic stable distribution. // Note: Adding back zeta creates the 0-parameterization defined in Nolan (1998): // X ~ S0_alpha(s,beta,u0) with s=1, u0=0 for a standard random variable. // As alpha -> 1 the translation zeta to create the stable deviate // in the 0-parameterization is increasingly large as tan(pi/2) -> infinity. // The max translation is approximately 1e16. // Without this translation the stable deviate is in the 1-parameterization // and the function is not continuous with respect to alpha. // Due to the large zeta when alpha -> 1 the number of bits of the output variable // are very low due to cancellation. // As alpha -> 0 or 2 then zeta -> 0 and cancellation is not relevant. // The formula can be modified for infinite terms to compute a result for extreme // deviates u and w when the CMS formula fails. // Note the following term is subject to floating point error: // final double xi = Math.atan(-zeta) / alpha; // final double alphaPhiXi = alpha * (phi + xi); // This is required: cos(phi - alphaPhiXi) > 0 => phi - alphaPhiXi in (-pi/2, pi/2). // Thus we compute atan(-zeta) and use it to compute two terms: // [1] alpha * (phi + xi) = alpha * (phi + atan(-zeta) / alpha) = alpha * phi + atan(-zeta) // [2] phi - alpha * (phi + xi) = phi - alpha * phi - atan(-zeta) = (1-alpha) * phi - atan(-zeta) final double atanZeta = Math.atan(-zeta); // Compute terms // Either term can be infinite or 0. Certain parameters compute 0 * inf. // t1=inf occurs alpha -> 0. // t1=0 occurs when beta = tan(-alpha * phi) / tan(alpha * pi / 2). // t2=inf occurs when w -> 0 and alpha -> 0. // t2=0 occurs when alpha -> 0 and phi -> pi/2. // Detect zeros and return as zeta. // Note sin(alpha * phi + atanZeta) is zero when: // alpha * phi = -atan(-zeta) // tan(-alpha * phi) = -zeta // = beta * tan(alpha * pi / 2) // Since |phi| < pi/2 this requires beta to have an opposite sign to phi // and a magnitude < 1. This is possible and in this case avoid a possible // 0 / 0 by setting the result as if term t1=0 and the result is zeta. double t1 = Math.sin(meps1 * phi + atanZeta); if (t1 == 0) { return zeta; } // Since cos(phi) is in (0, 1] this term will not create a // large magnitude to create t1 = 0. t1 /= Math.pow(Math.cos(phi), invAlpha); // Iff Math.cos(eps * phi - atanZeta) is zero then 0 / 0 can occur if w=0. // Iff Math.cos(eps * phi - atanZeta) is below zero then NaN will occur // in the power function. These cases are avoided by u=(0,1) and direct // use of arctan(-zeta). final double t2 = Math.pow(Math.cos(eps * phi - atanZeta) / w, invAlphaM1); if (t2 == 0) { return zeta; } return t1 * t2 * scale + zeta; } /** * Create a sample from a stable distribution. This is an implementation of the Weron * {@code alpha == 1} formula. The algorithm matches that * in the {@link Alpha1StableSampler} with the exception that * the uniform variate is provided in {@code (0, 1)}, not{@code (-pi/2, pi/2)}. * * @param alpha Stability parameter. Must be in the interval {@code (0, 2]}. * @param beta Skewness parameter. Must be in the interval {@code [-1, 1]}. * @param w Exponential variate * @param u Uniform variate * @return the sample * @see <a href="https://doi.org/10.1016%2F0167-7152%2895%2900113-1">Weron, R (1996). * "On the Chambers-Mallows-Stuck method for simulating skewed stable random variables". * Statistics &amp; Probability Letters. 28 (2): 165–171.</a> */ private static double sampleWeronAlpha1(double beta, double w, double u) { // phi in (-pi/2, pi/2) final double phi = Math.PI * (u - 0.5); // Generic stable distribution with alpha = 1 final double betaPhi = PI_2 + beta * phi; return (betaPhi * Math.tan(phi) - beta * Math.log(PI_2 * w * Math.cos(phi) / betaPhi)) / PI_2; } /*******************************/ /* Tests for the StableSampler */ /*******************************/ /** * Test the general CMS sampler when the random generator outputs create * deviates that cause the value {@code z} to be negative. */ @Test void testSamplesWithZBelow0() { // Call the CMS algorithm with u->1; phi/2 -> pi/4. // The value with all bits set generates phi/2 -> pi/4. // Add a long to create a big value for w of 5. // The parameters create cancellation in the numerator of z to create a negative z. final long[] longs = {Long.MAX_VALUE, -6261465550279131136L}; final double phiby2 = PI_4 - PI_4 * DU; final double w = 5.0; assertUWSequence(new double[] { phiby2, w, }, longs); // The alpha parameter has been identified via a search with beta=-1. // See testZIsNotAlwaysAboveZero() final double alpha = 1.291015625; final double beta = -1; Assertions.assertTrue(0.0 > computeNumerator(alpha, beta, Long.MAX_VALUE)); // z will be negative. Repeat computation assumed to be performed by the sampler. // This ensures the test should be updated if the sampler implementation changes. final double eps = 1 - alpha; final double tau = CMSStableSampler.getTau(alpha, beta); final double a = phiby2 * SpecialMath.tan2(phiby2); final double bb = SpecialMath.tan2(eps * phiby2); final double b = eps * phiby2 * bb; final double da = a * a; final double db = b * b; final double a2 = 1 - da; final double a2p = 1 + da; final double b2 = 1 - db; final double b2p = 1 + db; final double z = a2p * (b2 + 2 * phiby2 * bb * tau) / (w * a2 * b2p); Assertions.assertTrue(0.0 > z); final StableSampler sampler = StableSampler.of(createRngWithSequence(longs), alpha, beta); // It should not be NaN or infinite Assertions.assertTrue(Double.isFinite(sampler.sample()), "Sampler did not recover"); } /** * Test the general CMS sampler when the random generator outputs create * deviates that cause the value {@code z} to be infinite. */ @Test void testSamplesWithZInfinite() { // Call the CMS algorithm with w=0 (and phi/2 is not extreme). final long[] longs = {Long.MIN_VALUE >>> 1, 0}; assertUWSequence(new double[] { PI_4 / 2, 0, }, longs); for (final double alpha : new double[] {0.789, 1, 1.23}) { // Test all directions for (final double beta : new double[] {-0.56, 0, 0.56}) { // Ignore Cauchy case which does not use the exponential deviate if (alpha == 1 && beta == 0) { continue; } final StableSampler sampler = StableSampler.of(createRngWithSequence(longs), alpha, beta); final double x = sampler.sample(); // It should not be NaN Assertions.assertFalse(Double.isNaN(x), "Sampler did not recover"); if (beta != 0) { // The sample is extreme so should be at a limit of the support if (alpha < 0) { // Effectively +/- infinity Assertions.assertEquals(Math.copySign(Double.POSITIVE_INFINITY, beta), x); } else if (alpha > 1) { // At the distribution mean final double[] support = getSupport(alpha, beta); final double mu = support[2]; Assertions.assertEquals(mu, x); } } } } } /** * Test the CMS sampler when the random generator outputs create * deviates that cause the value {@code d} to be infinite. */ @Test void testSamplesWithDInfinite() { // beta != 0 but with low skew to allow the direction switch in // phi/2 to create opposite directions. testSamplesWithDInfinite(0.01); testSamplesWithDInfinite(-0.01); } /** * Test the {@code beta=0} CMS sampler when the random generator outputs create * deviates that cause the value {@code d} to be infinite. */ @Test void testBeta0SamplesWithDInfinite() { testSamplesWithDInfinite(0.0); } /** * Test the CMS sampler when the random generator outputs create deviates that * cause the value {@code d} to be infinite. This applies to the general sampler * or the sampler with {@code beta=0}. * * @param beta beta (should be close or equal to zero to allow direction changes due to the * angle phi/2 to be detected) */ private static void testSamplesWithDInfinite(double beta) { // Set-up the random deviate u to be close to -pi/4 (low), pi/4 (high) and 0.5. // The extreme values for u create terms during error correction that are infinite. final long xuLo = Long.MIN_VALUE + (1024 << 10); final long xuHi = Long.MAX_VALUE - (1023 << 10); // Call sampler with smallest possible w that is not 0. This creates a finite z // but an infinite d due to the use of alpha -> 0. final long x = 3L; final long[] longs = {xuLo, x, xuHi, x, 0, x}; assertUWSequence(new double[] { -PI_4 + 1024 * DU * PI_4, SMALL_W, PI_4 - 1024 * DU * PI_4, SMALL_W, 0.0, SMALL_W }, longs); // alpha must be small to create infinite d and beta with low skew // to allow the direction switch in phi/2 to create opposite directions. // If the skew is too large then the skew dominates the direction. // When u=0.5 then f=0 and a standard sum of (1 + eps * d) * f + tau * d // with d=inf would cause inf * 0 = NaN. final double alpha = 0.03; final StableSampler sampler = StableSampler.of(createRngWithSequence(longs), alpha, beta); final double x1 = sampler.sample(); final double x2 = sampler.sample(); final double x3 = sampler.sample(); // Expect the limit of the support (the direction is controlled by extreme phi) final double max = Double.POSITIVE_INFINITY; Assertions.assertEquals(-max, x1); Assertions.assertEquals(max, x2); // Expect the sampler to avoid inf * 0 Assertions.assertNotEquals(Double.NaN, x3); // When f=0 the sample should be in the middle (beta=0) or skewed in the direction of beta if (beta == 0) { // In the middle Assertions.assertEquals(0.0, x3); } else { // At the support limit Assertions.assertEquals(Math.copySign(max, beta), x3); } } /** * Test the {@code alpha=1} CMS sampler when the random generator outputs create * deviates that cause the value {@code phi/2} to be at the extreme limits. */ @Test void testAlpha1SamplesWithExtremePhi() { // The numerator is: // 1 + 2 * phiby2 * tau // tau = beta / pi/2 when alpha=1 // = +/-2 / pi when alpha=1, beta = +/-1 // This should not create zero if phi/2 is not pi/4. // Test the limits of phi/2 to check samples are finite. // Add a long to create an ordinary value for w of 1.0. // u -> -pi/4 final long[] longs1 = {Long.MIN_VALUE + (1 << 10), 2703662416942444033L}; assertUWSequence(new double[] { -PI_4 + PI_4 * DU, 1.0, }, longs1); final StableSampler sampler1 = StableSampler.of(createRngWithSequence(longs1), 1.0, 1.0); final double x1 = sampler1.sample(); Assertions.assertTrue(Double.isFinite(x1), "Sampler did not recover"); // u -> pi/4 final long[] longs2 = {Long.MAX_VALUE, 2703662416942444033L}; assertUWSequence(new double[] { PI_4 - PI_4 * DU, 1.0, }, longs2); final StableSampler sampler2 = StableSampler.of(createRngWithSequence(longs2), 1.0, -1.0); final double x2 = sampler2.sample(); Assertions.assertTrue(Double.isFinite(x2), "Sampler did not recover"); // Sample should be a reflection Assertions.assertEquals(x1, -x2); } /** * Test the support of the distribution when {@code gamma = 1} and * {@code delta = 0}. A non-infinite support applies when {@code alpha < 0} and * {@code |beta| = 1}. */ @Test void testSupport() { testSupport(1.0, 0.0); } /** * Test the support of the distribution when {@code gamma != 1} and * {@code delta != 0}. A non-infinite support applies when {@code alpha < 0} and * {@code |beta| = 1}. */ @Test void testSupportWithTransformation() { // This tests extreme values which should not create NaN results for (final double gamma : new double[] {0.78, 1.23, Double.MAX_VALUE, Double.MIN_VALUE}) { for (final double delta : new double[] {0.43, 12.34, Double.MAX_VALUE}) { testSupport(gamma, delta); testSupport(gamma, -delta); } } } /** * Test the support of the distribution. This applies when {@code alpha < 0} and * {@code |beta| = 1}. * * @param alpha Stability parameter. Must be in range {@code (0, 2]}. * @param beta Skewness parameter. Must be in range {@code [-1, 1]}. * @param gamma Scale parameter. Must be strictly positive and finite. * @param delta Location parameter. Must be finite. */ private static void testSupport(double gamma, double delta) { // When alpha is small (<=0.1) the computation becomes limited by floating-point precision. final double[] alphas = {2.0, 1.5, 1.0, Math.nextDown(1), 0.99, 0.75, 0.5, 0.25, 0.1, 0.01}; for (final double alpha : alphas) { testSupport(alpha, 1, gamma, delta); testSupport(alpha, -1, gamma, delta); } } /** * Test the support of the distribution. This applies when {@code alpha < 0} and * {@code |beta| = 1}. * * @param alpha Stability parameter. Must be in range {@code (0, 2]}. * @param beta Skewness parameter. Must be in range {@code [-1, 1]}. * @param gamma Scale parameter. Must be strictly positive and finite. * @param delta Location parameter. Must be finite. */ private static void testSupport(double alpha, double beta, double gamma, double delta) { // This is the inclusive bounds (no infinite values) final double[] support = getSupport(alpha, beta); // Do not scale the max value. It acts as an effective infinity. double lower; if (support[0] == -Double.MAX_VALUE) { lower = Double.NEGATIVE_INFINITY; } else { lower = support[0] * gamma + delta; } double upper; if (support[1] == Double.MAX_VALUE) { upper = Double.POSITIVE_INFINITY; } else { upper = support[1] * gamma + delta; } // Create an RNG that will generate extreme values: // Here we use 4 recursions into the tail of the exponential. The large exponential // deviate is approximately 30.3. final long[] longs = new long[] { // Note: Add a long of Long.MIN_VALUE to test the sampler ignores this value. // Hits edge case for generation of phi/4 in (-pi/4, pi/4) Long.MIN_VALUE, // phi/2 -> -pi/4, w=0 Long.MIN_VALUE + (1 << 10), 0, // phi/2 -> -pi/4, w=large Long.MIN_VALUE + (1 << 10), -1, -1, -1, -1, -1, -1, -1, -1, 0, // phi/2 -> pi/4, w=0 Long.MAX_VALUE, 0, // phi/2 -> pi/4, w=large Long.MAX_VALUE, -1, -1, -1, -1, -1, -1, -1, -1, 0, // phi/2=0, w=0 0, 0, // phi/2=0, w=inf 0, -1, -1, -1, -1, -1, -1, -1, -1, 0, // Add non extreme exponential deviate to test only extreme u // phi/2 -> -pi/4, w=1 Long.MIN_VALUE + (1 << 10), 2703662416942444033L, // phi/2 -> pi/4, w=1 Long.MAX_VALUE, 2703662416942444033L, // phi/2=0, w=1 0, 2703662416942444033L, // Add non extreme uniform deviate to test only extreme w // phi/2=pi/5, w=0 Long.MIN_VALUE >> 1, 0, // phi/2=pi/5, w=large Long.MIN_VALUE >> 1, -1, -1, -1, -1, -1, -1, -1, -1, 0, // phi/2=pi/5, w=0 Long.MIN_VALUE >>> 1, 0, // phi/2=pi/5, w=large Long.MIN_VALUE >>> 1, -1, -1, -1, -1, -1, -1, -1, -1, 0, }; // Validate series final double phiby2low = -PI_4 + PI_4 * DU; final double phiby2high = PI_4 - PI_4 * DU; assertUWSequence(new double[] { phiby2low, 0, phiby2low, LARGE_W, phiby2high, 0, phiby2high, LARGE_W, 0, 0, 0, LARGE_W, phiby2low, 1.0, phiby2high, 1.0, 0, 1.0, -PI_4 / 2, 0, -PI_4 / 2, LARGE_W, PI_4 / 2, 0, PI_4 / 2, LARGE_W, }, longs); final StableSampler sampler = StableSampler.of( createRngWithSequence(longs), alpha, beta, gamma, delta); for (int i = 0; i < 100; i++) { final double x = sampler.sample(); if (!(lower <= x && x <= upper)) { Assertions.fail(String.format("Invalid sample. alpha=%s, beta=%s, gamma=%s, delta=%s [%s, %s] x=%s", alpha, beta, gamma, delta, lower, upper, x)); } } } /** * Gets the support of the distribution. This returns the inclusive bounds. So exclusive * infinity is computed as the maximum finite value. Compute the value {@code mu} which is the * mean of the distribution when {@code alpha > 1}. * * <pre> * x in [mu, +inf) if alpha < 1, beta = 1 * x in (-inf, mu] if alpha < 1, beta = -1 * x in (-inf, -inf) otherwise * </pre> * * @param alpha the alpha * @param beta the beta * @return the support ({lower, upper, mu}) */ private static double[] getSupport(double alpha, double beta) { // Convert alpha as used by the sampler double eps = 1 - alpha; double meps1 = 1 - eps; // Since pi is approximate the symmetry is lost by wrapping. // Keep within the domain using (2-alpha). double mu; if (alpha > 1) { mu = beta * Math.tan((2 - meps1) * PI_2); } else { // Special case where tan(pi/4) is not 1 (it is Math.nextDown(1.0)). // This is needed when testing the Levy case during sampling. if (alpha == 0.5) { mu = -beta; } else { mu = -beta * Math.tan(meps1 * PI_2); } } // Standard support double lower = -Double.MAX_VALUE; double upper = Double.MAX_VALUE; if (meps1 < 1) { if (beta == 1) { // alpha < 0, beta = 1 lower = mu; } else if (beta == -1) { // alpha < 0, beta = -1 upper = mu; } } return new double[] {lower, upper, mu}; } /** * Assumption test: * Test the random deviates u and w can be generated by manipulating the RNG. */ @Test void testRandomDeviatesUandW() { // Extremes of the uniform deviate generated using the same method as the sampler final double d = DU * PI_4; // Test in (-pi/4, pi/4) Assertions.assertNotEquals(-PI_4, getU(createRngWithSequence(Long.MIN_VALUE))); Assertions.assertEquals(-PI_4 + d, getU(createRngWithSequence(Long.MIN_VALUE + (1 << 10)))); Assertions.assertEquals(-PI_4 / 2, getU(createRngWithSequence(Long.MIN_VALUE >> 1))); Assertions.assertEquals(-d, getU(createRngWithSequence(-1))); Assertions.assertEquals(0.0, getU(createRngWithSequence(0))); Assertions.assertEquals(d, getU(createRngWithSequence(1 << 10))); Assertions.assertEquals(PI_4 / 2, getU(createRngWithSequence(Long.MIN_VALUE >>> 1))); Assertions.assertEquals(PI_4 - d, getU(createRngWithSequence(Long.MAX_VALUE))); // Extremes of the exponential sampler Assertions.assertEquals(0, ZigguratSampler.Exponential.of( createRngWithSequence(0L)).sample()); Assertions.assertEquals(SMALL_W, ZigguratSampler.Exponential.of( createRngWithSequence(3)).sample()); Assertions.assertEquals(0.5, ZigguratSampler.Exponential.of( createRngWithSequence(1446480648965178882L)).sample()); Assertions.assertEquals(1.0, ZigguratSampler.Exponential.of( createRngWithSequence(2703662416942444033L)).sample()); Assertions.assertEquals(2.5, ZigguratSampler.Exponential.of( createRngWithSequence(6092639261715210240L)).sample()); Assertions.assertEquals(5.0, ZigguratSampler.Exponential.of( createRngWithSequence(-6261465550279131136L)).sample()); Assertions.assertEquals(TAIL_W, ZigguratSampler.Exponential.of( createRngWithSequence(-1, -1, 0)).sample()); Assertions.assertEquals(3 * TAIL_W, ZigguratSampler.Exponential.of( createRngWithSequence(-1, -1, -1, -1, -1, -1, 0)).sample(), 1e-14); } /** * Gets a uniform random variable in {@code (-pi/4, pi/4)}. * * <p>Copied from the StableSampler for testing. In the main sampler the variable u * is named either {@code phi} in {@code (-pi/2, pi/2)}, or * {@code phiby2} in {@code (-pi/4, pi/4)}. Here we test phiby2 for the CMS algorithm. * * @return u */ private static double getU(UniformRandomProvider rng) { final double x = getU(rng.nextLong()); if (x == -PI_4) { return getU(rng); } return x; } /** * Gets a uniform random variable in {@code [-pi/4, pi/4)} from a long value. * * <p>Copied from the StableSampler for testing. In the main sampler the variable u * is named either {@code phi} in {@code (-pi/2, pi/2)}, or * {@code phiby2} in {@code (-pi/4, pi/4)}. Here we test phiby2 for the CMS algorithm. * * <p>Examples of different output where {@code d} is the gap between values of {@code phi/2} * and is equal to {@code pi * 2^-55 = pi/4 * 2^-53}: * * <pre> * Long.MIN_VALUE -pi/4 * Long.MIN_VALUE + (1 << 10) -pi/4 + d * Long.MIN_VALUE >> 1 -pi/5 * -1 -d * 0 0.0 * 1 << 10 d * Long.MIN_VALUE >>> 1 pi/5 * Long.MAX_VALUE pi/4 - d * </pre> * * @return u */ private static double getU(long x) { return (x >> 10) * PI_4_SCALED; } /** * Creates a RNG that will return the provided output for the next double and * next long functions. When the sequence is complete a valid random output * continues. * * <p>The sampler generates (in order): * <ol> * <li>{@code phi/2} in {@code (-pi/4, pi/4)} using long values from the RNG. * <li>{@code w} using the {@link ZigguratSampler.Exponential}. * This uses a long values from the RNG. * </ol> * * <p>Careful control of the sequence can generate any value for {@code w} and {@code phi/2}. * The sampler creates a uniform deviate first, then an exponential deviate second. * Examples of different output where {@code d} is the gap between values of {@code phi/2} * and is equal to {@code pi * 2^-55 = pi/4 * 2^-53}: * * <pre> * longs phi/2 w * Long.MIN_VALUE try again [1] * Long.MIN_VALUE + (1 << 10) -pi/4 + d * Long.MIN_VALUE >> 1 -pi/5 * -1 -d * 0 0.0 0 * 1 << 10 d * Long.MIN_VALUE >>> 1 pi/5 * Long.MAX_VALUE pi/4 - d * 3 6.564735882096453E-19 * 1446480648965178882L 0.5 * 2703662416942444033L 1.0 * 6092639261715210240L 2.5 * -6261465550279131136L 5.0 * -1, -1, 0 7.569274694148063 * -1L * 2n, 0 n * 7.569274694148063 [2] * </pre> * * <ol> * <li>When phi/2=-pi/4 the method will ignore the value and obtain another long value. * <li>To create a large value for the exponential sampler requires recursion. Each input * of 2 * -1L will add 7.569274694148063 to the total. A long of zero will stop recursion. * </ol> * * @param longs the initial sequence of longs * @return the uniform random provider */ private static UniformRandomProvider createRngWithSequence(final long... longs) { // Note: // The StableSampler uniform deviate is generated from a long. // It is ignored if zero, a value of 1 << 11 generates the smallest value (2^-53). // // The ZigguratSampler.Exponential uses a single long value >98% of the time. // To create a certain value x the input y can be obtained by reversing the // computation of the corresponding precomputed factor X. The lowest 8 bits of y // choose the index i into X so must be set as the lowest bits. // The long is shifted right 1 before multiplying by X so this must be reversed. // // To find y to obtain the sample x use: // double[] X = { /* from ZigguratSampler.Exponential */ } // double x = 1.0; // or any other value < 7.5 // for (int i = 0; i < X.length; i++) { // // Add back the index to the lowest 8 bits. // // This will work if the number is so big that the lower bits // // are zerod when casting the 53-bit mantissa to a long. // long y = ((long) (x / X[i]) << 1) + i; // if ((y >>> 1) * X[i] == x) { // // Found y! // } // } // Start with a valid RNG. // This is required for nextDouble() since invoking super.nextDouble() when // the sequence has expired will call nextLong() and may use the intended // sequence of longs. final UniformRandomProvider rng = RandomAssert.seededRNG(); // A RNG with the provided output return new SplitMix64(0L) { private int l; @Override public long nextLong() { if (l == longs.length) { return rng.nextLong(); } return longs[l++]; } }; } /** * Assert the sequence of output from a uniform deviate and exponential deviate * created using the same method as the sampler. * * <p>The RNG is created using * {@link #createRngWithSequence(long[])}. See the method javadoc for * examples of how to generate different deviate values. * * @param expected the expected output (u1, w1, u2, w2, u3, w3, ...) * @param longs the initial sequence of longs */ private static void assertUWSequence(double[] expected, long[] longs) { final UniformRandomProvider rng = createRngWithSequence(longs); // Validate series final SharedStateContinuousSampler exp = ZigguratSampler.Exponential.of(rng); for (int i = 0; i < expected.length; i += 2) { final int j = i / 2; Assertions.assertEquals(expected[i], getU(rng), () -> j + ": Incorrect u"); if (i + 1 < expected.length) { Assertions.assertEquals(expected[i + 1], exp.sample(), () -> j + ": Incorrect w"); } } } /** * Test the sampler output is a continuous function of {@code alpha} and {@code beta}. * This test verifies the switch to the dedicated {@code alpha=1} or {@code beta=0} * samplers computes a continuous function of the parameters. */ @Test void testSamplerOutputIsContinuousFunction() { // Test alpha passing through 1 when beta!=0 (switch to an alpha=1 sampler) for (final double beta : new double[] {0.5, 0.2, 0.1, 0.001}) { testSamplerOutputIsContinuousFunction(1 + 8096 * DU, beta, 1.0, beta, 1 - 8096 * DU, beta, 0); testSamplerOutputIsContinuousFunction(1 + 1024 * DU, beta, 1.0, beta, 1 - 1024 * DU, beta, 1); // Not perfect when alpha -> 1 testSamplerOutputIsContinuousFunction(1 + 128 * DU, beta, 1.0, beta, 1 - 128 * DU, beta, 1); testSamplerOutputIsContinuousFunction(1 + 16 * DU, beta, 1.0, beta, 1 - 16 * DU, beta, 4); // This works with ulp=0. Either this is a lucky random seed or because the approach // to 1 creates equal output. testSamplerOutputIsContinuousFunction(1 + DU, beta, 1.0, beta, 1 - DU, beta, 0); } // Test beta passing through 0 when alpha!=1 (switch to a beta=0 sampler) for (final double alpha : new double[] {1.5, 1.2, 1.1, 1.001}) { testSamplerOutputIsContinuousFunction(alpha, 8096 * DU, alpha, 0, alpha, -8096 * DU, 0); testSamplerOutputIsContinuousFunction(alpha, 1024 * DU, alpha, 0, alpha, -1024 * DU, 0); testSamplerOutputIsContinuousFunction(alpha, 128 * DU, alpha, 0, alpha, -128 * DU, 1); // Not perfect when beta is very small testSamplerOutputIsContinuousFunction(alpha, 16 * DU, alpha, 0, alpha, -16 * DU, 64); testSamplerOutputIsContinuousFunction(alpha, DU, alpha, 0, alpha, -DU, 4); } // Note: No test for transition to the Cauchy case (alpha=1, beta=0). // Requires a RNG that discards output that would be used to create a exponential // deviate. Just create one each time a request for nextLong is performed and // ensure nextLong >>> 11 is not zero. // When the parameters create a special case sampler this will not work. // alpha passing through 0.5 when beta=1 (Levy sampler) // alpha -> 2 as the sampler (Gaussian sampler). } /** * Test sampler output is a continuous function of {@code alpha} and * {@code beta}. Create 3 samplers with the same RNG and test the middle sampler * computes a value between the upper and lower sampler. * * @param alpha1 lower sampler alpha * @param beta1 lower sampler beta * @param alpha2 middle sampler alpha * @param beta2 middle sampler beta * @param alpha3 upper sampler alpha * @param beta3 upper sampler beta */ private static void testSamplerOutputIsContinuousFunction(double alpha1, double beta1, double alpha2, double beta2, double alpha3, double beta3, int ulp) { final long seed = 0x62738468L; final UniformRandomProvider rng1 = RandomSource.XO_RO_SHI_RO_128_PP.create(seed); final UniformRandomProvider rng2 = RandomSource.XO_RO_SHI_RO_128_PP.create(seed); final UniformRandomProvider rng3 = RandomSource.XO_RO_SHI_RO_128_PP.create(seed); final StableSampler sampler1 = StableSampler.of(rng1, alpha1, beta1); final StableSampler sampler2 = StableSampler.of(rng2, alpha2, beta2); final StableSampler sampler3 = StableSampler.of(rng3, alpha3, beta3); final Supplier<String> msg = () -> String.format("alpha=%s, beta=%s", alpha2, beta2); for (int i = 0; i < 1000; i++) { final double x1 = sampler1.sample(); final double x2 = sampler2.sample(); final double x3 = sampler3.sample(); // x2 should be in between x1 and x3 if (x3 > x1) { if (x2 > x3) { // Should be the same Assertions.assertEquals(x3, x2, ulp * Math.ulp(x3), msg); } else if (x2 < x1) { Assertions.assertEquals(x1, x2, ulp * Math.ulp(x1), msg); } } else if (x3 < x1) { if (x2 < x3) { // Should be the same Assertions.assertEquals(x3, x2, ulp * Math.ulp(x3), msg); } else if (x2 > x1) { Assertions.assertEquals(x1, x2, ulp * Math.ulp(x1), msg); } } } } /** * Test the SharedStateSampler implementation for each case using a different implementation. */ @Test void testSharedStateSampler() { // Gaussian case testSharedStateSampler(2.0, 0.0); // Cauchy case testSharedStateSampler(1.0, 0.0); // Levy case testSharedStateSampler(0.5, 1.0); // Hit code coverage of alpha=0.5 (Levy case) but beta != 1 testSharedStateSampler(0.5, 0.1); // Beta 0 (symmetric) case testSharedStateSampler(1.3, 0.0); // Alpha 1 case testSharedStateSampler(1.0, 0.23); // Alpha close to 1 testSharedStateSampler(Math.nextUp(1.0), 0.23); // General case testSharedStateSampler(1.3, 0.1); // Small alpha cases testSharedStateSampler(1e-5, 0.1); testSharedStateSampler(1e-5, 0.0); // Large alpha case. // This hits code coverage for computing tau from (1-alpha) -> -1 testSharedStateSampler(1.99, 0.1); } /** * Test the SharedStateSampler implementation. This tests with and without the * {@code gamma} and {@code delta} parameters. * * @param alpha Alpha. * @param beta Beta. */ private static void testSharedStateSampler(double alpha, double beta) { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); StableSampler sampler1 = StableSampler.of(rng1, alpha, beta); StableSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); // Test shifted sampler1 = StableSampler.of(rng1, alpha, beta, 1.3, 13.2); sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * Test the implementation of the transformed sampler (scaled and translated). */ @Test void testTransformedSampler() { // Gaussian case // The Gaussian case has its own scaling where the StdDev is gamma * sqrt(2). // (N(x) * sqrt(2)) * gamma != N(x) * (sqrt(2) * gamma) // Test with a delta testTransformedSampler(2.0, 0.0, 1); // Cauchy case testTransformedSampler(1.0, 0.0); // Levy case testTransformedSampler(0.5, 1.0); // Symmetric case testTransformedSampler(1.3, 0.0); // Alpha 1 case testTransformedSampler(1.0, 0.23); // Alpha close to 1 testTransformedSampler(Math.nextUp(1.0), 0.23); // General case testTransformedSampler(1.3, 0.1); // Small alpha case testTransformedSampler(1e-5, 0.1); // Large alpha case. // This hits the case for computing tau from (1-alpha) -> -1. testTransformedSampler(1.99, 0.1); } /** * Test the implementation of the transformed sampler (scaled and translated). * The transformed output must match exactly. * * @param alpha Alpha. * @param beta Beta. */ private static void testTransformedSampler(double alpha, double beta) { testTransformedSampler(alpha, beta, 0); } /** * Test the implementation of the transformed sampler (scaled and translated). * The transformed output must match within the provided ULP. * * @param alpha Alpha. * @param beta Beta. * @param ulp Allowed ULP difference. */ private static void testTransformedSampler(double alpha, double beta, int ulp) { final UniformRandomProvider[] rngs = RandomAssert.createRNG(2); final UniformRandomProvider rng1 = rngs[0]; final UniformRandomProvider rng2 = rngs[1]; final double gamma = 3.4; final double delta = -17.3; final StableSampler sampler1 = StableSampler.of(rng1, alpha, beta, gamma, delta); final ContinuousSampler sampler2 = createTransformedSampler(rng2, alpha, beta, gamma, delta); if (ulp == 0) { RandomAssert.assertProduceSameSequence(sampler1, sampler2); } else { for (int i = 0; i < 10; i++) { final double x1 = sampler1.sample(); final double x2 = sampler2.sample(); Assertions.assertEquals(x1, x2, ulp * Math.ulp(x1)); } } } /** * Create a transformed sampler from a normalized sampler scaled and translated by * gamma and delta. * * @param rng Source of randomness. * @param alpha Alpha. * @param beta Beta. * @param gamma Gamma. * @param delta Delta. * @return the transformed sampler */ private static ContinuousSampler createTransformedSampler(UniformRandomProvider rng, double alpha, double beta, final double gamma, final double delta) { final StableSampler delegate = StableSampler.of(rng, alpha, beta); return new ContinuousSampler() { @Override public double sample() { return gamma * delegate.sample() + delta; } }; } /** * Test symmetry when when u and beta are mirrored around 0.5 and 0 respectively. */ @Test void testSymmetry() { final byte[] seed = RandomSource.KISS.createSeed(); for (final double alpha : new double[] {1e-4, 0.78, 1, 1.23}) { for (final double beta : new double[] {-0.43, 0.23}) { for (final double gamma : new double[] {0.78, 1, 1.23}) { for (final double delta : new double[] {-0.43, 0, 0.23}) { // The sampler generates u then w. // If u is not -pi/4 then only a single long is used. // This can be reversed around 0 by reversing the upper 54-bits. // w will use 1 long only for fast lookup and then additional longs // for edge of the ziggurat sampling. Fast look-up is always used // when the lowest 8-bits create a value below 252. // Use the same random source for two samplers. final UniformRandomProvider rng1 = RandomSource.KISS.create(seed); final UniformRandomProvider rng2 = RandomSource.KISS.create(seed); // RNG which will not return 0 for every other long. final UniformRandomProvider forward = new SplitMix64(0) { private int i; @Override public long nextLong() { // Manipulate alternate longs if ((i++ & 0x1) == 0) { // This must not be Long.MIN_VALUE. // So set the lowest bit of the upper 54-bits. final long x = rng1.nextLong() >>> 10 | 1L; // Shift back return x << 10; } // For the exponential sample ensure the lowest 8-bits are < 252. long x; do { x = rng1.nextLong(); } while ((x & 0xff) >= 252); return x; } }; // RNG which will not return 0 for every other long but this long is reversed. final UniformRandomProvider reverse = new SplitMix64(0) { private final long upper = 1L << 54; private int i; @Override public long nextLong() { // Manipulate alternate longs if ((i++ & 0x1) == 0) { // This must not be Long.MIN_VALUE. // So set the lowest bit of the upper 54-bits. final long x = rng2.nextLong() >>> 10 | 1L; // Reverse then shift back return (upper - x) << 10; } // For the exponential sample ensure the lowest 8-bits are < 252. long x; do { x = rng2.nextLong(); } while ((x & 0xff) >= 252); return x; } }; final StableSampler s1 = StableSampler.of(forward, alpha, beta, gamma, delta); // Since mirroring applies before the shift of delta this must be negated too final StableSampler s2 = StableSampler.of(reverse, alpha, -beta, gamma, -delta); for (int i = 0; i < 100; i++) { Assertions.assertEquals(s1.sample(), -s2.sample()); } } } } } } /** * Test symmetry for the Levy case ({@code alpha = 0.5} and {@code beta = 1}. */ @Test void testSymmetryLevy() { final double alpha = 0.5; final double beta = 1.0; final byte[] seed = RandomSource.KISS.createSeed(); final UniformRandomProvider rng1 = RandomSource.KISS.create(seed); final UniformRandomProvider rng2 = RandomSource.KISS.create(seed); for (final double gamma : new double[] {0.78, 1, 1.23}) { for (final double delta : new double[] {-0.43, 0, 0.23}) { final StableSampler s1 = StableSampler.of(rng1, alpha, beta, gamma, delta); // Since mirroring applies before the shift of delta this must be negated too final StableSampler s2 = StableSampler.of(rng2, alpha, -beta, gamma, -delta); for (int i = 0; i < 100; i++) { Assertions.assertEquals(s1.sample(), -s2.sample()); } } } } /** * Test the toString method for cases not hit in the rest of the test suite. * This test asserts the toString method always contains the string 'stable' * even for parameters that create the Gaussian, Cauchy or Levy cases. */ @Test void testToString() { final UniformRandomProvider rng = RandomAssert.seededRNG(); for (final double[] p : new double[][] { {1.3, 0.1}, {2.0, 0.0}, {1.0, 0.0}, {0.5, 1.0}, {1e-5, 0}, {1e-5, 0.1}, {0.7, 0.1, 3.0, 4.5}, }) { StableSampler sampler; if (p.length == 2) { sampler = StableSampler.of(rng, p[0], p[1]); } else { sampler = StableSampler.of(rng, p[0], p[1], p[2], p[3]); } final String s = sampler.toString().toLowerCase(); Assertions.assertTrue(s.contains("stable")); } } /** * Demonstrate the CMS sampler matches the Weron sampler when {@code alpha != 1}. * This shows the two are equivalent; they should match as the formulas are rearrangements. * Avoid testing as {@code alpha -> 1} as the Weron sampler loses bits of precision in * the output sample. * * <p>Note: Uses direct instantiation via the package-private constructors. This avoids * the factory method constructor to directly select the implementation. Constructor * parameters are not validated. */ @Test void testImplementationsMatch() { // Avoid extreme samples. Do this by manipulating the output of nextLong. // Generation of the random deviate u uses the top 54-bits of the long. // Unset a high bit to ensure getU cannot approach pi/4. // Set a low bit to ensure getU cannot approach -pi/4. final long unsetHighBit = ~(1L << 54); final long setLowBit = 1L << 53; final double hi = getU(Long.MAX_VALUE & unsetHighBit); final double lo = getU(Long.MIN_VALUE | setLowBit); // The limits are roughly pi/4 and -pi/4 Assertions.assertEquals(PI_4, hi, 2e-3); Assertions.assertEquals(-PI_4, lo, 2e-3); Assertions.assertEquals(0.0, lo + hi, 1e-3); // Setting a bit ensure the exponential sampler cannot be zero final UniformRandomProvider rng = createRngWithSequence(setLowBit); final double w = ZigguratSampler.Exponential.of(rng).sample(); Assertions.assertNotEquals(0.0, w); // This is the actual value; it is small but not extreme. Assertions.assertEquals(0.0036959349092519837, w); final RandomSource source = RandomSource.XO_RO_SHI_RO_128_SS; final long seed = 0x83762b3daf1c43L; final UniformRandomProvider rng1 = new SplitMix64(0L) { private UniformRandomProvider delegate = source.create(seed); @Override public long next() { final long x = delegate.nextLong(); return (x & unsetHighBit) | setLowBit; } }; final UniformRandomProvider rng2 = new SplitMix64(0L) { private UniformRandomProvider delegate = source.create(seed); @Override public long next() { final long x = delegate.nextLong(); return (x & unsetHighBit) | setLowBit; } }; // Not too close to alpha=1 final double[] alphas = {0.3, 0.5, 1.2, 1.5}; final double[] betas = {-0.5, -0.3, -0.1, 0}; final double relative = 1e-5; final double absolute = 1e-10; for (final double alpha : alphas) { for (final double beta : betas) { final Supplier<String> msg = () -> String.format("alpha=%s, beta=%s", alpha, beta); // WARNING: // Created by direct access to package-private constructor. // This is for testing only as these do not validate the parameters. StableSampler s1; StableSampler s2; if (beta == 0) { s1 = new Beta0CMSStableSampler(rng1, alpha); s2 = new Beta0WeronStableSampler(rng2, alpha); } else { s1 = new CMSStableSampler(rng1, alpha, beta); s2 = new WeronStableSampler(rng2, alpha, beta); } for (int i = 0; i < 1000; i++) { final double x = s1.sample(); final double y = s2.sample(); Assertions.assertEquals(x, y, Math.max(absolute, Math.abs(x) * relative), msg); } } } } /** * Demonstrate the general CMS sampler matches the {@code beta = 0} sampler. * The {@code beta = 0} sampler implements the same algorithm with cancelled terms removed. * * <p>Note: Uses direct instantiation via the package-private constructors. This avoids * the factory method constructor to directly select the implementation. Constructor * parameters are not validated. */ @Test void testSpecializedBeta0CMSImplementation() { final RandomSource source = RandomSource.XO_RO_SHI_RO_128_SS; // Should be robust to any seed final byte[] seed = source.createSeed(); final UniformRandomProvider rng1 = source.create(seed); final UniformRandomProvider rng2 = source.create(seed); final double[] alphas = {0.3, 0.5, 1.2, 1.5}; for (final double alpha : alphas) { // WARNING: // Created by direct access to package-private constructor. // This is for testing only as these do not validate the parameters. final StableSampler sampler1 = new CMSStableSampler(rng1, alpha, 0.0); final StableSampler sampler2 = new Beta0CMSStableSampler(rng2, alpha); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } } /** * Demonstrate the general Weron sampler matches the {@code beta = 0} sampler. * The {@code beta = 0} sampler implements the same algorithm with cancelled terms removed. * * <p>Note: Uses direct instantiation via the package-private constructors. This avoids * the factory method constructor to directly select the implementation. Constructor * parameters are not validated. */ @Test void testSpecializedBeta0WeronImplementation() { final RandomSource source = RandomSource.XO_RO_SHI_RO_128_SS; // Should be robust to any seed final byte[] seed = source.createSeed(); final UniformRandomProvider rng1 = source.create(seed); final UniformRandomProvider rng2 = source.create(seed); final double[] alphas = {0.3, 0.5, 1.2, 1.5}; for (final double alpha : alphas) { // WARNING: // Created by direct access to package-private constructor. // This is for testing only as these do not validate the parameters. final StableSampler sampler1 = new WeronStableSampler(rng1, alpha, 0.0); final StableSampler sampler2 = new Beta0WeronStableSampler(rng2, alpha); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } } /** * Test the Weron sampler when the term t1 is zero in the numerator. * This hits an edge case where sin(alpha * phi + atan(-zeta)) is zero. * * @see #testSinAlphaPhiMinusAtanZeta() */ @Test void testWeronImplementationEdgeCase() { double alpha = 0.25; // Solved in testSinAlphaPhiMinusAtanZeta() double beta = -0.48021693505171; // Require phi = PI_4. // This is the equivalent of phi/2 = pi/5 final long x = Long.MIN_VALUE >>> 1; final long[] longs = new long[] { // phi/2=pi/5, w=0 x, 0, // phi/2=pi/5, w=large x, -1, -1, -1, -1, -1, -1, -1, -1, 0, // phi/2=pi/5, w=1 x, 2703662416942444033L, }; // Validate series assertUWSequence(new double[] { PI_4 / 2, 0, PI_4 / 2, LARGE_W, PI_4 / 2, 1.0, }, longs); final double zeta = -beta * Math.tan(alpha * PI_2); Assertions.assertEquals(0.0, alpha * PI_4 + Math.atan(-zeta)); final UniformRandomProvider rng = createRngWithSequence(longs); final StableSampler sampler = new WeronStableSampler(rng, alpha, beta); // zeta is the offset used to shift the 1-parameterization to the // 0-parameterization. This is returned when other terms multiply to zero. Assertions.assertEquals(zeta, sampler.sample()); Assertions.assertEquals(zeta, sampler.sample()); Assertions.assertEquals(zeta, sampler.sample()); } }
2,956
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/PoissonSamplerCacheTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.RestorableUniformRandomProvider; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.apache.commons.rng.simple.RandomSource; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * This test checks the {@link PoissonSamplerCache} functions exactly like the * constructor of the {@link PoissonSampler}, irrespective of the range * covered by the cache. */ class PoissonSamplerCacheTest { // Set a range so that the SmallMeanPoissonSampler is also required. /** The minimum of the range of the mean */ private final int minRange = (int) Math.floor(PoissonSampler.PIVOT - 2); /** The maximum of the range of the mean */ private final int maxRange = (int) Math.floor(PoissonSampler.PIVOT + 6); /** The mid-point of the range of the mean */ private final int midRange = (minRange + maxRange) / 2; /** * Test the cache reports the minimum mean that uses an algorithm that supports caching. * This mean is the same level as the algorithm switch point in the PoissonSampler. */ @Test void testMinimumCachedMean() { Assertions.assertEquals(PoissonSampler.PIVOT, PoissonSamplerCache.getMinimumCachedMean()); } // Edge cases for construction /** * Test the cache can be created without a range that requires a cache. * In this case the cache will be a pass through to the constructor * of the SmallMeanPoissonSampler. */ @Test void testConstructorWithNoCache() { final double min = 0; final double max = PoissonSampler.PIVOT - 2; final PoissonSamplerCache cache = createPoissonSamplerCache(min, max); Assertions.assertFalse(cache.isValidRange()); Assertions.assertEquals(0, cache.getMinMean()); Assertions.assertEquals(0, cache.getMaxMean()); } /** * Test the cache can be created with a range of 1. * In this case the cache will be valid for all mean values * in the range {@code n <= mean < n+1}. */ @Test void testConstructorWhenMaxEqualsMin() { final double min = PoissonSampler.PIVOT + 2; final double max = min; final PoissonSamplerCache cache = createPoissonSamplerCache(min, max); Assertions.assertTrue(cache.isValidRange()); Assertions.assertEquals(min, cache.getMinMean()); Assertions.assertEquals(Math.nextDown(Math.floor(max) + 1), cache.getMaxMean()); } /** * Test the cache can be created with a range of 1. * In this case the cache will be valid for all mean values * in the range {@code n <= mean < n+1}. */ @Test void testConstructorWhenMaxAboveMin() { final double min = PoissonSampler.PIVOT + 2; final double max = min + 10; final PoissonSamplerCache cache = createPoissonSamplerCache(min, max); Assertions.assertTrue(cache.isValidRange()); Assertions.assertEquals(min, cache.getMinMean()); Assertions.assertEquals(Math.nextDown(Math.floor(max) + 1), cache.getMaxMean()); } /** * Test the cache requires a range with {@code max >= min}. */ @Test void testConstructorThrowsWhenMaxIsLessThanMin() { final double min = PoissonSampler.PIVOT; final double max = Math.nextDown(min); Assertions.assertThrows(IllegalArgumentException.class, () -> createPoissonSamplerCache(min, max)); } /** * Test the cache can be created with a min range below 0. * In this case the range is truncated to 0. */ @Test void testConstructorWhenMinBelow0() { final double min = -1; final double max = PoissonSampler.PIVOT + 2; final PoissonSamplerCache cache = createPoissonSamplerCache(min, max); Assertions.assertTrue(cache.isValidRange()); Assertions.assertEquals(PoissonSampler.PIVOT, cache.getMinMean()); Assertions.assertEquals(Math.nextDown(Math.floor(max) + 1), cache.getMaxMean()); } /** * Test the cache can be created with a max range below 0. * In this case the range is truncated to 0, i.e. no cache. */ @Test void testConstructorWhenMaxBelow0() { final double min = -10; final double max = -1; final PoissonSamplerCache cache = createPoissonSamplerCache(min, max); Assertions.assertFalse(cache.isValidRange()); Assertions.assertEquals(0, cache.getMinMean()); Assertions.assertEquals(0, cache.getMaxMean()); } /** * Test the cache can be created without a range that requires a cache. * In this case the cache will be a pass through to the constructor * of the SmallMeanPoissonSampler. */ @Test void testWithRangeConstructorWithNoCache() { final double min = 0; final double max = PoissonSampler.PIVOT - 2; final PoissonSamplerCache cache = createPoissonSamplerCache().withRange(min, max); Assertions.assertFalse(cache.isValidRange()); Assertions.assertEquals(0, cache.getMinMean()); Assertions.assertEquals(0, cache.getMaxMean()); } /** * Test the cache can be created with a range of 1. * In this case the cache will be valid for all mean values * in the range {@code n <= mean < n+1}. */ @Test void testWithRangeConstructorWhenMaxEqualsMin() { final double min = PoissonSampler.PIVOT + 2; final double max = min; final PoissonSamplerCache cache = createPoissonSamplerCache().withRange(min, max); Assertions.assertTrue(cache.isValidRange()); Assertions.assertEquals(min, cache.getMinMean()); Assertions.assertEquals(Math.nextDown(Math.floor(max) + 1), cache.getMaxMean()); } /** * Test the cache can be created with a range of 1. * In this case the cache will be valid for all mean values * in the range {@code n <= mean < n+1}. */ @Test void testWithRangeConstructorWhenMaxAboveMin() { final double min = PoissonSampler.PIVOT + 2; final double max = min + 10; final PoissonSamplerCache cache = createPoissonSamplerCache().withRange(min, max); Assertions.assertTrue(cache.isValidRange()); Assertions.assertEquals(min, cache.getMinMean()); Assertions.assertEquals(Math.nextDown(Math.floor(max) + 1), cache.getMaxMean()); } /** * Test the cache requires a range with {@code max >= min}. */ @Test void testWithRangeConstructorThrowsWhenMaxIsLessThanMin() { final double min = PoissonSampler.PIVOT; final double max = Math.nextDown(min); final PoissonSamplerCache cache = createPoissonSamplerCache(); Assertions.assertThrows(IllegalArgumentException.class, () -> cache.withRange(min, max)); } /** * Test the cache can be created with a min range below 0. * In this case the range is truncated to 0. */ @Test void testWithRangeConstructorWhenMinBelow0() { final double min = -1; final double max = PoissonSampler.PIVOT + 2; final PoissonSamplerCache cache = createPoissonSamplerCache().withRange(min, max); Assertions.assertTrue(cache.isValidRange()); Assertions.assertEquals(PoissonSampler.PIVOT, cache.getMinMean()); Assertions.assertEquals(Math.nextDown(Math.floor(max) + 1), cache.getMaxMean()); } /** * Test the cache can be created from a cache with no capacity. */ @Test void testWithRangeConstructorWhenCacheHasNoCapcity() { final double min = PoissonSampler.PIVOT + 2; final double max = min + 10; final PoissonSamplerCache cache = createPoissonSamplerCache(0, 0).withRange(min, max); Assertions.assertTrue(cache.isValidRange()); Assertions.assertEquals(min, cache.getMinMean()); Assertions.assertEquals(Math.nextDown(Math.floor(max) + 1), cache.getMaxMean()); } /** * Test the withinRange function of the cache signals when construction * cost is minimal. */ @Test void testWithinRange() { final double min = PoissonSampler.PIVOT + 10; final double max = PoissonSampler.PIVOT + 20; final PoissonSamplerCache cache = createPoissonSamplerCache(min, max); // Under the pivot point is always within range Assertions.assertTrue(cache.withinRange(PoissonSampler.PIVOT - 1)); Assertions.assertFalse(cache.withinRange(min - 1)); Assertions.assertTrue(cache.withinRange(min)); Assertions.assertTrue(cache.withinRange(max)); Assertions.assertFalse(cache.withinRange(max + 10)); } // Edge cases for creating a Poisson sampler /** * Test createSharedStateSampler() with a bad mean. * * <p>Note this test actually tests the SmallMeanPoissonSampler throws. */ @Test void testCreateSharedStateSamplerThrowsWithZeroMean() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final PoissonSamplerCache cache = createPoissonSamplerCache(); Assertions.assertThrows(IllegalArgumentException.class, () -> cache.createSharedStateSampler(rng, 0)); } /** * Test createSharedStateSampler() with a mean that is too large. */ @Test void testCreateSharedStateSamplerThrowsWithNonIntegerMean() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final PoissonSamplerCache cache = createPoissonSamplerCache(); final double mean = Integer.MAX_VALUE + 1.0; Assertions.assertThrows(IllegalArgumentException.class, () -> cache.createSharedStateSampler(rng, mean)); } // Sampling tests /** * Test the cache returns the same samples as the PoissonSampler when it * covers the entire range. */ @Test void testCanComputeSameSamplesAsPoissonSamplerWithFullRangeCache() { checkComputeSameSamplesAsPoissonSampler(minRange, maxRange); } /** * Test the cache returns the same samples as the PoissonSampler * with no cache. */ @Test void testCanComputeSameSamplesAsPoissonSamplerWithNoCache() { checkComputeSameSamplesAsPoissonSampler(0, minRange - 2); } /** * Test the cache returns the same samples as the PoissonSampler with * partial cache covering the lower range. */ @Test void testCanComputeSameSamplesAsPoissonSamplerWithPartialCacheCoveringLowerRange() { checkComputeSameSamplesAsPoissonSampler(minRange, midRange); } /** * Test the cache returns the same samples as the PoissonSampler with * partial cache covering the upper range. */ @Test void testCanComputeSameSamplesAsPoissonSamplerWithPartialCacheCoveringUpperRange() { checkComputeSameSamplesAsPoissonSampler(midRange, maxRange); } /** * Test the cache returns the same samples as the PoissonSampler with * cache above the upper range. */ @Test void testCanComputeSameSamplesAsPoissonSamplerWithCacheAboveTheUpperRange() { checkComputeSameSamplesAsPoissonSampler(maxRange + 10, maxRange + 20); } /** * Check poisson samples are the same from the {@link PoissonSampler} * and {@link PoissonSamplerCache}. * * @param minMean the min mean of the cache * @param maxMean the max mean of the cache */ private void checkComputeSameSamplesAsPoissonSampler(int minMean, int maxMean) { // Two identical RNGs final RandomSource source = RandomSource.SPLIT_MIX_64; final long seed = RandomSource.createLong(); final RestorableUniformRandomProvider rng1 = source.create(seed); final RestorableUniformRandomProvider rng2 = source.create(seed); // Create the cache with the given range final PoissonSamplerCache cache = createPoissonSamplerCache(minMean, maxMean); // Test all means in the test range (which may be different // from the cache range). for (int i = minRange; i <= maxRange; i++) { // Test integer mean (no SmallMeanPoissonSampler required) testPoissonSamples(rng1, rng2, cache, i); // Test non-integer mean (SmallMeanPoissonSampler required) testPoissonSamples(rng1, rng2, cache, i + 0.5); } } /** * Creates the poisson sampler cache with the given range. * * @param minMean the min mean * @param maxMean the max mean * @return the poisson sampler cache */ private static PoissonSamplerCache createPoissonSamplerCache(double minMean, double maxMean) { return new PoissonSamplerCache(minMean, maxMean); } /** * Creates a poisson sampler cache that will have a valid range for the cache. * * @return the poisson sampler cache */ private static PoissonSamplerCache createPoissonSamplerCache() { return new PoissonSamplerCache(PoissonSampler.PIVOT, PoissonSampler.PIVOT + 10); } /** * Test poisson samples are the same from the {@link PoissonSampler} * and {@link PoissonSamplerCache}. The random providers must be * identical (including state). * * @param rng1 the first random provider * @param rng2 the second random provider * @param cache the cache * @param mean the mean */ private static void testPoissonSamples( final RestorableUniformRandomProvider rng1, final RestorableUniformRandomProvider rng2, PoissonSamplerCache cache, double mean) { final DiscreteSampler s1 = PoissonSampler.of(rng1, mean); final DiscreteSampler s2 = cache.createSharedStateSampler(rng2, mean); for (int j = 0; j < 10; j++) { Assertions.assertEquals(s1.sample(), s2.sample()); } } /** * Test the cache returns the same samples as the PoissonSampler with * a new cache reusing the entire range. */ @Test void testCanComputeSameSamplesAsPoissonSamplerReusingCacheEntireRange() { checkComputeSameSamplesAsPoissonSamplerReusingCache(midRange, maxRange, midRange, maxRange); } /** * Test the cache returns the same samples as the PoissonSampler with * a new cache reusing none of the range. */ @Test void testCanComputeSameSamplesAsPoissonSamplerReusingCacheNoRange() { checkComputeSameSamplesAsPoissonSamplerReusingCache(midRange, maxRange, maxRange + 10, maxRange + 20); } /** * Test the cache returns the same samples as the PoissonSampler with * a new cache reusing some of the lower range. */ @Test void testCanComputeSameSamplesAsPoissonSamplerReusingCacheLowerRange() { checkComputeSameSamplesAsPoissonSamplerReusingCache(midRange, maxRange, minRange, midRange + 1); } /** * Test the cache returns the same samples as the PoissonSampler with * a new cache reusing some of the upper range. */ @Test void testCanComputeSameSamplesAsPoissonSamplerReusingCacheUpperRange() { checkComputeSameSamplesAsPoissonSamplerReusingCache(midRange, maxRange, maxRange - 1, maxRange + 5); } /** * Check poisson samples are the same from the {@link PoissonSampler} * and a {@link PoissonSamplerCache} created reusing values. * * <p>Note: This cannot check the cache values were reused but ensures * that a new cache created with a range functions correctly. * * @param minMean the min mean of the cache * @param maxMean the max mean of the cache * @param minMean2 the min mean of the second cache * @param maxMean2 the max mean of the second cache */ private void checkComputeSameSamplesAsPoissonSamplerReusingCache(int minMean, int maxMean, int minMean2, int maxMean2) { // Two identical RNGs final RandomSource source = RandomSource.SPLIT_MIX_64; final long seed = RandomSource.createLong(); final RestorableUniformRandomProvider rng1 = source.create(seed); final RestorableUniformRandomProvider rng2 = source.create(seed); // Create the cache with the given range and fill it final PoissonSamplerCache cache = createPoissonSamplerCache(minMean, maxMean); // Test all means in the test range (which may be different // from the cache range). for (int i = minMean; i <= maxMean; i++) { cache.createSharedStateSampler(rng1, i); } final PoissonSamplerCache cache2 = cache.withRange(minMean2, maxMean2); Assertions.assertNotSame(cache, cache2, "WithRange cache is the same object"); // Test all means in the test range (which may be different // from the cache range). for (int i = minRange; i <= maxRange; i++) { // Test integer mean (no SmallMeanPoissonSampler required) testPoissonSamples(rng1, rng2, cache2, i); // Test non-integer mean (SmallMeanPoissonSampler required) testPoissonSamples(rng1, rng2, cache2, i + 0.5); } } /** * Explicit test for the deprecated method createPoissonSampler(). * All other uses of this method have been removed. */ @SuppressWarnings("deprecation") @Test void testCreatePoissonSampler() { final PoissonSamplerCache cache = createPoissonSamplerCache(0, 100); final DiscreteSampler s2 = cache.createPoissonSampler(null, 42); Assertions.assertTrue(s2 instanceof LargeMeanPoissonSampler); } }
2,957
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/AhrensDieterMarsagliaTsangGammaSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test for the {@link AhrensDieterMarsagliaTsangGammaSampler}. The tests hit edge cases for the sampler. */ class AhrensDieterMarsagliaTsangGammaSamplerTest { /** * Test the constructor with a bad alpha. */ @Test void testConstructorThrowsWithZeroAlpha() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final double alpha = 0; final double theta = 1; Assertions.assertThrows(IllegalArgumentException.class, () -> AhrensDieterMarsagliaTsangGammaSampler.of(rng, alpha, theta)); } /** * Test the constructor with a bad theta. */ @Test void testConstructorThrowsWithZeroTheta() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final double alpha = 1; final double theta = 0; Assertions.assertThrows(IllegalArgumentException.class, () -> AhrensDieterMarsagliaTsangGammaSampler.of(rng, alpha, theta)); } /** * Test the SharedStateSampler implementation. */ @Test void testSharedStateSamplerWithAlphaBelowOne() { testSharedStateSampler(0.5, 3.456); } /** * Test the SharedStateSampler implementation. */ @Test void testSharedStateSamplerWithAlphaAboveOne() { testSharedStateSampler(3.5, 3.456); } /** * Test the SharedStateSampler implementation. * * @param alpha Alpha. * @param theta Theta. */ private static void testSharedStateSampler(double alpha, double theta) { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); // Use instance constructor not factory constructor to exercise 1.X public API final AhrensDieterMarsagliaTsangGammaSampler sampler1 = new AhrensDieterMarsagliaTsangGammaSampler(rng1, alpha, theta); final SharedStateContinuousSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * Test the toString method. This is added to ensure coverage as the factory constructor * used in other tests does not create an instance of the wrapper class. */ @Test void testToString() { final UniformRandomProvider rng = RandomAssert.seededRNG(); Assertions.assertTrue(new AhrensDieterMarsagliaTsangGammaSampler(rng, 1.0, 2.0).toString() .toLowerCase().contains("gamma")); } }
2,958
0
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/InverseTransformParetoSamplerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.RandomAssert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; /** * Test for the {@link InverseTransformParetoSampler}. The tests hit edge cases for the sampler. */ class InverseTransformParetoSamplerTest { /** * The multiplier to convert the least significant 53-bits of a {@code long} to a {@code double}. * This is the smallest non-zero value output from nextDouble. */ private static final double U = 0x1.0p-53d; /** * Test the constructor with a bad scale. */ @Test void testConstructorThrowsWithZeroScale() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final double scale = 0; final double shape = 1; Assertions.assertThrows(IllegalArgumentException.class, () -> InverseTransformParetoSampler.of(rng, scale, shape)); } /** * Test the constructor with a bad shape. */ @Test void testConstructorThrowsWithZeroShape() { final UniformRandomProvider rng = RandomAssert.seededRNG(); final double scale = 1; final double shape = 0; Assertions.assertThrows(IllegalArgumentException.class, () -> InverseTransformParetoSampler.of(rng, scale, shape)); } /** * Test the SharedStateSampler implementation with a shape above and below 1. */ @ParameterizedTest @CsvSource({ "1.23, 4.56", "1.23, 0.56", }) void testSharedStateSampler(double scale, double shape) { final UniformRandomProvider rng1 = RandomAssert.seededRNG(); final UniformRandomProvider rng2 = RandomAssert.seededRNG(); final SharedStateContinuousSampler sampler1 = InverseTransformParetoSampler.of(rng1, scale, shape); final SharedStateContinuousSampler sampler2 = sampler1.withUniformRandomProvider(rng2); RandomAssert.assertProduceSameSequence(sampler1, sampler2); } /** * Test a large shape is sampled using inversion of p in [0, 1). */ @ParameterizedTest @CsvSource({ "12.34, Infinity", "1.23, Infinity", "0.1, Infinity", // Also valid when shape is finite. // Limit taken from o.a.c.statistics.ParetoDistributionTest "12.34, 6.6179136542552806e17", "1.23, 6.6179136542552806e17", "0.1, 6.6179136542552806e17", }) void testLargeShape(double scale, double shape) { // Assert the inversion using the power function. // Note here the first argument to pow is (1 - p) final double oneOverShape = 1 / shape; // Note that inverse CDF(p=1) should be infinity (upper bound). // However this requires a check on the value of p and the // inversion returns the lower bound when 1 / shape = 0 due // to pow(0, 0) == 1 final double p1expected = oneOverShape == 0 ? scale : Double.POSITIVE_INFINITY; Assertions.assertEquals(p1expected, scale / Math.pow(0, oneOverShape)); Assertions.assertEquals(scale, scale / Math.pow(U, oneOverShape)); Assertions.assertEquals(scale, scale / Math.pow(1 - U, oneOverShape)); Assertions.assertEquals(scale, scale / Math.pow(1, oneOverShape)); // Sampling should be as if p in [0, 1) so avoiding an infinite sample for // large finite shape when p=1 assertSampler(scale, shape, scale); } /** * Test a tiny shape is sampled using inversion of p in (0, 1]. */ @ParameterizedTest @CsvSource({ "12.34, 4.9e-324", "1.23, 4.9e-324", "0.1, 4.9e-324", // Also valid when 1 / shape is finite. // Limit taken from o.a.c.statistics.ParetoDistributionTest "12.34, 7.456765604783329e-20", "1.23, 7.456765604783329e-20", "0.1, 7.456765604783329e-20", }) void testTinyShape(double scale, double shape) { // Assert the inversion using the power function. // Note here the first argument to pow is (1 - p) final double oneOverShape = 1 / shape; Assertions.assertEquals(Double.POSITIVE_INFINITY, scale / Math.pow(0, oneOverShape)); Assertions.assertEquals(Double.POSITIVE_INFINITY, scale / Math.pow(U, oneOverShape)); Assertions.assertEquals(Double.POSITIVE_INFINITY, scale / Math.pow(1 - U, oneOverShape)); // Note that inverse CDF(p=0) should be scale (lower bound). // However this requires a check on the value of p and the // inversion returns NaN due to pow(1, inf) == NaN. final double p0expected = oneOverShape == Double.POSITIVE_INFINITY ? Double.NaN : scale; Assertions.assertEquals(p0expected, scale / Math.pow(1, oneOverShape)); // Sampling should be as if p in (0, 1] so avoiding a NaN sample for // infinite 1 / shape when p=0 assertSampler(scale, shape, Double.POSITIVE_INFINITY); } /** * Assert the sampler produces the expected sample value irrespective of the values from the RNG. * * @param scale Distribution scale * @param shape Distribution shape * @param expected Expected sample value */ private static void assertSampler(double scale, double shape, double expected) { // Extreme random numbers using no bits or all bits, then combinations // that may be used to generate a double from the lower or upper 53-bits final long[] values = {0, -1, 1, 1L << 11, -2, -2L << 11}; final UniformRandomProvider rng = createRNG(values); ContinuousSampler s = InverseTransformParetoSampler.of(rng, scale, shape); for (final long l : values) { Assertions.assertEquals(expected, s.sample(), () -> "long bits = " + l); } // Any random number s = InverseTransformParetoSampler.of(RandomAssert.createRNG(), scale, shape); for (int i = 0; i < 100; i++) { Assertions.assertEquals(expected, s.sample()); } } /** * Creates the RNG to return the given values from the nextLong() method. * * @param values Long values * @return the RNG */ private static UniformRandomProvider createRNG(long... values) { return new UniformRandomProvider() { private int i; @Override public long nextLong() { return values[i++]; } @Override public double nextDouble() { throw new IllegalStateException("nextDouble cannot be trusted to be in [0, 1) and should be ignored"); } }; } }
2,959
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/CompositeSamplers.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling; import java.util.List; import java.util.Objects; import java.util.ArrayList; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.distribution.AliasMethodDiscreteSampler; import org.apache.commons.rng.sampling.distribution.ContinuousSampler; import org.apache.commons.rng.sampling.distribution.DiscreteSampler; import org.apache.commons.rng.sampling.distribution.DiscreteUniformSampler; import org.apache.commons.rng.sampling.distribution.GuideTableDiscreteSampler; import org.apache.commons.rng.sampling.distribution.LongSampler; import org.apache.commons.rng.sampling.distribution.MarsagliaTsangWangDiscreteSampler; import org.apache.commons.rng.sampling.distribution.SharedStateContinuousSampler; import org.apache.commons.rng.sampling.distribution.SharedStateDiscreteSampler; import org.apache.commons.rng.sampling.distribution.SharedStateLongSampler; /** * Factory class to create a sampler that combines sampling from multiple samplers. * * <p>The composite sampler is constructed using a {@link Builder builder} for the type of samplers * that will form the composite. Each sampler has a weight in the composition. * Samples are returned using a 2 step algorithm: * * <ol> * <li>Select a sampler based on its weighting * <li>Return a sample from the selected sampler * </ol> * * <p>The weights used for each sampler create a discrete probability distribution. This is * sampled using a discrete probability distribution sampler. The builder provides methods * to change the default implementation. * * <p>The following example will create a sampler to uniformly sample the border of a triangle * using the line segment lengths as weights: * * <pre> * UniformRandomProvider rng = RandomSource.KISS.create(); * double[] a = {1.23, 4.56}; * double[] b = {6.78, 9.01}; * double[] c = {3.45, 2.34}; * ObjectSampler&lt;double[]&gt; sampler = * CompositeSamplers.&lt;double[]&gt;newObjectSamplerBuilder() * .add(LineSampler.of(rng, a, b), Math.hypot(a[0] - b[0], a[1] - b[1])) * .add(LineSampler.of(rng, b, c), Math.hypot(b[0] - c[0], b[1] - c[1])) * .add(LineSampler.of(rng, c, a), Math.hypot(c[0] - a[0], c[1] - a[1])) * .build(rng); * </pre> * * @since 1.4 */ public final class CompositeSamplers { /** * A factory for creating a sampler of a user-defined * <a href="http://en.wikipedia.org/wiki/Probability_distribution#Discrete_probability_distribution"> * discrete probability distribution</a>. */ public interface DiscreteProbabilitySamplerFactory { /** * Creates the sampler. * * @param rng Source of randomness. * @param probabilities Discrete probability distribution. * @return the sampler */ DiscreteSampler create(UniformRandomProvider rng, double[] probabilities); } /** * The DiscreteProbabilitySampler class defines implementations that sample from a user-defined * <a href="http://en.wikipedia.org/wiki/Probability_distribution#Discrete_probability_distribution"> * discrete probability distribution</a>. * * <p>All implementations support the {@link SharedStateDiscreteSampler} interface. */ public enum DiscreteProbabilitySampler implements DiscreteProbabilitySamplerFactory { /** Sample using a guide table (see {@link GuideTableDiscreteSampler}). */ GUIDE_TABLE { @Override public SharedStateDiscreteSampler create(UniformRandomProvider rng, double[] probabilities) { return GuideTableDiscreteSampler.of(rng, probabilities); } }, /** Sample using the alias method (see {@link AliasMethodDiscreteSampler}). */ ALIAS_METHOD { @Override public SharedStateDiscreteSampler create(UniformRandomProvider rng, double[] probabilities) { return AliasMethodDiscreteSampler.of(rng, probabilities); } }, /** * Sample using an optimised look-up table (see * {@link org.apache.commons.rng.sampling.distribution.MarsagliaTsangWangDiscreteSampler.Enumerated * MarsagliaTsangWangDiscreteSampler.Enumerated}). */ LOOKUP_TABLE { @Override public SharedStateDiscreteSampler create(UniformRandomProvider rng, double[] probabilities) { return MarsagliaTsangWangDiscreteSampler.Enumerated.of(rng, probabilities); } } } /** * A class to implement the SharedStateDiscreteSampler interface for a discrete probability * sampler given a factory and the probability distribution. Each new instance will recreate * the distribution sampler using the factory. */ private static class SharedStateDiscreteProbabilitySampler implements SharedStateDiscreteSampler { /** The sampler. */ private final DiscreteSampler sampler; /** The factory to create a new discrete sampler. */ private final DiscreteProbabilitySamplerFactory factory; /** The probabilities. */ private final double[] probabilities; /** * @param sampler Sampler of the discrete distribution. * @param factory Factory to create a new discrete sampler. * @param probabilities Probabilities of the discrete distribution. * @throws NullPointerException if the {@code sampler} is null */ SharedStateDiscreteProbabilitySampler(DiscreteSampler sampler, DiscreteProbabilitySamplerFactory factory, double[] probabilities) { this.sampler = Objects.requireNonNull(sampler, "discrete sampler"); // Assume the factory and probabilities are not null this.factory = factory; this.probabilities = probabilities; } @Override public int sample() { // Delegate return sampler.sample(); } @Override public SharedStateDiscreteSampler withUniformRandomProvider(UniformRandomProvider rng) { // The factory may destructively modify the probabilities return new SharedStateDiscreteProbabilitySampler(factory.create(rng, probabilities.clone()), factory, probabilities); } } /** * Builds a composite sampler. * * <p>A composite sampler is a combination of multiple samplers * that all return the same sample type. Each sampler has a weighting in the composition. * Samples are returned using a 2 step algorithm: * * <ol> * <li>Select a sampler based on its weighting * <li>Return a sample from the selected sampler * </ol> * * <p>Step 1 requires a discrete sampler constructed from a discrete probability distribution. * The probability for each sampler is the sampler weight divided by the sum of the weights: * <pre> * p(i) = w(i) / sum(w) * </pre> * * <p>The builder provides a method to set the factory used to generate the discrete sampler. * * @param <S> Type of sampler */ public interface Builder<S> { /** * Return the number of samplers in the composite. The size must be non-zero before * the {@link #build(UniformRandomProvider) build} method can create a sampler. * * @return the size */ int size(); /** * Adds the sampler to the composite. A sampler with a zero weight is ignored. * * @param sampler Sampler. * @param weight Weight for the composition. * @return a reference to this builder * @throws IllegalArgumentException if {@code weight} is negative, infinite or {@code NaN}. * @throws NullPointerException if {@code sampler} is null. */ Builder<S> add(S sampler, double weight); /** * Sets the factory to use to generate the composite's discrete sampler from the sampler * weights. * * <p>Note: If the factory is not explicitly set then a default will be used. * * @param factory Factory. * @return a reference to this builder * @throws NullPointerException if {@code factory} is null. */ Builder<S> setFactory(DiscreteProbabilitySamplerFactory factory); /** * Builds the composite sampler. The {@code rng} is the source of randomness for selecting * which sampler to use for each sample. * * <p>Note: When the sampler is created the builder is reset to an empty state. * This prevents building multiple composite samplers with the same samplers and * their identical underlying source of randomness. * * @param rng Generator of uniformly distributed random numbers. * @return the sampler * @throws IllegalStateException if no samplers have been added to create a composite. * @see #size() */ S build(UniformRandomProvider rng); } /** * Builds a composite sampler. * * <p>A single builder can be used to create composites of different implementing classes * which support different sampler interfaces. The type of sampler is generic. The individual * samplers and their weights can be collected by the builder. The build method creates * the discrete probability distribution from the weights. The final composite is created * using a factory to create the class. * * @param <S> Type of sampler */ private static class SamplerBuilder<S> implements Builder<S> { /** The specialisation of the sampler. */ private final Specialisation specialisation; /** The weighted samplers. */ private final List<WeightedSampler<S>> weightedSamplers; /** The factory to create the discrete probability sampler from the weights. */ private DiscreteProbabilitySamplerFactory factory; /** The factory to create the composite sampler. */ private final SamplerFactory<S> compositeFactory; /** * The specialisation of composite sampler to build. * This is used to determine if specialised interfaces from the sampler * type must be supported, e.g. {@link SharedStateSampler}. */ enum Specialisation { /** Instance of {@link SharedStateSampler}. */ SHARED_STATE_SAMPLER, /** No specialisation. */ NONE } /** * A factory for creating composite samplers. * * <p>This interface is used to build concrete implementations * of different sampler interfaces. * * @param <S> Type of sampler */ interface SamplerFactory<S> { /** * Creates a new composite sampler. * * <p>If the composite specialisation is a * {@link Specialisation#SHARED_STATE_SAMPLER shared state sampler} * the discrete sampler passed to this method will be an instance of * {@link SharedStateDiscreteSampler}. * * @param discreteSampler Discrete sampler. * @param samplers Samplers. * @return the sampler */ S createSampler(DiscreteSampler discreteSampler, List<S> samplers); } /** * Contains a weighted sampler. * * @param <S> Sampler type */ private static class WeightedSampler<S> { /** The weight. */ private final double weight; /** The sampler. */ private final S sampler; /** * @param weight the weight * @param sampler the sampler * @throws IllegalArgumentException if {@code weight} is negative, infinite or {@code NaN}. * @throws NullPointerException if {@code sampler} is null. */ WeightedSampler(double weight, S sampler) { this.weight = requirePositiveFinite(weight, "weight"); this.sampler = Objects.requireNonNull(sampler, "sampler"); } /** * Gets the weight. * * @return the weight */ double getWeight() { return weight; } /** * Gets the sampler. * * @return the sampler */ S getSampler() { return sampler; } /** * Checks that the specified value is positive finite and throws a customized * {@link IllegalArgumentException} if it is not. * * @param value the value * @param message detail message to be used in the event that a {@code * IllegalArgumentException} is thrown * @return {@code value} if positive finite * @throws IllegalArgumentException if {@code weight} is negative, infinite or {@code NaN}. */ private static double requirePositiveFinite(double value, String message) { // Must be positive finite if (!(value >= 0 && value < Double.POSITIVE_INFINITY)) { throw new IllegalArgumentException(message + " is not positive finite: " + value); } return value; } } /** * @param specialisation Specialisation of the sampler. * @param compositeFactory Factory to create the final composite sampler. */ SamplerBuilder(Specialisation specialisation, SamplerFactory<S> compositeFactory) { this.specialisation = specialisation; this.compositeFactory = compositeFactory; weightedSamplers = new ArrayList<>(); factory = DiscreteProbabilitySampler.GUIDE_TABLE; } @Override public int size() { return weightedSamplers.size(); } @Override public Builder<S> add(S sampler, double weight) { // Ignore zero weights. The sampler and weight are validated by the WeightedSampler. if (weight != 0) { weightedSamplers.add(new WeightedSampler<>(weight, sampler)); } return this; } /** * {@inheritDoc} * * <p>If the weights are uniform the factory is ignored and composite's discrete sampler * is a {@link DiscreteUniformSampler uniform distribution sampler}. */ @Override public Builder<S> setFactory(DiscreteProbabilitySamplerFactory samplerFactory) { this.factory = Objects.requireNonNull(samplerFactory, "factory"); return this; } /** * {@inheritDoc} * * <p>If only one sampler has been added to the builder then the sampler is returned * and the builder is reset. * * @throws IllegalStateException if no samplers have been added to create a composite. */ @Override public S build(UniformRandomProvider rng) { final List<WeightedSampler<S>> list = this.weightedSamplers; final int n = list.size(); if (n == 0) { throw new IllegalStateException("No samplers to build the composite"); } if (n == 1) { // No composite final S sampler = list.get(0).sampler; reset(); return sampler; } // Extract the weights and samplers. final double[] weights = new double[n]; final ArrayList<S> samplers = new ArrayList<>(n); for (int i = 0; i < n; i++) { final WeightedSampler<S> weightedItem = list.get(i); weights[i] = weightedItem.getWeight(); samplers.add(weightedItem.getSampler()); } reset(); final DiscreteSampler discreteSampler = createDiscreteSampler(rng, weights); return compositeFactory.createSampler(discreteSampler, samplers); } /** * Reset the builder. */ private void reset() { weightedSamplers.clear(); } /** * Creates the discrete sampler of the enumerated probability distribution. * * <p>If the specialisation is a {@link Specialisation#SHARED_STATE_SAMPLER shared state sampler} * the discrete sampler will be an instance of {@link SharedStateDiscreteSampler}. * * @param rng Generator of uniformly distributed random numbers. * @param weights Weight associated to each item. * @return the sampler */ private DiscreteSampler createDiscreteSampler(UniformRandomProvider rng, double[] weights) { // Edge case. Detect uniform weights. final int n = weights.length; if (uniform(weights)) { // Uniformly sample from the size. // Note: Upper bound is inclusive. return DiscreteUniformSampler.of(rng, 0, n - 1); } // If possible normalise with a simple sum. final double sum = sum(weights); if (sum < Double.POSITIVE_INFINITY) { // Do not use f = 1.0 / sum and multiplication by f. // Use of divide handles a sub-normal sum. for (int i = 0; i < n; i++) { weights[i] /= sum; } } else { // The sum is not finite. We know the weights are all positive finite. // Compute the mean without overflow and divide by the mean and number of items. final double mean = mean(weights); for (int i = 0; i < n; i++) { // Two step division avoids using the denominator (mean * n) weights[i] = weights[i] / mean / n; } } // Create the sampler from the factory. // Check if a SharedStateSampler is required. // If a default factory then the result is a SharedStateDiscreteSampler, // otherwise the sampler must be checked. if (specialisation == Specialisation.SHARED_STATE_SAMPLER && !(factory instanceof DiscreteProbabilitySampler)) { // If the factory was user-defined then clone the weights as they may be required // to create a SharedStateDiscreteProbabilitySampler. final DiscreteSampler sampler = factory.create(rng, weights.clone()); return sampler instanceof SharedStateDiscreteSampler ? sampler : new SharedStateDiscreteProbabilitySampler(sampler, factory, weights); } return factory.create(rng, weights); } /** * Check if all the values are the same. * * <p>Warning: This method assumes there are input values. If the length is zero an * {@link ArrayIndexOutOfBoundsException} will be thrown. * * @param values the values * @return true if all values are the same */ private static boolean uniform(double[] values) { final double value = values[0]; for (int i = 1; i < values.length; i++) { if (value != values[i]) { return false; } } return true; } /** * Compute the sum of the values. * * @param values the values * @return the sum */ private static double sum(double[] values) { double sum = 0; for (final double value : values) { sum += value; } return sum; } /** * Compute the mean of the values. Uses a rolling algorithm to avoid overflow of a simple sum. * This method can be used to compute the mean of observed counts for normalisation to a * probability: * * <pre> * double[] values = ...; * int n = values.length; * double mean = mean(values); * for (int i = 0; i &lt; n; i++) { * // Two step division avoids using the denominator (mean * n) * values[i] = values[i] / mean / n; * } * </pre> * * <p>Warning: This method assumes there are input values. If the length is zero an * {@link ArrayIndexOutOfBoundsException} will be thrown. * * @param values the values * @return the mean */ private static double mean(double[] values) { double mean = values[0]; int i = 1; while (i < values.length) { // Deviation from the mean final double dev = values[i] - mean; i++; mean += dev / i; } return mean; } } /** * A composite sampler. * * <p>The source sampler for each sampler is chosen based on a user-defined continuous * probability distribution. * * @param <S> Type of sampler */ private static class CompositeSampler<S> { /** Continuous sampler to choose the individual sampler to sample. */ protected final DiscreteSampler discreteSampler; /** Collection of samplers to be sampled from. */ protected final List<S> samplers; /** * @param discreteSampler Continuous sampler to choose the individual sampler to sample. * @param samplers Collection of samplers to be sampled from. */ CompositeSampler(DiscreteSampler discreteSampler, List<S> samplers) { this.discreteSampler = discreteSampler; this.samplers = samplers; } /** * Gets the next sampler to use to create a sample. * * @return the sampler */ S nextSampler() { return samplers.get(discreteSampler.sample()); } } /** * A factory for creating a composite ObjectSampler. * * @param <T> Type of sample */ private static class ObjectSamplerFactory<T> implements SamplerBuilder.SamplerFactory<ObjectSampler<T>> { /** The instance. */ @SuppressWarnings("rawtypes") private static final ObjectSamplerFactory INSTANCE = new ObjectSamplerFactory(); /** * Get an instance. * * @param <T> Type of sample * @return the factory */ @SuppressWarnings("unchecked") static <T> ObjectSamplerFactory<T> instance() { return (ObjectSamplerFactory<T>) INSTANCE; } @Override public ObjectSampler<T> createSampler(DiscreteSampler discreteSampler, List<ObjectSampler<T>> samplers) { return new CompositeObjectSampler<>(discreteSampler, samplers); } /** * A composite object sampler. * * @param <T> Type of sample */ private static class CompositeObjectSampler<T> extends CompositeSampler<ObjectSampler<T>> implements ObjectSampler<T> { /** * @param discreteSampler Discrete sampler to choose the individual sampler to sample. * @param samplers Collection of samplers to be sampled from. */ CompositeObjectSampler(DiscreteSampler discreteSampler, List<ObjectSampler<T>> samplers) { super(discreteSampler, samplers); } @Override public T sample() { return nextSampler().sample(); } } } /** * A factory for creating a composite SharedStateObjectSampler. * * @param <T> Type of sample */ private static class SharedStateObjectSamplerFactory<T> implements SamplerBuilder.SamplerFactory<SharedStateObjectSampler<T>> { /** The instance. */ @SuppressWarnings("rawtypes") private static final SharedStateObjectSamplerFactory INSTANCE = new SharedStateObjectSamplerFactory(); /** * Get an instance. * * @param <T> Type of sample * @return the factory */ @SuppressWarnings("unchecked") static <T> SharedStateObjectSamplerFactory<T> instance() { return (SharedStateObjectSamplerFactory<T>) INSTANCE; } @Override public SharedStateObjectSampler<T> createSampler(DiscreteSampler discreteSampler, List<SharedStateObjectSampler<T>> samplers) { // The input discrete sampler is assumed to be a SharedStateDiscreteSampler return new CompositeSharedStateObjectSampler<>( (SharedStateDiscreteSampler) discreteSampler, samplers); } /** * A composite object sampler with shared state support. * * <p>The source sampler for each sampler is chosen based on a user-defined * discrete probability distribution. * * @param <T> Type of sample */ private static class CompositeSharedStateObjectSampler<T> extends CompositeSampler<SharedStateObjectSampler<T>> implements SharedStateObjectSampler<T> { /** * @param discreteSampler Discrete sampler to choose the individual sampler to sample. * @param samplers Collection of samplers to be sampled from. */ CompositeSharedStateObjectSampler(SharedStateDiscreteSampler discreteSampler, List<SharedStateObjectSampler<T>> samplers) { super(discreteSampler, samplers); } @Override public T sample() { return nextSampler().sample(); } @Override public CompositeSharedStateObjectSampler<T> withUniformRandomProvider(UniformRandomProvider rng) { // Duplicate each sampler with the same source of randomness return new CompositeSharedStateObjectSampler<>( ((SharedStateDiscreteSampler) this.discreteSampler).withUniformRandomProvider(rng), copy(samplers, rng)); } } } /** * A factory for creating a composite DiscreteSampler. */ private static class DiscreteSamplerFactory implements SamplerBuilder.SamplerFactory<DiscreteSampler> { /** The instance. */ static final DiscreteSamplerFactory INSTANCE = new DiscreteSamplerFactory(); @Override public DiscreteSampler createSampler(DiscreteSampler discreteSampler, List<DiscreteSampler> samplers) { return new CompositeDiscreteSampler(discreteSampler, samplers); } /** * A composite discrete sampler. */ private static class CompositeDiscreteSampler extends CompositeSampler<DiscreteSampler> implements DiscreteSampler { /** * @param discreteSampler Discrete sampler to choose the individual sampler to sample. * @param samplers Collection of samplers to be sampled from. */ CompositeDiscreteSampler(DiscreteSampler discreteSampler, List<DiscreteSampler> samplers) { super(discreteSampler, samplers); } @Override public int sample() { return nextSampler().sample(); } } } /** * A factory for creating a composite SharedStateDiscreteSampler. */ private static class SharedStateDiscreteSamplerFactory implements SamplerBuilder.SamplerFactory<SharedStateDiscreteSampler> { /** The instance. */ static final SharedStateDiscreteSamplerFactory INSTANCE = new SharedStateDiscreteSamplerFactory(); @Override public SharedStateDiscreteSampler createSampler(DiscreteSampler discreteSampler, List<SharedStateDiscreteSampler> samplers) { // The input discrete sampler is assumed to be a SharedStateDiscreteSampler return new CompositeSharedStateDiscreteSampler( (SharedStateDiscreteSampler) discreteSampler, samplers); } /** * A composite discrete sampler with shared state support. */ private static class CompositeSharedStateDiscreteSampler extends CompositeSampler<SharedStateDiscreteSampler> implements SharedStateDiscreteSampler { /** * @param discreteSampler Discrete sampler to choose the individual sampler to sample. * @param samplers Collection of samplers to be sampled from. */ CompositeSharedStateDiscreteSampler(SharedStateDiscreteSampler discreteSampler, List<SharedStateDiscreteSampler> samplers) { super(discreteSampler, samplers); } @Override public int sample() { return nextSampler().sample(); } @Override public CompositeSharedStateDiscreteSampler withUniformRandomProvider(UniformRandomProvider rng) { // Duplicate each sampler with the same source of randomness return new CompositeSharedStateDiscreteSampler( ((SharedStateDiscreteSampler) this.discreteSampler).withUniformRandomProvider(rng), copy(samplers, rng)); } } } /** * A factory for creating a composite ContinuousSampler. */ private static class ContinuousSamplerFactory implements SamplerBuilder.SamplerFactory<ContinuousSampler> { /** The instance. */ static final ContinuousSamplerFactory INSTANCE = new ContinuousSamplerFactory(); @Override public ContinuousSampler createSampler(DiscreteSampler discreteSampler, List<ContinuousSampler> samplers) { return new CompositeContinuousSampler(discreteSampler, samplers); } /** * A composite continuous sampler. */ private static class CompositeContinuousSampler extends CompositeSampler<ContinuousSampler> implements ContinuousSampler { /** * @param discreteSampler Continuous sampler to choose the individual sampler to sample. * @param samplers Collection of samplers to be sampled from. */ CompositeContinuousSampler(DiscreteSampler discreteSampler, List<ContinuousSampler> samplers) { super(discreteSampler, samplers); } @Override public double sample() { return nextSampler().sample(); } } } /** * A factory for creating a composite SharedStateContinuousSampler. */ private static class SharedStateContinuousSamplerFactory implements SamplerBuilder.SamplerFactory<SharedStateContinuousSampler> { /** The instance. */ static final SharedStateContinuousSamplerFactory INSTANCE = new SharedStateContinuousSamplerFactory(); @Override public SharedStateContinuousSampler createSampler(DiscreteSampler discreteSampler, List<SharedStateContinuousSampler> samplers) { // The sampler is assumed to be a SharedStateContinuousSampler return new CompositeSharedStateContinuousSampler( (SharedStateDiscreteSampler) discreteSampler, samplers); } /** * A composite continuous sampler with shared state support. */ private static class CompositeSharedStateContinuousSampler extends CompositeSampler<SharedStateContinuousSampler> implements SharedStateContinuousSampler { /** * @param discreteSampler Continuous sampler to choose the individual sampler to sample. * @param samplers Collection of samplers to be sampled from. */ CompositeSharedStateContinuousSampler(SharedStateDiscreteSampler discreteSampler, List<SharedStateContinuousSampler> samplers) { super(discreteSampler, samplers); } @Override public double sample() { return nextSampler().sample(); } @Override public CompositeSharedStateContinuousSampler withUniformRandomProvider(UniformRandomProvider rng) { // Duplicate each sampler with the same source of randomness return new CompositeSharedStateContinuousSampler( ((SharedStateDiscreteSampler) this.discreteSampler).withUniformRandomProvider(rng), copy(samplers, rng)); } } } /** * A factory for creating a composite LongSampler. */ private static class LongSamplerFactory implements SamplerBuilder.SamplerFactory<LongSampler> { /** The instance. */ static final LongSamplerFactory INSTANCE = new LongSamplerFactory(); @Override public LongSampler createSampler(DiscreteSampler discreteSampler, List<LongSampler> samplers) { return new CompositeLongSampler(discreteSampler, samplers); } /** * A composite long sampler. */ private static class CompositeLongSampler extends CompositeSampler<LongSampler> implements LongSampler { /** * @param discreteSampler Long sampler to choose the individual sampler to sample. * @param samplers Collection of samplers to be sampled from. */ CompositeLongSampler(DiscreteSampler discreteSampler, List<LongSampler> samplers) { super(discreteSampler, samplers); } @Override public long sample() { return nextSampler().sample(); } } } /** * A factory for creating a composite SharedStateLongSampler. */ private static class SharedStateLongSamplerFactory implements SamplerBuilder.SamplerFactory<SharedStateLongSampler> { /** The instance. */ static final SharedStateLongSamplerFactory INSTANCE = new SharedStateLongSamplerFactory(); @Override public SharedStateLongSampler createSampler(DiscreteSampler discreteSampler, List<SharedStateLongSampler> samplers) { // The input discrete sampler is assumed to be a SharedStateLongSampler return new CompositeSharedStateLongSampler( (SharedStateDiscreteSampler) discreteSampler, samplers); } /** * A composite long sampler with shared state support. */ private static class CompositeSharedStateLongSampler extends CompositeSampler<SharedStateLongSampler> implements SharedStateLongSampler { /** * @param discreteSampler Long sampler to choose the individual sampler to sample. * @param samplers Collection of samplers to be sampled from. */ CompositeSharedStateLongSampler(SharedStateDiscreteSampler discreteSampler, List<SharedStateLongSampler> samplers) { super(discreteSampler, samplers); } @Override public long sample() { return nextSampler().sample(); } @Override public CompositeSharedStateLongSampler withUniformRandomProvider(UniformRandomProvider rng) { // Duplicate each sampler with the same source of randomness return new CompositeSharedStateLongSampler( ((SharedStateDiscreteSampler) this.discreteSampler).withUniformRandomProvider(rng), copy(samplers, rng)); } } } /** No public instances. */ private CompositeSamplers() {} /** * Create a new builder for a composite {@link ObjectSampler}. * * <p>Note: If the compiler cannot infer the type parameter of the sampler it can be specified * within the diamond operator {@code <T>} preceding the call to * {@code newObjectSamplerBuilder()}, for example: * * <pre>{@code * CompositeSamplers.<double[]>newObjectSamplerBuilder() * }</pre> * * @param <T> Type of the sample. * @return the builder */ public static <T> Builder<ObjectSampler<T>> newObjectSamplerBuilder() { final SamplerBuilder.SamplerFactory<ObjectSampler<T>> factory = ObjectSamplerFactory.instance(); return new SamplerBuilder<>( SamplerBuilder.Specialisation.NONE, factory); } /** * Create a new builder for a composite {@link SharedStateObjectSampler}. * * <p>Note: If the compiler cannot infer the type parameter of the sampler it can be specified * within the diamond operator {@code <T>} preceding the call to * {@code newSharedStateObjectSamplerBuilder()}, for example: * * <pre>{@code * CompositeSamplers.<double[]>newSharedStateObjectSamplerBuilder() * }</pre> * * @param <T> Type of the sample. * @return the builder */ public static <T> Builder<SharedStateObjectSampler<T>> newSharedStateObjectSamplerBuilder() { final SamplerBuilder.SamplerFactory<SharedStateObjectSampler<T>> factory = SharedStateObjectSamplerFactory.instance(); return new SamplerBuilder<>( SamplerBuilder.Specialisation.SHARED_STATE_SAMPLER, factory); } /** * Create a new builder for a composite {@link DiscreteSampler}. * * @return the builder */ public static Builder<DiscreteSampler> newDiscreteSamplerBuilder() { return new SamplerBuilder<>( SamplerBuilder.Specialisation.NONE, DiscreteSamplerFactory.INSTANCE); } /** * Create a new builder for a composite {@link SharedStateDiscreteSampler}. * * @return the builder */ public static Builder<SharedStateDiscreteSampler> newSharedStateDiscreteSamplerBuilder() { return new SamplerBuilder<>( SamplerBuilder.Specialisation.SHARED_STATE_SAMPLER, SharedStateDiscreteSamplerFactory.INSTANCE); } /** * Create a new builder for a composite {@link ContinuousSampler}. * * @return the builder */ public static Builder<ContinuousSampler> newContinuousSamplerBuilder() { return new SamplerBuilder<>( SamplerBuilder.Specialisation.NONE, ContinuousSamplerFactory.INSTANCE); } /** * Create a new builder for a composite {@link SharedStateContinuousSampler}. * * @return the builder */ public static Builder<SharedStateContinuousSampler> newSharedStateContinuousSamplerBuilder() { return new SamplerBuilder<>( SamplerBuilder.Specialisation.SHARED_STATE_SAMPLER, SharedStateContinuousSamplerFactory.INSTANCE); } /** * Create a new builder for a composite {@link LongSampler}. * * @return the builder */ public static Builder<LongSampler> newLongSamplerBuilder() { return new SamplerBuilder<>( SamplerBuilder.Specialisation.NONE, LongSamplerFactory.INSTANCE); } /** * Create a new builder for a composite {@link SharedStateLongSampler}. * * @return the builder */ public static Builder<SharedStateLongSampler> newSharedStateLongSamplerBuilder() { return new SamplerBuilder<>( SamplerBuilder.Specialisation.SHARED_STATE_SAMPLER, SharedStateLongSamplerFactory.INSTANCE); } /** * Create a copy instance of each sampler in the list of samplers using the given * uniform random provider as the source of randomness. * * @param <T> the type of sampler * @param samplers Source to copy. * @param rng Generator of uniformly distributed random numbers. * @return the copy */ private static <T extends SharedStateSampler<T>> List<T> copy(List<T> samplers, UniformRandomProvider rng) { final ArrayList<T> newSamplers = new ArrayList<>(samplers.size()); for (final T s : samplers) { newSamplers.add(s.withUniformRandomProvider(rng)); } return newSamplers; } }
2,960
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/CombinationSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling; import org.apache.commons.rng.UniformRandomProvider; /** * Class for representing <a href="https://en.wikipedia.org/wiki/Combination">combinations</a> * of a sequence of integers. * * <p>A combination is a selection of items from a collection, such that (unlike * permutations) the order of selection <strong>does not matter</strong>. This * sampler can be used to generate a combination in an unspecified order and is * faster than the corresponding {@link PermutationSampler}.</p> * * <p>Note that the sample order is unspecified. For example a sample * combination of 2 from 4 may return {@code [0,1]} or {@code [1,0]} as the two are * equivalent, and the order of a given combination may change in subsequent samples.</p> * * <p>The sampler can be used to generate indices to select subsets where the * order of the subset is not important.</p> * * <p>Sampling uses {@link UniformRandomProvider#nextInt(int)}.</p> * * @see PermutationSampler */ public class CombinationSampler implements SharedStateObjectSampler<int[]> { /** Domain of the combination. */ private final int[] domain; /** The number of steps of a full shuffle to perform. */ private final int steps; /** * The section to copy the domain from after a partial shuffle. */ private final boolean upper; /** RNG. */ private final UniformRandomProvider rng; /** * Creates a generator of combinations. * * <p>The {@link #sample()} method will generate an integer array of * length {@code k} whose entries are selected randomly, without * repetition, from the integers 0, 1, ..., {@code n}-1 (inclusive). * The returned array represents a combination of {@code n} taken * {@code k}. * * <p>In contrast to a permutation, the returned array is <strong>not * guaranteed</strong> to be in a random order. The {@link #sample()} * method returns the array in an unspecified order. * * <p>If {@code n <= 0} or {@code k <= 0} or {@code k > n} then no combination * is required and an exception is raised. * * @param rng Generator of uniformly distributed random numbers. * @param n Domain of the combination. * @param k Size of the combination. * @throws IllegalArgumentException if {@code n <= 0} or {@code k <= 0} or * {@code k > n}. */ public CombinationSampler(UniformRandomProvider rng, int n, int k) { SubsetSamplerUtils.checkSubset(n, k); domain = PermutationSampler.natural(n); // The sample can be optimised by only performing the first k or (n - k) steps // from a full Fisher-Yates shuffle from the end of the domain to the start. // The upper positions will then contain a random sample from the domain. The // lower half is then by definition also a random sample (just not in a random order). // The sample is then picked using the upper or lower half depending which // makes the number of steps smaller. upper = k <= n / 2; steps = upper ? k : n - k; this.rng = rng; } /** * @param rng Generator of uniformly distributed random numbers. * @param source Source to copy. */ private CombinationSampler(UniformRandomProvider rng, CombinationSampler source) { // Do not clone the domain. This ensures: // 1. Thread safety as the domain may be shuffled during the clone // and a shuffle swap step can result in duplicates and missing elements // in the array. // 2. If the argument RNG is an exact match for the RNG in the source // then the output sequence will differ unless the domain is currently // in natural order. domain = PermutationSampler.natural(source.domain.length); steps = source.steps; upper = source.upper; this.rng = rng; } /** * Return a combination of {@code k} whose entries are selected randomly, * without repetition, from the integers 0, 1, ..., {@code n}-1 (inclusive). * * <p>The order of the returned array is not guaranteed to be in a random order * as the order of a combination <strong>does not matter</strong>. * * @return a random combination. */ @Override public int[] sample() { return SubsetSamplerUtils.partialSample(domain, steps, rng, upper); } /** * {@inheritDoc} * * @since 1.3 */ @Override public CombinationSampler withUniformRandomProvider(UniformRandomProvider rng) { return new CombinationSampler(rng, this); } }
2,961
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/SharedStateObjectSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling; /** * Sampler that generates values of a specified type and can create new instances to sample * from the same state with a given source of randomness. * * @param <T> Type of the sample. * @since 1.4 */ public interface SharedStateObjectSampler<T> extends ObjectSampler<T>, SharedStateSampler<SharedStateObjectSampler<T>> { // Composite interface }
2,962
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/DiscreteProbabilityCollectionSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling; import java.util.List; import java.util.Map; import java.util.ArrayList; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.distribution.GuideTableDiscreteSampler; import org.apache.commons.rng.sampling.distribution.SharedStateDiscreteSampler; /** * Sampling from a collection of items with user-defined * <a href="http://en.wikipedia.org/wiki/Probability_distribution#Discrete_probability_distribution"> * probabilities</a>. * Note that if all unique items are assigned the same probability, * it is much more efficient to use {@link CollectionSampler}. * * <p>Sampling uses {@link UniformRandomProvider#nextDouble()}.</p> * * @param <T> Type of items in the collection. * * @since 1.1 */ public class DiscreteProbabilityCollectionSampler<T> implements SharedStateObjectSampler<T> { /** The error message for an empty collection. */ private static final String EMPTY_COLLECTION = "Empty collection"; /** Collection to be sampled from. */ private final List<T> items; /** Sampler for the probabilities. */ private final SharedStateDiscreteSampler sampler; /** * Creates a sampler. * * @param rng Generator of uniformly distributed random numbers. * @param collection Collection to be sampled, with the probabilities * associated to each of its items. * A (shallow) copy of the items will be stored in the created instance. * The probabilities must be non-negative, but zero values are allowed * and their sum does not have to equal one (input will be normalized * to make the probabilities sum to one). * @throws IllegalArgumentException if {@code collection} is empty, a * probability is negative, infinite or {@code NaN}, or the sum of all * probabilities is not strictly positive. */ public DiscreteProbabilityCollectionSampler(UniformRandomProvider rng, Map<T, Double> collection) { if (collection.isEmpty()) { throw new IllegalArgumentException(EMPTY_COLLECTION); } // Extract the items and probabilities final int size = collection.size(); items = new ArrayList<>(size); final double[] probabilities = new double[size]; int count = 0; for (final Map.Entry<T, Double> e : collection.entrySet()) { items.add(e.getKey()); probabilities[count++] = e.getValue(); } // Delegate sampling sampler = createSampler(rng, probabilities); } /** * Creates a sampler. * * @param rng Generator of uniformly distributed random numbers. * @param collection Collection to be sampled. * A (shallow) copy of the items will be stored in the created instance. * @param probabilities Probability associated to each item of the * {@code collection}. * The probabilities must be non-negative, but zero values are allowed * and their sum does not have to equal one (input will be normalized * to make the probabilities sum to one). * @throws IllegalArgumentException if {@code collection} is empty or * a probability is negative, infinite or {@code NaN}, or if the number * of items in the {@code collection} is not equal to the number of * provided {@code probabilities}. */ public DiscreteProbabilityCollectionSampler(UniformRandomProvider rng, List<T> collection, double[] probabilities) { if (collection.isEmpty()) { throw new IllegalArgumentException(EMPTY_COLLECTION); } final int len = probabilities.length; if (len != collection.size()) { throw new IllegalArgumentException("Size mismatch: " + len + " != " + collection.size()); } // Shallow copy the list items = new ArrayList<>(collection); // Delegate sampling sampler = createSampler(rng, probabilities); } /** * @param rng Generator of uniformly distributed random numbers. * @param source Source to copy. */ private DiscreteProbabilityCollectionSampler(UniformRandomProvider rng, DiscreteProbabilityCollectionSampler<T> source) { this.items = source.items; this.sampler = source.sampler.withUniformRandomProvider(rng); } /** * Picks one of the items from the collection passed to the constructor. * * @return a random sample. */ @Override public T sample() { return items.get(sampler.sample()); } /** * {@inheritDoc} * * @since 1.3 */ @Override public DiscreteProbabilityCollectionSampler<T> withUniformRandomProvider(UniformRandomProvider rng) { return new DiscreteProbabilityCollectionSampler<>(rng, this); } /** * Creates the sampler of the enumerated probability distribution. * * @param rng Generator of uniformly distributed random numbers. * @param probabilities Probability associated to each item. * @return the sampler */ private static SharedStateDiscreteSampler createSampler(UniformRandomProvider rng, double[] probabilities) { return GuideTableDiscreteSampler.of(rng, probabilities); } }
2,963
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/ObjectSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling; import java.util.stream.Stream; /** * Sampler that generates values of a specified type. * * @param <T> Type of the sample. * @since 1.4 */ public interface ObjectSampler<T> { /** * Create an object sample. * * @return a sample. */ T sample(); /** * Returns an effectively unlimited stream of object sample values. * * <p>The default implementation produces a sequential stream that repeatedly * calls {@link #sample sample}(). * * @return a stream of object values. * @since 1.5 */ default Stream<T> samples() { return Stream.generate(this::sample).sequential(); } /** * Returns a stream producing the given {@code streamSize} number of object * sample values. * * <p>The default implementation produces a sequential stream that repeatedly * calls {@link #sample sample}(); the stream is limited to the given {@code streamSize}. * * @param streamSize Number of values to generate. * @return a stream of object values. * @since 1.5 */ default Stream<T> samples(long streamSize) { return samples().limit(streamSize); } }
2,964
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/CollectionSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling; import java.util.Collection; import java.util.List; import java.util.ArrayList; import org.apache.commons.rng.UniformRandomProvider; /** * Sampling from a {@link Collection}. * * <p>Sampling uses {@link UniformRandomProvider#nextInt(int)}.</p> * * @param <T> Type of items in the collection. * * @since 1.0 */ public class CollectionSampler<T> implements SharedStateObjectSampler<T> { /** Collection to be sampled from. */ private final List<T> items; /** RNG. */ private final UniformRandomProvider rng; /** * Creates a sampler. * * @param rng Generator of uniformly distributed random numbers. * @param collection Collection to be sampled. * A (shallow) copy will be stored in the created instance. * @throws IllegalArgumentException if {@code collection} is empty. */ public CollectionSampler(UniformRandomProvider rng, Collection<T> collection) { if (collection.isEmpty()) { throw new IllegalArgumentException("Empty collection"); } this.rng = rng; items = new ArrayList<>(collection); } /** * @param rng Generator of uniformly distributed random numbers. * @param source Source to copy. */ private CollectionSampler(UniformRandomProvider rng, CollectionSampler<T> source) { this.rng = rng; items = source.items; } /** * Picks one of the items from the * {@link #CollectionSampler(UniformRandomProvider,Collection) * collection passed to the constructor}. * * @return a random sample. */ @Override public T sample() { return items.get(rng.nextInt(items.size())); } /** * {@inheritDoc} * * @since 1.3 */ @Override public CollectionSampler<T> withUniformRandomProvider(UniformRandomProvider rng) { return new CollectionSampler<>(rng, this); } }
2,965
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/UnitSphereSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.distribution.NormalizedGaussianSampler; import org.apache.commons.rng.sampling.distribution.ZigguratSampler; /** * Generate vectors <a href="http://mathworld.wolfram.com/SpherePointPicking.html"> * isotropically located on the surface of a sphere</a>. * * <p>Sampling in 2 or more dimensions uses:</p> * * <ul> * <li>{@link UniformRandomProvider#nextLong()} * <li>{@link UniformRandomProvider#nextDouble()} * </ul> * * <p>Sampling in 1D uses the sign bit from {@link UniformRandomProvider#nextInt()} to set * the direction of the vector. * * @since 1.1 */ public class UnitSphereSampler implements SharedStateObjectSampler<double[]> { /** The dimension for 1D sampling. */ private static final int ONE_D = 1; /** The dimension for 2D sampling. */ private static final int TWO_D = 2; /** The dimension for 3D sampling. */ private static final int THREE_D = 3; /** * The mask to extract the second bit from an integer * (naming starts at bit 1 for the least significant bit). * The masked integer will have a value 0 or 2. */ private static final int MASK_BIT_2 = 0x2; /** The internal sampler optimised for the dimension. */ private final UnitSphereSampler delegate; /** * Sample uniformly from the ends of a 1D unit line. */ private static class UnitSphereSampler1D extends UnitSphereSampler { /** The source of randomness. */ private final UniformRandomProvider rng; /** * @param rng Source of randomness. */ UnitSphereSampler1D(UniformRandomProvider rng) { this.rng = rng; } @Override public double[] sample() { // Either: // 1 - 0 = 1 // 1 - 2 = -1 // Use the sign bit return new double[] {1.0 - ((rng.nextInt() >>> 30) & MASK_BIT_2)}; } @Override public UnitSphereSampler withUniformRandomProvider(UniformRandomProvider rng) { return new UnitSphereSampler1D(rng); } } /** * Sample uniformly from a 2D unit circle. * This is a 2D specialisation of the UnitSphereSamplerND. */ private static class UnitSphereSampler2D extends UnitSphereSampler { /** Sampler used for generating the individual components of the vectors. */ private final NormalizedGaussianSampler sampler; /** * @param rng Source of randomness. */ UnitSphereSampler2D(UniformRandomProvider rng) { sampler = ZigguratSampler.NormalizedGaussian.of(rng); } @Override public double[] sample() { final double x = sampler.sample(); final double y = sampler.sample(); final double sum = x * x + y * y; if (sum == 0) { // Zero-norm vector is discarded. return sample(); } final double f = 1.0 / Math.sqrt(sum); return new double[] {x * f, y * f}; } @Override public UnitSphereSampler withUniformRandomProvider(UniformRandomProvider rng) { return new UnitSphereSampler2D(rng); } } /** * Sample uniformly from a 3D unit sphere. * This is a 3D specialisation of the UnitSphereSamplerND. */ private static class UnitSphereSampler3D extends UnitSphereSampler { /** Sampler used for generating the individual components of the vectors. */ private final NormalizedGaussianSampler sampler; /** * @param rng Source of randomness. */ UnitSphereSampler3D(UniformRandomProvider rng) { sampler = ZigguratSampler.NormalizedGaussian.of(rng); } @Override public double[] sample() { final double x = sampler.sample(); final double y = sampler.sample(); final double z = sampler.sample(); final double sum = x * x + y * y + z * z; if (sum == 0) { // Zero-norm vector is discarded. return sample(); } final double f = 1.0 / Math.sqrt(sum); return new double[] {x * f, y * f, z * f}; } @Override public UnitSphereSampler withUniformRandomProvider(UniformRandomProvider rng) { return new UnitSphereSampler3D(rng); } } /** * Sample uniformly from a ND unit sphere. */ private static class UnitSphereSamplerND extends UnitSphereSampler { /** Space dimension. */ private final int dimension; /** Sampler used for generating the individual components of the vectors. */ private final NormalizedGaussianSampler sampler; /** * @param rng Source of randomness. * @param dimension Space dimension. */ UnitSphereSamplerND(UniformRandomProvider rng, int dimension) { this.dimension = dimension; sampler = ZigguratSampler.NormalizedGaussian.of(rng); } @Override public double[] sample() { final double[] v = new double[dimension]; // Pick a point by choosing a standard Gaussian for each element, // and then normalize to unit length. double sum = 0; for (int i = 0; i < dimension; i++) { final double x = sampler.sample(); v[i] = x; sum += x * x; } if (sum == 0) { // Zero-norm vector is discarded. // Using recursion as it is highly unlikely to generate more // than a few such vectors. It also protects against infinite // loop (in case a buggy generator is used), by eventually // raising a "StackOverflowError". return sample(); } final double f = 1 / Math.sqrt(sum); for (int i = 0; i < dimension; i++) { v[i] *= f; } return v; } @Override public UnitSphereSampler withUniformRandomProvider(UniformRandomProvider rng) { return new UnitSphereSamplerND(rng, dimension); } } /** * This instance delegates sampling. Use the factory method * {@link #of(UniformRandomProvider, int)} to create an optimal sampler. * * @param dimension Space dimension. * @param rng Generator for the individual components of the vectors. * A shallow copy will be stored in this instance. * @throws IllegalArgumentException If {@code dimension <= 0} * @deprecated Use {@link #of(UniformRandomProvider, int)}. */ @Deprecated public UnitSphereSampler(int dimension, UniformRandomProvider rng) { delegate = of(rng, dimension); } /** * Private constructor used by sub-class specialisations. * In future versions the public constructor should be removed and the class made abstract. */ private UnitSphereSampler() { delegate = null; } /** * @return a random normalized Cartesian vector. * @since 1.4 */ @Override public double[] sample() { return delegate.sample(); } /** * @return a random normalized Cartesian vector. * @deprecated Use {@link #sample()}. */ @Deprecated public double[] nextVector() { return sample(); } /** * {@inheritDoc} * * @since 1.3 */ @Override public UnitSphereSampler withUniformRandomProvider(UniformRandomProvider rng) { return delegate.withUniformRandomProvider(rng); } /** * Create a unit sphere sampler for the given dimension. * * @param rng Generator for the individual components of the vectors. A shallow * copy will be stored in the sampler. * @param dimension Space dimension. * @return the sampler * @throws IllegalArgumentException If {@code dimension <= 0} * * @since 1.4 */ public static UnitSphereSampler of(UniformRandomProvider rng, int dimension) { if (dimension <= 0) { throw new IllegalArgumentException("Dimension must be strictly positive"); } else if (dimension == ONE_D) { return new UnitSphereSampler1D(rng); } else if (dimension == TWO_D) { return new UnitSphereSampler2D(rng); } else if (dimension == THREE_D) { return new UnitSphereSampler3D(rng); } return new UnitSphereSamplerND(rng, dimension); } }
2,966
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/SharedStateSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling; import org.apache.commons.rng.UniformRandomProvider; /** * Applies to samplers that can share state between instances. Samplers can be created with a * new source of randomness that sample from the same state. * * @param <R> Type of the sampler. * @since 1.3 */ public interface SharedStateSampler<R> { /** * Create a new instance of the sampler with the same underlying state using the given * uniform random provider as the source of randomness. * * @param rng Generator of uniformly distributed random numbers. * @return the sampler */ R withUniformRandomProvider(UniformRandomProvider rng); }
2,967
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/SubsetSamplerUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling; import org.apache.commons.rng.UniformRandomProvider; /** * Utility class for selecting a subset of a sequence of integers. */ final class SubsetSamplerUtils { /** No public construction. */ private SubsetSamplerUtils() {} /** * Checks the subset of length {@code k} from {@code n} is valid. * * <p>If {@code n <= 0} or {@code k <= 0} or {@code k > n} then no subset * is required and an exception is raised.</p> * * @param n Size of the set. * @param k Size of the subset. * @throws IllegalArgumentException if {@code n <= 0} or {@code k <= 0} or * {@code k > n}. */ static void checkSubset(int n, int k) { if (n <= 0) { throw new IllegalArgumentException("n <= 0 : n=" + n); } if (k <= 0) { throw new IllegalArgumentException("k <= 0 : k=" + k); } if (k > n) { throw new IllegalArgumentException("k > n : k=" + k + ", n=" + n); } } /** * Perform a partial Fisher-Yates shuffle of the domain in-place and return * either the upper fully shuffled section or the remaining lower partially * shuffled section. * * <p>The returned combination will have a length of {@code steps} for * {@code upper=true}, or {@code domain.length - steps} otherwise.</p> * * <p>Sampling uses {@link UniformRandomProvider#nextInt(int)}.</p> * * @param domain The domain. * @param steps The number of shuffle steps. * @param rng Generator of uniformly distributed random numbers. * @param upper Set to true to return the upper fully shuffled section. * @return a random combination. */ static int[] partialSample(int[] domain, int steps, UniformRandomProvider rng, boolean upper) { // Shuffle from the end but limit to the number of steps. // Note: If 'steps' is the full length of the array then the final // swap is redundant so can be skipped. int swapCount = Math.min(steps, domain.length - 1); for (int i = domain.length - 1; swapCount > 0; i--, swapCount--) { // Swap index i with any position down to 0 (including itself) swap(domain, i, rng.nextInt(i + 1)); } final int size = upper ? steps : domain.length - steps; final int from = upper ? domain.length - steps : 0; final int[] result = new int[size]; System.arraycopy(domain, from, result, 0, size); return result; } /** * Swaps the two specified elements in the specified array. * * @param array the array * @param i the first index * @param j the second index */ static void swap(int[] array, int i, int j) { final int tmp = array[i]; array[i] = array[j]; array[j] = tmp; } }
2,968
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/PermutationSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling; import org.apache.commons.rng.UniformRandomProvider; /** * Class for representing <a href="https://en.wikipedia.org/wiki/Permutation">permutations</a> * of a sequence of integers. * * <p>Sampling uses {@link UniformRandomProvider#nextInt(int)}.</p> * * <p>This class also contains utilities for shuffling an {@code int[]} array in-place.</p> */ public class PermutationSampler implements SharedStateObjectSampler<int[]> { /** Domain of the permutation. */ private final int[] domain; /** Size of the permutation. */ private final int size; /** RNG. */ private final UniformRandomProvider rng; /** * Creates a generator of permutations. * * <p>The {@link #sample()} method will generate an integer array of * length {@code k} whose entries are selected randomly, without * repetition, from the integers 0, 1, ..., {@code n}-1 (inclusive). * The returned array represents a permutation of {@code n} taken * {@code k}.</p> * * @param rng Generator of uniformly distributed random numbers. * @param n Domain of the permutation. * @param k Size of the permutation. * @throws IllegalArgumentException if {@code n <= 0} or {@code k <= 0} * or {@code k > n}. */ public PermutationSampler(UniformRandomProvider rng, int n, int k) { SubsetSamplerUtils.checkSubset(n, k); domain = natural(n); size = k; this.rng = rng; } /** * @param rng Generator of uniformly distributed random numbers. * @param source Source to copy. */ private PermutationSampler(UniformRandomProvider rng, PermutationSampler source) { // Do not clone the domain. This ensures: // 1. Thread safety as the domain may be shuffled during the clone // and an incomplete shuffle swap step can result in duplicates and // missing elements in the array. // 2. If the argument RNG is an exact match for the RNG in the source // then the output sequence will differ unless the domain is currently // in natural order. domain = PermutationSampler.natural(source.domain.length); size = source.size; this.rng = rng; } /** * @return a random permutation. * * @see #PermutationSampler(UniformRandomProvider,int,int) */ @Override public int[] sample() { return SubsetSamplerUtils.partialSample(domain, size, rng, true); } /** * {@inheritDoc} * * @since 1.3 */ @Override public PermutationSampler withUniformRandomProvider(UniformRandomProvider rng) { return new PermutationSampler(rng, this); } /** * Shuffles the entries of the given array. * * @see #shuffle(UniformRandomProvider,int[],int,boolean) * * @param rng Random number generator. * @param list Array whose entries will be shuffled (in-place). */ public static void shuffle(UniformRandomProvider rng, int[] list) { shuffle(rng, list, list.length - 1, true); } /** * Shuffles the entries of the given array, using the * <a href="http://en.wikipedia.org/wiki/Fisher-Yates_shuffle#The_modern_algorithm"> * Fisher-Yates</a> algorithm. * The {@code start} and {@code towardHead} parameters select which part * of the array is randomized and which is left untouched. * * <p>Sampling uses {@link UniformRandomProvider#nextInt(int)}.</p> * * @param rng Random number generator. * @param list Array whose entries will be shuffled (in-place). * @param start Index at which shuffling begins. * @param towardHead Shuffling is performed for index positions between * {@code start} and either the end (if {@code false}) or the beginning * (if {@code true}) of the array. */ public static void shuffle(UniformRandomProvider rng, int[] list, int start, boolean towardHead) { if (towardHead) { // Visit all positions from start to 0. // Do not visit 0 to avoid a swap with itself. for (int i = start; i > 0; i--) { // Swap index with any position down to 0 SubsetSamplerUtils.swap(list, i, rng.nextInt(i + 1)); } } else { // Visit all positions from the end to start. // Start is not visited to avoid a swap with itself. for (int i = list.length - 1; i > start; i--) { // Swap index with any position down to start. // Note: i - start + 1 is the number of elements remaining. SubsetSamplerUtils.swap(list, i, rng.nextInt(i - start + 1) + start); } } } /** * Creates an array representing the natural number {@code n}. * * @param n Natural number. * @return an array whose entries are the numbers 0, 1, ..., {@code n}-1. * If {@code n == 0}, the returned array is empty. */ public static int[] natural(int n) { final int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = i; } return a; } }
2,969
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/ArraySampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling; import org.apache.commons.rng.UniformRandomProvider; /** * Utilities for shuffling an array in-place. * * <p>Shuffles use the <a * href="https://en.wikipedia.org/wiki/Fisher-Yates_shuffle#The_modern_algorithm"> * Fisher-Yates</a> algorithm. * * @since 1.6 */ public final class ArraySampler { /** Class contains only static methods. */ private ArraySampler() {} /** * Shuffles the entries of the given array. * * @param rng Source of randomness. * @param array Array whose entries will be shuffled (in-place). * @return a reference to the given array */ public static boolean[] shuffle(UniformRandomProvider rng, boolean[] array) { for (int i = array.length; i > 1; i--) { swap(array, i - 1, rng.nextInt(i)); } return array; } /** * Shuffles the entries of the given array. * * @param rng Source of randomness. * @param array Array whose entries will be shuffled (in-place). * @return a reference to the given array */ public static byte[] shuffle(UniformRandomProvider rng, byte[] array) { for (int i = array.length; i > 1; i--) { swap(array, i - 1, rng.nextInt(i)); } return array; } /** * Shuffles the entries of the given array. * * @param rng Source of randomness. * @param array Array whose entries will be shuffled (in-place). * @return a reference to the given array */ public static char[] shuffle(UniformRandomProvider rng, char[] array) { for (int i = array.length; i > 1; i--) { swap(array, i - 1, rng.nextInt(i)); } return array; } /** * Shuffles the entries of the given array. * * @param rng Source of randomness. * @param array Array whose entries will be shuffled (in-place). * @return a reference to the given array */ public static double[] shuffle(UniformRandomProvider rng, double[] array) { for (int i = array.length; i > 1; i--) { swap(array, i - 1, rng.nextInt(i)); } return array; } /** * Shuffles the entries of the given array. * * @param rng Source of randomness. * @param array Array whose entries will be shuffled (in-place). * @return a reference to the given array */ public static float[] shuffle(UniformRandomProvider rng, float[] array) { for (int i = array.length; i > 1; i--) { swap(array, i - 1, rng.nextInt(i)); } return array; } /** * Shuffles the entries of the given array. * * @param rng Source of randomness. * @param array Array whose entries will be shuffled (in-place). * @return a reference to the given array */ public static int[] shuffle(UniformRandomProvider rng, int[] array) { for (int i = array.length; i > 1; i--) { swap(array, i - 1, rng.nextInt(i)); } return array; } /** * Shuffles the entries of the given array. * * @param rng Source of randomness. * @param array Array whose entries will be shuffled (in-place). * @return a reference to the given array */ public static long[] shuffle(UniformRandomProvider rng, long[] array) { for (int i = array.length; i > 1; i--) { swap(array, i - 1, rng.nextInt(i)); } return array; } /** * Shuffles the entries of the given array. * * @param rng Source of randomness. * @param array Array whose entries will be shuffled (in-place). * @return a reference to the given array */ public static short[] shuffle(UniformRandomProvider rng, short[] array) { for (int i = array.length; i > 1; i--) { swap(array, i - 1, rng.nextInt(i)); } return array; } /** * Shuffles the entries of the given array. * * @param <T> Type of the items. * @param rng Source of randomness. * @param array Array whose entries will be shuffled (in-place). * @return a reference to the given array */ public static <T> T[] shuffle(UniformRandomProvider rng, T[] array) { for (int i = array.length; i > 1; i--) { swap(array, i - 1, rng.nextInt(i)); } return array; } /** * Shuffles the entries of the given array in the range {@code [from, to)}. * * @param rng Source of randomness. * @param array Array whose entries will be shuffled (in-place). * @param from Lower-bound (inclusive) of the sub-range. * @param to Upper-bound (exclusive) of the sub-range. * @return a reference to the given array * @throws IndexOutOfBoundsException if the sub-range is out of bounds */ public static boolean[] shuffle(UniformRandomProvider rng, boolean[] array, int from, int to) { final int length = to - checkFromToIndex(from, to, array.length); for (int i = length; i > 1; i--) { swap(array, from + i - 1, from + rng.nextInt(i)); } return array; } /** * Shuffles the entries of the given array in the range {@code [from, to)}. * * @param rng Source of randomness. * @param array Array whose entries will be shuffled (in-place). * @param from Lower-bound (inclusive) of the sub-range. * @param to Upper-bound (exclusive) of the sub-range. * @return a reference to the given array * @throws IndexOutOfBoundsException if the sub-range is out of bounds */ public static byte[] shuffle(UniformRandomProvider rng, byte[] array, int from, int to) { final int length = to - checkFromToIndex(from, to, array.length); for (int i = length; i > 1; i--) { swap(array, from + i - 1, from + rng.nextInt(i)); } return array; } /** * Shuffles the entries of the given array in the range {@code [from, to)}. * * @param rng Source of randomness. * @param array Array whose entries will be shuffled (in-place). * @param from Lower-bound (inclusive) of the sub-range. * @param to Upper-bound (exclusive) of the sub-range. * @return a reference to the given array * @throws IndexOutOfBoundsException if the sub-range is out of bounds */ public static char[] shuffle(UniformRandomProvider rng, char[] array, int from, int to) { final int length = to - checkFromToIndex(from, to, array.length); for (int i = length; i > 1; i--) { swap(array, from + i - 1, from + rng.nextInt(i)); } return array; } /** * Shuffles the entries of the given array in the range {@code [from, to)}. * * @param rng Source of randomness. * @param array Array whose entries will be shuffled (in-place). * @param from Lower-bound (inclusive) of the sub-range. * @param to Upper-bound (exclusive) of the sub-range. * @return a reference to the given array * @throws IndexOutOfBoundsException if the sub-range is out of bounds */ public static double[] shuffle(UniformRandomProvider rng, double[] array, int from, int to) { final int length = to - checkFromToIndex(from, to, array.length); for (int i = length; i > 1; i--) { swap(array, from + i - 1, from + rng.nextInt(i)); } return array; } /** * Shuffles the entries of the given array in the range {@code [from, to)}. * * @param rng Source of randomness. * @param array Array whose entries will be shuffled (in-place). * @param from Lower-bound (inclusive) of the sub-range. * @param to Upper-bound (exclusive) of the sub-range. * @return a reference to the given array * @throws IndexOutOfBoundsException if the sub-range is out of bounds */ public static float[] shuffle(UniformRandomProvider rng, float[] array, int from, int to) { final int length = to - checkFromToIndex(from, to, array.length); for (int i = length; i > 1; i--) { swap(array, from + i - 1, from + rng.nextInt(i)); } return array; } /** * Shuffles the entries of the given array in the range {@code [from, to)}. * * @param rng Source of randomness. * @param array Array whose entries will be shuffled (in-place). * @param from Lower-bound (inclusive) of the sub-range. * @param to Upper-bound (exclusive) of the sub-range. * @return a reference to the given array * @throws IndexOutOfBoundsException if the sub-range is out of bounds */ public static int[] shuffle(UniformRandomProvider rng, int[] array, int from, int to) { final int length = to - checkFromToIndex(from, to, array.length); for (int i = length; i > 1; i--) { swap(array, from + i - 1, from + rng.nextInt(i)); } return array; } /** * Shuffles the entries of the given array in the range {@code [from, to)}. * * @param rng Source of randomness. * @param array Array whose entries will be shuffled (in-place). * @param from Lower-bound (inclusive) of the sub-range. * @param to Upper-bound (exclusive) of the sub-range. * @return a reference to the given array * @throws IndexOutOfBoundsException if the sub-range is out of bounds */ public static long[] shuffle(UniformRandomProvider rng, long[] array, int from, int to) { final int length = to - checkFromToIndex(from, to, array.length); for (int i = length; i > 1; i--) { swap(array, from + i - 1, from + rng.nextInt(i)); } return array; } /** * Shuffles the entries of the given array in the range {@code [from, to)}. * * @param rng Source of randomness. * @param array Array whose entries will be shuffled (in-place). * @param from Lower-bound (inclusive) of the sub-range. * @param to Upper-bound (exclusive) of the sub-range. * @return a reference to the given array * @throws IndexOutOfBoundsException if the sub-range is out of bounds */ public static short[] shuffle(UniformRandomProvider rng, short[] array, int from, int to) { final int length = to - checkFromToIndex(from, to, array.length); for (int i = length; i > 1; i--) { swap(array, from + i - 1, from + rng.nextInt(i)); } return array; } /** * Shuffles the entries of the given array in the range {@code [from, to)}. * * @param <T> Type of the items. * @param rng Source of randomness. * @param array Array whose entries will be shuffled (in-place). * @param from Lower-bound (inclusive) of the sub-range. * @param to Upper-bound (exclusive) of the sub-range. * @return a reference to the given array * @throws IndexOutOfBoundsException if the sub-range is out of bounds */ public static <T> T[] shuffle(UniformRandomProvider rng, T[] array, int from, int to) { final int length = to - checkFromToIndex(from, to, array.length); for (int i = length; i > 1; i--) { swap(array, from + i - 1, from + rng.nextInt(i)); } return array; } /** * Swaps the two specified elements in the array. * * @param array Array. * @param i First index. * @param j Second index. */ private static void swap(boolean[] array, int i, int j) { final boolean tmp = array[i]; array[i] = array[j]; array[j] = tmp; } /** * Swaps the two specified elements in the array. * * @param array Array. * @param i First index. * @param j Second index. */ private static void swap(byte[] array, int i, int j) { final byte tmp = array[i]; array[i] = array[j]; array[j] = tmp; } /** * Swaps the two specified elements in the array. * * @param array Array. * @param i First index. * @param j Second index. */ private static void swap(char[] array, int i, int j) { final char tmp = array[i]; array[i] = array[j]; array[j] = tmp; } /** * Swaps the two specified elements in the array. * * @param array Array. * @param i First index. * @param j Second index. */ private static void swap(double[] array, int i, int j) { final double tmp = array[i]; array[i] = array[j]; array[j] = tmp; } /** * Swaps the two specified elements in the array. * * @param array Array. * @param i First index. * @param j Second index. */ private static void swap(float[] array, int i, int j) { final float tmp = array[i]; array[i] = array[j]; array[j] = tmp; } /** * Swaps the two specified elements in the array. * * @param array Array. * @param i First index. * @param j Second index. */ private static void swap(int[] array, int i, int j) { final int tmp = array[i]; array[i] = array[j]; array[j] = tmp; } /** * Swaps the two specified elements in the array. * * @param array Array. * @param i First index. * @param j Second index. */ private static void swap(long[] array, int i, int j) { final long tmp = array[i]; array[i] = array[j]; array[j] = tmp; } /** * Swaps the two specified elements in the array. * * @param array Array. * @param i First index. * @param j Second index. */ private static void swap(short[] array, int i, int j) { final short tmp = array[i]; array[i] = array[j]; array[j] = tmp; } /** * Swaps the two specified elements in the array. * * @param array Array. * @param i First index. * @param j Second index. */ private static void swap(Object[] array, int i, int j) { final Object tmp = array[i]; array[i] = array[j]; array[j] = tmp; } /** * Checks if the sub-range from fromIndex (inclusive) to toIndex (exclusive) is * within the bounds of range from 0 (inclusive) to length (exclusive). * * <p>This function provides the functionality of * {@code java.utils.Objects.checkFromToIndex} introduced in JDK 9. The <a * href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Objects.html#checkFromToIndex(int,int,int)">Objects</a> * javadoc has been reproduced for reference. * * <p>The sub-range is defined to be out of bounds if any of the following * inequalities is true: * <ul> * <li>{@code fromIndex < 0} * <li>{@code fromIndex > toIndex} * <li>{@code toIndex > length} * <li>{@code length < 0}, which is implied from the former inequalities * </ul> * * @param fromIndex Lower-bound (inclusive) of the sub-range. * @param toIndex Upper-bound (exclusive) of the sub-range. * @param length Upper-bound (exclusive) of the range * @return fromIndex if the sub-range is within the bounds of the range * @throws IndexOutOfBoundsException if the sub-range is out of bounds */ private static int checkFromToIndex(int fromIndex, int toIndex, int length) { // Checks as documented above if (fromIndex < 0 || fromIndex > toIndex || toIndex > length) { throw new IndexOutOfBoundsException( String.format("Range [%d, %d) out of bounds for length %d", fromIndex, toIndex, length)); } return fromIndex; } }
2,970
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/package-info.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This package provides sampling utilities. * <p> * The {@link org.apache.commons.rng.sampling.distribution distribution} * sub-package provides sampling from statistical distributions. * </p> * <p> * The {@link org.apache.commons.rng.sampling.shape shape} * sub-package provides sampling coordinates from shapes. * </p> */ package org.apache.commons.rng.sampling;
2,971
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/ListSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling; import java.util.List; import java.util.ListIterator; import java.util.RandomAccess; import java.util.ArrayList; import org.apache.commons.rng.UniformRandomProvider; /** * Sampling from a {@link List}. * * <p>This class also contains utilities for shuffling a {@link List} in-place.</p> * * @since 1.0 */ public final class ListSampler { /** * The size threshold for using the random access algorithm * when the list does not implement java.util.RandomAccess. */ private static final int RANDOM_ACCESS_SIZE_THRESHOLD = 4; /** * Class contains only static methods. */ private ListSampler() {} /** * Generates a list of size {@code k} whose entries are selected * randomly, without repetition, from the items in the given * {@code collection}. * * <p> * Sampling is without replacement; but if the source collection * contains identical objects, the sample may include repeats. * </p> * * <p> * Sampling uses {@link UniformRandomProvider#nextInt(int)}. * </p> * * @param <T> Type of the list items. * @param rng Generator of uniformly distributed random numbers. * @param collection List to be sampled from. * @param k Size of the returned sample. * @throws IllegalArgumentException if {@code k <= 0} or * {@code k > collection.size()}. * @return a shuffled sample from the source collection. */ public static <T> List<T> sample(UniformRandomProvider rng, List<T> collection, int k) { final int n = collection.size(); final PermutationSampler p = new PermutationSampler(rng, n, k); final List<T> result = new ArrayList<>(k); final int[] index = p.sample(); for (int i = 0; i < k; i++) { result.add(collection.get(index[i])); } return result; } /** * Shuffles the entries of the given array, using the * <a href="http://en.wikipedia.org/wiki/Fisher-Yates_shuffle#The_modern_algorithm"> * Fisher-Yates</a> algorithm. * * <p> * Sampling uses {@link UniformRandomProvider#nextInt(int)}. * </p> * * @param <T> Type of the list items. * @param rng Random number generator. * @param list List whose entries will be shuffled (in-place). */ @SuppressWarnings({"rawtypes", "unchecked"}) public static <T> void shuffle(UniformRandomProvider rng, List<T> list) { if (list instanceof RandomAccess || list.size() < RANDOM_ACCESS_SIZE_THRESHOLD) { // Shuffle list in-place for (int i = list.size(); i > 1; i--) { swap(list, i - 1, rng.nextInt(i)); } } else { // Shuffle as an array final Object[] array = list.toArray(); for (int i = array.length; i > 1; i--) { swap(array, i - 1, rng.nextInt(i)); } // Copy back. Use raw types. final ListIterator it = list.listIterator(); for (final Object item : array) { it.next(); it.set(item); } } } /** * Shuffles the entries of the given array, using the * <a href="http://en.wikipedia.org/wiki/Fisher-Yates_shuffle#The_modern_algorithm"> * Fisher-Yates</a> algorithm. * * <p> * The {@code start} and {@code pos} parameters select which part * of the array is randomized and which is left untouched. * </p> * * <p> * Sampling uses {@link UniformRandomProvider#nextInt(int)}. * </p> * * @param <T> Type of the list items. * @param rng Random number generator. * @param list List whose entries will be shuffled (in-place). * @param start Index at which shuffling begins. * @param towardHead Shuffling is performed for index positions between * {@code start} and either the end (if {@code false}) or the beginning * (if {@code true}) of the array. */ public static <T> void shuffle(UniformRandomProvider rng, List<T> list, int start, boolean towardHead) { // Shuffle in-place as a sub-list. if (towardHead) { shuffle(rng, list.subList(0, start + 1)); } else { shuffle(rng, list.subList(start, list.size())); } } /** * Swaps the two specified elements in the list. * * @param <T> Type of the list items. * @param list List. * @param i First index. * @param j Second index. */ private static <T> void swap(List<T> list, int i, int j) { final T tmp = list.get(i); list.set(i, list.get(j)); list.set(j, tmp); } /** * Swaps the two specified elements in the array. * * @param array Array. * @param i First index. * @param j Second index. */ private static void swap(Object[] array, int i, int j) { final Object tmp = array[i]; array[i] = array[j]; array[j] = tmp; } }
2,972
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/shape/Coordinates.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.shape; /** * Utility class for common coordinate operations for shape samplers. * * @since 1.4 */ final class Coordinates { /** No public construction. */ private Coordinates() {} /** * Check that the values are finite. This method is primarily for parameter * validation in methods and constructors, for example: * * <pre> * public Line(double[] start, double[] end) { * this.start = Coordinates.requireFinite(start, "start"); * this.end = Coordinates.requireFinite(end, "end"); * } * </pre> * * @param values the values * @param message the message detail to prepend to the message in the event an exception is thrown * @return the values * @throws IllegalArgumentException if a non-finite value is found */ static double[] requireFinite(double[] values, String message) { for (final double value : values) { if (!Double.isFinite(value)) { throw new IllegalArgumentException(message + " contains non-finite value: " + value); } } return values; } /** * Check that the values is the specified length. This method is primarily for * parameter validation in methods and constructors, for example: * * <pre> * public Square(double[] topLeft, double[] bottomRight) { * this.topLeft = Coordinates.requireLength(topLeft, 2, "topLeft"); * this.bottomRight = Coordinates.requireLength(bottomRight, 2, "bottomRight"); * } * </pre> * * @param values the values * @param length the length * @param message the message detail to prepend to the message in the event an * exception is thrown * @return the values * @throws IllegalArgumentException if the array length is not the specified length */ static double[] requireLength(double[] values, int length, String message) { if (values.length != length) { throw new IllegalArgumentException(String.format("%s length mismatch: %d != %d", message, values.length, length)); } return values; } }
2,973
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/shape/BoxSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.shape; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.SharedStateObjectSampler; /** * Generate points uniformly distributed within a n-dimension box (hyperrectangle). * * <p>Sampling uses:</p> * * <ul> * <li>{@link UniformRandomProvider#nextDouble()} * </ul> * * @see <a href="https://en.wikipedia.org/wiki/Hyperrectangle">Hyperrectangle (Wikipedia)</a> * @since 1.4 */ public abstract class BoxSampler implements SharedStateObjectSampler<double[]> { /** The dimension for 2D sampling. */ private static final int TWO_D = 2; /** The dimension for 3D sampling. */ private static final int THREE_D = 3; /** The source of randomness. */ private final UniformRandomProvider rng; // The following code defines a point within the range ab: // p = (1 - u)a + ub, u in [0, 1] // // This is the same method used in the // o.a.c.rng.sampling.distribution.ContinuousUniformSampler but extended to N-dimensions. /** * Sample uniformly from a box in 2D. This is an non-array based specialisation of * {@link BoxSamplerND} for performance. */ private static class BoxSampler2D extends BoxSampler { /** The x component of bound a. */ private final double ax; /** The y component of bound a. */ private final double ay; /** The x component of bound b. */ private final double bx; /** The y component of bound b. */ private final double by; /** * @param rng Source of randomness. * @param a Bound a. * @param b Bound b. */ BoxSampler2D(UniformRandomProvider rng, double[] a, double[] b) { super(rng); ax = a[0]; ay = a[1]; bx = b[0]; by = b[1]; } /** * @param rng Source of randomness. * @param source Source to copy. */ BoxSampler2D(UniformRandomProvider rng, BoxSampler2D source) { super(rng); ax = source.ax; ay = source.ay; bx = source.bx; by = source.by; } @Override public double[] sample() { return new double[] {createSample(ax, bx), createSample(ay, by)}; } @Override public BoxSampler withUniformRandomProvider(UniformRandomProvider rng) { return new BoxSampler2D(rng, this); } } /** * Sample uniformly from a box in 3D. This is an non-array based specialisation of * {@link BoxSamplerND} for performance. */ private static class BoxSampler3D extends BoxSampler { /** The x component of bound a. */ private final double ax; /** The y component of bound a. */ private final double ay; /** The z component of bound a. */ private final double az; /** The x component of bound b. */ private final double bx; /** The y component of bound b. */ private final double by; /** The z component of bound b. */ private final double bz; /** * @param rng Source of randomness. * @param a Bound a. * @param b Bound b. */ BoxSampler3D(UniformRandomProvider rng, double[] a, double[] b) { super(rng); ax = a[0]; ay = a[1]; az = a[2]; bx = b[0]; by = b[1]; bz = b[2]; } /** * @param rng Source of randomness. * @param source Source to copy. */ BoxSampler3D(UniformRandomProvider rng, BoxSampler3D source) { super(rng); ax = source.ax; ay = source.ay; az = source.az; bx = source.bx; by = source.by; bz = source.bz; } @Override public double[] sample() { return new double[] {createSample(ax, bx), createSample(ay, by), createSample(az, bz)}; } @Override public BoxSampler withUniformRandomProvider(UniformRandomProvider rng) { return new BoxSampler3D(rng, this); } } /** * Sample uniformly from a box in ND. */ private static class BoxSamplerND extends BoxSampler { /** Bound a. */ private final double[] a; /** Bound b. */ private final double[] b; /** * @param rng Source of randomness. * @param a Bound a. * @param b Bound b. */ BoxSamplerND(UniformRandomProvider rng, double[] a, double[] b) { super(rng); // Defensive copy this.a = a.clone(); this.b = b.clone(); } /** * @param rng Source of randomness. * @param source Source to copy. */ BoxSamplerND(UniformRandomProvider rng, BoxSamplerND source) { super(rng); // Shared state is immutable a = source.a; b = source.b; } @Override public double[] sample() { final double[] x = new double[a.length]; for (int i = 0; i < x.length; i++) { x[i] = createSample(a[i], b[i]); } return x; } @Override public BoxSampler withUniformRandomProvider(UniformRandomProvider rng) { return new BoxSamplerND(rng, this); } } /** * @param rng Source of randomness. */ BoxSampler(UniformRandomProvider rng) { this.rng = rng; } /** * @return a random Cartesian coordinate within the box. */ @Override public abstract double[] sample(); /** * Creates the sample between bound a and b. * * @param a Bound a * @param b Bound b * @return the sample */ double createSample(double a, double b) { final double u = rng.nextDouble(); return (1.0 - u) * a + u * b; } /** {@inheritDoc} */ // Redeclare the signature to return a BoxSampler not a SharedStateObjectSampler<double[]> @Override public abstract BoxSampler withUniformRandomProvider(UniformRandomProvider rng); /** * Create a box sampler with bounds {@code a} and {@code b}. * Sampled points are uniformly distributed within the box defined by the bounds. * * <p>Sampling is supported in dimensions of 2 or above. Single dimension sampling * can be performed using a {@link LineSampler}. * * <p>Note: There is no requirement that {@code a <= b}. The samples will be uniformly * distributed in the range {@code a} to {@code b} for each dimension. * * @param rng Source of randomness. * @param a Bound a. * @param b Bound b. * @return the sampler * @throws IllegalArgumentException If the bounds do not have the same * dimension; the dimension is less than 2; or bounds have non-finite coordinates. */ public static BoxSampler of(UniformRandomProvider rng, double[] a, double[] b) { final int dimension = a.length; if (dimension != b.length) { throw new IllegalArgumentException( new StringBuilder("Mismatch of box dimensions: ").append(dimension).append(',') .append(b.length).toString()); } // Detect non-finite bounds Coordinates.requireFinite(a, "Bound a"); Coordinates.requireFinite(b, "Bound b"); // Low dimension specialisations if (dimension == TWO_D) { return new BoxSampler2D(rng, a, b); } else if (dimension == THREE_D) { return new BoxSampler3D(rng, a, b); } else if (dimension > THREE_D) { return new BoxSamplerND(rng, a, b); } // Less than 2D throw new IllegalArgumentException("Unsupported dimension: " + dimension); } }
2,974
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/shape/UnitBallSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.shape; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.SharedStateObjectSampler; import org.apache.commons.rng.sampling.distribution.ContinuousSampler; import org.apache.commons.rng.sampling.distribution.NormalizedGaussianSampler; import org.apache.commons.rng.sampling.distribution.ZigguratSampler; /** * Generate coordinates <a href="http://mathworld.wolfram.com/BallPointPicking.html"> * uniformly distributed within the unit n-ball</a>. * * <p>Sampling uses:</p> * * <ul> * <li>{@link UniformRandomProvider#nextLong()} * <li>{@link UniformRandomProvider#nextDouble()} (only for dimensions above 2) * </ul> * * @since 1.4 */ public abstract class UnitBallSampler implements SharedStateObjectSampler<double[]> { /** The dimension for 1D sampling. */ private static final int ONE_D = 1; /** The dimension for 2D sampling. */ private static final int TWO_D = 2; /** The dimension for 3D sampling. */ private static final int THREE_D = 3; /** * The multiplier to convert the least significant 53-bits of a {@code long} to a {@code double}. * Taken from o.a.c.rng.core.utils.NumberFactory. * * <p>This is equivalent to {@code 1.0 / (1L << 53)}. */ private static final double DOUBLE_MULTIPLIER = 0x1.0p-53d; /** * Sample uniformly from a 1D unit line. */ private static class UnitBallSampler1D extends UnitBallSampler { /** The source of randomness. */ private final UniformRandomProvider rng; /** * @param rng Source of randomness. */ UnitBallSampler1D(UniformRandomProvider rng) { this.rng = rng; } @Override public double[] sample() { return new double[] {makeSignedDouble(rng.nextLong())}; } @Override public UnitBallSampler withUniformRandomProvider(UniformRandomProvider rng) { return new UnitBallSampler1D(rng); } } /** * Sample uniformly from a 2D unit disk. */ private static class UnitBallSampler2D extends UnitBallSampler { /** The source of randomness. */ private final UniformRandomProvider rng; /** * @param rng Source of randomness. */ UnitBallSampler2D(UniformRandomProvider rng) { this.rng = rng; } @Override public double[] sample() { // Generate via rejection method of a circle inside a square of edge length 2. // This should compute approximately 2^2 / pi = 1.27 square positions per sample. double x; double y; do { x = makeSignedDouble(rng.nextLong()); y = makeSignedDouble(rng.nextLong()); } while (x * x + y * y > 1.0); return new double[] {x, y}; } @Override public UnitBallSampler withUniformRandomProvider(UniformRandomProvider rng) { return new UnitBallSampler2D(rng); } } /** * Sample uniformly from a 3D unit ball. This is an non-array based specialisation of * {@link UnitBallSamplerND} for performance. */ private static class UnitBallSampler3D extends UnitBallSampler { /** The standard normal distribution. */ private final NormalizedGaussianSampler normal; /** The exponential distribution (mean=1). */ private final ContinuousSampler exp; /** * @param rng Source of randomness. */ UnitBallSampler3D(UniformRandomProvider rng) { normal = ZigguratSampler.NormalizedGaussian.of(rng); // Require an Exponential(mean=2). // Here we use mean = 1 and scale the output later. exp = ZigguratSampler.Exponential.of(rng); } @Override public double[] sample() { final double x = normal.sample(); final double y = normal.sample(); final double z = normal.sample(); // Include the exponential sample. It has mean 1 so multiply by 2. final double sum = exp.sample() * 2 + x * x + y * y + z * z; // Note: Handle the possibility of a zero sum and invalid inverse if (sum == 0) { return sample(); } final double f = 1.0 / Math.sqrt(sum); return new double[] {x * f, y * f, z * f}; } @Override public UnitBallSampler withUniformRandomProvider(UniformRandomProvider rng) { return new UnitBallSampler3D(rng); } } /** * Sample using ball point picking. * @see <a href="https://mathworld.wolfram.com/BallPointPicking.html">Ball point picking</a> */ private static class UnitBallSamplerND extends UnitBallSampler { /** The dimension. */ private final int dimension; /** The standard normal distribution. */ private final NormalizedGaussianSampler normal; /** The exponential distribution (mean=1). */ private final ContinuousSampler exp; /** * @param rng Source of randomness. * @param dimension Space dimension. */ UnitBallSamplerND(UniformRandomProvider rng, int dimension) { this.dimension = dimension; normal = ZigguratSampler.NormalizedGaussian.of(rng); // Require an Exponential(mean=2). // Here we use mean = 1 and scale the output later. exp = ZigguratSampler.Exponential.of(rng); } @Override public double[] sample() { final double[] sample = new double[dimension]; // Include the exponential sample. It has mean 1 so multiply by 2. double sum = exp.sample() * 2; for (int i = 0; i < dimension; i++) { final double x = normal.sample(); sum += x * x; sample[i] = x; } // Note: Handle the possibility of a zero sum and invalid inverse if (sum == 0) { return sample(); } final double f = 1.0 / Math.sqrt(sum); for (int i = 0; i < dimension; i++) { sample[i] *= f; } return sample; } @Override public UnitBallSampler withUniformRandomProvider(UniformRandomProvider rng) { return new UnitBallSamplerND(rng, dimension); } } /** * @return a random Cartesian coordinate within the unit n-ball. */ @Override public abstract double[] sample(); /** {@inheritDoc} */ // Redeclare the signature to return a UnitBallSampler not a SharedStateObjectSampler<double[]> @Override public abstract UnitBallSampler withUniformRandomProvider(UniformRandomProvider rng); /** * Create a unit n-ball sampler for the given dimension. * Sampled points are uniformly distributed within the unit n-ball. * * <p>Sampling is supported in dimensions of 1 or above. * * @param rng Source of randomness. * @param dimension Space dimension. * @return the sampler * @throws IllegalArgumentException If {@code dimension <= 0} */ public static UnitBallSampler of(UniformRandomProvider rng, int dimension) { if (dimension <= 0) { throw new IllegalArgumentException("Dimension must be strictly positive"); } else if (dimension == ONE_D) { return new UnitBallSampler1D(rng); } else if (dimension == TWO_D) { return new UnitBallSampler2D(rng); } else if (dimension == THREE_D) { return new UnitBallSampler3D(rng); } return new UnitBallSamplerND(rng, dimension); } /** * Creates a signed double in the range {@code [-1, 1)}. The magnitude is sampled evenly * from the 2<sup>54</sup> dyadic rationals in the range. * * <p>Note: This method will not return samples for both -0.0 and 0.0. * * @param bits the bits * @return the double */ private static double makeSignedDouble(long bits) { // As per o.a.c.rng.core.utils.NumberFactory.makeDouble(long) but using a signed // shift of 10 in place of an unsigned shift of 11. // Use the upper 54 bits on the assumption they are more random. // The sign bit is maintained by the signed shift. // The next 53 bits generates a magnitude in the range [0, 2^53) or [-2^53, 0). return (bits >> 10) * DOUBLE_MULTIPLIER; } }
2,975
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/shape/TetrahedronSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.shape; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.SharedStateObjectSampler; /** * Generate points uniformly distributed within a * <a href="https://en.wikipedia.org/wiki/Tetrahedron">tetrahedron</a>. * * <ul> * <li> * Uses the algorithm described in: * <blockquote> * Rocchini, C. and Cignoni, P. (2001)<br> * <i>Generating Random Points in a Tetrahedron</i>.<br> * <strong>Journal of Graphics Tools</strong> 5(4), pp. 9-12. * </blockquote> * </li> * </ul> * * <p>Sampling uses:</p> * * <ul> * <li>{@link UniformRandomProvider#nextDouble()} * </ul> * * @see <a href="https://doi.org/10.1080/10867651.2000.10487528"> * Rocchini, C. &amp; Cignoni, P. (2001) Journal of Graphics Tools 5, pp. 9-12</a> * @since 1.4 */ public class TetrahedronSampler implements SharedStateObjectSampler<double[]> { /** The dimension for 3D sampling. */ private static final int THREE_D = 3; /** The name of vertex a. */ private static final String VERTEX_A = "Vertex a"; /** The name of vertex b. */ private static final String VERTEX_B = "Vertex b"; /** The name of vertex c. */ private static final String VERTEX_C = "Vertex c"; /** The name of vertex d. */ private static final String VERTEX_D = "Vertex d"; /** The first vertex. */ private final double[] a; /** The second vertex. */ private final double[] b; /** The third vertex. */ private final double[] c; /** The fourth vertex. */ private final double[] d; /** The source of randomness. */ private final UniformRandomProvider rng; /** * @param rng Source of randomness. * @param a The first vertex. * @param b The second vertex. * @param c The third vertex. * @param d The fourth vertex. */ TetrahedronSampler(UniformRandomProvider rng, double[] a, double[] b, double[] c, double[] d) { // Defensive copy this.a = a.clone(); this.b = b.clone(); this.c = c.clone(); this.d = d.clone(); this.rng = rng; } /** * @param rng Generator of uniformly distributed random numbers * @param source Source to copy. */ TetrahedronSampler(UniformRandomProvider rng, TetrahedronSampler source) { // Shared state is immutable a = source.a; b = source.b; c = source.c; d = source.d; this.rng = rng; } /** * @return a random Cartesian point within the tetrahedron. */ @Override public double[] sample() { double s = rng.nextDouble(); double t = rng.nextDouble(); final double u = rng.nextDouble(); // Care is taken to ensure the 3 deviates remain in the 2^53 dyadic rationals in [0, 1). // The following are exact for all the 2^53 dyadic rationals: // 1 - u; u in [0, 1] // u - 1; u in [0, 1] // u + 1; u in [-1, 0] // u + v; u in [-1, 0], v in [0, 1] // u + v; u, v in [0, 1], u + v <= 1 // Cut and fold with the plane s + t = 1 if (s + t > 1) { // (s, t, u) = (1 - s, 1 - t, u) if s + t > 1 s = 1 - s; t = 1 - t; } // Now s + t <= 1. // Cut and fold with the planes t + u = 1 and s + t + u = 1. final double tpu = t + u; final double sptpu = s + tpu; if (sptpu > 1) { if (tpu > 1) { // (s, t, u) = (s, 1 - u, 1 - s - t) if t + u > 1 // 1 - s - (1-u) - (1-s-t) == u - 1 + t return createSample(u - 1 + t, s, 1 - u, 1 - s - t); } // (s, t, u) = (1 - t - u, t, s + t + u - 1) if t + u <= 1 // 1 - (1-t-u) - t - (s+t+u-1) == 1 - s - t return createSample(1 - s - t, 1 - tpu, t, s - 1 + tpu); } return createSample(1 - sptpu, s, t, u); } /** * Creates the sample given the random variates {@code s}, {@code t} and {@code u} in the * interval {@code [0, 1]} and {@code s + t + u <= 1}. The sum {@code 1 - s - t - u} is * provided. The sample can be obtained from the tetrahedron {@code abcd} using: * * <pre> * p = (1 - s - t - u)a + sb + tc + ud * </pre> * * @param p1msmtmu plus 1 minus s minus t minus u ({@code 1 - s - t - u}) * @param s the first variate s * @param t the second variate t * @param u the third variate u * @return the sample */ private double[] createSample(double p1msmtmu, double s, double t, double u) { // From the barycentric coordinates s,t,u create the point by moving along // vectors ab, ac and ad. // Here we do not compute the vectors and use the original vertices: // p = a + s(b-a) + t(c-a) + u(d-a) // = (1-s-t-u)a + sb + tc + ud return new double[] {p1msmtmu * a[0] + s * b[0] + t * c[0] + u * d[0], p1msmtmu * a[1] + s * b[1] + t * c[1] + u * d[1], p1msmtmu * a[2] + s * b[2] + t * c[2] + u * d[2]}; } /** {@inheritDoc} */ @Override public TetrahedronSampler withUniformRandomProvider(UniformRandomProvider rng) { return new TetrahedronSampler(rng, this); } /** * Create a tetrahedron sampler with vertices {@code a}, {@code b}, {@code c} and {@code d}. * Sampled points are uniformly distributed within the tetrahedron. * * <p>No test for a volume is performed. If the vertices are coplanar the sampling * distribution is undefined. * * @param rng Source of randomness. * @param a The first vertex. * @param b The second vertex. * @param c The third vertex. * @param d The fourth vertex. * @return the sampler * @throws IllegalArgumentException If the vertices do not have length 3; * or vertices have non-finite coordinates */ public static TetrahedronSampler of(UniformRandomProvider rng, double[] a, double[] b, double[] c, double[] d) { // Must be 3D Coordinates.requireLength(a, THREE_D, VERTEX_A); Coordinates.requireLength(b, THREE_D, VERTEX_B); Coordinates.requireLength(c, THREE_D, VERTEX_C); Coordinates.requireLength(d, THREE_D, VERTEX_D); // Detect non-finite vertices Coordinates.requireFinite(a, VERTEX_A); Coordinates.requireFinite(b, VERTEX_B); Coordinates.requireFinite(c, VERTEX_C); Coordinates.requireFinite(d, VERTEX_D); return new TetrahedronSampler(rng, a, b, c, d); } }
2,976
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/shape/LineSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.shape; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.SharedStateObjectSampler; /** * Generate points uniformly distributed on a line. * * <p>Sampling uses:</p> * * <ul> * <li>{@link UniformRandomProvider#nextDouble()} * </ul> * * @since 1.4 */ public abstract class LineSampler implements SharedStateObjectSampler<double[]> { /** The dimension for 1D sampling. */ private static final int ONE_D = 1; /** The dimension for 2D sampling. */ private static final int TWO_D = 2; /** The dimension for 3D sampling. */ private static final int THREE_D = 3; /** The source of randomness. */ private final UniformRandomProvider rng; // The following code defines a point on a line as: // p = a + u * (b - a), u in [0, 1] // // This is rearranged to: // p = a + ub - ua // = (1 - u)a + ub // // This is the same method used in the // o.a.c.rng.sampling.distribution.ContinuousUniformSampler but extended to N-dimensions. /** * Sample uniformly from a line in 1D. This is an non-array based specialisation of * {@link LineSamplerND} for performance. */ private static class LineSampler1D extends LineSampler { /** The x component of vertex a. */ private final double ax; /** The x component of vertex b. */ private final double bx; /** * @param rng Source of randomness. * @param a The first vertex. * @param b The second vertex. */ LineSampler1D(UniformRandomProvider rng, double[] a, double[] b) { super(rng); ax = a[0]; bx = b[0]; } /** * @param rng Source of randomness. * @param source Source to copy. */ LineSampler1D(UniformRandomProvider rng, LineSampler1D source) { super(rng); ax = source.ax; bx = source.bx; } @Override public double[] createSample(double p1mu, double u) { return new double[] {p1mu * ax + u * bx}; } @Override public LineSampler withUniformRandomProvider(UniformRandomProvider rng) { return new LineSampler1D(rng, this); } } /** * Sample uniformly from a line in 2D. This is an non-array based specialisation of * {@link LineSamplerND} for performance. */ private static class LineSampler2D extends LineSampler { /** The x component of vertex a. */ private final double ax; /** The y component of vertex a. */ private final double ay; /** The x component of vertex b. */ private final double bx; /** The y component of vertex b. */ private final double by; /** * @param rng Source of randomness. * @param a The first vertex. * @param b The second vertex. */ LineSampler2D(UniformRandomProvider rng, double[] a, double[] b) { super(rng); ax = a[0]; ay = a[1]; bx = b[0]; by = b[1]; } /** * @param rng Source of randomness. * @param source Source to copy. */ LineSampler2D(UniformRandomProvider rng, LineSampler2D source) { super(rng); ax = source.ax; ay = source.ay; bx = source.bx; by = source.by; } @Override public double[] createSample(double p1mu, double u) { return new double[] {p1mu * ax + u * bx, p1mu * ay + u * by}; } @Override public LineSampler withUniformRandomProvider(UniformRandomProvider rng) { return new LineSampler2D(rng, this); } } /** * Sample uniformly from a line in 3D. This is an non-array based specialisation of * {@link LineSamplerND} for performance. */ private static class LineSampler3D extends LineSampler { /** The x component of vertex a. */ private final double ax; /** The y component of vertex a. */ private final double ay; /** The z component of vertex a. */ private final double az; /** The x component of vertex b. */ private final double bx; /** The y component of vertex b. */ private final double by; /** The z component of vertex b. */ private final double bz; /** * @param rng Source of randomness. * @param a The first vertex. * @param b The second vertex. */ LineSampler3D(UniformRandomProvider rng, double[] a, double[] b) { super(rng); ax = a[0]; ay = a[1]; az = a[2]; bx = b[0]; by = b[1]; bz = b[2]; } /** * @param rng Source of randomness. * @param source Source to copy. */ LineSampler3D(UniformRandomProvider rng, LineSampler3D source) { super(rng); ax = source.ax; ay = source.ay; az = source.az; bx = source.bx; by = source.by; bz = source.bz; } @Override public double[] createSample(double p1mu, double u) { return new double[] {p1mu * ax + u * bx, p1mu * ay + u * by, p1mu * az + u * bz}; } @Override public LineSampler withUniformRandomProvider(UniformRandomProvider rng) { return new LineSampler3D(rng, this); } } /** * Sample uniformly from a line in ND. */ private static class LineSamplerND extends LineSampler { /** The first vertex. */ private final double[] a; /** The second vertex. */ private final double[] b; /** * @param rng Source of randomness. * @param a The first vertex. * @param b The second vertex. */ LineSamplerND(UniformRandomProvider rng, double[] a, double[] b) { super(rng); // Defensive copy this.a = a.clone(); this.b = b.clone(); } /** * @param rng Source of randomness. * @param source Source to copy. */ LineSamplerND(UniformRandomProvider rng, LineSamplerND source) { super(rng); // Shared state is immutable a = source.a; b = source.b; } @Override public double[] createSample(double p1mu, double u) { final double[] x = new double[a.length]; for (int i = 0; i < x.length; i++) { x[i] = p1mu * a[i] + u * b[i]; } return x; } @Override public LineSampler withUniformRandomProvider(UniformRandomProvider rng) { return new LineSamplerND(rng, this); } } /** * @param rng Source of randomness. */ LineSampler(UniformRandomProvider rng) { this.rng = rng; } /** * @return a random Cartesian coordinate on the line. */ @Override public double[] sample() { final double u = rng.nextDouble(); return createSample(1.0 - u, u); } /** * Creates the sample given the random variate {@code u} in the * interval {@code [0, 1]}. The sum {@code 1 - u} is provided. * The sample can be obtained from the line ab using: * <pre> * p = a(1 - u) + ub * </pre> * * @param p1mu plus 1 minus u (1 - u) * @param u the variate u * @return the sample */ protected abstract double[] createSample(double p1mu, double u); /** {@inheritDoc} */ // Redeclare the signature to return a LineSampler not a SharedStateObjectSampler<double[]> @Override public abstract LineSampler withUniformRandomProvider(UniformRandomProvider rng); /** * Create a line sampler with vertices {@code a} and {@code b}. * Sampled points are uniformly distributed on the line segment {@code ab}. * * <p>Sampling is supported in dimensions of 1 or above. * * @param rng Source of randomness. * @param a The first vertex. * @param b The second vertex. * @return the sampler * @throws IllegalArgumentException If the vertices do not have the same * dimension; the dimension is less than 1; or vertices have non-finite coordinates. */ public static LineSampler of(UniformRandomProvider rng, double[] a, double[] b) { final int dimension = a.length; if (dimension != b.length) { throw new IllegalArgumentException( new StringBuilder("Mismatch of vertex dimensions: ").append(dimension).append(',') .append(b.length).toString()); } // Detect non-finite vertices Coordinates.requireFinite(a, "Vertex a"); Coordinates.requireFinite(b, "Vertex b"); // Low dimension specialisations if (dimension == TWO_D) { return new LineSampler2D(rng, a, b); } else if (dimension == THREE_D) { return new LineSampler3D(rng, a, b); } else if (dimension > THREE_D) { return new LineSamplerND(rng, a, b); } else if (dimension == ONE_D) { // Unlikely case of 1D is placed last. // Use o.a.c.rng.sampling.distribution.ContinuousUniformSampler for non-array samples. return new LineSampler1D(rng, a, b); } // Less than 1D throw new IllegalArgumentException("Unsupported dimension: " + dimension); } }
2,977
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/shape/package-info.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This package contains classes for sampling coordinates from shapes, for example a unit ball. * * @since 1.4 */ package org.apache.commons.rng.sampling.shape;
2,978
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/shape/TriangleSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.shape; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.SharedStateObjectSampler; /** * Generate points <a href="https://mathworld.wolfram.com/TrianglePointPicking.html"> * uniformly distributed within a triangle</a>. * * <ul> * <li> * Uses the algorithm described in: * <blockquote> * Turk, G. <i>Generating random points in triangles</i>. Glassner, A. S. (ed) (1990).<br> * <strong>Graphic Gems</strong> Academic Press, pp. 24-28. * </blockquote> * </li> * </ul> * * <p>Sampling uses:</p> * * <ul> * <li>{@link UniformRandomProvider#nextDouble()} * </ul> * * @since 1.4 */ public abstract class TriangleSampler implements SharedStateObjectSampler<double[]> { /** The dimension for 2D sampling. */ private static final int TWO_D = 2; /** The dimension for 3D sampling. */ private static final int THREE_D = 3; /** The source of randomness. */ private final UniformRandomProvider rng; // The following code defines a plane as the set of all points r: // r = r0 + sv + tw // where s and t range over all real numbers, v and w are given linearly independent // vectors defining the plane, and r0 is an arbitrary (but fixed) point in the plane. // // Sampling from a triangle (a,b,c) is performed when: // s and t are in [0, 1] and s+t <= 1; // r0 is one triangle vertex (a); // and v (b-a) and w (c-a) are vectors from the other two vertices to r0. // // For robustness with large value coordinates the point r is computed without // the requirement to compute v and w which can overflow: // // a + s(b-a) + t(c-a) == a + sb - sa + tc - ta // == a(1 - s - t) + sb + tc // // Assuming the uniform deviates are from the 2^53 dyadic rationals in [0, 1) if s+t <= 1 // then 1 - (s+t) is exact. Sampling is then done using: // // if (s + t <= 1): // p = a(1 - (s + t)) + sb + tc // else: // p = a(1 - (1 - s) - (1 - t)) + (1 - s)b + (1 - t)c // p = a(s - 1 + t) + (1 - s)b + (1 - t)c // // Note do not simplify (1 - (1 - s) - (1 - t)) to (s + t - 1) as s+t > 1 and has potential // loss of a single bit of randomness due to rounding. An exact sum is s - 1 + t. /** * Sample uniformly from a triangle in 2D. This is an non-array based specialisation of * {@link TriangleSamplerND} for performance. */ private static class TriangleSampler2D extends TriangleSampler { /** The x component of vertex a. */ private final double ax; /** The y component of vertex a. */ private final double ay; /** The x component of vertex b. */ private final double bx; /** The y component of vertex b. */ private final double by; /** The x component of vertex c. */ private final double cx; /** The y component of vertex c. */ private final double cy; /** * @param rng Source of randomness. * @param a The first vertex. * @param b The second vertex. * @param c The third vertex. */ TriangleSampler2D(UniformRandomProvider rng, double[] a, double[] b, double[] c) { super(rng); ax = a[0]; ay = a[1]; bx = b[0]; by = b[1]; cx = c[0]; cy = c[1]; } /** * @param rng Generator of uniformly distributed random numbers * @param source Source to copy. */ TriangleSampler2D(UniformRandomProvider rng, TriangleSampler2D source) { super(rng); ax = source.ax; ay = source.ay; bx = source.bx; by = source.by; cx = source.cx; cy = source.cy; } @Override public double[] createSample(double p1msmt, double s, double t) { return new double[] {p1msmt * ax + s * bx + t * cx, p1msmt * ay + s * by + t * cy}; } @Override public TriangleSampler withUniformRandomProvider(UniformRandomProvider rng) { return new TriangleSampler2D(rng, this); } } /** * Sample uniformly from a triangle in 3D. This is an non-array based specialisation of * {@link TriangleSamplerND} for performance. */ private static class TriangleSampler3D extends TriangleSampler { /** The x component of vertex a. */ private final double ax; /** The y component of vertex a. */ private final double ay; /** The z component of vertex a. */ private final double az; /** The x component of vertex b. */ private final double bx; /** The y component of vertex b. */ private final double by; /** The z component of vertex b. */ private final double bz; /** The x component of vertex c. */ private final double cx; /** The y component of vertex c. */ private final double cy; /** The z component of vertex c. */ private final double cz; /** * @param rng Source of randomness. * @param a The first vertex. * @param b The second vertex. * @param c The third vertex. */ TriangleSampler3D(UniformRandomProvider rng, double[] a, double[] b, double[] c) { super(rng); ax = a[0]; ay = a[1]; az = a[2]; bx = b[0]; by = b[1]; bz = b[2]; cx = c[0]; cy = c[1]; cz = c[2]; } /** * @param rng Generator of uniformly distributed random numbers * @param source Source to copy. */ TriangleSampler3D(UniformRandomProvider rng, TriangleSampler3D source) { super(rng); ax = source.ax; ay = source.ay; az = source.az; bx = source.bx; by = source.by; bz = source.bz; cx = source.cx; cy = source.cy; cz = source.cz; } @Override public double[] createSample(double p1msmt, double s, double t) { return new double[] {p1msmt * ax + s * bx + t * cx, p1msmt * ay + s * by + t * cy, p1msmt * az + s * bz + t * cz}; } @Override public TriangleSampler withUniformRandomProvider(UniformRandomProvider rng) { return new TriangleSampler3D(rng, this); } } /** * Sample uniformly from a triangle in ND. */ private static class TriangleSamplerND extends TriangleSampler { /** The first vertex. */ private final double[] a; /** The second vertex. */ private final double[] b; /** The third vertex. */ private final double[] c; /** * @param rng Source of randomness. * @param a The first vertex. * @param b The second vertex. * @param c The third vertex. */ TriangleSamplerND(UniformRandomProvider rng, double[] a, double[] b, double[] c) { super(rng); // Defensive copy this.a = a.clone(); this.b = b.clone(); this.c = c.clone(); } /** * @param rng Generator of uniformly distributed random numbers * @param source Source to copy. */ TriangleSamplerND(UniformRandomProvider rng, TriangleSamplerND source) { super(rng); // Shared state is immutable a = source.a; b = source.b; c = source.c; } @Override public double[] createSample(double p1msmt, double s, double t) { final double[] x = new double[a.length]; for (int i = 0; i < x.length; i++) { x[i] = p1msmt * a[i] + s * b[i] + t * c[i]; } return x; } @Override public TriangleSampler withUniformRandomProvider(UniformRandomProvider rng) { return new TriangleSamplerND(rng, this); } } /** * @param rng Source of randomness. */ TriangleSampler(UniformRandomProvider rng) { this.rng = rng; } /** * @return a random Cartesian coordinate within the triangle. */ @Override public double[] sample() { final double s = rng.nextDouble(); final double t = rng.nextDouble(); final double spt = s + t; if (spt > 1) { // Transform: s1 = 1 - s; t1 = 1 - t. // Compute: 1 - s1 - t1 // Do not assume (1 - (1-s) - (1-t)) is (s + t - 1), i.e. (spt - 1.0), // to avoid loss of a random bit due to rounding when s + t > 1. // An exact sum is (s - 1 + t). return createSample(s - 1.0 + t, 1.0 - s, 1.0 - t); } // Here s + t is exact so can be subtracted to make 1 - s - t return createSample(1.0 - spt, s, t); } /** * Creates the sample given the random variates {@code s} and {@code t} in the * interval {@code [0, 1]} and {@code s + t <= 1}. The sum {@code 1 - s - t} is provided. * The sample can be obtained from the triangle abc using: * <pre> * p = a(1 - s - t) + sb + tc * </pre> * * @param p1msmt plus 1 minus s minus t (1 - s - t) * @param s the first variate s * @param t the second variate t * @return the sample */ protected abstract double[] createSample(double p1msmt, double s, double t); /** {@inheritDoc} */ // Redeclare the signature to return a TriangleSampler not a SharedStateObjectSampler<double[]> @Override public abstract TriangleSampler withUniformRandomProvider(UniformRandomProvider rng); /** * Create a triangle sampler with vertices {@code a}, {@code b} and {@code c}. * Sampled points are uniformly distributed within the triangle. * * <p>Sampling is supported in dimensions of 2 or above. Samples will lie in the * plane (2D Euclidean space) defined by using the three triangle vertices to * create two vectors starting at a point in the plane and orientated in * different directions along the plane. * * <p>No test for collinear points is performed. If the points are collinear the sampling * distribution is undefined. * * @param rng Source of randomness. * @param a The first vertex. * @param b The second vertex. * @param c The third vertex. * @return the sampler * @throws IllegalArgumentException If the vertices do not have the same * dimension; the dimension is less than 2; or vertices have non-finite coordinates */ public static TriangleSampler of(UniformRandomProvider rng, double[] a, double[] b, double[] c) { final int dimension = a.length; if (dimension != b.length || dimension != c.length) { throw new IllegalArgumentException( new StringBuilder("Mismatch of vertex dimensions: ").append(dimension).append(',') .append(b.length).append(',') .append(c.length).toString()); } // Detect non-finite vertices Coordinates.requireFinite(a, "Vertex a"); Coordinates.requireFinite(b, "Vertex b"); Coordinates.requireFinite(c, "Vertex c"); // Low dimension specialisations if (dimension == TWO_D) { return new TriangleSampler2D(rng, a, b, c); } else if (dimension == THREE_D) { return new TriangleSampler3D(rng, a, b, c); } else if (dimension > THREE_D) { return new TriangleSamplerND(rng, a, b, c); } // Less than 2D throw new IllegalArgumentException( "Unsupported dimension: " + dimension); } }
2,979
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/SamplerBase.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; /** * Base class for a sampler. * * @since 1.0 * * @deprecated Since version 1.1. Class intended for internal use only. */ @Deprecated public class SamplerBase { /** RNG. */ private final UniformRandomProvider rng; /** * @param rng Generator of uniformly distributed random numbers. */ protected SamplerBase(UniformRandomProvider rng) { this.rng = rng; } /** * @return a random value from a uniform distribution in the * interval {@code [0, 1)}. */ protected double nextDouble() { return rng.nextDouble(); } /** * @return a random {@code int} value. */ protected int nextInt() { return rng.nextInt(); } /** * @param max Upper bound (excluded). * @return a random {@code int} value in the interval {@code [0, max)}. */ protected int nextInt(int max) { return rng.nextInt(max); } /** * @return a random {@code long} value. */ protected long nextLong() { return rng.nextLong(); } /** {@inheritDoc} */ @Override public String toString() { return "rng=" + rng.toString(); } }
2,980
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/MarsagliaTsangWangDiscreteSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; /** * Sampler for a discrete distribution using an optimised look-up table. * * <ul> * <li> * The method requires 30-bit integer probabilities that sum to 2<sup>30</sup> as described * in George Marsaglia, Wai Wan Tsang, Jingbo Wang (2004) Fast Generation of Discrete * Random Variables. Journal of Statistical Software. Vol. 11, Issue. 3, pp. 1-11. * </li> * </ul> * * <p>Sampling uses 1 call to {@link UniformRandomProvider#nextInt()}.</p> * * <p>Memory requirements depend on the maximum number of possible sample values, {@code n}, * and the values for the probabilities. Storage is optimised for {@code n}. The worst case * scenario is a uniform distribution of the maximum sample size. This is capped at 0.06MB for * {@code n <= } 2<sup>8</sup>, 17.0MB for {@code n <= } 2<sup>16</sup>, and 4.3GB for * {@code n <=} 2<sup>30</sup>. Realistic requirements will be in the kB range.</p> * * <p>The sampler supports the following distributions:</p> * * <ul> * <li>Enumerated distribution (probabilities must be provided for each sample) * <li>Poisson distribution up to {@code mean = 1024} * <li>Binomial distribution up to {@code trials = 65535} * </ul> * * @see <a href="http://dx.doi.org/10.18637/jss.v011.i03">Margsglia, et al (2004) JSS Vol. * 11, Issue 3</a> * @since 1.3 */ public final class MarsagliaTsangWangDiscreteSampler { /** The value 2<sup>8</sup> as an {@code int}. */ private static final int INT_8 = 1 << 8; /** The value 2<sup>16</sup> as an {@code int}. */ private static final int INT_16 = 1 << 16; /** The value 2<sup>30</sup> as an {@code int}. */ private static final int INT_30 = 1 << 30; /** The value 2<sup>31</sup> as a {@code double}. */ private static final double DOUBLE_31 = 1L << 31; // ========================================================================= // Implementation note: // // This sampler uses prepared look-up tables that are searched using a single // random int variate. The look-up tables contain the sample value. The tables // are constructed using probabilities that sum to 2^30. The original paper // by Marsaglia, et al (2004) describes the use of 5, 3, or 2 look-up tables // indexed using digits of base 2^6, 2^10 or 2^15. Currently only base 64 (2^6) // is supported using 5 look-up tables. // // The implementations use 8, 16 or 32 bit storage tables to support different // distribution sizes with optimal storage. Separate class implementations of // the same algorithm allow array storage to be accessed directly from 1D tables. // This provides a performance gain over using: abstracted storage accessed via // an interface; or a single 2D table. // // To allow the optimal implementation to be chosen the sampler is created // using factory methods. The sampler supports any probability distribution // when provided via an array of probabilities and the Poisson and Binomial // distributions for a restricted set of parameters. The restrictions are // imposed by the requirement to compute the entire probability distribution // from the controlling parameter(s) using a recursive method. Factory // constructors return a SharedStateDiscreteSampler instance. Each distribution // type is contained in an inner class. // ========================================================================= /** * The base class for Marsaglia-Tsang-Wang samplers. */ private abstract static class AbstractMarsagliaTsangWangDiscreteSampler implements SharedStateDiscreteSampler { /** Underlying source of randomness. */ protected final UniformRandomProvider rng; /** The name of the distribution. */ private final String distributionName; /** * @param rng Generator of uniformly distributed random numbers. * @param distributionName Distribution name. */ AbstractMarsagliaTsangWangDiscreteSampler(UniformRandomProvider rng, String distributionName) { this.rng = rng; this.distributionName = distributionName; } /** * @param rng Generator of uniformly distributed random numbers. * @param source Source to copy. */ AbstractMarsagliaTsangWangDiscreteSampler(UniformRandomProvider rng, AbstractMarsagliaTsangWangDiscreteSampler source) { this.rng = rng; this.distributionName = source.distributionName; } /** {@inheritDoc} */ @Override public String toString() { return "Marsaglia Tsang Wang " + distributionName + " deviate [" + rng.toString() + "]"; } } /** * An implementation for the sample algorithm based on the decomposition of the * index in the range {@code [0,2^30)} into 5 base-64 digits with 8-bit backing storage. */ private static class MarsagliaTsangWangBase64Int8DiscreteSampler extends AbstractMarsagliaTsangWangDiscreteSampler { /** The mask to convert a {@code byte} to an unsigned 8-bit integer. */ private static final int MASK = 0xff; /** Limit for look-up table 1. */ private final int t1; /** Limit for look-up table 2. */ private final int t2; /** Limit for look-up table 3. */ private final int t3; /** Limit for look-up table 4. */ private final int t4; /** Look-up table table1. */ private final byte[] table1; /** Look-up table table2. */ private final byte[] table2; /** Look-up table table3. */ private final byte[] table3; /** Look-up table table4. */ private final byte[] table4; /** Look-up table table5. */ private final byte[] table5; /** * @param rng Generator of uniformly distributed random numbers. * @param distributionName Distribution name. * @param prob The probabilities. * @param offset The offset (must be positive). */ MarsagliaTsangWangBase64Int8DiscreteSampler(UniformRandomProvider rng, String distributionName, int[] prob, int offset) { super(rng, distributionName); // Get table sizes for each base-64 digit int n1 = 0; int n2 = 0; int n3 = 0; int n4 = 0; int n5 = 0; for (final int m : prob) { n1 += getBase64Digit(m, 1); n2 += getBase64Digit(m, 2); n3 += getBase64Digit(m, 3); n4 += getBase64Digit(m, 4); n5 += getBase64Digit(m, 5); } table1 = new byte[n1]; table2 = new byte[n2]; table3 = new byte[n3]; table4 = new byte[n4]; table5 = new byte[n5]; // Compute offsets t1 = n1 << 24; t2 = t1 + (n2 << 18); t3 = t2 + (n3 << 12); t4 = t3 + (n4 << 6); n1 = n2 = n3 = n4 = n5 = 0; // Fill tables for (int i = 0; i < prob.length; i++) { final int m = prob[i]; // Primitive type conversion will extract lower 8 bits final byte k = (byte) (i + offset); n1 = fill(table1, n1, n1 + getBase64Digit(m, 1), k); n2 = fill(table2, n2, n2 + getBase64Digit(m, 2), k); n3 = fill(table3, n3, n3 + getBase64Digit(m, 3), k); n4 = fill(table4, n4, n4 + getBase64Digit(m, 4), k); n5 = fill(table5, n5, n5 + getBase64Digit(m, 5), k); } } /** * @param rng Generator of uniformly distributed random numbers. * @param source Source to copy. */ private MarsagliaTsangWangBase64Int8DiscreteSampler(UniformRandomProvider rng, MarsagliaTsangWangBase64Int8DiscreteSampler source) { super(rng, source); t1 = source.t1; t2 = source.t2; t3 = source.t3; t4 = source.t4; table1 = source.table1; table2 = source.table2; table3 = source.table3; table4 = source.table4; table5 = source.table5; } /** * Fill the table with the value. * * @param table Table. * @param from Lower bound index (inclusive) * @param to Upper bound index (exclusive) * @param value Value. * @return the upper bound index */ private static int fill(byte[] table, int from, int to, byte value) { for (int i = from; i < to; i++) { table[i] = value; } return to; } @Override public int sample() { final int j = rng.nextInt() >>> 2; if (j < t1) { return table1[j >>> 24] & MASK; } if (j < t2) { return table2[(j - t1) >>> 18] & MASK; } if (j < t3) { return table3[(j - t2) >>> 12] & MASK; } if (j < t4) { return table4[(j - t3) >>> 6] & MASK; } // Note the tables are filled on the assumption that the sum of the probabilities. // is >=2^30. If this is not true then the final table table5 will be smaller by the // difference. So the tables *must* be constructed correctly. return table5[j - t4] & MASK; } @Override public SharedStateDiscreteSampler withUniformRandomProvider(UniformRandomProvider rng) { return new MarsagliaTsangWangBase64Int8DiscreteSampler(rng, this); } } /** * An implementation for the sample algorithm based on the decomposition of the * index in the range {@code [0,2^30)} into 5 base-64 digits with 16-bit backing storage. */ private static class MarsagliaTsangWangBase64Int16DiscreteSampler extends AbstractMarsagliaTsangWangDiscreteSampler { /** The mask to convert a {@code byte} to an unsigned 16-bit integer. */ private static final int MASK = 0xffff; /** Limit for look-up table 1. */ private final int t1; /** Limit for look-up table 2. */ private final int t2; /** Limit for look-up table 3. */ private final int t3; /** Limit for look-up table 4. */ private final int t4; /** Look-up table table1. */ private final short[] table1; /** Look-up table table2. */ private final short[] table2; /** Look-up table table3. */ private final short[] table3; /** Look-up table table4. */ private final short[] table4; /** Look-up table table5. */ private final short[] table5; /** * @param rng Generator of uniformly distributed random numbers. * @param distributionName Distribution name. * @param prob The probabilities. * @param offset The offset (must be positive). */ MarsagliaTsangWangBase64Int16DiscreteSampler(UniformRandomProvider rng, String distributionName, int[] prob, int offset) { super(rng, distributionName); // Get table sizes for each base-64 digit int n1 = 0; int n2 = 0; int n3 = 0; int n4 = 0; int n5 = 0; for (final int m : prob) { n1 += getBase64Digit(m, 1); n2 += getBase64Digit(m, 2); n3 += getBase64Digit(m, 3); n4 += getBase64Digit(m, 4); n5 += getBase64Digit(m, 5); } table1 = new short[n1]; table2 = new short[n2]; table3 = new short[n3]; table4 = new short[n4]; table5 = new short[n5]; // Compute offsets t1 = n1 << 24; t2 = t1 + (n2 << 18); t3 = t2 + (n3 << 12); t4 = t3 + (n4 << 6); n1 = n2 = n3 = n4 = n5 = 0; // Fill tables for (int i = 0; i < prob.length; i++) { final int m = prob[i]; // Primitive type conversion will extract lower 16 bits final short k = (short) (i + offset); n1 = fill(table1, n1, n1 + getBase64Digit(m, 1), k); n2 = fill(table2, n2, n2 + getBase64Digit(m, 2), k); n3 = fill(table3, n3, n3 + getBase64Digit(m, 3), k); n4 = fill(table4, n4, n4 + getBase64Digit(m, 4), k); n5 = fill(table5, n5, n5 + getBase64Digit(m, 5), k); } } /** * @param rng Generator of uniformly distributed random numbers. * @param source Source to copy. */ private MarsagliaTsangWangBase64Int16DiscreteSampler(UniformRandomProvider rng, MarsagliaTsangWangBase64Int16DiscreteSampler source) { super(rng, source); t1 = source.t1; t2 = source.t2; t3 = source.t3; t4 = source.t4; table1 = source.table1; table2 = source.table2; table3 = source.table3; table4 = source.table4; table5 = source.table5; } /** * Fill the table with the value. * * @param table Table. * @param from Lower bound index (inclusive) * @param to Upper bound index (exclusive) * @param value Value. * @return the upper bound index */ private static int fill(short[] table, int from, int to, short value) { for (int i = from; i < to; i++) { table[i] = value; } return to; } @Override public int sample() { final int j = rng.nextInt() >>> 2; if (j < t1) { return table1[j >>> 24] & MASK; } if (j < t2) { return table2[(j - t1) >>> 18] & MASK; } if (j < t3) { return table3[(j - t2) >>> 12] & MASK; } if (j < t4) { return table4[(j - t3) >>> 6] & MASK; } // Note the tables are filled on the assumption that the sum of the probabilities. // is >=2^30. If this is not true then the final table table5 will be smaller by the // difference. So the tables *must* be constructed correctly. return table5[j - t4] & MASK; } @Override public SharedStateDiscreteSampler withUniformRandomProvider(UniformRandomProvider rng) { return new MarsagliaTsangWangBase64Int16DiscreteSampler(rng, this); } } /** * An implementation for the sample algorithm based on the decomposition of the * index in the range {@code [0,2^30)} into 5 base-64 digits with 32-bit backing storage. */ private static class MarsagliaTsangWangBase64Int32DiscreteSampler extends AbstractMarsagliaTsangWangDiscreteSampler { /** Limit for look-up table 1. */ private final int t1; /** Limit for look-up table 2. */ private final int t2; /** Limit for look-up table 3. */ private final int t3; /** Limit for look-up table 4. */ private final int t4; /** Look-up table table1. */ private final int[] table1; /** Look-up table table2. */ private final int[] table2; /** Look-up table table3. */ private final int[] table3; /** Look-up table table4. */ private final int[] table4; /** Look-up table table5. */ private final int[] table5; /** * @param rng Generator of uniformly distributed random numbers. * @param distributionName Distribution name. * @param prob The probabilities. * @param offset The offset (must be positive). */ MarsagliaTsangWangBase64Int32DiscreteSampler(UniformRandomProvider rng, String distributionName, int[] prob, int offset) { super(rng, distributionName); // Get table sizes for each base-64 digit int n1 = 0; int n2 = 0; int n3 = 0; int n4 = 0; int n5 = 0; for (final int m : prob) { n1 += getBase64Digit(m, 1); n2 += getBase64Digit(m, 2); n3 += getBase64Digit(m, 3); n4 += getBase64Digit(m, 4); n5 += getBase64Digit(m, 5); } table1 = new int[n1]; table2 = new int[n2]; table3 = new int[n3]; table4 = new int[n4]; table5 = new int[n5]; // Compute offsets t1 = n1 << 24; t2 = t1 + (n2 << 18); t3 = t2 + (n3 << 12); t4 = t3 + (n4 << 6); n1 = n2 = n3 = n4 = n5 = 0; // Fill tables for (int i = 0; i < prob.length; i++) { final int m = prob[i]; final int k = i + offset; n1 = fill(table1, n1, n1 + getBase64Digit(m, 1), k); n2 = fill(table2, n2, n2 + getBase64Digit(m, 2), k); n3 = fill(table3, n3, n3 + getBase64Digit(m, 3), k); n4 = fill(table4, n4, n4 + getBase64Digit(m, 4), k); n5 = fill(table5, n5, n5 + getBase64Digit(m, 5), k); } } /** * @param rng Generator of uniformly distributed random numbers. * @param source Source to copy. */ private MarsagliaTsangWangBase64Int32DiscreteSampler(UniformRandomProvider rng, MarsagliaTsangWangBase64Int32DiscreteSampler source) { super(rng, source); t1 = source.t1; t2 = source.t2; t3 = source.t3; t4 = source.t4; table1 = source.table1; table2 = source.table2; table3 = source.table3; table4 = source.table4; table5 = source.table5; } /** * Fill the table with the value. * * @param table Table. * @param from Lower bound index (inclusive) * @param to Upper bound index (exclusive) * @param value Value. * @return the upper bound index */ private static int fill(int[] table, int from, int to, int value) { for (int i = from; i < to; i++) { table[i] = value; } return to; } @Override public int sample() { final int j = rng.nextInt() >>> 2; if (j < t1) { return table1[j >>> 24]; } if (j < t2) { return table2[(j - t1) >>> 18]; } if (j < t3) { return table3[(j - t2) >>> 12]; } if (j < t4) { return table4[(j - t3) >>> 6]; } // Note the tables are filled on the assumption that the sum of the probabilities. // is >=2^30. If this is not true then the final table table5 will be smaller by the // difference. So the tables *must* be constructed correctly. return table5[j - t4]; } @Override public SharedStateDiscreteSampler withUniformRandomProvider(UniformRandomProvider rng) { return new MarsagliaTsangWangBase64Int32DiscreteSampler(rng, this); } } /** Class contains only static methods. */ private MarsagliaTsangWangDiscreteSampler() {} /** * Gets the k<sup>th</sup> base 64 digit of {@code m}. * * @param m the value m. * @param k the digit. * @return the base 64 digit */ private static int getBase64Digit(int m, int k) { return (m >>> (30 - 6 * k)) & 63; } /** * Convert the probability to an integer in the range [0,2^30]. This is the numerator of * a fraction with assumed denominator 2<sup>30</sup>. * * @param p Probability. * @return the fraction numerator */ private static int toUnsignedInt30(double p) { return (int) (p * INT_30 + 0.5); } /** * Create a new instance for probabilities {@code p(i)} where the sample value {@code x} is * {@code i + offset}. * * <p>The sum of the probabilities must be {@code >=} 2<sup>30</sup>. Only the * values for cumulative probability up to 2<sup>30</sup> will be sampled.</p> * * @param rng Generator of uniformly distributed random numbers. * @param distributionName Distribution name. * @param prob The probabilities. * @param offset The offset (must be positive). * @return Sampler. */ private static SharedStateDiscreteSampler createSampler(UniformRandomProvider rng, String distributionName, int[] prob, int offset) { // Note: No argument checks for private method. // Choose implementation based on the maximum index final int maxIndex = prob.length + offset - 1; if (maxIndex < INT_8) { return new MarsagliaTsangWangBase64Int8DiscreteSampler(rng, distributionName, prob, offset); } if (maxIndex < INT_16) { return new MarsagliaTsangWangBase64Int16DiscreteSampler(rng, distributionName, prob, offset); } return new MarsagliaTsangWangBase64Int32DiscreteSampler(rng, distributionName, prob, offset); } // ========================================================================= // The following public classes provide factory methods to construct a sampler for: // - Enumerated probability distribution (from provided double[] probabilities) // - Poisson distribution for mean <= 1024 // - Binomial distribution for trials <= 65535 // ========================================================================= /** * Create a sampler for an enumerated distribution of {@code n} values each with an * associated probability. * The samples corresponding to each probability are assumed to be a natural sequence * starting at zero. */ public static final class Enumerated { /** The name of the enumerated probability distribution. */ private static final String ENUMERATED_NAME = "Enumerated"; /** Class contains only static methods. */ private Enumerated() {} /** * Creates a sampler for an enumerated distribution of {@code n} values each with an * associated probability. * * <p>The probabilities will be normalised using their sum. The only requirement * is the sum is positive.</p> * * <p>The sum of the probabilities is normalised to 2<sup>30</sup>. Note that * probabilities are adjusted to the nearest 2<sup>-30</sup> due to round-off during * the normalisation conversion. Consequently any probability less than 2<sup>-31</sup> * will not be observed in samples.</p> * * @param rng Generator of uniformly distributed random numbers. * @param probabilities The list of probabilities. * @return Sampler. * @throws IllegalArgumentException if {@code probabilities} is null or empty, a * probability is negative, infinite or {@code NaN}, or the sum of all * probabilities is not strictly positive. */ public static SharedStateDiscreteSampler of(UniformRandomProvider rng, double[] probabilities) { return createSampler(rng, ENUMERATED_NAME, normaliseProbabilities(probabilities), 0); } /** * Normalise the probabilities to integers that sum to 2<sup>30</sup>. * * @param probabilities The list of probabilities. * @return the normalised probabilities. * @throws IllegalArgumentException if {@code probabilities} is null or empty, a * probability is negative, infinite or {@code NaN}, or the sum of all * probabilities is not strictly positive. */ private static int[] normaliseProbabilities(double[] probabilities) { final double sumProb = InternalUtils.validateProbabilities(probabilities); // Compute the normalisation: 2^30 / sum final double normalisation = INT_30 / sumProb; final int[] prob = new int[probabilities.length]; int sum = 0; int max = 0; int mode = 0; for (int i = 0; i < prob.length; i++) { // Add 0.5 for rounding final int p = (int) (probabilities[i] * normalisation + 0.5); sum += p; // Find the mode (maximum probability) if (max < p) { max = p; mode = i; } prob[i] = p; } // The sum must be >= 2^30. // Here just compensate the difference onto the highest probability. prob[mode] += INT_30 - sum; return prob; } } /** * Create a sampler for the Poisson distribution. */ public static final class Poisson { /** The name of the Poisson distribution. */ private static final String POISSON_NAME = "Poisson"; /** * Upper bound on the mean for the Poisson distribution. * * <p>The original source code provided in Marsaglia, et al (2004) has no explicit * limit but the code fails at mean {@code >= 1941} as the transform to compute p(x=mode) * produces infinity. Use a conservative limit of 1024.</p> */ private static final double MAX_MEAN = 1024; /** * The threshold for the mean of the Poisson distribution to switch the method used * to compute the probabilities. This is taken from the example software provided by * Marsaglia, et al (2004). */ private static final double MEAN_THRESHOLD = 21.4; /** Class contains only static methods. */ private Poisson() {} /** * Creates a sampler for the Poisson distribution. * * <p>Any probability less than 2<sup>-31</sup> will not be observed in samples.</p> * * <p>Storage requirements depend on the tabulated probability values. Example storage * requirements are listed below.</p> * * <pre> * mean table size kB * 0.25 882 0.88 * 0.5 1135 1.14 * 1 1200 1.20 * 2 1451 1.45 * 4 1955 1.96 * 8 2961 2.96 * 16 4410 4.41 * 32 6115 6.11 * 64 8499 8.50 * 128 11528 11.53 * 256 15935 31.87 * 512 20912 41.82 * 1024 30614 61.23 * </pre> * * <p>Note: Storage changes to 2 bytes per index between {@code mean=128} and {@code mean=256}.</p> * * @param rng Generator of uniformly distributed random numbers. * @param mean Mean. * @return Sampler. * @throws IllegalArgumentException if {@code mean <= 0} or {@code mean > 1024}. */ public static SharedStateDiscreteSampler of(UniformRandomProvider rng, double mean) { validatePoissonDistributionParameters(mean); // Create the distribution either from X=0 or from X=mode when the mean is high. return mean < MEAN_THRESHOLD ? createPoissonDistributionFromX0(rng, mean) : createPoissonDistributionFromXMode(rng, mean); } /** * Validate the Poisson distribution parameters. * * @param mean Mean. * @throws IllegalArgumentException if {@code mean <= 0} or {@code mean > 1024}. */ private static void validatePoissonDistributionParameters(double mean) { if (mean <= 0) { throw new IllegalArgumentException("mean is not strictly positive: " + mean); } if (mean > MAX_MEAN) { throw new IllegalArgumentException("mean " + mean + " > " + MAX_MEAN); } } /** * Creates the Poisson distribution by computing probabilities recursively from {@code X=0}. * * @param rng Generator of uniformly distributed random numbers. * @param mean Mean. * @return Sampler. */ private static SharedStateDiscreteSampler createPoissonDistributionFromX0( UniformRandomProvider rng, double mean) { final double p0 = Math.exp(-mean); // Recursive update of Poisson probability until the value is too small // p(x + 1) = p(x) * mean / (x + 1) double p = p0; int i = 1; while (p * DOUBLE_31 >= 1) { p *= mean / i++; } // Probabilities are 30-bit integers, assumed denominator 2^30 final int size = i - 1; final int[] prob = new int[size]; p = p0; prob[0] = toUnsignedInt30(p); // The sum must exceed 2^30. In edges cases this is false due to round-off. int sum = prob[0]; for (i = 1; i < prob.length; i++) { p *= mean / i; prob[i] = toUnsignedInt30(p); sum += prob[i]; } // If the sum is < 2^30 add the remaining sum to the mode (floor(mean)). prob[(int) mean] += Math.max(0, INT_30 - sum); // Note: offset = 0 return createSampler(rng, POISSON_NAME, prob, 0); } /** * Creates the Poisson distribution by computing probabilities recursively upward and downward * from {@code X=mode}, the location of the largest p-value. * * @param rng Generator of uniformly distributed random numbers. * @param mean Mean. * @return Sampler. */ private static SharedStateDiscreteSampler createPoissonDistributionFromXMode( UniformRandomProvider rng, double mean) { // If mean >= 21.4, generate from largest p-value up, then largest down. // The largest p-value will be at the mode (floor(mean)). // Find p(x=mode) final int mode = (int) mean; // This transform is stable until mean >= 1941 where p will result in Infinity // before the divisor i is large enough to start reducing the product (i.e. i > c). final double c = mean * Math.exp(-mean / mode); double p = 1.0; for (int i = 1; i <= mode; i++) { p *= c / i; } final double pMode = p; // Find the upper limit using recursive computation of the p-value. // Note this will exit when i overflows to negative so no check on the range int i = mode + 1; while (p * DOUBLE_31 >= 1) { p *= mean / i++; } final int last = i - 2; // Find the lower limit using recursive computation of the p-value. p = pMode; int j = -1; for (i = mode - 1; i >= 0; i--) { p *= (i + 1) / mean; if (p * DOUBLE_31 < 1) { j = i; break; } } // Probabilities are 30-bit integers, assumed denominator 2^30. // This is the minimum sample value: prob[x - offset] = p(x) final int offset = j + 1; final int size = last - offset + 1; final int[] prob = new int[size]; p = pMode; prob[mode - offset] = toUnsignedInt30(p); // The sum must exceed 2^30. In edges cases this is false due to round-off. int sum = prob[mode - offset]; // From mode to upper limit for (i = mode + 1; i <= last; i++) { p *= mean / i; prob[i - offset] = toUnsignedInt30(p); sum += prob[i - offset]; } // From mode to lower limit p = pMode; for (i = mode - 1; i >= offset; i--) { p *= (i + 1) / mean; prob[i - offset] = toUnsignedInt30(p); sum += prob[i - offset]; } // If the sum is < 2^30 add the remaining sum to the mode. // If above 2^30 then the effect is truncation of the long tail of the distribution. prob[mode - offset] += Math.max(0, INT_30 - sum); return createSampler(rng, POISSON_NAME, prob, offset); } } /** * Create a sampler for the Binomial distribution. */ public static final class Binomial { /** The name of the Binomial distribution. */ private static final String BINOMIAL_NAME = "Binomial"; /** * Return a fixed result for the Binomial distribution. This is a special class to handle * an edge case of probability of success equal to 0 or 1. */ private static class MarsagliaTsangWangFixedResultBinomialSampler extends AbstractMarsagliaTsangWangDiscreteSampler { /** The result. */ private final int result; /** * @param result Result. */ MarsagliaTsangWangFixedResultBinomialSampler(int result) { super(null, BINOMIAL_NAME); this.result = result; } @Override public int sample() { return result; } @Override public String toString() { return BINOMIAL_NAME + " deviate"; } @Override public SharedStateDiscreteSampler withUniformRandomProvider(UniformRandomProvider rng) { // No shared state return this; } } /** * Return an inversion result for the Binomial distribution. This assumes the * following: * * <pre> * Binomial(n, p) = 1 - Binomial(n, 1 - p) * </pre> */ private static class MarsagliaTsangWangInversionBinomialSampler extends AbstractMarsagliaTsangWangDiscreteSampler { /** The number of trials. */ private final int trials; /** The Binomial distribution sampler. */ private final SharedStateDiscreteSampler sampler; /** * @param trials Number of trials. * @param sampler Binomial distribution sampler. */ MarsagliaTsangWangInversionBinomialSampler(int trials, SharedStateDiscreteSampler sampler) { super(null, BINOMIAL_NAME); this.trials = trials; this.sampler = sampler; } @Override public int sample() { return trials - sampler.sample(); } @Override public String toString() { return sampler.toString(); } @Override public SharedStateDiscreteSampler withUniformRandomProvider(UniformRandomProvider rng) { return new MarsagliaTsangWangInversionBinomialSampler(this.trials, this.sampler.withUniformRandomProvider(rng)); } } /** Class contains only static methods. */ private Binomial() {} /** * Creates a sampler for the Binomial distribution. * * <p>Any probability less than 2<sup>-31</sup> will not be observed in samples.</p> * * <p>Storage requirements depend on the tabulated probability values. Example storage * requirements are listed below (in kB).</p> * * <pre> * p * trials 0.5 0.1 0.01 0.001 * 4 0.06 0.63 0.44 0.44 * 16 0.69 1.14 0.76 0.44 * 64 4.73 2.40 1.14 0.51 * 256 8.63 5.17 1.89 0.82 * 1024 31.12 9.45 3.34 0.89 * </pre> * * <p>The method requires that the Binomial distribution probability at {@code x=0} can be computed. * This will fail when {@code (1 - p)^trials == 0} which requires {@code trials} to be large * and/or {@code p} to be small. In this case an exception is raised.</p> * * @param rng Generator of uniformly distributed random numbers. * @param trials Number of trials. * @param probabilityOfSuccess Probability of success (p). * @return Sampler. * @throws IllegalArgumentException if {@code trials < 0} or {@code trials >= 2^16}, * {@code p} is not in the range {@code [0-1]}, or the probability distribution cannot * be computed. */ public static SharedStateDiscreteSampler of(UniformRandomProvider rng, int trials, double probabilityOfSuccess) { validateBinomialDistributionParameters(trials, probabilityOfSuccess); // Handle edge cases if (probabilityOfSuccess == 0) { return new MarsagliaTsangWangFixedResultBinomialSampler(0); } if (probabilityOfSuccess == 1) { return new MarsagliaTsangWangFixedResultBinomialSampler(trials); } // Check the supported size. if (trials >= INT_16) { throw new IllegalArgumentException("Unsupported number of trials: " + trials); } return createBinomialDistributionSampler(rng, trials, probabilityOfSuccess); } /** * Validate the Binomial distribution parameters. * * @param trials Number of trials. * @param probabilityOfSuccess Probability of success (p). * @throws IllegalArgumentException if {@code trials < 0} or * {@code p} is not in the range {@code [0-1]} */ private static void validateBinomialDistributionParameters(int trials, double probabilityOfSuccess) { if (trials < 0) { throw new IllegalArgumentException("Trials is not positive: " + trials); } if (probabilityOfSuccess < 0 || probabilityOfSuccess > 1) { throw new IllegalArgumentException("Probability is not in range [0,1]: " + probabilityOfSuccess); } } /** * Creates the Binomial distribution sampler. * * <p>This assumes the parameters for the distribution are valid. The method * will only fail if the initial probability for {@code X=0} is zero.</p> * * @param rng Generator of uniformly distributed random numbers. * @param trials Number of trials. * @param probabilityOfSuccess Probability of success (p). * @return Sampler. * @throws IllegalArgumentException if the probability distribution cannot be * computed. */ private static SharedStateDiscreteSampler createBinomialDistributionSampler( UniformRandomProvider rng, int trials, double probabilityOfSuccess) { // The maximum supported value for Math.exp is approximately -744. // This occurs when trials is large and p is close to 1. // Handle this by using an inversion: generate j=Binomial(n,1-p), return n-j final boolean useInversion = probabilityOfSuccess > 0.5; final double p = useInversion ? 1 - probabilityOfSuccess : probabilityOfSuccess; // Check if the distribution can be computed final double p0 = Math.exp(trials * Math.log(1 - p)); if (p0 < Double.MIN_VALUE) { throw new IllegalArgumentException("Unable to compute distribution"); } // First find size of probability array double t = p0; final double h = p / (1 - p); // Find first probability above the threshold of 2^-31 int begin = 0; if (t * DOUBLE_31 < 1) { // Somewhere after p(0) // Note: // If this loop is entered p(0) is < 2^-31. // This has been tested at the extreme for p(0)=Double.MIN_VALUE and either // p=0.5 or trials=2^16-1 and does not fail to find the beginning. for (int i = 1; i <= trials; i++) { t *= (trials + 1 - i) * h / i; if (t * DOUBLE_31 >= 1) { begin = i; break; } } } // Find last probability int end = trials; for (int i = begin + 1; i <= trials; i++) { t *= (trials + 1 - i) * h / i; if (t * DOUBLE_31 < 1) { end = i - 1; break; } } return createBinomialDistributionSamplerFromRange(rng, trials, p, useInversion, p0, begin, end); } /** * Creates the Binomial distribution sampler using only the probability values for {@code X} * between the begin and the end (inclusive). * * @param rng Generator of uniformly distributed random numbers. * @param trials Number of trials. * @param p Probability of success (p). * @param useInversion Set to {@code true} if the probability was inverted. * @param p0 Probability at {@code X=0} * @param begin Begin value {@code X} for the distribution. * @param end End value {@code X} for the distribution. * @return Sampler. */ private static SharedStateDiscreteSampler createBinomialDistributionSamplerFromRange( UniformRandomProvider rng, int trials, double p, boolean useInversion, double p0, int begin, int end) { // Assign probability values as 30-bit integers final int size = end - begin + 1; final int[] prob = new int[size]; double t = p0; final double h = p / (1 - p); for (int i = 1; i <= begin; i++) { t *= (trials + 1 - i) * h / i; } int sum = toUnsignedInt30(t); prob[0] = sum; for (int i = begin + 1; i <= end; i++) { t *= (trials + 1 - i) * h / i; prob[i - begin] = toUnsignedInt30(t); sum += prob[i - begin]; } // If the sum is < 2^30 add the remaining sum to the mode (floor((n+1)p))). // If above 2^30 then the effect is truncation of the long tail of the distribution. final int mode = (int) ((trials + 1) * p) - begin; prob[mode] += Math.max(0, INT_30 - sum); final SharedStateDiscreteSampler sampler = createSampler(rng, BINOMIAL_NAME, prob, begin); // Check if an inversion was made return useInversion ? new MarsagliaTsangWangInversionBinomialSampler(trials, sampler) : sampler; } } }
2,981
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/SmallMeanPoissonSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; /** * Sampler for the <a href="http://mathworld.wolfram.com/PoissonDistribution.html">Poisson distribution</a>. * * <ul> * <li> * For small means, a Poisson process is simulated using uniform deviates, as described in * <blockquote> * Knuth (1969). <i>Seminumerical Algorithms</i>. The Art of Computer Programming, * Volume 2. Chapter 3.4.1.F.3 Important integer-valued distributions: The Poisson distribution. * Addison Wesley. * </blockquote> * The Poisson process (and hence, the returned value) is bounded by {@code 1000 * mean}. * </li> * </ul> * * <p>This sampler is suitable for {@code mean < 40}. * For large means, {@link LargeMeanPoissonSampler} should be used instead.</p> * * <p>Sampling uses {@link UniformRandomProvider#nextDouble()} and requires on average * {@code mean + 1} deviates per sample.</p> * * @since 1.1 */ public class SmallMeanPoissonSampler implements SharedStateDiscreteSampler { /** * Pre-compute {@code Math.exp(-mean)}. * Note: This is the probability of the Poisson sample {@code P(n=0)}. */ private final double p0; /** Pre-compute {@code 1000 * mean} as the upper limit of the sample. */ private final int limit; /** Underlying source of randomness. */ private final UniformRandomProvider rng; /** * @param rng Generator of uniformly distributed random numbers. * @param mean Mean. * @throws IllegalArgumentException if {@code mean <= 0} or {@code Math.exp(-mean) == 0} */ public SmallMeanPoissonSampler(UniformRandomProvider rng, double mean) { this.rng = rng; if (mean <= 0) { throw new IllegalArgumentException("mean is not strictly positive: " + mean); } p0 = Math.exp(-mean); if (p0 > 0) { // The returned sample is bounded by 1000 * mean limit = (int) Math.ceil(1000 * mean); } else { // This excludes NaN values for the mean throw new IllegalArgumentException("No p(x=0) probability for mean: " + mean); } } /** * @param rng Generator of uniformly distributed random numbers. * @param source Source to copy. */ private SmallMeanPoissonSampler(UniformRandomProvider rng, SmallMeanPoissonSampler source) { this.rng = rng; p0 = source.p0; limit = source.limit; } /** {@inheritDoc} */ @Override public int sample() { int n = 0; double r = 1; while (n < limit) { r *= rng.nextDouble(); if (r >= p0) { n++; } else { break; } } return n; } /** {@inheritDoc} */ @Override public String toString() { return "Small Mean Poisson deviate [" + rng.toString() + "]"; } /** * {@inheritDoc} * * @since 1.3 */ @Override public SharedStateDiscreteSampler withUniformRandomProvider(UniformRandomProvider rng) { return new SmallMeanPoissonSampler(rng, this); } /** * Creates a new sampler for the Poisson distribution. * * @param rng Generator of uniformly distributed random numbers. * @param mean Mean of the distribution. * @return the sampler * @throws IllegalArgumentException if {@code mean <= 0} or {@code Math.exp(-mean) == 0}. * @since 1.3 */ public static SharedStateDiscreteSampler of(UniformRandomProvider rng, double mean) { return new SmallMeanPoissonSampler(rng, mean); } }
2,982
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/DiscreteUniformSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; /** * Discrete uniform distribution sampler. * * <p>Sampling uses {@link UniformRandomProvider#nextInt}.</p> * * <p>When the range is a power of two the number of calls is 1 per sample. * Otherwise a rejection algorithm is used to ensure uniformity. In the worst * case scenario where the range spans half the range of an {@code int} * (2<sup>31</sup> + 1) the expected number of calls is 2 per sample.</p> * * <p>This sampler can be used as a replacement for {@link UniformRandomProvider#nextInt} * with appropriate adjustment of the upper bound to be inclusive and will outperform that * method when the range is not a power of two. The advantage is gained by pre-computation * of the rejection threshold.</p> * * <p>The sampling algorithm is described in:</p> * * <blockquote> * Lemire, D (2019). <i>Fast Random Integer Generation in an Interval.</i> * <strong>ACM Transactions on Modeling and Computer Simulation</strong> 29 (1). * </blockquote> * * <p>The number of {@code int} values required per sample follows a geometric distribution with * a probability of success p of {@code 1 - ((2^32 % n) / 2^32)}. This requires on average 1/p random * {@code int} values per sample.</p> * * @see <a href="https://arxiv.org/abs/1805.10941">Fast Random Integer Generation in an Interval</a> * * @since 1.0 */ public class DiscreteUniformSampler extends SamplerBase implements SharedStateDiscreteSampler { /** The appropriate uniform sampler for the parameters. */ private final SharedStateDiscreteSampler delegate; /** * Base class for a sampler from a discrete uniform distribution. This contains the * source of randomness. */ private abstract static class AbstractDiscreteUniformSampler implements SharedStateDiscreteSampler { /** Underlying source of randomness. */ protected final UniformRandomProvider rng; /** * @param rng Generator of uniformly distributed random numbers. */ AbstractDiscreteUniformSampler(UniformRandomProvider rng) { this.rng = rng; } @Override public String toString() { return "Uniform deviate [" + rng.toString() + "]"; } } /** * Discrete uniform distribution sampler when the sample value is fixed. */ private static class FixedDiscreteUniformSampler extends AbstractDiscreteUniformSampler { /** The value. */ private final int value; /** * @param value The value. */ FixedDiscreteUniformSampler(int value) { // No requirement for the RNG super(null); this.value = value; } @Override public int sample() { return value; } @Override public String toString() { // No RNG to include in the string return "Uniform deviate [X=" + value + "]"; } @Override public SharedStateDiscreteSampler withUniformRandomProvider(UniformRandomProvider rng) { // No requirement for the RNG return this; } } /** * Discrete uniform distribution sampler when the range is a power of 2 and greater than 1. * This sampler assumes the lower bound of the range is 0. * * <p>Note: This cannot be used when the range is 1 (2^0) as the shift would be 32-bits * which is ignored by the shift operator.</p> */ private static class PowerOf2RangeDiscreteUniformSampler extends AbstractDiscreteUniformSampler { /** Bit shift to apply to the integer sample. */ private final int shift; /** * @param rng Generator of uniformly distributed random numbers. * @param range Maximum range of the sample (exclusive). * Must be a power of 2 greater than 2^0. */ PowerOf2RangeDiscreteUniformSampler(UniformRandomProvider rng, int range) { super(rng); this.shift = Integer.numberOfLeadingZeros(range) + 1; } /** * @param rng Generator of uniformly distributed random numbers. * @param source Source to copy. */ PowerOf2RangeDiscreteUniformSampler(UniformRandomProvider rng, PowerOf2RangeDiscreteUniformSampler source) { super(rng); this.shift = source.shift; } @Override public int sample() { // Use a bit shift to favour the most significant bits. // Note: The result would be the same as the rejection method used in the // small range sampler when there is no rejection threshold. return rng.nextInt() >>> shift; } @Override public SharedStateDiscreteSampler withUniformRandomProvider(UniformRandomProvider rng) { return new PowerOf2RangeDiscreteUniformSampler(rng, this); } } /** * Discrete uniform distribution sampler when the range is small * enough to fit in a positive integer. * This sampler assumes the lower bound of the range is 0. * * <p>Implements the algorithm of Lemire (2019).</p> * * @see <a href="https://arxiv.org/abs/1805.10941">Fast Random Integer Generation in an Interval</a> */ private static class SmallRangeDiscreteUniformSampler extends AbstractDiscreteUniformSampler { /** Maximum range of the sample (exclusive). */ private final long n; /** * The level below which samples are rejected based on the fraction remainder. * * <p>Any remainder below this denotes that there are still floor(2^32 / n) more * observations of this sample from the interval [0, 2^32), where n is the range.</p> */ private final long threshold; /** * @param rng Generator of uniformly distributed random numbers. * @param range Maximum range of the sample (exclusive). */ SmallRangeDiscreteUniformSampler(UniformRandomProvider rng, int range) { super(rng); // Handle range as an unsigned 32-bit integer this.n = range & 0xffffffffL; // Compute 2^32 % n threshold = (1L << 32) % n; } /** * @param rng Generator of uniformly distributed random numbers. * @param source Source to copy. */ SmallRangeDiscreteUniformSampler(UniformRandomProvider rng, SmallRangeDiscreteUniformSampler source) { super(rng); this.n = source.n; this.threshold = source.threshold; } @Override public int sample() { // Rejection method using multiply by a fraction: // n * [0, 2^32 - 1) // ------------- // 2^32 // The result is mapped back to an integer and will be in the range [0, n). // Note this is comparable to range * rng.nextDouble() but with compensation for // non-uniformity due to round-off. long result; do { // Compute 64-bit unsigned product of n * [0, 2^32 - 1). // The upper 32-bits contains the sample value in the range [0, n), i.e. result / 2^32. // The lower 32-bits contains the remainder, i.e. result % 2^32. result = n * (rng.nextInt() & 0xffffffffL); // Test the sample uniformity. // Samples are observed on average (2^32 / n) times at a frequency of either // floor(2^32 / n) or ceil(2^32 / n). // To ensure all samples have a frequency of floor(2^32 / n) reject any results with // a remainder < (2^32 % n), i.e. the level below which denotes that there are still // floor(2^32 / n) more observations of this sample. } while ((result & 0xffffffffL) < threshold); // Divide by 2^32 to get the sample. return (int)(result >>> 32); } @Override public SharedStateDiscreteSampler withUniformRandomProvider(UniformRandomProvider rng) { return new SmallRangeDiscreteUniformSampler(rng, this); } } /** * Discrete uniform distribution sampler when the range between lower and upper is too large * to fit in a positive integer. */ private static class LargeRangeDiscreteUniformSampler extends AbstractDiscreteUniformSampler { /** Lower bound. */ private final int lower; /** Upper bound. */ private final int upper; /** * @param rng Generator of uniformly distributed random numbers. * @param lower Lower bound (inclusive) of the distribution. * @param upper Upper bound (inclusive) of the distribution. */ LargeRangeDiscreteUniformSampler(UniformRandomProvider rng, int lower, int upper) { super(rng); this.lower = lower; this.upper = upper; } @Override public int sample() { // Use a simple rejection method. // This is used when (upper-lower) >= Integer.MAX_VALUE. // This will loop on average 2 times in the worst case scenario // when (upper-lower) == Integer.MAX_VALUE. while (true) { final int r = rng.nextInt(); if (r >= lower && r <= upper) { return r; } } } @Override public SharedStateDiscreteSampler withUniformRandomProvider(UniformRandomProvider rng) { return new LargeRangeDiscreteUniformSampler(rng, lower, upper); } } /** * Adds an offset to an underlying discrete sampler. */ private static class OffsetDiscreteUniformSampler extends AbstractDiscreteUniformSampler { /** The offset. */ private final int offset; /** The discrete sampler. */ private final SharedStateDiscreteSampler sampler; /** * @param offset The offset for the sample. * @param sampler The discrete sampler. */ OffsetDiscreteUniformSampler(int offset, SharedStateDiscreteSampler sampler) { super(null); this.offset = offset; this.sampler = sampler; } @Override public int sample() { return offset + sampler.sample(); } @Override public String toString() { return sampler.toString(); } @Override public SharedStateDiscreteSampler withUniformRandomProvider(UniformRandomProvider rng) { return new OffsetDiscreteUniformSampler(offset, sampler.withUniformRandomProvider(rng)); } } /** * This instance delegates sampling. Use the factory method * {@link #of(UniformRandomProvider, int, int)} to create an optimal sampler. * * @param rng Generator of uniformly distributed random numbers. * @param lower Lower bound (inclusive) of the distribution. * @param upper Upper bound (inclusive) of the distribution. * @throws IllegalArgumentException if {@code lower > upper}. */ public DiscreteUniformSampler(UniformRandomProvider rng, int lower, int upper) { super(null); delegate = of(rng, lower, upper); } /** {@inheritDoc} */ @Override public int sample() { return delegate.sample(); } /** {@inheritDoc} */ @Override public String toString() { return delegate.toString(); } /** * {@inheritDoc} * * @since 1.3 */ @Override public SharedStateDiscreteSampler withUniformRandomProvider(UniformRandomProvider rng) { // Direct return of the optimised sampler return delegate.withUniformRandomProvider(rng); } /** * Creates a new discrete uniform distribution sampler. * * @param rng Generator of uniformly distributed random numbers. * @param lower Lower bound (inclusive) of the distribution. * @param upper Upper bound (inclusive) of the distribution. * @return the sampler * @throws IllegalArgumentException if {@code lower > upper}. * @since 1.3 */ public static SharedStateDiscreteSampler of(UniformRandomProvider rng, int lower, int upper) { if (lower > upper) { throw new IllegalArgumentException(lower + " > " + upper); } // Choose the algorithm depending on the range // Edge case for no range. // This must be done first as the methods to handle lower == 0 // do not handle upper == 0. if (upper == lower) { return new FixedDiscreteUniformSampler(lower); } // Algorithms to ignore the lower bound if it is zero. if (lower == 0) { return createZeroBoundedSampler(rng, upper); } final int range = (upper - lower) + 1; // Check power of 2 first to handle range == 2^31. if (isPowerOf2(range)) { return new OffsetDiscreteUniformSampler(lower, new PowerOf2RangeDiscreteUniformSampler(rng, range)); } if (range <= 0) { // The range is too wide to fit in a positive int (larger // than 2^31); use a simple rejection method. // Note: if range == 0 then the input is [Integer.MIN_VALUE, Integer.MAX_VALUE]. // No specialisation exists for this and it is handled as a large range. return new LargeRangeDiscreteUniformSampler(rng, lower, upper); } // Use a sample from the range added to the lower bound. return new OffsetDiscreteUniformSampler(lower, new SmallRangeDiscreteUniformSampler(rng, range)); } /** * Create a new sampler for the range {@code 0} inclusive to {@code upper} inclusive. * * <p>This can handle any positive {@code upper}. * * @param rng Generator of uniformly distributed random numbers. * @param upper Upper bound (inclusive) of the distribution. Must be positive. * @return the sampler */ private static AbstractDiscreteUniformSampler createZeroBoundedSampler(UniformRandomProvider rng, int upper) { // Note: Handle any range up to 2^31 (which is negative as a signed // 32-bit integer but handled as a power of 2) final int range = upper + 1; return isPowerOf2(range) ? new PowerOf2RangeDiscreteUniformSampler(rng, range) : new SmallRangeDiscreteUniformSampler(rng, range); } /** * Checks if the value is a power of 2. * * <p>This returns {@code true} for the value {@code Integer.MIN_VALUE} which can be * handled as an unsigned integer of 2^31.</p> * * @param value Value. * @return {@code true} if a power of 2 */ private static boolean isPowerOf2(final int value) { return value != 0 && (value & (value - 1)) == 0; } }
2,983
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/FastLoadedDiceRollerDiscreteSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import java.math.BigInteger; import java.util.Arrays; import org.apache.commons.rng.UniformRandomProvider; /** * Distribution sampler that uses the Fast Loaded Dice Roller (FLDR). It can be used to * sample from {@code n} values each with an associated relative weight. If all unique items * are assigned the same weight it is more efficient to use the {@link DiscreteUniformSampler}. * * <p>Given a list {@code L} of {@code n} positive numbers, * where {@code L[i]} represents the relative weight of the {@code i}th side, FLDR returns * integer {@code i} with relative probability {@code L[i]}. * * <p>FLDR produces <em>exact</em> samples from the specified probability distribution. * <ul> * <li>For integer weights, the probability of returning {@code i} is precisely equal to the * rational number {@code L[i] / m}, where {@code m} is the sum of {@code L}. * <li>For floating-points weights, each weight {@code L[i]} is converted to the * corresponding rational number {@code p[i] / q[i]} where {@code p[i]} is a positive integer and * {@code q[i]} is a power of 2. The rational weights are then normalized (exactly) to sum to unity. * </ul> * * <p>Note that if <em>exact</em> samples are not required then an alternative sampler that * ignores very small relative weights may have improved sampling performance. * * <p>This implementation is based on the algorithm in: * * <blockquote> * Feras A. Saad, Cameron E. Freer, Martin C. Rinard, and Vikash K. Mansinghka. * The Fast Loaded Dice Roller: A Near-Optimal Exact Sampler for Discrete Probability * Distributions. In AISTATS 2020: Proceedings of the 23rd International Conference on * Artificial Intelligence and Statistics, Proceedings of Machine Learning Research 108, * Palermo, Sicily, Italy, 2020. * </blockquote> * * <p>Sampling uses {@link UniformRandomProvider#nextInt()} as the source of random bits. * * @see <a href="https://arxiv.org/abs/2003.03830">Saad et al (2020) * Proceedings of the 23rd International Conference on Artificial Intelligence and Statistics, * PMLR 108:1036-1046.</a> * @since 1.5 */ public abstract class FastLoadedDiceRollerDiscreteSampler implements SharedStateDiscreteSampler { /** * The maximum size of an array. * * <p>This value is taken from the limit in Open JDK 8 {@code java.util.ArrayList}. * It allows VMs to reserve some header words in an array. */ private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; /** The maximum biased exponent for a finite double. * This is offset by 1023 from {@code Math.getExponent(Double.MAX_VALUE)}. */ private static final int MAX_BIASED_EXPONENT = 2046; /** Size of the mantissa of a double. Equal to 52 bits. */ private static final int MANTISSA_SIZE = 52; /** Mask to extract the 52-bit mantissa from a long representation of a double. */ private static final long MANTISSA_MASK = 0x000f_ffff_ffff_ffffL; /** BigInteger representation of {@link Long#MAX_VALUE}. */ private static final BigInteger MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE); /** The maximum offset that will avoid loss of bits for a left shift of a 53-bit value. * The value will remain positive for any shift {@code <=} this value. */ private static final int MAX_OFFSET = 10; /** Initial value for no leaf node label. */ private static final int NO_LABEL = Integer.MAX_VALUE; /** Name of the sampler. */ private static final String SAMPLER_NAME = "Fast Loaded Dice Roller"; /** * Class to handle the edge case of observations in only one category. */ private static class FixedValueDiscreteSampler extends FastLoadedDiceRollerDiscreteSampler { /** The sample value. */ private final int sampleValue; /** * @param sampleValue Sample value. */ FixedValueDiscreteSampler(int sampleValue) { this.sampleValue = sampleValue; } @Override public int sample() { return sampleValue; } @Override public FastLoadedDiceRollerDiscreteSampler withUniformRandomProvider(UniformRandomProvider rng) { return this; } @Override public String toString() { return SAMPLER_NAME; } } /** * Class to implement the FLDR sample algorithm. */ private static class FLDRSampler extends FastLoadedDiceRollerDiscreteSampler { /** Empty boolean source. This is the location of the sign-bit after 31 right shifts on * the boolean source. */ private static final int EMPTY_BOOL_SOURCE = 1; /** Underlying source of randomness. */ private final UniformRandomProvider rng; /** Number of categories. */ private final int n; /** Number of levels in the discrete distribution generating (DDG) tree. * Equal to {@code ceil(log2(m))} where {@code m} is the sum of observations. */ private final int k; /** Number of leaf nodes at each level. */ private final int[] h; /** Stores the leaf node labels in increasing order. Named {@code H} in the FLDR paper. */ private final int[] lH; /** * Provides a bit source for booleans. * * <p>A cached value from a call to {@link UniformRandomProvider#nextInt()}. * * <p>Only stores 31-bits when full as 1 bit has already been consumed. * The sign bit is a flag that shifts down so the source eventually equals 1 * when all bits are consumed and will trigger a refill. */ private int booleanSource = EMPTY_BOOL_SOURCE; /** * Creates a sampler. * * <p>The input parameters are not validated and must be correctly computed tables. * * @param rng Generator of uniformly distributed random numbers. * @param n Number of categories * @param k Number of levels in the discrete distribution generating (DDG) tree. * Equal to {@code ceil(log2(m))} where {@code m} is the sum of observations. * @param h Number of leaf nodes at each level. * @param lH Stores the leaf node labels in increasing order. */ FLDRSampler(UniformRandomProvider rng, int n, int k, int[] h, int[] lH) { this.rng = rng; this.n = n; this.k = k; // Deliberate direct storage of input arrays this.h = h; this.lH = lH; } /** * Creates a copy with a new source of randomness. * * @param rng Generator of uniformly distributed random numbers. * @param source Source to copy. */ private FLDRSampler(UniformRandomProvider rng, FLDRSampler source) { this.rng = rng; this.n = source.n; this.k = source.k; this.h = source.h; this.lH = source.lH; } /** {@inheritDoc} */ @Override public int sample() { // ALGORITHM 5: SAMPLE int c = 0; int d = 0; for (;;) { // b = flip() // d = 2 * d + (1 - b) d = (d << 1) + flip(); if (d < h[c]) { // z = H[d][c] final int z = lH[d * k + c]; // assert z != NO_LABEL if (z < n) { return z; } d = 0; c = 0; } else { d = d - h[c]; c++; } } } /** * Provides a source of boolean bits. * * <p>Note: This replicates the boolean cache functionality of * {@code o.a.c.rng.core.source32.IntProvider}. The method has been simplified to return * an {@code int} value rather than a {@code boolean}. * * @return the bit (0 or 1) */ private int flip() { int bits = booleanSource; if (bits == 1) { // Refill bits = rng.nextInt(); // Store a refill flag in the sign bit and the unused 31 bits, return lowest bit booleanSource = Integer.MIN_VALUE | (bits >>> 1); return bits & 0x1; } // Shift down eventually triggering refill, return current lowest bit booleanSource = bits >>> 1; return bits & 0x1; } /** {@inheritDoc} */ @Override public String toString() { return SAMPLER_NAME + " [" + rng.toString() + "]"; } /** {@inheritDoc} */ @Override public FastLoadedDiceRollerDiscreteSampler withUniformRandomProvider(UniformRandomProvider rng) { return new FLDRSampler(rng, this); } } /** Package-private constructor. */ FastLoadedDiceRollerDiscreteSampler() { // Intentionally empty } /** {@inheritDoc} */ // Redeclare the signature to return a FastLoadedDiceRollerSampler not a SharedStateLongSampler @Override public abstract FastLoadedDiceRollerDiscreteSampler withUniformRandomProvider(UniformRandomProvider rng); /** * Creates a sampler. * * <p>Note: The discrete distribution generating (DDG) tree requires {@code (n + 1) * k} entries * where {@code n} is the number of categories, {@code k == ceil(log2(m))} and {@code m} * is the sum of the observed frequencies. An exception is raised if this cannot be allocated * as a single array. * * <p>For reference the sum is limited to {@link Long#MAX_VALUE} and the value {@code k} to 63. * The number of categories is limited to approximately {@code ((2^31 - 1) / k) = 34,087,042} * when the sum of frequencies is large enough to create k=63. * * @param rng Generator of uniformly distributed random numbers. * @param frequencies Observed frequencies of the discrete distribution. * @return the sampler * @throws IllegalArgumentException if {@code frequencies} is null or empty, a * frequency is negative, the sum of all frequencies is either zero or * above {@link Long#MAX_VALUE}, or the size of the discrete distribution generating tree * is too large. */ public static FastLoadedDiceRollerDiscreteSampler of(UniformRandomProvider rng, long[] frequencies) { final long m = sum(frequencies); // Obtain indices of non-zero frequencies final int[] indices = indicesOfNonZero(frequencies); // Edge case for 1 non-zero weight. This also handles edge case for 1 observation // (as log2(m) == 0 will break the computation of the DDG tree). if (indices.length == 1) { return new FixedValueDiscreteSampler(indexOfNonZero(frequencies)); } return createSampler(rng, frequencies, indices, m); } /** * Creates a sampler. * * <p>Weights are converted to rational numbers {@code p / q} where {@code q} is a power of 2. * The numerators {@code p} are scaled to use a common denominator before summing. * * <p>All weights are used to create the sampler. Weights with a small magnitude relative * to the largest weight can be excluded using the constructor method with the * relative magnitude parameter {@code alpha} (see {@link #of(UniformRandomProvider, double[], int)}). * * @param rng Generator of uniformly distributed random numbers. * @param weights Weights of the discrete distribution. * @return the sampler * @throws IllegalArgumentException if {@code weights} is null or empty, a * weight is negative, infinite or {@code NaN}, the sum of all weights is zero, or the size * of the discrete distribution generating tree is too large. * @see #of(UniformRandomProvider, double[], int) */ public static FastLoadedDiceRollerDiscreteSampler of(UniformRandomProvider rng, double[] weights) { return of(rng, weights, 0); } /** * Creates a sampler. * * <p>Weights are converted to rational numbers {@code p / q} where {@code q} is * a power of 2. The numerators {@code p} are scaled to use a common * denominator before summing. * * <p>Note: The discrete distribution generating (DDG) tree requires * {@code (n + 1) * k} entries where {@code n} is the number of categories, * {@code k == ceil(log2(m))} and {@code m} is the sum of the weight numerators * {@code q}. An exception is raised if this cannot be allocated as a single * array. * * <p>For reference the value {@code k} is equal to or greater than the ratio of * the largest to the smallest weight expressed as a power of 2. For * {@code Double.MAX_VALUE / Double.MIN_VALUE} this is ~2098. The value * {@code k} increases with the sum of the weight numerators. A number of * weights in excess of 1,000,000 with values equal to {@link Double#MAX_VALUE} * would be required to raise an exception when the minimum weight is * {@link Double#MIN_VALUE}. * * <p>Weights with a small magnitude relative to the largest weight can be * excluded using the relative magnitude parameter {@code alpha}. This will set * any weight to zero if the magnitude is approximately 2<sup>alpha</sup> * <em>smaller</em> than the largest weight. This comparison is made using only * the exponent of the input weights. The {@code alpha} parameter is ignored if * not above zero. Note that a small {@code alpha} parameter will exclude more * weights than a large {@code alpha} parameter. * * <p>The alpha parameter can be used to exclude categories that * have a very low probability of occurrence and will improve the construction * performance of the sampler. The effect on sampling performance depends on * the relative weights of the excluded categories; typically a high {@code alpha} * is used to exclude categories that would be visited with a very low probability * and the sampling performance is unchanged. * * <p><b>Implementation Note</b> * * <p>This method creates a sampler with <em>exact</em> samples from the * specified probability distribution. It is recommended to use this method: * <ul> * <li>if the weights are computed, for example from a probability mass function; or * <li>if the weights sum to an infinite value. * </ul> * * <p>If the weights are computed from empirical observations then it is * recommended to use the factory method * {@link #of(UniformRandomProvider, long[]) accepting frequencies}. This * requires the total number of observations to be representable as a long * integer. * * <p>Note that if all weights are scaled by a power of 2 to be integers, and * each integer can be represented as a positive 64-bit long value, then the * sampler created using this method will match the output from a sampler * created with the scaled weights converted to long values for the factory * method {@link #of(UniformRandomProvider, long[]) accepting frequencies}. This * assumes the sum of the integer values does not overflow. * * <p>It should be noted that the conversion of weights to rational numbers has * a performance overhead during construction (sampling performance is not * affected). This may be avoided by first converting them to integer values * that can be summed without overflow. For example by scaling values by * {@code 2^62 / sum} and converting to long by casting or rounding. * * <p>This approach may increase the efficiency of construction. The resulting * sampler may no longer produce <em>exact</em> samples from the distribution. * In particular any weights with a converted frequency of zero cannot be * sampled. * * @param rng Generator of uniformly distributed random numbers. * @param weights Weights of the discrete distribution. * @param alpha Alpha parameter. * @return the sampler * @throws IllegalArgumentException if {@code weights} is null or empty, a * weight is negative, infinite or {@code NaN}, the sum of all weights is zero, * or the size of the discrete distribution generating tree is too large. * @see #of(UniformRandomProvider, long[]) */ public static FastLoadedDiceRollerDiscreteSampler of(UniformRandomProvider rng, double[] weights, int alpha) { final int n = checkWeightsNonZeroLength(weights); // Convert floating-point double to a relative weight // using a shifted integer representation final long[] frequencies = new long[n]; final int[] offsets = new int[n]; convertToIntegers(weights, frequencies, offsets, alpha); // Obtain indices of non-zero weights final int[] indices = indicesOfNonZero(frequencies); // Edge case for 1 non-zero weight. if (indices.length == 1) { return new FixedValueDiscreteSampler(indexOfNonZero(frequencies)); } final BigInteger m = sum(frequencies, offsets, indices); // Use long arithmetic if possible. This occurs when the weights are similar in magnitude. if (m.compareTo(MAX_LONG) <= 0) { // Apply the offset for (int i = 0; i < n; i++) { frequencies[i] <<= offsets[i]; } return createSampler(rng, frequencies, indices, m.longValue()); } return createSampler(rng, frequencies, offsets, indices, m); } /** * Sum the frequencies. * * @param frequencies Frequencies. * @return the sum * @throws IllegalArgumentException if {@code frequencies} is null or empty, a * frequency is negative, or the sum of all frequencies is either zero or above * {@link Long#MAX_VALUE} */ private static long sum(long[] frequencies) { // Validate if (frequencies == null || frequencies.length == 0) { throw new IllegalArgumentException("frequencies must contain at least 1 value"); } // Sum the values. // Combine all the sign bits in the observations and the intermediate sum in a flag. long m = 0; long signFlag = 0; for (final long o : frequencies) { m += o; signFlag |= o | m; } // Check for a sign-bit. if (signFlag < 0) { // One or more observations were negative, or the sum overflowed. for (final long o : frequencies) { if (o < 0) { throw new IllegalArgumentException("frequencies must contain positive values: " + o); } } throw new IllegalArgumentException("Overflow when summing frequencies"); } if (m == 0) { throw new IllegalArgumentException("Sum of frequencies is zero"); } return m; } /** * Convert the floating-point weights to relative weights represented as * integers {@code value * 2^exponent}. The relative weight as an integer is: * * <pre> * BigInteger.valueOf(value).shiftLeft(exponent) * </pre> * * <p>Note that the weights are created using a common power-of-2 scaling * operation so the minimum exponent is zero. * * <p>A positive {@code alpha} parameter is used to set any weight to zero if * the magnitude is approximately 2<sup>alpha</sup> <em>smaller</em> than the * largest weight. This comparison is made using only the exponent of the input * weights. * * @param weights Weights of the discrete distribution. * @param values Output floating-point mantissas converted to 53-bit integers. * @param exponents Output power of 2 exponent. * @param alpha Alpha parameter. * @throws IllegalArgumentException if a weight is negative, infinite or * {@code NaN}, or the sum of all weights is zero. */ private static void convertToIntegers(double[] weights, long[] values, int[] exponents, int alpha) { int maxExponent = Integer.MIN_VALUE; for (int i = 0; i < weights.length; i++) { final double weight = weights[i]; // Ignore zero. // When creating the integer value later using bit shifts the result will remain zero. if (weight == 0) { continue; } final long bits = Double.doubleToRawLongBits(weight); // For the IEEE 754 format see Double.longBitsToDouble(long). // Extract the exponent (with the sign bit) int exp = (int) (bits >>> MANTISSA_SIZE); // Detect negative, infinite or NaN. // Note: Negative values sign bit will cause the exponent to be too high. if (exp > MAX_BIASED_EXPONENT) { throw new IllegalArgumentException("Invalid weight: " + weight); } long mantissa; if (exp == 0) { // Sub-normal number: mantissa = (bits & MANTISSA_MASK) << 1; // Here we convert to a normalised number by counting the leading zeros // to obtain the number of shifts of the most significant bit in // the mantissa that is required to get a 1 at position 53 (i.e. as // if it were a normal number with assumed leading bit). final int shift = Long.numberOfLeadingZeros(mantissa << 11); mantissa <<= shift; exp -= shift; } else { // Normal number. Add the implicit leading 1-bit. mantissa = (bits & MANTISSA_MASK) | (1L << MANTISSA_SIZE); } // Here the floating-point number is equal to: // mantissa * 2^(exp-1075) values[i] = mantissa; exponents[i] = exp; maxExponent = Math.max(maxExponent, exp); } // No exponent indicates that all weights are zero if (maxExponent == Integer.MIN_VALUE) { throw new IllegalArgumentException("Sum of weights is zero"); } filterWeights(values, exponents, alpha, maxExponent); scaleWeights(values, exponents); } /** * Filters small weights using the {@code alpha} parameter. * A positive {@code alpha} parameter is used to set any weight to zero if * the magnitude is approximately 2<sup>alpha</sup> <em>smaller</em> than the * largest weight. This comparison is made using only the exponent of the input * weights. * * @param values 53-bit values. * @param exponents Power of 2 exponent. * @param alpha Alpha parameter. * @param maxExponent Maximum exponent. */ private static void filterWeights(long[] values, int[] exponents, int alpha, int maxExponent) { if (alpha > 0) { // Filter weights. This must be done before the values are shifted so // the exponent represents the approximate magnitude of the value. for (int i = 0; i < exponents.length; i++) { if (maxExponent - exponents[i] > alpha) { values[i] = 0; } } } } /** * Scale the weights represented as integers {@code value * 2^exponent} to use a * minimum exponent of zero. The values are scaled to remove any common trailing zeros * in their representation. This ultimately reduces the size of the discrete distribution * generating (DGG) tree. * * @param values 53-bit values. * @param exponents Power of 2 exponent. */ private static void scaleWeights(long[] values, int[] exponents) { // Find the minimum exponent and common trailing zeros. int minExponent = Integer.MAX_VALUE; for (int i = 0; i < exponents.length; i++) { if (values[i] != 0) { minExponent = Math.min(minExponent, exponents[i]); } } // Trailing zeros occur when the original weights have a representation with // less than 52 binary digits, e.g. {1.5, 0.5, 0.25}. int trailingZeros = Long.SIZE; for (int i = 0; i < values.length && trailingZeros != 0; i++) { trailingZeros = Math.min(trailingZeros, Long.numberOfTrailingZeros(values[i])); } // Scale by a power of 2 so the minimum exponent is zero. for (int i = 0; i < exponents.length; i++) { exponents[i] -= minExponent; } // Remove common trailing zeros. if (trailingZeros != 0) { for (int i = 0; i < values.length; i++) { values[i] >>>= trailingZeros; } } } /** * Sum the integers at the specified indices. * Integers are represented as {@code value * 2^exponent}. * * @param values 53-bit values. * @param exponents Power of 2 exponent. * @param indices Indices to sum. * @return the sum */ private static BigInteger sum(long[] values, int[] exponents, int[] indices) { BigInteger m = BigInteger.ZERO; for (final int i : indices) { m = m.add(toBigInteger(values[i], exponents[i])); } return m; } /** * Convert the value and left shift offset to a BigInteger. * It is assumed the value is at most 53-bits. This allows optimising the left * shift if it is below 11 bits. * * @param value 53-bit value. * @param offset Left shift offset (must be positive). * @return the BigInteger */ private static BigInteger toBigInteger(long value, int offset) { // Ignore zeros. The sum method uses indices of non-zero values. if (offset <= MAX_OFFSET) { // Assume (value << offset) <= Long.MAX_VALUE return BigInteger.valueOf(value << offset); } return BigInteger.valueOf(value).shiftLeft(offset); } /** * Creates the sampler. * * <p>It is assumed the frequencies are all positive and the sum does not * overflow. * * @param rng Generator of uniformly distributed random numbers. * @param frequencies Observed frequencies of the discrete distribution. * @param indices Indices of non-zero frequencies. * @param m Sum of the frequencies. * @return the sampler */ private static FastLoadedDiceRollerDiscreteSampler createSampler(UniformRandomProvider rng, long[] frequencies, int[] indices, long m) { // ALGORITHM 5: PREPROCESS // a == frequencies // m = sum(a) // h = leaf node count // H = leaf node label (lH) final int n = frequencies.length; // k = ceil(log2(m)) final int k = 64 - Long.numberOfLeadingZeros(m - 1); // r = a(n+1) = 2^k - m final long r = (1L << k) - m; // Note: // A sparse matrix can often be used for H, as most of its entries are empty. // This implementation uses a 1D array for efficiency at the cost of memory. // This is limited to approximately ((2^31 - 1) / k), e.g. 34087042 when the sum of // observations is large enough to create k=63. // This could be handled using a 2D array. In practice a number of categories this // large is not expected and is currently not supported. final int[] h = new int[k]; final int[] lH = new int[checkArraySize((n + 1L) * k)]; Arrays.fill(lH, NO_LABEL); int d; for (int j = 0; j < k; j++) { final int shift = (k - 1) - j; final long bitMask = 1L << shift; d = 0; for (final int i : indices) { // bool w ← (a[i] >> (k − 1) − j)) & 1 // h[j] = h[j] + w // if w then: if ((frequencies[i] & bitMask) != 0) { h[j]++; // H[d][j] = i lH[d * k + j] = i; d++; } } // process a(n+1) without extending the input frequencies array by 1 if ((r & bitMask) != 0) { h[j]++; lH[d * k + j] = n; } } return new FLDRSampler(rng, n, k, h, lH); } /** * Creates the sampler. Frequencies are represented as a 53-bit value with a * left-shift offset. * <pre> * BigInteger.valueOf(value).shiftLeft(offset) * </pre> * * <p>It is assumed the frequencies are all positive. * * @param rng Generator of uniformly distributed random numbers. * @param frequencies Observed frequencies of the discrete distribution. * @param offsets Left shift offsets (must be positive). * @param indices Indices of non-zero frequencies. * @param m Sum of the frequencies. * @return the sampler */ private static FastLoadedDiceRollerDiscreteSampler createSampler(UniformRandomProvider rng, long[] frequencies, int[] offsets, int[] indices, BigInteger m) { // Repeat the logic from createSampler(...) using extended arithmetic to test the bits // ALGORITHM 5: PREPROCESS // a == frequencies // m = sum(a) // h = leaf node count // H = leaf node label (lH) final int n = frequencies.length; // k = ceil(log2(m)) final int k = m.subtract(BigInteger.ONE).bitLength(); // r = a(n+1) = 2^k - m final BigInteger r = BigInteger.ONE.shiftLeft(k).subtract(m); final int[] h = new int[k]; final int[] lH = new int[checkArraySize((n + 1L) * k)]; Arrays.fill(lH, NO_LABEL); int d; for (int j = 0; j < k; j++) { final int shift = (k - 1) - j; d = 0; for (final int i : indices) { // bool w ← (a[i] >> (k − 1) − j)) & 1 // h[j] = h[j] + w // if w then: if (testBit(frequencies[i], offsets[i], shift)) { h[j]++; // H[d][j] = i lH[d * k + j] = i; d++; } } // process a(n+1) without extending the input frequencies array by 1 if (r.testBit(shift)) { h[j]++; lH[d * k + j] = n; } } return new FLDRSampler(rng, n, k, h, lH); } /** * Test the logical bit of the shifted integer representation. * The value is assumed to have at most 53-bits of information. The offset * is assumed to be positive. This is functionally equivalent to: * <pre> * BigInteger.valueOf(value).shiftLeft(offset).testBit(n) * </pre> * * @param value 53-bit value. * @param offset Left shift offset. * @param n Index of bit to test. * @return true if the bit is 1 */ private static boolean testBit(long value, int offset, int n) { if (n < offset) { // All logical trailing bits are zero return false; } // Test if outside the 53-bit value (note that the implicit 1 bit // has been added to the 52-bit mantissas for 'normal' floating-point numbers). final int bit = n - offset; return bit <= MANTISSA_SIZE && (value & (1L << bit)) != 0; } /** * Check the weights have a non-zero length. * * @param weights Weights. * @return the length */ private static int checkWeightsNonZeroLength(double[] weights) { if (weights == null || weights.length == 0) { throw new IllegalArgumentException("weights must contain at least 1 value"); } return weights.length; } /** * Create the indices of non-zero values. * * @param values Values. * @return the indices */ private static int[] indicesOfNonZero(long[] values) { int n = 0; final int[] indices = new int[values.length]; for (int i = 0; i < values.length; i++) { if (values[i] != 0) { indices[n++] = i; } } return Arrays.copyOf(indices, n); } /** * Find the index of the first non-zero frequency. * * @param frequencies Frequencies. * @return the index * @throws IllegalStateException if all frequencies are zero. */ static int indexOfNonZero(long[] frequencies) { for (int i = 0; i < frequencies.length; i++) { if (frequencies[i] != 0) { return i; } } throw new IllegalStateException("All frequencies are zero"); } /** * Check the size is valid for a 1D array. * * @param size Size * @return the size as an {@code int} * @throws IllegalArgumentException if the size is too large for a 1D array. */ static int checkArraySize(long size) { if (size > MAX_ARRAY_SIZE) { throw new IllegalArgumentException("Unable to allocate array of size: " + size); } return (int) size; } }
2,984
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/LevySampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; /** * Sampling from a Lévy distribution. * * @see <a href="https://en.wikipedia.org/wiki/L%C3%A9vy_distribution">Lévy distribution</a> * @since 1.4 */ public final class LevySampler implements SharedStateContinuousSampler { /** Gaussian sampler. */ private final NormalizedGaussianSampler gaussian; /** Location. */ private final double location; /** Scale. */ private final double scale; /** RNG (used for the toString() method). */ private final UniformRandomProvider rng; /** * @param rng Generator of uniformly distributed random numbers. * @param location Location of the Lévy distribution. * @param scale Scale of the Lévy distribution. */ private LevySampler(UniformRandomProvider rng, double location, double scale) { this.gaussian = ZigguratSampler.NormalizedGaussian.of(rng); this.location = location; this.scale = scale; this.rng = rng; } /** * @param rng Generator of uniformly distributed random numbers. * @param source Source to copy. */ private LevySampler(UniformRandomProvider rng, LevySampler source) { this.gaussian = ZigguratSampler.NormalizedGaussian.of(rng); this.location = source.location; this.scale = source.scale; this.rng = rng; } /** {@inheritDoc} */ @Override public double sample() { final double n = gaussian.sample(); return scale / (n * n) + location; } /** {@inheritDoc} */ @Override public String toString() { return "Lévy deviate [" + rng.toString() + "]"; } /** {@inheritDoc} */ @Override public LevySampler withUniformRandomProvider(UniformRandomProvider rng) { return new LevySampler(rng, this); } /** * Create a new Lévy distribution sampler. * * @param rng Generator of uniformly distributed random numbers. * @param location Location of the Lévy distribution. * @param scale Scale of the Lévy distribution. * @return the sampler * @throws IllegalArgumentException if {@code scale <= 0} */ public static LevySampler of(UniformRandomProvider rng, double location, double scale) { if (scale <= 0) { throw new IllegalArgumentException("scale is not strictly positive: " + scale); } return new LevySampler(rng, location, scale); } }
2,985
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/ContinuousUniformSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; /** * Sampling from a uniform distribution. * * <p>Sampling uses {@link UniformRandomProvider#nextDouble()}.</p> * * @since 1.0 */ public class ContinuousUniformSampler extends SamplerBase implements SharedStateContinuousSampler { /** The minimum ULP gap for the open interval when the doubles have the same sign. */ private static final int MIN_ULP_SAME_SIGN = 2; /** The minimum ULP gap for the open interval when the doubles have the opposite sign. */ private static final int MIN_ULP_OPPOSITE_SIGN = 3; /** Lower bound. */ private final double lo; /** Higher bound. */ private final double hi; /** Underlying source of randomness. */ private final UniformRandomProvider rng; /** * Specialization to sample from an open interval {@code (lo, hi)}. */ private static class OpenIntervalContinuousUniformSampler extends ContinuousUniformSampler { /** * @param rng Generator of uniformly distributed random numbers. * @param lo Lower bound. * @param hi Higher bound. */ OpenIntervalContinuousUniformSampler(UniformRandomProvider rng, double lo, double hi) { super(rng, lo, hi); } @Override public double sample() { final double x = super.sample(); // Due to rounding using a variate u in the open interval (0,1) with the original // algorithm may generate a value at the bound. Thus the bound is explicitly tested // and the sample repeated if necessary. if (x == getHi() || x == getLo()) { return sample(); } return x; } @Override public SharedStateContinuousSampler withUniformRandomProvider(UniformRandomProvider rng) { return new OpenIntervalContinuousUniformSampler(rng, getLo(), getHi()); } } /** * @param rng Generator of uniformly distributed random numbers. * @param lo Lower bound. * @param hi Higher bound. */ public ContinuousUniformSampler(UniformRandomProvider rng, double lo, double hi) { super(null); this.rng = rng; this.lo = lo; this.hi = hi; } /** {@inheritDoc} */ @Override public double sample() { final double u = rng.nextDouble(); return u * hi + (1 - u) * lo; } /** * Gets the lower bound. This is deliberately scoped as package private. * * @return the lower bound */ double getLo() { return lo; } /** * Gets the higher bound. This is deliberately scoped as package private. * * @return the higher bound */ double getHi() { return hi; } /** {@inheritDoc} */ @Override public String toString() { return "Uniform deviate [" + rng.toString() + "]"; } /** * {@inheritDoc} * * @since 1.3 */ @Override public SharedStateContinuousSampler withUniformRandomProvider(UniformRandomProvider rng) { return new ContinuousUniformSampler(rng, lo, hi); } /** * Creates a new continuous uniform distribution sampler. * * @param rng Generator of uniformly distributed random numbers. * @param lo Lower bound. * @param hi Higher bound. * @return the sampler * @since 1.3 */ public static SharedStateContinuousSampler of(UniformRandomProvider rng, double lo, double hi) { return new ContinuousUniformSampler(rng, lo, hi); } /** * Creates a new continuous uniform distribution sampler. * * <p>The bounds can be optionally excluded to sample from the open interval * {@code (lower, upper)}. In this case if the bounds have the same sign the * open interval must contain at least 1 double value between the limits; if the * bounds have opposite signs the open interval must contain at least 2 double values * between the limits excluding {@code -0.0}. Thus the interval {@code (-x,x)} will * raise an exception when {@code x} is {@link Double#MIN_VALUE}. * * @param rng Generator of uniformly distributed random numbers. * @param lo Lower bound. * @param hi Higher bound. * @param excludeBounds Set to {@code true} to use the open interval * {@code (lower, upper)}. * @return the sampler * @throws IllegalArgumentException If the open interval is invalid. * @since 1.4 */ public static SharedStateContinuousSampler of(UniformRandomProvider rng, double lo, double hi, boolean excludeBounds) { if (excludeBounds) { if (!validateOpenInterval(lo, hi)) { throw new IllegalArgumentException("Invalid open interval (" + lo + "," + hi + ")"); } return new OpenIntervalContinuousUniformSampler(rng, lo, hi); } return new ContinuousUniformSampler(rng, lo, hi); } /** * Check that the open interval is valid. It must contain at least one double value * between the limits if the signs are the same, or two double values between the limits * if the signs are different (excluding {@code -0.0}). * * @param lo Lower bound. * @param hi Higher bound. * @return false is the interval is invalid */ private static boolean validateOpenInterval(double lo, double hi) { // Get the raw bit representation. long bitsx = Double.doubleToRawLongBits(lo); long bitsy = Double.doubleToRawLongBits(hi); // xor will set the sign bit if the signs are different if ((bitsx ^ bitsy) < 0) { // Opposite signs. Drop the sign bit to represent the count of // bits above +0.0. When combined this should be above 2. // This prevents the range (-Double.MIN_VALUE, Double.MIN_VALUE) // which cannot be sampled unless the uniform deviate u=0.5. // (MAX_VALUE has all bits set except the most significant sign bit.) bitsx &= Long.MAX_VALUE; bitsy &= Long.MAX_VALUE; return !lessThanUnsigned(bitsx + bitsy, MIN_ULP_OPPOSITE_SIGN); } // Same signs, subtraction will count the ULP difference. // This should be above 1. return Math.abs(bitsx - bitsy) >= MIN_ULP_SAME_SIGN; } /** * Compares two {@code long} values numerically treating the values as unsigned * to test if the first value is less than the second value. * * <p>See Long.compareUnsigned(long, long) in JDK 1.8. * * @param x the first value * @param y the second value * @return true if {@code x < y} */ private static boolean lessThanUnsigned(long x, long y) { return x + Long.MIN_VALUE < y + Long.MIN_VALUE; } }
2,986
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/UniformLongSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; /** * Discrete uniform distribution sampler generating values of type {@code long}. * * <p>Sampling uses {@link UniformRandomProvider#nextLong}.</p> * * <p>When the range is a power of two the number of calls is 1 per sample. * Otherwise a rejection algorithm is used to ensure uniformity. In the worst * case scenario where the range spans half the range of a {@code long} * (2<sup>63</sup> + 1) the expected number of calls is 2 per sample.</p> * * @since 1.4 */ public abstract class UniformLongSampler implements SharedStateLongSampler { /** Underlying source of randomness. */ protected final UniformRandomProvider rng; /** * Discrete uniform distribution sampler when the sample value is fixed. */ private static class FixedUniformLongSampler extends UniformLongSampler { /** The value. */ private final long value; /** * @param value The value. */ FixedUniformLongSampler(long value) { // No requirement for the RNG super(null); this.value = value; } @Override public long sample() { return value; } @Override public String toString() { // No RNG to include in the string return "Uniform deviate [X=" + value + "]"; } @Override public UniformLongSampler withUniformRandomProvider(UniformRandomProvider rng) { // No requirement for the RNG return this; } } /** * Discrete uniform distribution sampler when the range is a power of 2 and greater than 1. * This sampler assumes the lower bound of the range is 0. * * <p>Note: This cannot be used when the range is 1 (2^0) as the shift would be 64-bits * which is ignored by the shift operator.</p> */ private static class PowerOf2RangeUniformLongSampler extends UniformLongSampler { /** Bit shift to apply to the long sample. */ private final int shift; /** * @param rng Generator of uniformly distributed random numbers. * @param range Maximum range of the sample (exclusive). * Must be a power of 2 greater than 2^0. */ PowerOf2RangeUniformLongSampler(UniformRandomProvider rng, long range) { super(rng); this.shift = Long.numberOfLeadingZeros(range) + 1; } /** * @param rng Generator of uniformly distributed random numbers. * @param source Source to copy. */ PowerOf2RangeUniformLongSampler(UniformRandomProvider rng, PowerOf2RangeUniformLongSampler source) { super(rng); this.shift = source.shift; } @Override public long sample() { // Use a bit shift to favour the most significant bits. return rng.nextLong() >>> shift; } @Override public UniformLongSampler withUniformRandomProvider(UniformRandomProvider rng) { return new PowerOf2RangeUniformLongSampler(rng, this); } } /** * Discrete uniform distribution sampler when the range is small * enough to fit in a positive long. * This sampler assumes the lower bound of the range is 0 and the range is * non-zero. */ private static class SmallRangeUniformLongSampler extends UniformLongSampler { /** Maximum range of the sample (exclusive). */ private final long n; /** Limit of the uniform range (inclusive) to sample a positive long. * This is the largest positive multiple of {@code n} minus 1: * {@code floor(2^63 / n) * n - 1}. * The -1 changes the limit to an inclusive bound and allows support * for a power of 2 range. */ private final long limit; /** * @param rng Generator of uniformly distributed random numbers. * @param range Maximum range of the sample (exclusive). */ SmallRangeUniformLongSampler(UniformRandomProvider rng, long range) { super(rng); this.n = range; // Set the upper limit for the positive long. // The sample must be selected from the largest multiple // of 'range' that fits within a positive value: // limit = floor(2^63 / range) * range // = 2^63 - (2^63 % range) // Sample: // X in [0, limit) or X in [0, limit - 1] // return X % range // This is a one-off computation cost. // The divide will truncate towards zero (do not use Math.floorDiv). // Note: This is invalid if range is not strictly positive. limit = (Long.MIN_VALUE / range) * -range - 1; } /** * @param rng Generator of uniformly distributed random numbers. * @param source Source to copy. */ SmallRangeUniformLongSampler(UniformRandomProvider rng, SmallRangeUniformLongSampler source) { super(rng); this.n = source.n; this.limit = source.limit; } @Override public long sample() { // Note: // This will have the same output as the rejection algorithm // from o.a.c.rng.core.BaseProvider. The limit for the uniform // positive value can be pre-computed. This ensures exactly // 1 modulus operation per call. for (;;) { // bits in [0, limit] final long bits = rng.nextLong() >>> 1; if (bits <= limit) { return bits % n; } } } @Override public UniformLongSampler withUniformRandomProvider(UniformRandomProvider rng) { return new SmallRangeUniformLongSampler(rng, this); } } /** * Discrete uniform distribution sampler when the range between lower and upper is too large * to fit in a positive long. */ private static class LargeRangeUniformLongSampler extends UniformLongSampler { /** Lower bound. */ private final long lower; /** Upper bound. */ private final long upper; /** * @param rng Generator of uniformly distributed random numbers. * @param lower Lower bound (inclusive) of the distribution. * @param upper Upper bound (inclusive) of the distribution. */ LargeRangeUniformLongSampler(UniformRandomProvider rng, long lower, long upper) { super(rng); this.lower = lower; this.upper = upper; } @Override public long sample() { // Use a simple rejection method. // This is used when (upper-lower) >= Long.MAX_VALUE. // This will loop on average 2 times in the worst case scenario // when (upper-lower) == Long.MAX_VALUE. while (true) { final long r = rng.nextLong(); if (r >= lower && r <= upper) { return r; } } } @Override public UniformLongSampler withUniformRandomProvider(UniformRandomProvider rng) { return new LargeRangeUniformLongSampler(rng, lower, upper); } } /** * Adds an offset to an underlying discrete sampler. */ private static class OffsetUniformLongSampler extends UniformLongSampler { /** The offset. */ private final long offset; /** The long sampler. */ private final UniformLongSampler sampler; /** * @param offset The offset for the sample. * @param sampler The discrete sampler. */ OffsetUniformLongSampler(long offset, UniformLongSampler sampler) { // No requirement for the RNG super(null); this.offset = offset; this.sampler = sampler; } @Override public long sample() { return offset + sampler.sample(); } @Override public String toString() { return sampler.toString(); } @Override public UniformLongSampler withUniformRandomProvider(UniformRandomProvider rng) { return new OffsetUniformLongSampler(offset, sampler.withUniformRandomProvider(rng)); } } /** * @param rng Generator of uniformly distributed random numbers. */ UniformLongSampler(UniformRandomProvider rng) { this.rng = rng; } /** {@inheritDoc} */ @Override public String toString() { return "Uniform deviate [" + rng.toString() + "]"; } /** {@inheritDoc} */ // Redeclare the signature to return a UniformLongSampler not a SharedStateLongSampler @Override public abstract UniformLongSampler withUniformRandomProvider(UniformRandomProvider rng); /** * Creates a new discrete uniform distribution sampler. * * @param rng Generator of uniformly distributed random numbers. * @param lower Lower bound (inclusive) of the distribution. * @param upper Upper bound (inclusive) of the distribution. * @return the sampler * @throws IllegalArgumentException if {@code lower > upper}. */ public static UniformLongSampler of(UniformRandomProvider rng, long lower, long upper) { if (lower > upper) { throw new IllegalArgumentException(lower + " > " + upper); } // Choose the algorithm depending on the range // Edge case for no range. // This must be done first as the methods to handle lower == 0 // do not handle upper == 0. if (upper == lower) { return new FixedUniformLongSampler(lower); } // Algorithms to ignore the lower bound if it is zero. if (lower == 0) { return createZeroBoundedSampler(rng, upper); } final long range = (upper - lower) + 1; // Check power of 2 first to handle range == 2^63. if (isPowerOf2(range)) { return new OffsetUniformLongSampler(lower, new PowerOf2RangeUniformLongSampler(rng, range)); } if (range <= 0) { // The range is too wide to fit in a positive long (larger // than 2^63); use a simple rejection method. // Note: if range == 0 then the input is [Long.MIN_VALUE, Long.MAX_VALUE]. // No specialisation exists for this and it is handled as a large range. return new LargeRangeUniformLongSampler(rng, lower, upper); } // Use a sample from the range added to the lower bound. return new OffsetUniformLongSampler(lower, new SmallRangeUniformLongSampler(rng, range)); } /** * Create a new sampler for the range {@code 0} inclusive to {@code upper} inclusive. * * <p>This can handle any positive {@code upper}. * * @param rng Generator of uniformly distributed random numbers. * @param upper Upper bound (inclusive) of the distribution. Must be positive. * @return the sampler */ private static UniformLongSampler createZeroBoundedSampler(UniformRandomProvider rng, long upper) { // Note: Handle any range up to 2^63 (which is negative as a signed // 64-bit long but handled as a power of 2) final long range = upper + 1; return isPowerOf2(range) ? new PowerOf2RangeUniformLongSampler(rng, range) : new SmallRangeUniformLongSampler(rng, range); } /** * Checks if the value is a power of 2. * * <p>This returns {@code true} for the value {@code Long.MIN_VALUE} which can be * handled as an unsigned long of 2^63.</p> * * @param value Value. * @return {@code true} if a power of 2 */ private static boolean isPowerOf2(final long value) { return value != 0 && (value & (value - 1)) == 0; } }
2,987
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/ChengBetaSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; /** * Sampling from a <a href="http://en.wikipedia.org/wiki/Beta_distribution">beta distribution</a>. * * <p>Uses Cheng's algorithms for beta distribution sampling:</p> * * <blockquote> * <pre> * R. C. H. Cheng, * "Generating beta variates with nonintegral shape parameters", * Communications of the ACM, 21, 317-322, 1978. * </pre> * </blockquote> * * <p>Sampling uses {@link UniformRandomProvider#nextDouble()}.</p> * * @since 1.0 */ public class ChengBetaSampler extends SamplerBase implements SharedStateContinuousSampler { /** Natural logarithm of 4. */ private static final double LN_4 = Math.log(4.0); /** The appropriate beta sampler for the parameters. */ private final SharedStateContinuousSampler delegate; /** * Base class to implement Cheng's algorithms for the beta distribution. */ private abstract static class BaseChengBetaSampler implements SharedStateContinuousSampler { /** * Flag set to true if {@code a} is the beta distribution alpha shape parameter. * Otherwise {@code a} is the beta distribution beta shape parameter. * * <p>From the original Cheng paper this is equal to the result of: {@code a == a0}.</p> */ protected final boolean aIsAlphaShape; /** * First shape parameter. * The meaning of this is dependent on the {@code aIsAlphaShape} flag. */ protected final double a; /** * Second shape parameter. * The meaning of this is dependent on the {@code aIsAlphaShape} flag. */ protected final double b; /** Underlying source of randomness. */ protected final UniformRandomProvider rng; /** * The algorithm alpha factor. This is not the beta distribution alpha shape parameter. * It is the sum of the two shape parameters ({@code a + b}. */ protected final double alpha; /** The logarithm of the alpha factor. */ protected final double logAlpha; /** * @param rng Generator of uniformly distributed random numbers. * @param aIsAlphaShape true if {@code a} is the beta distribution alpha shape parameter. * @param a Distribution first shape parameter. * @param b Distribution second shape parameter. */ BaseChengBetaSampler(UniformRandomProvider rng, boolean aIsAlphaShape, double a, double b) { this.rng = rng; this.aIsAlphaShape = aIsAlphaShape; this.a = a; this.b = b; alpha = a + b; logAlpha = Math.log(alpha); } /** * @param rng Generator of uniformly distributed random numbers. * @param source Source to copy. */ private BaseChengBetaSampler(UniformRandomProvider rng, BaseChengBetaSampler source) { this.rng = rng; aIsAlphaShape = source.aIsAlphaShape; a = source.a; b = source.b; // Compute algorithm factors. alpha = source.alpha; logAlpha = source.logAlpha; } /** {@inheritDoc} */ @Override public String toString() { return "Cheng Beta deviate [" + rng.toString() + "]"; } /** * Compute the sample result X. * * <blockquote> * If a == a0 deliver X = W/(b + W); otherwise deliver X = b/(b + W). * </blockquote> * * <p>The finalisation step is shared between the BB and BC algorithm (as step 5 of the * BB algorithm and step 6 of the BC algorithm).</p> * * @param w Algorithm value W. * @return the sample value */ protected double computeX(double w) { // Avoid (infinity / infinity) producing NaN final double tmp = Math.min(w, Double.MAX_VALUE); return aIsAlphaShape ? tmp / (b + tmp) : b / (b + tmp); } } /** * Computes one sample using Cheng's BB algorithm, when beta distribution {@code alpha} and * {@code beta} shape parameters are both larger than 1. */ private static class ChengBBBetaSampler extends BaseChengBetaSampler { /** 1 + natural logarithm of 5. */ private static final double LN_5_P1 = 1 + Math.log(5.0); /** The algorithm beta factor. This is not the beta distribution beta shape parameter. */ private final double beta; /** The algorithm gamma factor. */ private final double gamma; /** * @param rng Generator of uniformly distributed random numbers. * @param aIsAlphaShape true if {@code a} is the beta distribution alpha shape parameter. * @param a min(alpha, beta) shape parameter. * @param b max(alpha, beta) shape parameter. */ ChengBBBetaSampler(UniformRandomProvider rng, boolean aIsAlphaShape, double a, double b) { super(rng, aIsAlphaShape, a, b); beta = Math.sqrt((alpha - 2) / (2 * a * b - alpha)); gamma = a + 1 / beta; } /** * @param rng Generator of uniformly distributed random numbers. * @param source Source to copy. */ private ChengBBBetaSampler(UniformRandomProvider rng, ChengBBBetaSampler source) { super(rng, source); // Compute algorithm factors. beta = source.beta; gamma = source.gamma; } @Override public double sample() { double r; double w; double t; do { // Step 1: final double u1 = rng.nextDouble(); final double u2 = rng.nextDouble(); final double v = beta * (Math.log(u1) - Math.log1p(-u1)); w = a * Math.exp(v); final double z = u1 * u1 * u2; r = gamma * v - LN_4; final double s = a + r - w; // Step 2: if (s + LN_5_P1 >= 5 * z) { break; } // Step 3: t = Math.log(z); if (s >= t) { break; } // Step 4: } while (r + alpha * (logAlpha - Math.log(b + w)) < t); // Step 5: return computeX(w); } @Override public SharedStateContinuousSampler withUniformRandomProvider(UniformRandomProvider rng) { return new ChengBBBetaSampler(rng, this); } } /** * Computes one sample using Cheng's BC algorithm, when at least one of beta distribution * {@code alpha} or {@code beta} shape parameters is smaller than 1. */ private static class ChengBCBetaSampler extends BaseChengBetaSampler { /** 1/2. */ private static final double ONE_HALF = 1d / 2; /** 1/4. */ private static final double ONE_QUARTER = 1d / 4; /** The algorithm beta factor. This is not the beta distribution beta shape parameter. */ private final double beta; /** The algorithm delta factor. */ private final double delta; /** The algorithm k1 factor. */ private final double k1; /** The algorithm k2 factor. */ private final double k2; /** * @param rng Generator of uniformly distributed random numbers. * @param aIsAlphaShape true if {@code a} is the beta distribution alpha shape parameter. * @param a max(alpha, beta) shape parameter. * @param b min(alpha, beta) shape parameter. */ ChengBCBetaSampler(UniformRandomProvider rng, boolean aIsAlphaShape, double a, double b) { super(rng, aIsAlphaShape, a, b); // Compute algorithm factors. beta = 1 / b; delta = 1 + a - b; // The following factors are divided by 4: // k1 = delta * (1 + 3b) / (18a/b - 14) // k2 = 1 + (2 + 1/delta) * b k1 = delta * (1.0 / 72.0 + 3.0 / 72.0 * b) / (a * beta - 7.0 / 9.0); k2 = 0.25 + (0.5 + 0.25 / delta) * b; } /** * @param rng Generator of uniformly distributed random numbers. * @param source Source to copy. */ private ChengBCBetaSampler(UniformRandomProvider rng, ChengBCBetaSampler source) { super(rng, source); beta = source.beta; delta = source.delta; k1 = source.k1; k2 = source.k2; } @Override public double sample() { double w; while (true) { // Step 1: final double u1 = rng.nextDouble(); final double u2 = rng.nextDouble(); // Compute Y and Z final double y = u1 * u2; final double z = u1 * y; if (u1 < ONE_HALF) { // Step 2: if (ONE_QUARTER * u2 + z - y >= k1) { continue; } } else { // Step 3: if (z <= ONE_QUARTER) { final double v = beta * (Math.log(u1) - Math.log1p(-u1)); w = a * Math.exp(v); break; } // Step 4: if (z >= k2) { continue; } } // Step 5: final double v = beta * (Math.log(u1) - Math.log1p(-u1)); w = a * Math.exp(v); if (alpha * (logAlpha - Math.log(b + w) + v) - LN_4 >= Math.log(z)) { break; } } // Step 6: return computeX(w); } @Override public SharedStateContinuousSampler withUniformRandomProvider(UniformRandomProvider rng) { return new ChengBCBetaSampler(rng, this); } } /** * Creates a sampler instance. * * @param rng Generator of uniformly distributed random numbers. * @param alpha Distribution first shape parameter. * @param beta Distribution second shape parameter. * @throws IllegalArgumentException if {@code alpha <= 0} or {@code beta <= 0} */ public ChengBetaSampler(UniformRandomProvider rng, double alpha, double beta) { super(null); delegate = of(rng, alpha, beta); } /** {@inheritDoc} */ @Override public double sample() { return delegate.sample(); } /** {@inheritDoc} */ @Override public String toString() { return delegate.toString(); } /** * {@inheritDoc} * * @since 1.3 */ @Override public SharedStateContinuousSampler withUniformRandomProvider(UniformRandomProvider rng) { return delegate.withUniformRandomProvider(rng); } /** * Creates a new beta distribution sampler. * * @param rng Generator of uniformly distributed random numbers. * @param alpha Distribution first shape parameter. * @param beta Distribution second shape parameter. * @return the sampler * @throws IllegalArgumentException if {@code alpha <= 0} or {@code beta <= 0} * @since 1.3 */ public static SharedStateContinuousSampler of(UniformRandomProvider rng, double alpha, double beta) { if (alpha <= 0) { throw new IllegalArgumentException("alpha is not strictly positive: " + alpha); } if (beta <= 0) { throw new IllegalArgumentException("beta is not strictly positive: " + beta); } // Choose the algorithm. final double a = Math.min(alpha, beta); final double b = Math.max(alpha, beta); final boolean aIsAlphaShape = a == alpha; return a > 1 ? // BB algorithm new ChengBBBetaSampler(rng, aIsAlphaShape, a, b) : // The BC algorithm is deliberately invoked with reversed parameters // as the argument order is: max(alpha,beta), min(alpha,beta). // Also invert the 'a is alpha' flag. new ChengBCBetaSampler(rng, !aIsAlphaShape, b, a); } }
2,988
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/KempSmallMeanPoissonSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; /** * Sampler for the <a href="http://mathworld.wolfram.com/PoissonDistribution.html">Poisson * distribution</a>. * * <ul> * <li> * Kemp, A, W, (1981) Efficient Generation of Logarithmically Distributed * Pseudo-Random Variables. Journal of the Royal Statistical Society. Vol. 30, No. 3, pp. * 249-253. * </li> * </ul> * * <p>This sampler is suitable for {@code mean < 40}. For large means, * {@link LargeMeanPoissonSampler} should be used instead.</p> * * <p>Note: The algorithm uses a recurrence relation to compute the Poisson probability * and a rolling summation for the cumulative probability. When the mean is large the * initial probability (Math.exp(-mean)) is zero and an exception is raised by the * constructor.</p> * * <p>Sampling uses 1 call to {@link UniformRandomProvider#nextDouble()}. This method provides * an alternative to the {@link SmallMeanPoissonSampler} for slow generators of {@code double}.</p> * * @see <a href="https://www.jstor.org/stable/2346348">Kemp, A.W. (1981) JRSS Vol. 30, pp. * 249-253</a> * @since 1.3 */ public final class KempSmallMeanPoissonSampler implements SharedStateDiscreteSampler { /** Underlying source of randomness. */ private final UniformRandomProvider rng; /** * Pre-compute {@code Math.exp(-mean)}. * Note: This is the probability of the Poisson sample {@code p(x=0)}. */ private final double p0; /** * The mean of the Poisson sample. */ private final double mean; /** * @param rng Generator of uniformly distributed random numbers. * @param p0 Probability of the Poisson sample {@code p(x=0)}. * @param mean Mean. */ private KempSmallMeanPoissonSampler(UniformRandomProvider rng, double p0, double mean) { this.rng = rng; this.p0 = p0; this.mean = mean; } /** {@inheritDoc} */ @Override public int sample() { // Note on the algorithm: // - X is the unknown sample deviate (the output of the algorithm) // - x is the current value from the distribution // - p is the probability of the current value x, p(X=x) // - u is effectively the cumulative probability that the sample X // is equal or above the current value x, p(X>=x) // So if p(X>=x) > p(X=x) the sample must be above x, otherwise it is x double u = rng.nextDouble(); int x = 0; double p = p0; while (u > p) { u -= p; // Compute the next probability using a recurrence relation. // p(x+1) = p(x) * mean / (x+1) p *= mean / ++x; // The algorithm listed in Kemp (1981) does not check that the rolling probability // is positive. This check is added to ensure no errors when the limit of the summation // 1 - sum(p(x)) is above 0 due to cumulative error in floating point arithmetic. if (p == 0) { return x; } } return x; } /** {@inheritDoc} */ @Override public String toString() { return "Kemp Small Mean Poisson deviate [" + rng.toString() + "]"; } /** {@inheritDoc} */ @Override public SharedStateDiscreteSampler withUniformRandomProvider(UniformRandomProvider rng) { return new KempSmallMeanPoissonSampler(rng, p0, mean); } /** * Creates a new sampler for the Poisson distribution. * * @param rng Generator of uniformly distributed random numbers. * @param mean Mean of the distribution. * @return the sampler * @throws IllegalArgumentException if {@code mean <= 0} or * {@code Math.exp(-mean) == 0}. */ public static SharedStateDiscreteSampler of(UniformRandomProvider rng, double mean) { if (mean <= 0) { throw new IllegalArgumentException("Mean is not strictly positive: " + mean); } final double p0 = Math.exp(-mean); // Probability must be positive. As mean increases then p(0) decreases. if (p0 > 0) { return new KempSmallMeanPoissonSampler(rng, p0, mean); } // This catches the edge case of a NaN mean throw new IllegalArgumentException("No probability for mean: " + mean); } }
2,989
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/BoxMullerNormalizedGaussianSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; /** * <a href="https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform"> * Box-Muller algorithm</a> for sampling from Gaussian distribution with * mean 0 and standard deviation 1. * * <p>Sampling uses:</p> * * <ul> * <li>{@link UniformRandomProvider#nextDouble()} * <li>{@link UniformRandomProvider#nextLong()} * </ul> * * @since 1.1 */ public class BoxMullerNormalizedGaussianSampler implements NormalizedGaussianSampler, SharedStateContinuousSampler { /** Next gaussian. */ private double nextGaussian = Double.NaN; /** Underlying source of randomness. */ private final UniformRandomProvider rng; /** * @param rng Generator of uniformly distributed random numbers. */ public BoxMullerNormalizedGaussianSampler(UniformRandomProvider rng) { this.rng = rng; } /** {@inheritDoc} */ @Override public double sample() { double random; if (Double.isNaN(nextGaussian)) { // Generate a pair of Gaussian numbers. // Avoid zero for the uniform deviate y. // The extreme tail of the sample is: // y = 2^-53 // r = 8.57167 final double x = rng.nextDouble(); final double y = InternalUtils.makeNonZeroDouble(rng.nextLong()); final double alpha = 2 * Math.PI * x; final double r = Math.sqrt(-2 * Math.log(y)); // Return the first element of the generated pair. random = r * Math.cos(alpha); // Keep second element of the pair for next invocation. nextGaussian = r * Math.sin(alpha); } else { // Use the second element of the pair (generated at the // previous invocation). random = nextGaussian; // Both elements of the pair have been used. nextGaussian = Double.NaN; } return random; } /** {@inheritDoc} */ @Override public String toString() { return "Box-Muller normalized Gaussian deviate [" + rng.toString() + "]"; } /** * {@inheritDoc} * * @since 1.3 */ @Override public SharedStateContinuousSampler withUniformRandomProvider(UniformRandomProvider rng) { return new BoxMullerNormalizedGaussianSampler(rng); } /** * Create a new normalised Gaussian sampler. * * @param <S> Sampler type. * @param rng Generator of uniformly distributed random numbers. * @return the sampler * @since 1.3 */ @SuppressWarnings("unchecked") public static <S extends NormalizedGaussianSampler & SharedStateContinuousSampler> S of(UniformRandomProvider rng) { return (S) new BoxMullerNormalizedGaussianSampler(rng); } }
2,990
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/ContinuousInverseCumulativeProbabilityFunction.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; /** * Interface for a continuous distribution that can be sampled using * the <a href="https://en.wikipedia.org/wiki/Inverse_transform_sampling"> * inversion method</a>. * * @since 1.0 */ public interface ContinuousInverseCumulativeProbabilityFunction { /** * Computes the quantile function of the distribution. * For a random variable {@code X} distributed according to this distribution, * the returned value is * <ul> * <li>\( \inf_{x \in \mathcal{R}} P(X \le x) \ge p \) for \( 0 \lt p \le 1 \)</li> * <li>\( \inf_{x \in \mathcal{R}} P(X \le x) \gt 0 \) for \( p = 0 \)</li> * </ul> * * @param p Cumulative probability. * @return the smallest {@code p}-quantile of the distribution * (largest 0-quantile for {@code p = 0}). * @throws IllegalArgumentException if {@code p < 0} or {@code p > 1}. */ double inverseCumulativeProbability(double p); }
2,991
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/BoxMullerGaussianSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; /** * <a href="https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform"> * Box-Muller algorithm</a> for sampling from a Gaussian distribution. * * <p>Sampling uses:</p> * * <ul> * <li>{@link UniformRandomProvider#nextDouble()} * <li>{@link UniformRandomProvider#nextLong()} * </ul> * * @since 1.0 * * @deprecated Since version 1.1. Please use {@link BoxMullerNormalizedGaussianSampler} * and {@link GaussianSampler} instead. */ @Deprecated public class BoxMullerGaussianSampler extends SamplerBase implements ContinuousSampler { /** Next gaussian. */ private double nextGaussian = Double.NaN; /** Mean. */ private final double mean; /** standardDeviation. */ private final double standardDeviation; /** Underlying source of randomness. */ private final UniformRandomProvider rng; /** * @param rng Generator of uniformly distributed random numbers. * @param mean Mean of the Gaussian distribution. * @param standardDeviation Standard deviation of the Gaussian distribution. * @throws IllegalArgumentException if {@code standardDeviation <= 0} */ public BoxMullerGaussianSampler(UniformRandomProvider rng, double mean, double standardDeviation) { super(null); if (standardDeviation <= 0) { throw new IllegalArgumentException("standard deviation is not strictly positive: " + standardDeviation); } this.rng = rng; this.mean = mean; this.standardDeviation = standardDeviation; } /** {@inheritDoc} */ @Override public double sample() { double random; if (Double.isNaN(nextGaussian)) { // Generate a pair of Gaussian numbers. // Avoid zero for the uniform deviate y. // The extreme tail of the sample is: // y = 2^-53 // r = 8.57167 final double x = rng.nextDouble(); final double y = InternalUtils.makeNonZeroDouble(rng.nextLong()); final double alpha = 2 * Math.PI * x; final double r = Math.sqrt(-2 * Math.log(y)); // Return the first element of the generated pair. random = r * Math.cos(alpha); // Keep second element of the pair for next invocation. nextGaussian = r * Math.sin(alpha); } else { // Use the second element of the pair (generated at the // previous invocation). random = nextGaussian; // Both elements of the pair have been used. nextGaussian = Double.NaN; } return standardDeviation * random + mean; } /** {@inheritDoc} */ @Override public String toString() { return "Box-Muller Gaussian deviate [" + rng.toString() + "]"; } }
2,992
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/NormalizedGaussianSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; /** * Marker interface for a sampler that generates values from an N(0,1) * <a href="https://en.wikipedia.org/wiki/Normal_distribution"> * Gaussian distribution</a>. * * @since 1.1 */ public interface NormalizedGaussianSampler extends ContinuousSampler {}
2,993
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/MarsagliaNormalizedGaussianSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; /** * <a href="https://en.wikipedia.org/wiki/Marsaglia_polar_method"> * Marsaglia polar method</a> for sampling from a Gaussian distribution * with mean 0 and standard deviation 1. * This is a variation of the algorithm implemented in * {@link BoxMullerNormalizedGaussianSampler}. * * <p>Sampling uses {@link UniformRandomProvider#nextDouble()}.</p> * * @since 1.1 */ public class MarsagliaNormalizedGaussianSampler implements NormalizedGaussianSampler, SharedStateContinuousSampler { /** Next gaussian. */ private double nextGaussian = Double.NaN; /** Underlying source of randomness. */ private final UniformRandomProvider rng; /** * @param rng Generator of uniformly distributed random numbers. */ public MarsagliaNormalizedGaussianSampler(UniformRandomProvider rng) { this.rng = rng; } /** {@inheritDoc} */ @Override public double sample() { if (Double.isNaN(nextGaussian)) { // Rejection scheme for selecting a pair that lies within the unit circle. while (true) { // Generate a pair of numbers within [-1 , 1). final double x = 2 * rng.nextDouble() - 1; final double y = 2 * rng.nextDouble() - 1; final double r2 = x * x + y * y; if (r2 < 1 && r2 > 0) { // Pair (x, y) is within unit circle. final double alpha = Math.sqrt(-2 * Math.log(r2) / r2); // Keep second element of the pair for next invocation. nextGaussian = alpha * y; // Return the first element of the generated pair. return alpha * x; } // Pair is not within the unit circle: Generate another one. } } // Use the second element of the pair (generated at the // previous invocation). final double r = nextGaussian; // Both elements of the pair have been used. nextGaussian = Double.NaN; return r; } /** {@inheritDoc} */ @Override public String toString() { return "Box-Muller (with rejection) normalized Gaussian deviate [" + rng.toString() + "]"; } /** * {@inheritDoc} * * @since 1.3 */ @Override public SharedStateContinuousSampler withUniformRandomProvider(UniformRandomProvider rng) { return new MarsagliaNormalizedGaussianSampler(rng); } /** * Create a new normalised Gaussian sampler. * * @param <S> Sampler type. * @param rng Generator of uniformly distributed random numbers. * @return the sampler * @since 1.3 */ @SuppressWarnings("unchecked") public static <S extends NormalizedGaussianSampler & SharedStateContinuousSampler> S of(UniformRandomProvider rng) { return (S) new MarsagliaNormalizedGaussianSampler(rng); } }
2,994
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/LogNormalSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; /** * Sampling from a log-normal distribution. * * @since 1.1 */ public class LogNormalSampler implements SharedStateContinuousSampler { /** Mean of the natural logarithm of the distribution values. */ private final double mu; /** Standard deviation of the natural logarithm of the distribution values. */ private final double sigma; /** Gaussian sampling. */ private final NormalizedGaussianSampler gaussian; /** * @param gaussian N(0,1) generator. * @param mu Mean of the natural logarithm of the distribution values. * @param sigma Standard deviation of the natural logarithm of the distribution values. * @throws IllegalArgumentException if {@code sigma <= 0}. */ public LogNormalSampler(NormalizedGaussianSampler gaussian, double mu, double sigma) { if (sigma <= 0) { throw new IllegalArgumentException("sigma is not strictly positive: " + sigma); } this.mu = mu; this.sigma = sigma; this.gaussian = gaussian; } /** * @param rng Generator of uniformly distributed random numbers. * @param source Source to copy. */ private LogNormalSampler(UniformRandomProvider rng, LogNormalSampler source) { this.mu = source.mu; this.sigma = source.sigma; this.gaussian = InternalUtils.newNormalizedGaussianSampler(source.gaussian, rng); } /** {@inheritDoc} */ @Override public double sample() { return Math.exp(mu + sigma * gaussian.sample()); } /** {@inheritDoc} */ @Override public String toString() { return "Log-normal deviate [" + gaussian.toString() + "]"; } /** * {@inheritDoc} * * <p>Note: This function is available if the underlying {@link NormalizedGaussianSampler} * is a {@link org.apache.commons.rng.sampling.SharedStateSampler SharedStateSampler}. * Otherwise a run-time exception is thrown.</p> * * @throws UnsupportedOperationException if the underlying sampler is not a * {@link org.apache.commons.rng.sampling.SharedStateSampler SharedStateSampler} or * does not return a {@link NormalizedGaussianSampler} when sharing state. * * @since 1.3 */ @Override public SharedStateContinuousSampler withUniformRandomProvider(UniformRandomProvider rng) { return new LogNormalSampler(rng, this); } /** * Create a new log-normal distribution sampler. * * <p>Note: The shared-state functionality is available if the {@link NormalizedGaussianSampler} * is a {@link org.apache.commons.rng.sampling.SharedStateSampler SharedStateSampler}. * Otherwise a run-time exception will be thrown when the sampler is used to share state.</p> * * @param gaussian N(0,1) generator. * @param mu Mean of the natural logarithm of the distribution values. * @param sigma Standard deviation of the natural logarithm of the distribution values. * @return the sampler * @throws IllegalArgumentException if {@code sigma <= 0}. * @see #withUniformRandomProvider(UniformRandomProvider) * @since 1.3 */ public static SharedStateContinuousSampler of(NormalizedGaussianSampler gaussian, double mu, double sigma) { return new LogNormalSampler(gaussian, mu, sigma); } }
2,995
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/PoissonSamplerCache.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.distribution.LargeMeanPoissonSampler.LargeMeanPoissonSamplerState; /** * Create a sampler for the * <a href="http://mathworld.wolfram.com/PoissonDistribution.html">Poisson * distribution</a> using a cache to minimise construction cost. * * <p>The cache will return a sampler equivalent to * {@link PoissonSampler#PoissonSampler(UniformRandomProvider, double)}.</p> * * <p>The cache allows the {@link PoissonSampler} construction cost to be minimised * for low size Poisson samples. The cache stores state for a range of integers where * integer value {@code n} can be used to construct a sampler for the range * {@code n <= mean < n+1}.</p> * * <p>The cache is advantageous under the following conditions:</p> * * <ul> * <li>The mean of the Poisson distribution falls within a known range. * <li>The sample size to be made with the <strong>same</strong> sampler is * small. * <li>The Poisson samples have different means with the same integer * value(s) after rounding down. * </ul> * * <p>If the sample size to be made with the <strong>same</strong> sampler is large * then the construction cost is low compared to the sampling time and the cache * has minimal benefit.</p> * * <p>Performance improvement is dependent on the speed of the * {@link UniformRandomProvider}. A fast provider can obtain a two-fold speed * improvement for a single-use Poisson sampler.</p> * * <p>The cache is thread safe. Note that concurrent threads using the cache * must ensure a thread safe {@link UniformRandomProvider} is used when creating * samplers, e.g. a unique sampler per thread.</p> * * <p>Sampling uses:</p> * * <ul> * <li>{@link UniformRandomProvider#nextDouble()} * <li>{@link UniformRandomProvider#nextLong()} (large means only) * </ul> * * @since 1.2 */ public class PoissonSamplerCache { /** * The minimum N covered by the cache where * {@code N = (int)Math.floor(mean)}. */ private final int minN; /** * The maximum N covered by the cache where * {@code N = (int)Math.floor(mean)}. */ private final int maxN; /** The cache of states between {@link #minN} and {@link #maxN}. */ private final LargeMeanPoissonSamplerState[] values; /** * @param minMean The minimum mean covered by the cache. * @param maxMean The maximum mean covered by the cache. * @throws IllegalArgumentException if {@code maxMean < minMean} */ public PoissonSamplerCache(double minMean, double maxMean) { checkMeanRange(minMean, maxMean); // The cache can only be used for the LargeMeanPoissonSampler. if (maxMean < PoissonSampler.PIVOT) { // The upper limit is too small so no cache will be used. // This class will just construct new samplers. minN = 0; maxN = 0; values = null; } else { // Convert the mean into integers. // Note the minimum is clipped to the algorithm switch point. this.minN = (int) Math.floor(Math.max(minMean, PoissonSampler.PIVOT)); this.maxN = (int) Math.floor(Math.min(maxMean, Integer.MAX_VALUE)); values = new LargeMeanPoissonSamplerState[maxN - minN + 1]; } } /** * @param minN The minimum N covered by the cache where {@code N = (int)Math.floor(mean)}. * @param maxN The maximum N covered by the cache where {@code N = (int)Math.floor(mean)}. * @param states The precomputed states. */ private PoissonSamplerCache(int minN, int maxN, LargeMeanPoissonSamplerState[] states) { this.minN = minN; this.maxN = maxN; // Stored directly as the states were newly created within this class. this.values = states; } /** * Check the mean range. * * @param minMean The minimum mean covered by the cache. * @param maxMean The maximum mean covered by the cache. * @throws IllegalArgumentException if {@code maxMean < minMean} */ private static void checkMeanRange(double minMean, double maxMean) { // Note: // Although a mean of 0 is invalid for a Poisson sampler this case // is handled to make the cache user friendly. Any low means will // be handled by the SmallMeanPoissonSampler and not cached. // For this reason it is also OK if the means are negative. // Allow minMean == maxMean so that the cache can be used // to create samplers with distinct RNGs and the same mean. if (maxMean < minMean) { throw new IllegalArgumentException( "Max mean: " + maxMean + " < " + minMean); } } /** * Creates a new Poisson sampler. * * <p>The returned sampler will function exactly the * same as {@link PoissonSampler#of(UniformRandomProvider, double)}. * * @param rng Generator of uniformly distributed random numbers. * @param mean Mean. * @return A Poisson sampler * @throws IllegalArgumentException if {@code mean <= 0} or * {@code mean >} {@link Integer#MAX_VALUE}. * @deprecated Use {@link #createSharedStateSampler(UniformRandomProvider, double)}. */ @Deprecated public DiscreteSampler createPoissonSampler(UniformRandomProvider rng, double mean) { return createSharedStateSampler(rng, mean); } /** * Creates a new Poisson sampler. * * <p>The returned sampler will function exactly the * same as {@link PoissonSampler#of(UniformRandomProvider, double)}. * * @param rng Generator of uniformly distributed random numbers. * @param mean Mean. * @return A Poisson sampler * @throws IllegalArgumentException if {@code mean <= 0} or * {@code mean >} {@link Integer#MAX_VALUE}. * @since 1.4 */ public SharedStateDiscreteSampler createSharedStateSampler(UniformRandomProvider rng, double mean) { // Ensure the same functionality as the PoissonSampler by // using a SmallMeanPoissonSampler under the switch point. if (mean < PoissonSampler.PIVOT) { return SmallMeanPoissonSampler.of(rng, mean); } if (mean > maxN) { // Outside the range of the cache. // This avoids extra parameter checks and handles the case when // the cache is empty or if Math.floor(mean) is not an integer. return LargeMeanPoissonSampler.of(rng, mean); } // Convert the mean into an integer. final int n = (int) Math.floor(mean); if (n < minN) { // Outside the lower range of the cache. return LargeMeanPoissonSampler.of(rng, mean); } // Look in the cache for a state that can be reused. // Note: The cache is offset by minN. final int index = n - minN; final LargeMeanPoissonSamplerState state = values[index]; if (state == null) { // Create a sampler and store the state for reuse. // Do not worry about thread contention // as the state is effectively immutable. // If recomputed and replaced it will the same. final LargeMeanPoissonSampler sampler = new LargeMeanPoissonSampler(rng, mean); values[index] = sampler.getState(); return sampler; } // Compute the remaining fraction of the mean final double lambdaFractional = mean - n; return new LargeMeanPoissonSampler(rng, state, lambdaFractional); } /** * Check if the mean is within the range where the cache can minimise the * construction cost of the {@link PoissonSampler}. * * @param mean * the mean * @return true, if within the cache range */ public boolean withinRange(double mean) { if (mean < PoissonSampler.PIVOT) { // Construction is optimal return true; } // Convert the mean into an integer. final int n = (int) Math.floor(mean); return n <= maxN && n >= minN; } /** * Checks if the cache covers a valid range of mean values. * * <p>Note that the cache is only valid for one of the Poisson sampling * algorithms. In the instance that a range was requested that was too * low then there is nothing to cache and this functions returns * {@code false}. * * <p>The cache can still be used to create a {@link PoissonSampler} using * {@link #createSharedStateSampler(UniformRandomProvider, double)}. * * <p>This method can be used to determine if the cache has a potential * performance benefit. * * @return true, if the cache covers a range of mean values */ public boolean isValidRange() { return values != null; } /** * Gets the minimum mean covered by the cache. * * <p>This value is the inclusive lower bound and is equal to * the lowest integer-valued mean that is covered by the cache. * * <p>Note that this value may not match the value passed to the constructor * due to the following reasons: * * <ul> * <li>At small mean values a different algorithm is used for Poisson * sampling and the cache is unnecessary. * <li>The minimum is always an integer so may be below the constructor * minimum mean. * </ul> * * <p>If {@link #isValidRange()} returns {@code true} the cache will store * state to reduce construction cost of samplers in * the range {@link #getMinMean()} inclusive to {@link #getMaxMean()} * inclusive. Otherwise this method returns 0; * * @return The minimum mean covered by the cache. */ public double getMinMean() { return minN; } /** * Gets the maximum mean covered by the cache. * * <p>This value is the inclusive upper bound and is equal to * the double value below the first integer-valued mean that is * above range covered by the cache. * * <p>Note that this value may not match the value passed to the constructor * due to the following reasons: * <ul> * <li>At small mean values a different algorithm is used for Poisson * sampling and the cache is unnecessary. * <li>The maximum is always the double value below an integer so * may be above the constructor maximum mean. * </ul> * * <p>If {@link #isValidRange()} returns {@code true} the cache will store * state to reduce construction cost of samplers in * the range {@link #getMinMean()} inclusive to {@link #getMaxMean()} * inclusive. Otherwise this method returns 0; * * @return The maximum mean covered by the cache. */ public double getMaxMean() { if (isValidRange()) { return Math.nextDown(maxN + 1.0); } return 0; } /** * Gets the minimum mean value that can be cached. * * <p>Any {@link PoissonSampler} created with a mean below this level will not * have any state that can be cached. * * @return the minimum cached mean */ public static double getMinimumCachedMean() { return PoissonSampler.PIVOT; } /** * Create a new {@link PoissonSamplerCache} with the given range * reusing the current cache values. * * <p>This will create a new object even if the range is smaller or the * same as the current cache. * * @param minMean The minimum mean covered by the cache. * @param maxMean The maximum mean covered by the cache. * @throws IllegalArgumentException if {@code maxMean < minMean} * @return the poisson sampler cache */ public PoissonSamplerCache withRange(double minMean, double maxMean) { if (values == null) { // Nothing to reuse return new PoissonSamplerCache(minMean, maxMean); } checkMeanRange(minMean, maxMean); // The cache can only be used for the LargeMeanPoissonSampler. if (maxMean < PoissonSampler.PIVOT) { return new PoissonSamplerCache(0, 0); } // Convert the mean into integers. // Note the minimum is clipped to the algorithm switch point. final int withMinN = (int) Math.floor(Math.max(minMean, PoissonSampler.PIVOT)); final int withMaxN = (int) Math.floor(maxMean); final LargeMeanPoissonSamplerState[] states = new LargeMeanPoissonSamplerState[withMaxN - withMinN + 1]; // Preserve values from the current array to the next int currentIndex; int nextIndex; if (this.minN <= withMinN) { // The current array starts before the new array currentIndex = withMinN - this.minN; nextIndex = 0; } else { // The new array starts before the current array currentIndex = 0; nextIndex = this.minN - withMinN; } final int length = Math.min(values.length - currentIndex, states.length - nextIndex); if (length > 0) { System.arraycopy(values, currentIndex, states, nextIndex, length); } return new PoissonSamplerCache(withMinN, withMaxN, states); } }
2,996
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/GaussianSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; /** * Sampling from a Gaussian distribution with given mean and * standard deviation. * * <h2>Note</h2> * * <p>The mean and standard deviation are validated to ensure they are finite. This prevents * generation of NaN samples by avoiding invalid arithmetic (inf * 0 or inf - inf). * However use of an extremely large standard deviation and/or mean may result in samples that are * infinite; that is the parameters are not validated to prevent truncation of the output * distribution. * * @since 1.1 */ public class GaussianSampler implements SharedStateContinuousSampler { /** Mean. */ private final double mean; /** standardDeviation. */ private final double standardDeviation; /** Normalized Gaussian sampler. */ private final NormalizedGaussianSampler normalized; /** * @param normalized Generator of N(0,1) Gaussian distributed random numbers. * @param mean Mean of the Gaussian distribution. * @param standardDeviation Standard deviation of the Gaussian distribution. * @throws IllegalArgumentException if {@code standardDeviation <= 0} or is infinite; * or {@code mean} is infinite */ public GaussianSampler(NormalizedGaussianSampler normalized, double mean, double standardDeviation) { if (!(standardDeviation > 0 && standardDeviation < Double.POSITIVE_INFINITY)) { throw new IllegalArgumentException( "standard deviation is not strictly positive and finite: " + standardDeviation); } if (!Double.isFinite(mean)) { throw new IllegalArgumentException("mean is not finite: " + mean); } this.normalized = normalized; this.mean = mean; this.standardDeviation = standardDeviation; } /** * @param rng Generator of uniformly distributed random numbers. * @param source Source to copy. */ private GaussianSampler(UniformRandomProvider rng, GaussianSampler source) { this.mean = source.mean; this.standardDeviation = source.standardDeviation; this.normalized = InternalUtils.newNormalizedGaussianSampler(source.normalized, rng); } /** {@inheritDoc} */ @Override public double sample() { return standardDeviation * normalized.sample() + mean; } /** {@inheritDoc} */ @Override public String toString() { return "Gaussian deviate [" + normalized.toString() + "]"; } /** * {@inheritDoc} * * <p>Note: This function is available if the underlying {@link NormalizedGaussianSampler} * is a {@link org.apache.commons.rng.sampling.SharedStateSampler SharedStateSampler}. * Otherwise a run-time exception is thrown.</p> * * @throws UnsupportedOperationException if the underlying sampler is not a * {@link org.apache.commons.rng.sampling.SharedStateSampler SharedStateSampler} or * does not return a {@link NormalizedGaussianSampler} when sharing state. * * @since 1.3 */ @Override public SharedStateContinuousSampler withUniformRandomProvider(UniformRandomProvider rng) { return new GaussianSampler(rng, this); } /** * Create a new normalised Gaussian sampler. * * <p>Note: The shared-state functionality is available if the {@link NormalizedGaussianSampler} * is a {@link org.apache.commons.rng.sampling.SharedStateSampler SharedStateSampler}. * Otherwise a run-time exception will be thrown when the sampler is used to share state.</p> * * @param normalized Generator of N(0,1) Gaussian distributed random numbers. * @param mean Mean of the Gaussian distribution. * @param standardDeviation Standard deviation of the Gaussian distribution. * @return the sampler * @throws IllegalArgumentException if {@code standardDeviation <= 0} or is infinite; * or {@code mean} is infinite * @see #withUniformRandomProvider(UniformRandomProvider) * @since 1.3 */ public static SharedStateContinuousSampler of(NormalizedGaussianSampler normalized, double mean, double standardDeviation) { return new GaussianSampler(normalized, mean, standardDeviation); } }
2,997
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/SharedStateLongSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.sampling.SharedStateSampler; /** * Sampler that generates values of type {@code long} and can create new instances to sample * from the same state with a given source of randomness. * * @since 1.4 */ public interface SharedStateLongSampler extends LongSampler, SharedStateSampler<SharedStateLongSampler> { // Composite interface }
2,998
0
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling
Create_ds/commons-rng/commons-rng-sampling/src/main/java/org/apache/commons/rng/sampling/distribution/ZigguratSampler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import org.apache.commons.rng.UniformRandomProvider; /** * Modified ziggurat method for sampling from Gaussian and exponential distributions. * * <p>Uses the algorithm from: * * <blockquote> * McFarland, C.D. (2016)<br> * "A modified ziggurat algorithm for generating exponentially and normally distributed pseudorandom numbers".<br> * <i>Journal of Statistical Computation and Simulation</i> <b>86</b>, 1281-1294. * </blockquote> * * <p>Note: The algorithm is a modification of the * {@link ZigguratNormalizedGaussianSampler Marsaglia and Tsang "Ziggurat" method}. * The modification improves performance by: * <ol> * <li>Creating layers of the ziggurat entirely inside the probability density function (area B); * this allows the majority of samples to be obtained without checking if the value is in the * region of the ziggurat layer that requires a rejection test. * <li>For samples not within the main ziggurat (area A) alias sampling is used to choose a * layer and rejection of points above the PDF is accelerated using precomputation of * triangle regions entirely below or above the curve. * </ol> * * <pre> * \ * ----------+\ * | \ * B |A \ * -------------+\ * | \ * </pre> * * <p>Sampling uses {@link UniformRandomProvider#nextLong()}. * * @see <a href="https://www.tandfonline.com/doi/abs/10.1080/00949655.2015.1060234"> * McFarland (2016) JSCS 86, 1281-1294</a> * @since 1.4 */ public abstract class ZigguratSampler implements SharedStateContinuousSampler { /** Mask to extract the lowest 8-bits from an integer. */ private static final int MASK_INT8 = 0xff; /** Mask to create an unsigned long from a signed long. This is the maximum value of a 64-bit long. */ private static final long MAX_INT64 = Long.MAX_VALUE; /** 2^63. */ private static final double TWO_POW_63 = 0x1.0p63; /** Underlying source of randomness. */ private final UniformRandomProvider rng; // ========================================================================= // Implementation note: // // This has been adapted from the reference c implementation provided // by C.D. McFarland: // // https://github.com/cd-mcfarland/fast_prng // // The adaption was based on the reference as of July-2021. // The code uses similar naming conventions from the exponential.h and normal.h // reference. Naming has been updated to be consistent in the exponential and normal // samplers. Comments from the c source have been included. // Branch frequencies have been measured and added as comments. // // Notable changes based on performance tests across JDKs and platforms: // The generation of unsigned longs has been changed to use bit shifts to favour // the significant bits of the long. The interpolation of X and Y uses a single method. // Recursion in the exponential sampler has been avoided. // // Note: The c implementation uses a RNG where the current value can be obtained // without advancing the generator. The entry point to the sample generation // always has this value as a previously unused value. The RNG is advanced when new // bits are required. This Java implementation will generate new values with calls // to the RNG and cache the value if it is to be recycled. // // The script used to generate the tables has been modified to scale values by 2^63 // or 2^64 instead of 2^63 - 1 and 2^64 - 1. This allows a random 64-bit long to // represent a uniform value in [0, 1) as the numerator of a fraction with a value of // [0, 2^63) / 2^63 or [0, 2^64) / 2^64 respectively (the denominator is assumed). // Scaling of the high precision float values in the script is exact before // conversion to integers. // // Entries in the probability alias table are always compared to a long with the same // lower 8-bits since these bits identify the index in the table. // The entries in the IPMF tables have had the lower 8-bits set to zero. If these bits // are >= 128 then 256 is added to the alias table to round the number. The alias table // thus represents the numerator of a fraction with an unsigned magnitude of [0, 2^56 - 1) // and denominator 2^56. The numerator is effectively left-shifted 8 bits and 2^63 is // subtracted to store the value using a signed 64-bit long. // // Computation of these tables is dependent on the platform used to run the python script. // The X and Y tables are identical to 1 ULP. The MAP is identical. The IPMF table is computed // using rebalancing of the overhang probabilities to create the alias map. The table has // been observed to exhibit differences in the last 7 bits of the 56 bits used (ignoring the // final 8 bits) for the exponential and 11 bits for the normal. This corresponds to a // probability of 2^-49 (1.78e-15), or 2^-45 (2.84e-14) respectively. The tables may be // regenerated in future versions if the reference script receives updates to improve // accuracy. // // Method Description // // The ziggurat is constructed using layers that fit exactly within the probability density // function. Each layer has the same area. This area is chosen to be a fraction of the total // area under the PDF with the denominator of the fraction a power of 2. These tables // use 1/256 as the volume of each layer. The remaining part of the PDF that is not represented // by the layers is the overhang. There is an overhang above each layer and a final tail. // The following is a ziggurat with 3 layers: // // Y3 |\ // | \ j=3 // | \ // Y2 | \ // |----\ // | |\ // | i=2| \ j=2 // | | \ // Y1 |--------\ // | i=1 | \ j=1 // | | \ // Y0 |-----------\ // | i=0 | \ j=0 (tail) // +-------------- // X3 | | X0 // | X1 // X2 // // There are N layers referenced using i in [0, N). The overhangs are referenced using // j in [1, N]; j=0 is the tail. Note that N is < 256. // Information about the ziggurat is pre-computed: // X = The length of each layer (supplemented with zero for Xn) // Y = PDF(X) for each layer (supplemented with PDF(x=0) for Yn) // // Sampling is performed as: // - Pick index i in [0, 256). // - If i is a layer then return a uniform deviate multiplied by the layer length // - If i is not a layer then sample from the overhang or tail // // The overhangs and tail have different volumes. Sampling must pick a region j based the // probability p(j) = vol(j) / sum (vol(j)). This is performed using alias sampling. // (See Walker, AJ (1977) "An Efficient Method for Generating Discrete Random Variables with // General Distributions" ACM Transactions on Mathematical Software 3 (3), 253-256.) // This uses a table that has been constructed to evenly balance A categories with // probabilities around the mean into B sections each allocated the 'mean'. For the 4 // regions in the ziggurat shown above balanced into 8 sections: // // 3 // 3 // 32 // 32 // 321 // 321 => 31133322 // 3210 01233322 // // section abcdefgh // // A section with an index below the number of categories represents the category j and // optionally an alias. Sections with an index above the number // of categories are entirely filled with the alias. The region is chosen // by selecting a section and then checking if a uniform deviate is above the alias // threshold. If so then the alias is used in place of the original index. // // Alias sampling uses a table size of 256. This allows fast computation of the index // as a power of 2. The probability threshold is stored as the numerator of a fraction // allowing direct comparison with a uniform long deviate. // // MAP = Alias map for j in [0, 256) // IPMF = Alias probability threshold for j // // Note: The IPMF table is larger than the number of regions. Thus the final entries // must represent a probability of zero so that the alias is always used. // // If the selected region j is the tail then sampling uses a sampling method appropriate // for the PDF. If the selected region is an overhang then sampling generates a random // coordinate inside the rectangle covering the overhang using random deviates u1 and u2: // // X[j],Y[j] // |\-->u1 // | \ | // | \ | // | \| Overhang j (with hypotenuse not pdf(x)) // | \ // | |\ // | | \ // | u2 \ // +-------- X[j-1],Y[j-1] // // The random point (x,y) has coordinates: // x = X[j] + u1 * (X[j-1] - X[j]) // y = Y[j] + u2 * (Y[j-1] - Y[j]) // // The expressions can be evaluated from the opposite direction using (1-u), e.g: // y = Y[j-1] + (1-u2) * (Y[j] - Y[j-1]) // This allows the large value to subtract the small value before multiplying by u. // This method is used in the reference c code. It uses an addition subtraction to create 1-u. // Note that the tables X and Y have been scaled by 2^-63. This allows U to be a uniform // long in [0, 2^63). Thus the value c in 'c + m * x' must be scaled up by 2^63. // // If point (x,y) is below pdf(x) then the sample is accepted. // If u2 > u1 then the point is below the hypotenuse. // If u1 > u2 then the point is above the hypotenuse. // The distance above/below the hypotenuse is the difference u2 - u1: negative is above; // positive is below. // // The pdf(x) may lie completely above or below the hypotenuse. If the region under the pdf // is the inside then the curve is referred to as either convex (above) or concave (below). // The exponential function is concave for all regions. The normal function is convex below // x=1, and concave above x=1. x=1 is the point of inflection. // // Concave Convex // |- |---- // | - | --- // | - | -- // | -- | -- // | -- | - // | --- | - // | ---- | - // // Optimisations: // // Regions that are concave can detect a point (x,y) above the hypotenuse and reflect the // point in the hypotenuse by swapping u1 and u2. // // Regions that are convex can detect a point (x,y) below the hypotenuse and immediately accept // the sample. // // The maximum distance of pdf(x) from the hypotenuse can be precomputed. This can be done for // each region or by taking the largest distance across all regions. This value can be // compared to the distance between u1 and u2 and the point immediately accepted (concave) // or rejected (convex) as it is known to be respectively inside or outside the pdf. // This sampler uses a single value for the maximum distance of pdf(x) from the hypotenuse. // For the normal distribution this is two values to separate the maximum for convex and // concave regions. // ========================================================================= /** * Modified ziggurat method for sampling from an exponential distribution. */ public static class Exponential extends ZigguratSampler { // Ziggurat volumes: // Inside the layers = 98.4375% (252/256) // Fraction outside the layers: // concave overhangs = 96.6972% // tail = 3.3028% (x > 7.56...) /** The number of layers in the ziggurat. Maximum i value for early exit. */ private static final int I_MAX = 252; /** Maximum deviation of concave pdf(x) below the hypotenuse value for early exit. * Equal to approximately 0.0926 scaled by 2^63. */ private static final long E_MAX = 853965788476313647L; /** Beginning of tail. Equal to X[0] * 2^63. */ private static final double X_0 = 7.569274694148063; /** The alias map. An integer in [0, 255] stored as a byte to save space. * Contains the alias j for each index. j=0 is the tail; j in [1, N] is the overhang * for each layer. */ private static final byte[] MAP = { /* [ 0] */ (byte) 0, (byte) 0, (byte) 1, (byte) 235, (byte) 3, (byte) 4, (byte) 5, (byte) 0, /* [ 8] */ (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, /* [ 16] */ (byte) 0, (byte) 0, (byte) 1, (byte) 1, (byte) 1, (byte) 1, (byte) 2, (byte) 2, /* [ 24] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, /* [ 32] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, /* [ 40] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, /* [ 48] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, /* [ 56] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, /* [ 64] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, /* [ 72] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, /* [ 80] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, /* [ 88] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, /* [ 96] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, /* [104] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, /* [112] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, /* [120] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, /* [128] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, /* [136] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, /* [144] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, /* [152] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, /* [160] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, /* [168] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, /* [176] */ (byte) 252, (byte) 251, (byte) 251, (byte) 251, (byte) 251, (byte) 251, (byte) 251, (byte) 251, /* [184] */ (byte) 251, (byte) 251, (byte) 251, (byte) 251, (byte) 251, (byte) 251, (byte) 250, (byte) 250, /* [192] */ (byte) 250, (byte) 250, (byte) 250, (byte) 250, (byte) 250, (byte) 249, (byte) 249, (byte) 249, /* [200] */ (byte) 249, (byte) 249, (byte) 249, (byte) 248, (byte) 248, (byte) 248, (byte) 248, (byte) 247, /* [208] */ (byte) 247, (byte) 247, (byte) 247, (byte) 246, (byte) 246, (byte) 246, (byte) 245, (byte) 245, /* [216] */ (byte) 244, (byte) 244, (byte) 243, (byte) 243, (byte) 242, (byte) 241, (byte) 241, (byte) 240, /* [224] */ (byte) 239, (byte) 237, (byte) 3, (byte) 3, (byte) 4, (byte) 4, (byte) 6, (byte) 0, /* [232] */ (byte) 0, (byte) 0, (byte) 0, (byte) 236, (byte) 237, (byte) 238, (byte) 239, (byte) 240, /* [240] */ (byte) 241, (byte) 242, (byte) 243, (byte) 244, (byte) 245, (byte) 246, (byte) 247, (byte) 248, /* [248] */ (byte) 249, (byte) 250, (byte) 251, (byte) 252, (byte) 2, (byte) 0, (byte) 0, (byte) 0, }; /** The alias inverse PMF. This is the probability threshold to use the alias for j in-place of j. * This has been scaled by 2^64 and offset by -2^63. It represents the numerator of a fraction * with denominator 2^64 and can be compared directly to a uniform long deviate. * The value probability 0.0 is Long.MIN_VALUE and is used when {@code j > I_MAX}. */ private static final long[] IPMF = { /* [ 0] */ 9223372036854774016L, 1623796909450834944L, 2664290944894291200L, 7387971354164060928L, /* [ 4] */ 6515064486552723200L, 8840508362680718848L, 6099647593382936320L, 7673130333659513856L, /* [ 8] */ 6220332867583438080L, 5045979640552813824L, 4075305837223955456L, 3258413672162525440L, /* [ 12] */ 2560664887087762432L, 1957224924672899584L, 1429800935350577408L, 964606309710808320L, /* [ 16] */ 551043923599587072L, 180827629096890368L, -152619738120023552L, -454588624410291456L, /* [ 20] */ -729385126147774976L, -980551509819447040L, -1211029700667463936L, -1423284293868548352L, /* [ 24] */ -1619396356369050368L, -1801135830956211712L, -1970018048575618048L, -2127348289059705344L, /* [ 28] */ -2274257249303686400L, -2411729520096655360L, -2540626634159181056L, -2661705860113406464L, /* [ 32] */ -2775635634532450560L, -2883008316030465280L, -2984350790383654912L, -3080133339198116352L, /* [ 36] */ -3170777096303091200L, -3256660348483819008L, -3338123885075136256L, -3415475560473299200L, /* [ 40] */ -3488994201966428160L, -3558932970354473216L, -3625522261068041216L, -3688972217741989376L, /* [ 44] */ -3749474917563782656L, -3807206277531056128L, -3862327722496843520L, -3914987649156779776L, /* [ 48] */ -3965322714631865344L, -4013458973776895488L, -4059512885612783360L, -4103592206186241024L, /* [ 52] */ -4145796782586128128L, -4186219260694347008L, -4224945717447275264L, -4262056226866285568L, /* [ 56] */ -4297625367836519680L, -4331722680528537344L, -4364413077437472512L, -4395757214229401600L, /* [ 60] */ -4425811824915135744L, -4454630025296932608L, -4482261588141290496L, -4508753193105288192L, /* [ 64] */ -4534148654077808896L, -4558489126279958272L, -4581813295192216576L, -4604157549138257664L, /* [ 68] */ -4625556137145255168L, -4646041313519104512L, -4665643470413305856L, -4684391259530326528L, /* [ 72] */ -4702311703971761664L, -4719430301145103360L, -4735771117539946240L, -4751356876102087168L, /* [ 76] */ -4766209036859133952L, -4780347871386013440L, -4793792531638892032L, -4806561113635132672L, /* [ 80] */ -4818670716409306624L, -4830137496634465536L, -4840976719260837888L, -4851202804490348800L, /* [ 84] */ -4860829371376460032L, -4869869278311657472L, -4878334660640771072L, -4886236965617427200L, /* [ 88] */ -4893586984900802560L, -4900394884772702720L, -4906670234238885376L, -4912422031164496896L, /* [ 92] */ -4917658726580119808L, -4922388247283532288L, -4926618016851066624L, -4930354975163335168L, /* [ 96] */ -4933605596540651264L, -4936375906575303936L, -4938671497741366016L, -4940497543854575616L, /* [100] */ -4941858813449629440L, -4942759682136114944L, -4943204143989086720L, -4943195822025528064L, /* [104] */ -4942737977813206528L, -4941833520255033344L, -4940485013586738944L, -4938694684624359424L, /* [108] */ -4936464429291795968L, -4933795818458825728L, -4930690103114057984L, -4927148218896864000L, /* [112] */ -4923170790008275968L, -4918758132519213568L, -4913910257091645696L, -4908626871126539264L, /* [116] */ -4902907380349533952L, -4896750889844272896L, -4890156204540531200L, -4883121829162554368L, /* [120] */ -4875645967641781248L, -4867726521994927104L, -4859361090668103424L, -4850546966345113600L, /* [124] */ -4841281133215539200L, -4831560263698491904L, -4821380714613447424L, -4810738522790066176L, /* [128] */ -4799629400105481984L, -4788048727936307200L, -4775991551010514944L, -4763452570642114304L, /* [132] */ -4750426137329494528L, -4736906242696389120L, -4722886510751377664L, -4708360188440089088L, /* [136] */ -4693320135461421056L, -4677758813316108032L, -4661668273553489152L, -4645040145179241472L, /* [140] */ -4627865621182772224L, -4610135444140930048L, -4591839890849345536L, -4572968755929961472L, /* [144] */ -4553511334358205696L, -4533456402849101568L, -4512792200036279040L, -4491506405372580864L, /* [148] */ -4469586116675402496L, -4447017826233107968L, -4423787395382284800L, -4399880027458416384L, /* [152] */ -4375280239014115072L, -4349971829190472192L, -4323937847117721856L, -4297160557210933504L, /* [156] */ -4269621402214949888L, -4241300963840749312L, -4212178920821861632L, -4182234004204451584L, /* [160] */ -4151443949668877312L, -4119785446662287616L, -4087234084103201536L, -4053764292396156928L, /* [164] */ -4019349281473081856L, -3983960974549692672L, -3947569937258423296L, -3910145301787345664L, /* [168] */ -3871654685619032064L, -3832064104425388800L, -3791337878631544832L, -3749438533114327552L, /* [172] */ -3706326689447984384L, -3661960950051848192L, -3616297773528534784L, -3569291340409189376L, /* [176] */ -3520893408440946176L, -3471053156460654336L, -3419717015797782528L, -3366828488034805504L, /* [180] */ -3312327947826460416L, -3256152429334010368L, -3198235394669719040L, -3138506482563172864L, /* [184] */ -3076891235255162880L, -3013310801389730816L, -2947681612411374848L, -2879915029671670784L, /* [188] */ -2809916959107513856L, -2737587429961866240L, -2662820133571325696L, -2585501917733380096L, /* [192] */ -2505512231579385344L, -2422722515205211648L, -2336995527534088448L, -2248184604988727552L, /* [196] */ -2156132842510765056L, -2060672187261025536L, -1961622433929371904L, -1858790108950105600L, /* [200] */ -1751967229002895616L, -1640929916937142784L, -1525436855617582592L, -1405227557075253248L, /* [204] */ -1280020420662650112L, -1149510549536596224L, -1013367289578704896L, -871231448632104192L, /* [208] */ -722712146453667840L, -567383236774436096L, -404779231966938368L, -234390647591545856L, /* [212] */ -55658667960119296L, 132030985907841280L, 329355128892811776L, 537061298001085184L, /* [216] */ 755977262693564160L, 987022116608033280L, 1231219266829431296L, 1489711711346518528L, /* [220] */ 1763780090187553792L, 2054864117341795072L, 2364588157623768832L, 2694791916990503168L, /* [224] */ 3047567482883476224L, 3425304305830816256L, 3830744187097297920L, 4267048975685830400L, /* [228] */ 4737884547990017280L, 5247525842198998272L, 5800989391535355392L, 6404202162993295360L, /* [232] */ 7064218894258540544L, 7789505049452331520L, 8590309807749444864L, 7643763810684489984L, /* [236] */ 8891950541491446016L, 5457384281016206080L, 9083704440929284096L, 7976211653914433280L, /* [240] */ 8178631350487117568L, 2821287825726744832L, 6322989683301709568L, 4309503753387611392L, /* [244] */ 4685170734960170496L, 8404845967535199744L, 7330522972447554048L, 1960945799076992000L, /* [248] */ 4742910674644899072L, -751799822533509888L, 7023456603741959936L, 3843116882594676224L, /* [252] */ 3927231442413903104L, -9223372036854775808L, -9223372036854775808L, -9223372036854775808L, }; /** * The precomputed ziggurat lengths, denoted X_i in the main text. * <ul> * <li>X_i = length of ziggurat layer i. * <li>X_j is the upper-left X coordinate of overhang j (starting from 1). * <li>X_(j-1) is the lower-right X coordinate of overhang j. * </ul> * <p>Values have been scaled by 2^-63. * Contains {@code I_MAX + 1} entries as the final value is 0. */ private static final double[] X = { /* [ 0] */ 8.2066240675348816e-19, 7.3973732351607284e-19, 6.9133313377915293e-19, 6.5647358820964533e-19, /* [ 4] */ 6.2912539959818508e-19, 6.0657224129604964e-19, 5.8735276103737269e-19, 5.7058850528536941e-19, /* [ 8] */ 5.557094569162239e-19, 5.4232438903743953e-19, 5.3015297696508776e-19, 5.1898739257708062e-19, /* [ 12] */ 5.086692261799833e-19, 4.9907492938796469e-19, 4.9010625894449536e-19, 4.8168379010649187e-19, /* [ 16] */ 4.7374238653644714e-19, 4.6622795807196824e-19, 4.5909509017784048e-19, 4.5230527790658154e-19, /* [ 20] */ 4.458255881635396e-19, 4.3962763126368381e-19, 4.336867596710647e-19, 4.2798143618469714e-19, /* [ 24] */ 4.2249273027064889e-19, 4.172039125346411e-19, 4.1210012522465616e-19, 4.0716811225869233e-19, /* [ 28] */ 4.0239599631006903e-19, 3.9777309342877357e-19, 3.9328975785334499e-19, 3.8893725129310323e-19, /* [ 32] */ 3.8470763218720385e-19, 3.8059366138180143e-19, 3.765887213854473e-19, 3.7268674692030177e-19, /* [ 36] */ 3.6888216492248162e-19, 3.6516984248800068e-19, 3.6154504153287473e-19, 3.5800337915318032e-19, /* [ 40] */ 3.5454079284533432e-19, 3.5115350988784242e-19, 3.4783802030030962e-19, 3.4459105288907336e-19, /* [ 44] */ 3.4140955396563316e-19, 3.3829066838741162e-19, 3.3523172262289001e-19, 3.3223020958685874e-19, /* [ 48] */ 3.2928377502804472e-19, 3.2639020528202049e-19, 3.2354741622810815e-19, 3.2075344331080789e-19, /* [ 52] */ 3.1800643250478609e-19, 3.1530463211820845e-19, 3.1264638534265134e-19, 3.1003012346934211e-19, /* [ 56] */ 3.0745435970137301e-19, 3.0491768350005559e-19, 3.0241875541094565e-19, 2.999563023214455e-19, /* [ 60] */ 2.9752911310742592e-19, 2.9513603463113224e-19, 2.9277596805684267e-19, 2.9044786545442563e-19, /* [ 64] */ 2.8815072666416712e-19, 2.8588359639906928e-19, 2.8364556156331615e-19, 2.8143574876779799e-19, /* [ 68] */ 2.7925332202553125e-19, 2.7709748061152879e-19, 2.7496745707320232e-19, 2.7286251537873397e-19, /* [ 72] */ 2.7078194919206054e-19, 2.687250802641905e-19, 2.6669125693153442e-19, 2.6467985271278891e-19, /* [ 76] */ 2.6269026499668434e-19, 2.6072191381359757e-19, 2.5877424068465143e-19, 2.5684670754248168e-19, /* [ 80] */ 2.5493879571835479e-19, 2.5305000499077481e-19, 2.511798526911271e-19, 2.4932787286227806e-19, /* [ 84] */ 2.474936154663866e-19, 2.4567664563848669e-19, 2.4387654298267842e-19, 2.4209290090801527e-19, /* [ 88] */ 2.4032532600140538e-19, 2.3857343743505147e-19, 2.3683686640614648e-19, 2.3511525560671253e-19, /* [ 92] */ 2.3340825872163284e-19, 2.3171553995306794e-19, 2.3003677356958333e-19, 2.2837164347843482e-19, /* [ 96] */ 2.2671984281957174e-19, 2.2508107358001938e-19, 2.2345504622739592e-19, 2.2184147936140775e-19, /* [100] */ 2.2024009938224424e-19, 2.1865064017486842e-19, 2.1707284280826716e-19, 2.1550645524878675e-19, /* [104] */ 2.1395123208673778e-19, 2.124069342755064e-19, 2.1087332888245875e-19, 2.0935018885097035e-19, /* [108] */ 2.0783729277295508e-19, 2.0633442467130712e-19, 2.0484137379170616e-19, 2.0335793440326865e-19, /* [112] */ 2.018839056075609e-19, 2.0041909115551697e-19, 1.9896329927183254e-19, 1.975163424864309e-19, /* [116] */ 1.9607803747261946e-19, 1.9464820489157862e-19, 1.9322666924284314e-19, 1.9181325872045647e-19, /* [120] */ 1.9040780507449479e-19, 1.8901014347767504e-19, 1.8762011239677479e-19, 1.8623755346860768e-19, /* [124] */ 1.8486231138030984e-19, 1.8349423375370566e-19, 1.8213317103353295e-19, 1.8077897637931708e-19, /* [128] */ 1.7943150556069476e-19, 1.7809061685599652e-19, 1.7675617095390567e-19, 1.7542803085801941e-19, /* [132] */ 1.7410606179414531e-19, 1.727901311201724e-19, 1.7148010823836362e-19, 1.7017586450992059e-19, /* [136] */ 1.6887727317167824e-19, 1.6758420925479093e-19, 1.6629654950527621e-19, 1.6501417230628659e-19, /* [140] */ 1.6373695760198277e-19, 1.624647868228856e-19, 1.6119754281258616e-19, 1.5993510975569615e-19, /* [144] */ 1.5867737310692309e-19, 1.5742421952115544e-19, 1.5617553678444595e-19, 1.5493121374578016e-19, /* [148] */ 1.5369114024951992e-19, 1.5245520706841019e-19, 1.5122330583703858e-19, 1.4999532898563561e-19, /* [152] */ 1.4877116967410352e-19, 1.4755072172615974e-19, 1.4633387956347966e-19, 1.4512053813972103e-19, /* [156] */ 1.4391059287430991e-19, 1.4270393958586506e-19, 1.4150047442513381e-19, 1.4030009380730888e-19, /* [160] */ 1.3910269434359025e-19, 1.3790817277185197e-19, 1.3671642588626657e-19, 1.3552735046573446e-19, /* [164] */ 1.3434084320095729e-19, 1.3315680061998685e-19, 1.3197511901207148e-19, 1.3079569434961214e-19, /* [168] */ 1.2961842220802957e-19, 1.2844319768333099e-19, 1.2726991530715219e-19, 1.2609846895903523e-19, /* [172] */ 1.2492875177568625e-19, 1.237606560569394e-19, 1.2259407316813331e-19, 1.2142889343858445e-19, /* [176] */ 1.2026500605581765e-19, 1.1910229895518744e-19, 1.1794065870449425e-19, 1.1677997038316715e-19, /* [180] */ 1.1562011745554883e-19, 1.1446098163777869e-19, 1.1330244275772562e-19, 1.1214437860737343e-19, /* [184] */ 1.109866647870073e-19, 1.0982917454048923e-19, 1.0867177858084351e-19, 1.0751434490529747e-19, /* [188] */ 1.0635673859884002e-19, 1.0519882162526621e-19, 1.0404045260457141e-19, 1.0288148657544097e-19, /* [192] */ 1.0172177474144965e-19, 1.0056116419943559e-19, 9.9399497648346677e-20, 9.8236613076667446e-20, /* [196] */ 9.7072343426320094e-20, 9.5906516230690634e-20, 9.4738953224154196e-20, 9.3569469920159036e-20, /* [200] */ 9.2397875154569468e-20, 9.1223970590556472e-20, 9.0047550180852874e-20, 8.8868399582647627e-20, /* [204] */ 8.768629551976745e-20, 8.6501005086071005e-20, 8.5312284983141187e-20, 8.4119880684385214e-20, /* [208] */ 8.292352551651342e-20, 8.1722939648034506e-20, 8.0517828972839211e-20, 7.9307883875099226e-20, /* [212] */ 7.8092777859524425e-20, 7.6872166028429042e-20, 7.5645683383965122e-20, 7.4412942930179128e-20, /* [216] */ 7.3173533545093332e-20, 7.1927017587631075e-20, 7.0672928197666785e-20, 6.9410766239500362e-20, /* [220] */ 6.8139996829256425e-20, 6.6860045374610234e-20, 6.5570293040210081e-20, 6.4270071533368528e-20, /* [224] */ 6.2958657080923559e-20, 6.1635263438143136e-20, 6.02990337321517e-20, 5.8949030892850181e-20, /* [228] */ 5.758422635988593e-20, 5.6203486669597397e-20, 5.4805557413499315e-20, 5.3389043909003295e-20, /* [232] */ 5.1952387717989917e-20, 5.0493837866338355e-20, 4.9011415222629489e-20, 4.7502867933366117e-20, /* [236] */ 4.5965615001265455e-20, 4.4396673897997565e-20, 4.2792566302148588e-20, 4.1149193273430015e-20, /* [240] */ 3.9461666762606287e-20, 3.7724077131401685e-20, 3.592916408620436e-20, 3.4067836691100565e-20, /* [244] */ 3.2128447641564046e-20, 3.0095646916399994e-20, 2.7948469455598328e-20, 2.5656913048718645e-20, /* [248] */ 2.3175209756803909e-20, 2.0426695228251291e-20, 1.7261770330213488e-20, 1.3281889259442579e-20, /* [252] */ 0, }; /** * The precomputed ziggurat heights, denoted Y_i in the main text. * <ul> * <li>Y_i = height of ziggurat layer i. * <li>Y_j is the upper-left Y coordinate of overhang j (starting from 1). * <li>Y_(j-1) is the lower-right Y coordinate of overhang j. * </ul> * <p>Values have been scaled by 2^-63. * Contains {@code I_MAX + 1} entries as the final value is pdf(x=0). */ private static final double[] Y = { /* [ 0] */ 5.595205495112736e-23, 1.1802509982703313e-22, 1.8444423386735829e-22, 2.5439030466698309e-22, /* [ 4] */ 3.2737694311509334e-22, 4.0307732132706715e-22, 4.8125478319495115e-22, 5.6172914896583308e-22, /* [ 8] */ 6.4435820540443526e-22, 7.2902662343463681e-22, 8.1563888456321941e-22, 9.0411453683482223e-22, /* [ 12] */ 9.9438488486399206e-22, 1.0863906045969114e-21, 1.1800799775461269e-21, 1.2754075534831208e-21, /* [ 16] */ 1.372333117637729e-21, 1.4708208794375214e-21, 1.5708388257440445e-21, 1.6723581984374566e-21, /* [ 20] */ 1.7753530675030514e-21, 1.8797999785104595e-21, 1.9856776587832504e-21, 2.0929667704053244e-21, /* [ 24] */ 2.201649700995824e-21, 2.3117103852306179e-21, 2.4231341516125464e-21, 2.5359075901420891e-21, /* [ 28] */ 2.6500184374170538e-21, 2.7654554763660391e-21, 2.8822084483468604e-21, 3.0002679757547711e-21, /* [ 32] */ 3.1196254936130377e-21, 3.2402731888801749e-21, 3.3622039464187092e-21, 3.4854113007409036e-21, /* [ 36] */ 3.6098893927859475e-21, 3.7356329310971768e-21, 3.8626371568620053e-21, 3.9908978123552837e-21, /* [ 40] */ 4.1204111123918948e-21, 4.2511737184488913e-21, 4.3831827151633737e-21, 4.5164355889510656e-21, /* [ 44] */ 4.6509302085234806e-21, 4.7866648071096003e-21, 4.9236379662119969e-21, 5.0618486007478993e-21, /* [ 48] */ 5.2012959454434732e-21, 5.3419795423648946e-21, 5.4838992294830959e-21, 5.6270551301806347e-21, /* [ 52] */ 5.7714476436191935e-21, 5.9170774358950678e-21, 6.0639454319177027e-21, 6.2120528079531677e-21, /* [ 56] */ 6.3614009847804375e-21, 6.5119916214136427e-21, 6.6638266093481696e-21, 6.8169080672926277e-21, /* [ 60] */ 6.9712383363524377e-21, 7.1268199756340822e-21, 7.2836557582420336e-21, 7.4417486676430174e-21, /* [ 64] */ 7.6011018943746355e-21, 7.7617188330775411e-21, 7.9236030798322572e-21, 8.0867584297834842e-21, /* [ 68] */ 8.2511888750363333e-21, 8.4168986028103258e-21, 8.5838919938383098e-21, 8.7521736209986459e-21, /* [ 72] */ 8.9217482481700712e-21, 9.0926208292996504e-21, 9.2647965076751277e-21, 9.4382806153938292e-21, /* [ 76] */ 9.6130786730210328e-21, 9.7891963894314161e-21, 9.966639661827884e-21, 1.0145414575932636e-20, /* [ 80] */ 1.0325527406345955e-20, 1.0506984617068672e-20, 1.0689792862184811e-20, 1.0873958986701341e-20, /* [ 84] */ 1.10594900275424e-20, 1.1246393214695825e-20, 1.1434675972510121e-20, 1.1624345921140471e-20, /* [ 88] */ 1.1815410878142659e-20, 1.2007878860214202e-20, 1.2201758085082226e-20, 1.239705697353804e-20, /* [ 92] */ 1.2593784151618565e-20, 1.2791948452935152e-20, 1.29915589211506e-20, 1.3192624812605428e-20, /* [ 96] */ 1.3395155599094805e-20, 1.3599160970797774e-20, 1.3804650839360727e-20, 1.4011635341137284e-20, /* [100] */ 1.4220124840587164e-20, 1.4430129933836705e-20, 1.4641661452404201e-20, 1.485473046709328e-20, /* [104] */ 1.5069348292058084e-20, 1.5285526489044053e-20, 1.5503276871808626e-20, 1.5722611510726402e-20, /* [108] */ 1.5943542737583543e-20, 1.6166083150566702e-20, 1.6390245619451956e-20, 1.6616043290999594e-20, /* [112] */ 1.6843489594561079e-20, 1.7072598247904713e-20, 1.7303383263267072e-20, 1.7535858953637607e-20, /* [116] */ 1.7770039939284241e-20, 1.8005941154528286e-20, 1.8243577854777398e-20, 1.8482965623825808e-20, /* [120] */ 1.8724120381431627e-20, 1.8967058391181452e-20, 1.9211796268653192e-20, 1.9458350989888484e-20, /* [124] */ 1.9706739900186868e-20, 1.9956980723234356e-20, 2.0209091570579904e-20, 2.0463090951473895e-20, /* [128] */ 2.0718997783083593e-20, 2.097683140110135e-20, 2.123661157076213e-20, 2.1498358498287976e-20, /* [132] */ 2.1762092842777868e-20, 2.2027835728562592e-20, 2.2295608758045219e-20, 2.2565434025049041e-20, /* [136] */ 2.2837334128696004e-20, 2.311133218784001e-20, 2.3387451856080863e-20, 2.3665717337386111e-20, /* [140] */ 2.394615340234961e-20, 2.422878540511741e-20, 2.4513639301013211e-20, 2.4800741664897764e-20, /* [144] */ 2.5090119710298442e-20, 2.5381801309347597e-20, 2.56758150135705e-20, 2.5972190075566336e-20, /* [148] */ 2.6270956471628253e-20, 2.6572144925351523e-20, 2.6875786932281841e-20, 2.7181914785659148e-20, /* [152] */ 2.7490561603315974e-20, 2.7801761355793055e-20, 2.8115548895739172e-20, 2.8431959988666534e-20, /* [156] */ 2.8751031345137833e-20, 2.9072800654466307e-20, 2.9397306620015486e-20, 2.9724588996191657e-20, /* [160] */ 3.0054688627228112e-20, 3.0387647487867642e-20, 3.0723508726057078e-20, 3.1062316707775905e-20, /* [164] */ 3.1404117064129991e-20, 3.1748956740850969e-20, 3.2096884050352357e-20, 3.2447948726504914e-20, /* [168] */ 3.2802201982306013e-20, 3.3159696570631373e-20, 3.352048684827223e-20, 3.3884628843476888e-20, /* [172] */ 3.4252180327233346e-20, 3.4623200888548644e-20, 3.4997752014001677e-20, 3.537589717186906e-20, /* [176] */ 3.5757701901149035e-20, 3.6143233905835799e-20, 3.65325631548274e-20, 3.6925761987883572e-20, /* [180] */ 3.7322905228086981e-20, 3.7724070301302117e-20, 3.8129337363171041e-20, 3.8538789434235234e-20, /* [184] */ 3.8952512543827862e-20, 3.9370595883442399e-20, 3.9793131970351439e-20, 4.0220216822325769e-20, /* [188] */ 4.0651950144388133e-20, 4.1088435528630944e-20, 4.1529780668232712e-20, 4.1976097586926582e-20, /* [192] */ 4.2427502885307452e-20, 4.2884118005513604e-20, 4.3346069515987453e-20, 4.3813489418210257e-20, /* [196] */ 4.4286515477520838e-20, 4.4765291580372353e-20, 4.5249968120658306e-20, 4.5740702418054417e-20, /* [200] */ 4.6237659171683015e-20, 4.6741010952818368e-20, 4.7250938740823415e-20, 4.7767632507051219e-20, /* [204] */ 4.8291291852069895e-20, 4.8822126702292804e-20, 4.9360358072933852e-20, 4.9906218905182021e-20, /* [208] */ 5.0459954986625539e-20, 5.1021825965285324e-20, 5.1592106469178258e-20, 5.2171087345169234e-20, /* [212] */ 5.2759077033045284e-20, 5.3356403093325858e-20, 5.3963413910399511e-20, 5.4580480596259246e-20, /* [216] */ 5.5207999124535584e-20, 5.584639272987383e-20, 5.649611461419377e-20, 5.7157651009290713e-20, /* [220] */ 5.7831524654956632e-20, 5.8518298763794323e-20, 5.9218581558791713e-20, 5.99330314883387e-20, /* [224] */ 6.0662363246796887e-20, 6.1407354758435e-20, 6.2168855320499763e-20, 6.2947795150103727e-20, /* [228] */ 6.3745196643214394e-20, 6.4562187737537985e-20, 6.5400017881889097e-20, 6.6260077263309343e-20, /* [232] */ 6.714392014514662e-20, 6.8053293447301698e-20, 6.8990172088133e-20, 6.9956803158564498e-20, /* [236] */ 7.095576179487843e-20, 7.199002278894508e-20, 7.3063053739105458e-20, 7.4178938266266881e-20, /* [240] */ 7.5342542134173124e-20, 7.6559742171142969e-20, 7.783774986341285e-20, 7.9185582674029512e-20, /* [244] */ 8.06147755373533e-20, 8.2140502769818073e-20, 8.3783445978280519e-20, 8.5573129249678161e-20, /* [248] */ 8.75544596695901e-20, 8.9802388057706877e-20, 9.2462471421151086e-20, 9.5919641344951721e-20, /* [252] */ 1.0842021724855044e-19, }; /** * Specialisation which multiplies the standard exponential result by a specified mean. */ private static class ExponentialMean extends Exponential { /** Mean. */ private final double mean; /** * @param rng Generator of uniformly distributed random numbers. * @param mean Mean. */ ExponentialMean(UniformRandomProvider rng, double mean) { super(rng); this.mean = mean; } @Override public double sample() { return super.sample() * mean; } @Override public ExponentialMean withUniformRandomProvider(UniformRandomProvider rng) { return new ExponentialMean(rng, this.mean); } } /** * @param rng Generator of uniformly distributed random numbers. */ private Exponential(UniformRandomProvider rng) { super(rng); } /** {@inheritDoc} */ @Override public String toString() { return toString("exponential"); } /** {@inheritDoc} */ @Override public double sample() { // Ideally this method byte code size should be below -XX:MaxInlineSize // (which defaults to 35 bytes). This compiles to 35 bytes. final long x = nextLong(); // Float multiplication squashes these last 8 bits, so they can be used to sample i final int i = ((int) x) & MASK_INT8; if (i < I_MAX) { // Early exit. // Expected frequency = 0.984375 // Drop the sign bit to multiply by [0, 2^63). return X[i] * (x >>> 1); } // Expected frequency = 0.015625 // Tail frequency = 0.000516062 (recursion) // Overhang frequency = 0.0151089 // Recycle x as the upper 56 bits have not been used. return edgeSample(x); } /** * Create the sample from the edge of the ziggurat. * * <p>This method has been extracted to fit the main sample method within 35 bytes (the * default size for a JVM to inline a method). * * @param xx Initial random deviate * @return a sample */ private double edgeSample(long xx) { int j = selectRegion(); if (j != 0) { // Expected overhang frequency = 0.966972 return sampleOverhang(j, xx); } // Expected tail frequency = 0.033028 (recursion) // xx must be discarded as the lower bits have already been used to generate i // If the tail then exploit the memoryless property of the exponential distribution. // Perform a new sample and add it to the start of the tail. // This loop sums tail values until a sample can be returned from the exponential. // The sum is added to the final sample on return. double x0 = X_0; for (;;) { // Duplicate of the sample() method final long x = nextLong(); final int i = ((int) x) & 0xff; if (i < I_MAX) { // Early exit. return x0 + X[i] * (x >>> 1); } // Edge of the ziggurat j = selectRegion(); if (j != 0) { return x0 + sampleOverhang(j, x); } // Add another tail sample x0 += X_0; } } /** * Select the overhang region or the tail using alias sampling. * * @return the region */ private int selectRegion() { final long x = nextLong(); // j in [0, 256) final int j = ((int) x) & MASK_INT8; // map to j in [0, N] with N the number of layers of the ziggurat return x >= IPMF[j] ? MAP[j] & MASK_INT8 : j; } /** * Sample from overhang region {@code j}. * * @param j Index j (must be {@code > 0}) * @param xx Initial random deviate * @return the sample */ private double sampleOverhang(int j, long xx) { // Recycle the initial random deviate. // Shift right to make an unsigned long. long u1 = xx >>> 1; for (;;) { // Sample from the triangle: // X[j],Y[j] // |\-->u1 // | \ | // | \ | // | \| Overhang j (with hypotenuse not pdf(x)) // | \ // | |\ // | | \ // | u2 \ // +-------- X[j-1],Y[j-1] // Create a second uniform deviate (as u1 is recycled). final long u = randomInt63(); // If u2 < u1 then reflect in the hypotenuse by swapping u1 and u2. // Use conditional ternary to avoid a 50/50 branch statement to swap the pair. final long u2 = u1 < u ? u : u1; u1 = u1 < u ? u1 : u; final double x = interpolate(X, j, u1); if (u2 - u1 >= E_MAX) { // Early Exit: x < y - epsilon return x; } // Note: Frequencies have been empirically measured per call into expOverhang: // Early Exit = 0.823328 // Accept Y = 0.161930 // Reject Y = 0.0147417 (recursion) if (interpolate(Y, j, u2) <= Math.exp(-x)) { return x; } // Generate another variate for the next iteration u1 = randomInt63(); } } /** {@inheritDoc} */ @Override public Exponential withUniformRandomProvider(UniformRandomProvider rng) { return new Exponential(rng); } /** * Create a new exponential sampler with {@code mean = 1}. * * @param rng Generator of uniformly distributed random numbers. * @return the sampler */ public static Exponential of(UniformRandomProvider rng) { return new Exponential(rng); } /** * Create a new exponential sampler with the specified {@code mean}. * * @param rng Generator of uniformly distributed random numbers. * @param mean Mean. * @return the sampler * @throws IllegalArgumentException if the mean is not strictly positive ({@code mean <= 0}) */ public static Exponential of(UniformRandomProvider rng, double mean) { if (mean > 0) { return new ExponentialMean(rng, mean); } throw new IllegalArgumentException("Mean is not strictly positive: " + mean); } } /** * Modified ziggurat method for sampling from a Gaussian distribution with * mean 0 and standard deviation 1. * * <p>Note: The algorithm is a modification of the * {@link ZigguratNormalizedGaussianSampler Marsaglia and Tsang "Ziggurat" method}. * The modification improves performance of the rejection method used to generate * samples at the edge of the ziggurat. * * @see NormalizedGaussianSampler * @see GaussianSampler */ public static final class NormalizedGaussian extends ZigguratSampler implements NormalizedGaussianSampler, SharedStateContinuousSampler { // Ziggurat volumes: // Inside the layers = 98.8281% (253/256) // Fraction outside the layers: // convex overhangs = 76.1941% (x < 1) // inflection overhang = 0.1358% (x ~ 1) // concave overhangs = 21.3072% (x > 1) // tail = 2.3629% (x > 3.63...) /** The number of layers in the ziggurat. Maximum i value for early exit. */ private static final int I_MAX = 253; /** The point where the Gaussian switches from convex to concave. * This is the largest value of X[j] below 1. */ private static final int J_INFLECTION = 204; /** Maximum epsilon distance of convex pdf(x) above the hypotenuse value for early rejection. * Equal to approximately 0.2460 scaled by 2^63. This is negated on purpose as the * distance for a point (x,y) above the hypotenuse is negative: * {@code (|d| < max) == (d >= -max)}. */ private static final long CONVEX_E_MAX = -2269182951627976004L; /** Maximum distance of concave pdf(x) below the hypotenuse value for early exit. * Equal to approximately 0.08244 scaled by 2^63. */ private static final long CONCAVE_E_MAX = 760463704284035184L; /** Beginning of tail. Equal to X[0] * 2^63. */ private static final double X_0 = 3.6360066255009455861; /** 1/X_0. Used for tail sampling. */ private static final double ONE_OVER_X_0 = 1.0 / X_0; /** The alias map. An integer in [0, 255] stored as a byte to save space. * Contains the alias j for each index. j=0 is the tail; j in [1, N] is the overhang * for each layer. */ private static final byte[] MAP = { /* [ 0] */ (byte) 0, (byte) 0, (byte) 239, (byte) 2, (byte) 0, (byte) 0, (byte) 0, (byte) 0, /* [ 8] */ (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 1, (byte) 1, (byte) 1, (byte) 253, /* [ 16] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, /* [ 24] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, /* [ 32] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, /* [ 40] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, /* [ 48] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, /* [ 56] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, /* [ 64] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, /* [ 72] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, /* [ 80] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, /* [ 88] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, /* [ 96] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, /* [104] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, /* [112] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, /* [120] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, /* [128] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, /* [136] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, /* [144] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, /* [152] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, /* [160] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, /* [168] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, /* [176] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, /* [184] */ (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, (byte) 253, /* [192] */ (byte) 253, (byte) 253, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 252, /* [200] */ (byte) 252, (byte) 252, (byte) 252, (byte) 252, (byte) 251, (byte) 251, (byte) 251, (byte) 251, /* [208] */ (byte) 251, (byte) 251, (byte) 251, (byte) 250, (byte) 250, (byte) 250, (byte) 250, (byte) 250, /* [216] */ (byte) 249, (byte) 249, (byte) 249, (byte) 248, (byte) 248, (byte) 248, (byte) 247, (byte) 247, /* [224] */ (byte) 247, (byte) 246, (byte) 246, (byte) 245, (byte) 244, (byte) 244, (byte) 243, (byte) 242, /* [232] */ (byte) 240, (byte) 2, (byte) 2, (byte) 3, (byte) 3, (byte) 0, (byte) 0, (byte) 240, /* [240] */ (byte) 241, (byte) 242, (byte) 243, (byte) 244, (byte) 245, (byte) 246, (byte) 247, (byte) 248, /* [248] */ (byte) 249, (byte) 250, (byte) 251, (byte) 252, (byte) 253, (byte) 1, (byte) 0, (byte) 0, }; /** The alias inverse PMF. This is the probability threshold to use the alias for j in-place of j. * This has been scaled by 2^64 and offset by -2^63. It represents the numerator of a fraction * with denominator 2^64 and can be compared directly to a uniform long deviate. * The value probability 0.0 is Long.MIN_VALUE and is used when {@code j > I_MAX}. */ private static final long[] IPMF = { /* [ 0] */ 9223372036854775296L, 1100243796534090752L, 7866600928998383104L, 6788754710675124736L, /* [ 4] */ 9022865200181688320L, 6522434035205502208L, 4723064097360024576L, 3360495653216416000L, /* [ 8] */ 2289663232373870848L, 1423968905551920384L, 708364817827798016L, 106102487305601280L, /* [ 12] */ -408333464665794560L, -853239722779025152L, -1242095211825521408L, -1585059631105762048L, /* [ 16] */ -1889943050287169024L, -2162852901990669824L, -2408637386594511104L, -2631196530262954496L, /* [ 20] */ -2833704942520925696L, -3018774289025787392L, -3188573753472222208L, -3344920681707410944L, /* [ 24] */ -3489349705062150656L, -3623166100042179584L, -3747487436868335360L, -3863276422712173824L, /* [ 28] */ -3971367044063130880L, -4072485557029824000L, -4167267476830916608L, -4256271432240159744L, /* [ 32] */ -4339990541927306752L, -4418861817133802240L, -4493273980372377088L, -4563574004462246656L, /* [ 36] */ -4630072609770453760L, -4693048910430964992L, -4752754358862894848L, -4809416110052769536L, /* [ 40] */ -4863239903586985984L, -4914412541515875840L, -4963104028439161088L, -5009469424769119232L, /* [ 44] */ -5053650458856559360L, -5095776932695077632L, -5135967952544929024L, -5174333008451230720L, /* [ 48] */ -5210972924952654336L, -5245980700100460288L, -5279442247516297472L, -5311437055462369280L, /* [ 52] */ -5342038772315650560L, -5371315728843297024L, -5399331404632512768L, -5426144845448965120L, /* [ 56] */ -5451811038519422464L, -5476381248265593088L, -5499903320558339072L, -5522421955752311296L, /* [ 60] */ -5543978956085263616L, -5564613449659060480L, -5584362093436146432L, -5603259257517428736L, /* [ 64] */ -5621337193070986240L, -5638626184974132224L, -5655154691220933888L, -5670949470294763008L, /* [ 68] */ -5686035697601807872L, -5700437072199152384L, -5714175914219812352L, -5727273255295220992L, /* [ 72] */ -5739748920271997440L, -5751621603810412032L, -5762908939773946112L, -5773627565915007744L, /* [ 76] */ -5783793183152377600L, -5793420610475628544L, -5802523835894661376L, -5811116062947570176L, /* [ 80] */ -5819209754516120832L, -5826816672854571776L, -5833947916825278208L, -5840613956570608128L, /* [ 84] */ -5846824665591763456L, -5852589350491075328L, -5857916778480726528L, -5862815203334800384L, /* [ 88] */ -5867292388935742464L, -5871355631762284032L, -5875011781262890752L, -5878267259039093760L, /* [ 92] */ -5881128076579883520L, -5883599852028851456L, -5885687825288565248L, -5887396872144963840L, /* [ 96] */ -5888731517955042304L, -5889695949247728384L, -5890294025706689792L, -5890529289910829568L, /* [100] */ -5890404977675987456L, -5889924026487208448L, -5889089083913555968L, -5887902514965209344L, /* [104] */ -5886366408898372096L, -5884482585690639872L, -5882252601321090304L, -5879677752995027712L, /* [108] */ -5876759083794175232L, -5873497386318840832L, -5869893206505510144L, -5865946846617024256L, /* [112] */ -5861658367354159104L, -5857027590486131456L, -5852054100063428352L, -5846737243971504640L, /* [116] */ -5841076134082373632L, -5835069647234580480L, -5828716424754549248L, -5822014871949021952L, /* [120] */ -5814963157357531648L, -5807559211080072192L, -5799800723447229952L, -5791685142338073344L, /* [124] */ -5783209670985158912L, -5774371264582489344L, -5765166627072226560L, -5755592207057667840L, /* [128] */ -5745644193442049280L, -5735318510777133824L, -5724610813433666560L, -5713516480340333056L, /* [132] */ -5702030608556698112L, -5690148005851018752L, -5677863184109371904L, -5665170350903313408L, /* [136] */ -5652063400924580608L, -5638535907000141312L, -5624581109999480320L, -5610191908627599872L, /* [140] */ -5595360848093632768L, -5580080108034218752L, -5564341489875549952L, -5548136403221394688L, /* [144] */ -5531455851545399296L, -5514290416593586944L, -5496630242226406656L, -5478465016761742848L, /* [148] */ -5459783954986665216L, -5440575777891777024L, -5420828692432397824L, -5400530368638773504L, /* [152] */ -5379667916699401728L, -5358227861294116864L, -5336196115274292224L, -5313557951078385920L, /* [156] */ -5290297970633451520L, -5266400072915222272L, -5241847420214015744L, -5216622401043726592L, /* [160] */ -5190706591719534080L, -5164080714589203200L, -5136724594099067136L, -5108617109269313024L, /* [164] */ -5079736143458214912L, -5050058530461741312L, -5019559997031891968L, -4988215100963582976L, /* [168] */ -4955997165645491968L, -4922878208652041728L, -4888828866780320000L, -4853818314258475776L, /* [172] */ -4817814175855180032L, -4780782432601701888L, -4742687321746719232L, -4703491227581444608L, /* [176] */ -4663154564978699264L, -4621635653358766336L, -4578890580370785792L, -4534873055659683584L, /* [180] */ -4489534251700611840L, -4442822631898829568L, -4394683764809104128L, -4345060121983362560L, /* [184] */ -4293890858708922880L, -4241111576153830144L, -4186654061692619008L, -4130446006804747776L, /* [188] */ -4072410698657718784L, -4012466683838401024L, -3950527400305017856L, -3886500774061896704L, /* [192] */ -3820288777467837184L, -3751786943594897664L, -3680883832433527808L, -3607460442623922176L, /* [196] */ -3531389562483324160L, -3452535052891361792L, -3370751053395887872L, -3285881101633968128L, /* [200] */ -3197757155301365504L, -3106198503156485376L, -3011010550911937280L, -2911983463883580928L, /* [204] */ -2808890647470271744L, -2701487041141149952L, -2589507199690603520L, -2472663129329160192L, /* [208] */ -2350641842139870464L, -2223102583770035200L, -2089673683684728576L, -1949948966090106880L, /* [212] */ -1803483646855993856L, -1649789631480328192L, -1488330106139747584L, -1318513295725618176L, /* [216] */ -1139685236927327232L, -951121376596854784L, -752016768184775936L, -541474585642866432L, /* [220] */ -318492605725778432L, -81947227249193216L, 169425512612864512L, 437052607232193536L, /* [224] */ 722551297568809984L, 1027761939299714304L, 1354787941622770432L, 1706044619203941632L, /* [228] */ 2084319374409574144L, 2492846399593711360L, 2935400169348532480L, 3416413484613111552L, /* [232] */ 3941127949860576256L, 4515787798793437952L, 5147892401439714304L, 5846529325380406016L, /* [236] */ 6622819682216655360L, 7490522659874166016L, 8466869998277892096L, 8216968526387345408L, /* [240] */ 4550693915488934656L, 7628019504138977280L, 6605080500908005888L, 7121156327650272512L, /* [244] */ 2484871780331574272L, 7179104797032803328L, 7066086283830045440L, 1516500120817362944L, /* [248] */ 216305945438803456L, 6295963418525324544L, 2889316805630113280L, -2712587580533804032L, /* [252] */ 6562498853538167040L, 7975754821147501312L, -9223372036854775808L, -9223372036854775808L, }; /** * The precomputed ziggurat lengths, denoted X_i in the main text. * <ul> * <li>X_i = length of ziggurat layer i. * <li>X_j is the upper-left X coordinate of overhang j (starting from 1). * <li>X_(j-1) is the lower-right X coordinate of overhang j. * </ul> * <p>Values have been scaled by 2^-63. * Contains {@code I_MAX + 1} entries as the final value is 0. */ private static final double[] X = { /* [ 0] */ 3.9421662825398133e-19, 3.7204945004119012e-19, 3.5827024480628678e-19, 3.4807476236540249e-19, /* [ 4] */ 3.3990177171882136e-19, 3.3303778360340139e-19, 3.270943881761755e-19, 3.21835771324951e-19, /* [ 8] */ 3.1710758541840432e-19, 3.1280307407034065e-19, 3.0884520655804019e-19, 3.0517650624107352e-19, /* [ 12] */ 3.01752902925846e-19, 2.985398344070532e-19, 2.9550967462801797e-19, 2.9263997988491663e-19, /* [ 16] */ 2.8991225869977476e-19, 2.8731108780226291e-19, 2.8482346327101335e-19, 2.8243831535194389e-19, /* [ 20] */ 2.8014613964727031e-19, 2.7793871261807797e-19, 2.7580886921411212e-19, 2.7375032698308758e-19, /* [ 24] */ 2.7175754543391047e-19, 2.6982561247538484e-19, 2.6795015188771505e-19, 2.6612724730440033e-19, /* [ 28] */ 2.6435337927976633e-19, 2.6262537282028438e-19, 2.6094035335224142e-19, 2.5929570954331002e-19, /* [ 32] */ 2.5768906173214726e-19, 2.5611823497719608e-19, 2.5458123593393361e-19, 2.5307623292372459e-19, /* [ 36] */ 2.51601538677984e-19, 2.5015559533646191e-19, 2.4873696135403158e-19, 2.4734430003079206e-19, /* [ 40] */ 2.4597636942892726e-19, 2.446320134791245e-19, 2.4331015411139206e-19, 2.4200978427132955e-19, /* [ 44] */ 2.4072996170445879e-19, 2.3946980340903347e-19, 2.3822848067252674e-19, 2.3700521461931801e-19, /* [ 48] */ 2.357992722074133e-19, 2.3460996262069972e-19, 2.3343663401054455e-19, 2.322786705467384e-19, /* [ 52] */ 2.3113548974303765e-19, 2.3000654002704238e-19, 2.2889129852797606e-19, 2.2778926905921897e-19, /* [ 56] */ 2.2669998027527321e-19, 2.2562298398527416e-19, 2.245578536072726e-19, 2.2350418274933911e-19, /* [ 60] */ 2.2246158390513294e-19, 2.2142968725296249e-19, 2.2040813954857555e-19, 2.1939660310297601e-19, /* [ 64] */ 2.1839475483749618e-19, 2.1740228540916853e-19, 2.1641889840016519e-19, 2.1544430956570613e-19, /* [ 68] */ 2.1447824613540345e-19, 2.1352044616350571e-19, 2.1257065792395107e-19, 2.1162863934653125e-19, /* [ 72] */ 2.1069415749082026e-19, 2.0976698805483467e-19, 2.0884691491567363e-19, 2.0793372969963634e-19, /* [ 76] */ 2.0702723137954107e-19, 2.0612722589717129e-19, 2.0523352580895635e-19, 2.0434594995315797e-19, /* [ 80] */ 2.0346432313698148e-19, 2.0258847584216418e-19, 2.0171824394771313e-19, 2.0085346846857531e-19, /* [ 84] */ 1.9999399530912015e-19, 1.9913967503040585e-19, 1.9829036263028144e-19, 1.9744591733545175e-19, /* [ 88] */ 1.9660620240469857e-19, 1.9577108494251485e-19, 1.9494043572246307e-19, 1.9411412901962161e-19, /* [ 92] */ 1.9329204245152935e-19, 1.9247405682708168e-19, 1.9166005600287074e-19, 1.9084992674649826e-19, /* [ 96] */ 1.900435586064234e-19, 1.8924084378793725e-19, 1.8844167703488436e-19, 1.8764595551677749e-19, /* [100] */ 1.868535787209745e-19, 1.8606444834960934e-19, 1.8527846822098793e-19, 1.8449554417517928e-19, /* [104] */ 1.8371558398354868e-19, 1.8293849726199566e-19, 1.8216419538767393e-19, 1.8139259141898448e-19, /* [108] */ 1.8062360001864453e-19, 1.7985713737964743e-19, 1.7909312115393845e-19, 1.78331470383642e-19, /* [112] */ 1.7757210543468428e-19, 1.7681494793266395e-19, 1.760599207008314e-19, 1.7530694770004409e-19, /* [116] */ 1.7455595397057217e-19, 1.7380686557563475e-19, 1.7305960954655264e-19, 1.7231411382940904e-19, /* [120] */ 1.7157030723311378e-19, 1.7082811937877138e-19, 1.7008748065025788e-19, 1.6934832214591352e-19, /* [124] */ 1.6861057563126349e-19, 1.6787417349268046e-19, 1.6713904869190636e-19, 1.6640513472135291e-19, /* [128] */ 1.6567236556010242e-19, 1.6494067563053266e-19, 1.6420999975549115e-19, 1.6348027311594532e-19, /* [132] */ 1.6275143120903661e-19, 1.6202340980646725e-19, 1.6129614491314931e-19, 1.6056957272604589e-19, /* [136] */ 1.5984362959313479e-19, 1.5911825197242491e-19, 1.5839337639095554e-19, 1.57668939403708e-19, /* [140] */ 1.5694487755235889e-19, 1.5622112732380261e-19, 1.554976251083707e-19, 1.5477430715767271e-19, /* [144] */ 1.540511095419833e-19, 1.5332796810709688e-19, 1.5260481843056974e-19, 1.5188159577726683e-19, /* [148] */ 1.5115823505412761e-19, 1.5043467076406199e-19, 1.4971083695888395e-19, 1.4898666719118714e-19, /* [152] */ 1.4826209446506113e-19, 1.4753705118554365e-19, 1.468114691066983e-19, 1.4608527927820112e-19, /* [156] */ 1.4535841199031451e-19, 1.4463079671711862e-19, 1.4390236205786415e-19, 1.4317303567630177e-19, /* [160] */ 1.4244274423783481e-19, 1.4171141334433217e-19, 1.4097896746642792e-19, 1.4024532987312287e-19, /* [164] */ 1.3951042255849034e-19, 1.3877416616527576e-19, 1.3803647990516385e-19, 1.3729728147547174e-19, /* [168] */ 1.3655648697200824e-19, 1.3581401079782068e-19, 1.3506976556752901e-19, 1.3432366200692418e-19, /* [172] */ 1.3357560884748263e-19, 1.3282551271542047e-19, 1.3207327801488087e-19, 1.3131880680481524e-19, /* [176] */ 1.3056199866908076e-19, 1.2980275057923788e-19, 1.2904095674948608e-19, 1.2827650848312727e-19, /* [180] */ 1.2750929400989213e-19, 1.2673919831340482e-19, 1.2596610294799512e-19, 1.2518988584399374e-19, /* [184] */ 1.2441042110056523e-19, 1.2362757876504165e-19, 1.2284122459762072e-19, 1.2205121982017852e-19, /* [188] */ 1.2125742084782245e-19, 1.2045967900166973e-19, 1.196578402011802e-19, 1.1885174463419555e-19, /* [192] */ 1.1804122640264091e-19, 1.1722611314162064e-19, 1.1640622560939109e-19, 1.1558137724540874e-19, /* [196] */ 1.1475137369333185e-19, 1.1391601228549047e-19, 1.1307508148492592e-19, 1.1222836028063025e-19, /* [200] */ 1.1137561753107903e-19, 1.1051661125053526e-19, 1.0965108783189755e-19, 1.0877878119905372e-19, /* [204] */ 1.0789941188076655e-19, 1.070126859970364e-19, 1.0611829414763286e-19, 1.0521591019102928e-19, /* [208] */ 1.0430518990027552e-19, 1.0338576948035472e-19, 1.0245726392923699e-19, 1.015192652220931e-19, /* [212] */ 1.0057134029488235e-19, 9.9613028799672809e-20, 9.8643840599459914e-20, 9.7663252964755816e-20, /* [216] */ 9.6670707427623454e-20, 9.566560624086667e-20, 9.4647308380433213e-20, 9.3615125017323508e-20, /* [220] */ 9.2568314370887282e-20, 9.1506075837638774e-20, 9.0427543267725716e-20, 8.933177723376368e-20, /* [224] */ 8.8217756102327883e-20, 8.7084365674892319e-20, 8.5930387109612162e-20, 8.4754482764244349e-20, /* [228] */ 8.3555179508462343e-20, 8.2330848933585364e-20, 8.1079683729129853e-20, 7.9799669284133864e-20, /* [232] */ 7.8488549286072745e-20, 7.7143783700934692e-20, 7.5762496979467566e-20, 7.4341413578485329e-20, /* [236] */ 7.2876776807378431e-20, 7.1364245443525374e-20, 6.9798760240761066e-20, 6.8174368944799054e-20, /* [240] */ 6.6483992986198539e-20, 6.4719110345162767e-20, 6.2869314813103699e-20, 6.0921687548281263e-20, /* [244] */ 5.8859873575576818e-20, 5.6662675116090981e-20, 5.4301813630894571e-20, 5.173817174449422e-20, /* [248] */ 4.8915031722398545e-20, 4.5744741890755301e-20, 4.2078802568583416e-20, 3.7625986722404761e-20, /* [252] */ 3.1628589805881879e-20, 0, }; /** * The precomputed ziggurat heights, denoted Y_i in the main text. * <ul> * <li>Y_i = height of ziggurat layer i. * <li>Y_j is the upper-left Y coordinate of overhang j (starting from 1). * <li>Y_(j-1) is the lower-right Y coordinate of overhang j. * </ul> * <p>Values have been scaled by 2^-63. * Contains {@code I_MAX + 1} entries as the final value is pdf(x=0). */ private static final double[] Y = { /* [ 0] */ 1.4598410796619063e-22, 3.0066613427942797e-22, 4.6129728815103466e-22, 6.2663350049234362e-22, /* [ 4] */ 7.9594524761881544e-22, 9.6874655021705039e-22, 1.1446877002379439e-21, 1.3235036304379167e-21, /* [ 8] */ 1.5049857692053131e-21, 1.6889653000719298e-21, 1.8753025382711626e-21, 2.0638798423695191e-21, /* [ 12] */ 2.2545966913644708e-21, 2.4473661518801799e-21, 2.6421122727763533e-21, 2.8387681187879908e-21, /* [ 16] */ 3.0372742567457284e-21, 3.2375775699986589e-21, 3.439630315794878e-21, 3.6433893657997798e-21, /* [ 20] */ 3.8488155868912312e-21, 4.0558733309492775e-21, 4.264530010428359e-21, 4.4747557422305067e-21, /* [ 24] */ 4.6865230465355582e-21, 4.8998065902775257e-21, 5.1145829672105489e-21, 5.3308305082046173e-21, /* [ 28] */ 5.5485291167031758e-21, 5.7676601252690476e-21, 5.9882061699178461e-21, 6.2101510795442221e-21, /* [ 32] */ 6.4334797782257209e-21, 6.6581781985713897e-21, 6.8842332045893181e-21, 7.1116325227957095e-21, /* [ 36] */ 7.3403646804903092e-21, 7.5704189502886418e-21, 7.8017853001379744e-21, 8.0344543481570017e-21, /* [ 40] */ 8.2684173217333118e-21, 8.5036660203915022e-21, 8.7401927820109521e-21, 8.9779904520281901e-21, /* [ 44] */ 9.2170523553061439e-21, 9.457372270392882e-21, 9.698944405926943e-21, 9.9417633789758424e-21, /* [ 48] */ 1.0185824195119818e-20, 1.043112223011477e-20, 1.0677653212987396e-20, 1.0925413210432004e-20, /* [ 52] */ 1.1174398612392891e-20, 1.1424606118728715e-20, 1.1676032726866302e-20, 1.1928675720361027e-20, /* [ 56] */ 1.2182532658289373e-20, 1.2437601365406785e-20, 1.2693879923010674e-20, 1.2951366660454145e-20, /* [ 60] */ 1.3210060147261461e-20, 1.3469959185800733e-20, 1.3731062804473644e-20, 1.3993370251385596e-20, /* [ 64] */ 1.4256880988463136e-20, 1.4521594685988369e-20, 1.4787511217522902e-20, 1.505463065519617e-20, /* [ 68] */ 1.5322953265335218e-20, 1.5592479504415048e-20, 1.5863210015310328e-20, 1.6135145623830982e-20, /* [ 72] */ 1.6408287335525592e-20, 1.6682636332737932e-20, 1.6958193971903124e-20, 1.7234961781071113e-20, /* [ 76] */ 1.7512941457646084e-20, 1.7792134866331487e-20, 1.807254403727107e-20, 1.8354171164377277e-20, /* [ 80] */ 1.8637018603838945e-20, 1.8921088872801004e-20, 1.9206384648209468e-20, 1.9492908765815636e-20, /* [ 84] */ 1.9780664219333857e-20, 2.0069654159747839e-20, 2.0359881894760859e-20, 2.0651350888385696e-20, /* [ 88] */ 2.0944064760670539e-20, 2.1238027287557466e-20, 2.1533242400870487e-20, 2.1829714188430474e-20, /* [ 92] */ 2.2127446894294597e-20, 2.242644491911827e-20, 2.2726712820637798e-20, 2.3028255314272276e-20, /* [ 96] */ 2.3331077273843558e-20, 2.3635183732413286e-20, 2.3940579883236352e-20, 2.4247271080830277e-20, /* [100] */ 2.455526284216033e-20, 2.4864560847940368e-20, 2.5175170944049622e-20, 2.5487099143065929e-20, /* [104] */ 2.5800351625915997e-20, 2.6114934743643687e-20, 2.6430855019297323e-20, 2.6748119149937411e-20, /* [108] */ 2.7066734008766247e-20, 2.7386706647381193e-20, 2.7708044298153558e-20, 2.8030754376735269e-20, /* [112] */ 2.8354844484695747e-20, 2.8680322412291631e-20, 2.9007196141372126e-20, 2.9335473848423219e-20, /* [116] */ 2.9665163907753988e-20, 2.9996274894828624e-20, 3.0328815589748056e-20, 3.0662794980885287e-20, /* [120] */ 3.099822226867876e-20, 3.1335106869588609e-20, 3.1673458420220558e-20, 3.2013286781622988e-20, /* [124] */ 3.2354602043762612e-20, 3.2697414530184806e-20, 3.304173480286495e-20, 3.3387573667257349e-20, /* [128] */ 3.3734942177548938e-20, 3.4083851642125208e-20, 3.4434313629256243e-20, 3.4786339973011376e-20, /* [132] */ 3.5139942779411164e-20, 3.5495134432826171e-20, 3.585192760263246e-20, 3.6210335250134172e-20, /* [136] */ 3.6570370635764384e-20, 3.6932047326575882e-20, 3.7295379204034252e-20, 3.7660380472126401e-20, /* [140] */ 3.8027065665798284e-20, 3.8395449659736649e-20, 3.8765547677510167e-20, 3.9137375301086406e-20, /* [144] */ 3.9510948480742172e-20, 3.988628354538543e-20, 4.0263397213308566e-20, 4.0642306603393541e-20, /* [148] */ 4.1023029246790967e-20, 4.1405583099096438e-20, 4.1789986553048817e-20, 4.2176258451776819e-20, /* [152] */ 4.2564418102621759e-20, 4.2954485291566197e-20, 4.3346480298300118e-20, 4.3740423911958146e-20, /* [156] */ 4.4136337447563716e-20, 4.4534242763218286e-20, 4.4934162278076256e-20, 4.5336118991149025e-20, /* [160] */ 4.5740136500984466e-20, 4.6146239026271279e-20, 4.6554451427421133e-20, 4.6964799229185088e-20, /* [164] */ 4.7377308644364938e-20, 4.7792006598684169e-20, 4.8208920756888113e-20, 4.8628079550147814e-20, /* [168] */ 4.9049512204847653e-20, 4.9473248772842596e-20, 4.9899320163277674e-20, 5.0327758176068971e-20, /* [172] */ 5.0758595537153414e-20, 5.1191865935622696e-20, 5.1627604062866059e-20, 5.2065845653856416e-20, /* [176] */ 5.2506627530725194e-20, 5.2949987648783448e-20, 5.3395965145159426e-20, 5.3844600390237576e-20, /* [180] */ 5.4295935042099358e-20, 5.4750012104183868e-20, 5.5206875986405073e-20, 5.5666572569983821e-20, /* [184] */ 5.6129149276275792e-20, 5.6594655139902476e-20, 5.7063140886520563e-20, 5.7534659015596918e-20, /* [188] */ 5.8009263888591218e-20, 5.8487011822987583e-20, 5.8967961192659803e-20, 5.9452172535103471e-20, /* [192] */ 5.9939708666122605e-20, 6.0430634802618929e-20, 6.0925018694200531e-20, 6.142293076440286e-20, /* [196] */ 6.1924444262401531e-20, 6.2429635426193939e-20, 6.2938583658336214e-20, 6.3451371715447563e-20, /* [200] */ 6.3968085912834963e-20, 6.4488816345752736e-20, 6.5013657128995346e-20, 6.5542706656731714e-20, /* [204] */ 6.6076067884730717e-20, 6.6613848637404196e-20, 6.715616194241298e-20, 6.770312639595058e-20, /* [208] */ 6.8254866562246408e-20, 6.8811513411327825e-20, 6.9373204799659681e-20, 6.9940085998959109e-20, /* [212] */ 7.0512310279279503e-20, 7.1090039553397167e-20, 7.1673445090644796e-20, 7.2262708309655784e-20, /* [216] */ 7.2858021661057338e-20, 7.34595896130358e-20, 7.4067629754967553e-20, 7.4682374037052817e-20, /* [220] */ 7.5304070167226666e-20, 7.5932983190698547e-20, 7.6569397282483754e-20, 7.7213617789487678e-20, /* [224] */ 7.7865973566417016e-20, 7.8526819659456755e-20, 7.919654040385056e-20, 7.9875553017037968e-20, /* [228] */ 8.056431178890163e-20, 8.1263312996426176e-20, 8.1973100703706304e-20, 8.2694273652634034e-20, /* [232] */ 8.3427493508836792e-20, 8.4173494807453416e-20, 8.4933097052832066e-20, 8.5707219578230905e-20, /* [236] */ 8.6496899985930695e-20, 8.7303317295655327e-20, 8.8127821378859504e-20, 8.8971970928196666e-20, /* [240] */ 8.9837583239314064e-20, 9.0726800697869543e-20, 9.1642181484063544e-20, 9.2586826406702765e-20, /* [244] */ 9.3564561480278864e-20, 9.4580210012636175e-20, 9.5640015550850358e-20, 9.675233477050313e-20, /* [248] */ 9.7928851697808831e-20, 9.9186905857531331e-20, 1.0055456271343397e-19, 1.0208407377305566e-19, /* [252] */ 1.0390360993240711e-19, 1.0842021724855044e-19, }; /** Exponential sampler used for the long tail. */ private final SharedStateContinuousSampler exponential; /** * @param rng Generator of uniformly distributed random numbers. */ private NormalizedGaussian(UniformRandomProvider rng) { super(rng); exponential = ZigguratSampler.Exponential.of(rng); } /** {@inheritDoc} */ @Override public String toString() { return toString("normalized Gaussian"); } /** {@inheritDoc} */ @Override public double sample() { // Ideally this method byte code size should be below -XX:MaxInlineSize // (which defaults to 35 bytes). This compiles to 33 bytes. final long xx = nextLong(); // Float multiplication squashes these last 8 bits, so they can be used to sample i final int i = ((int) xx) & MASK_INT8; if (i < I_MAX) { // Early exit. // Expected frequency = 0.988281 return X[i] * xx; } return edgeSample(xx); } /** * Create the sample from the edge of the ziggurat. * * <p>This method has been extracted to fit the main sample method within 35 bytes (the * default size for a JVM to inline a method). * * @param xx Initial random deviate * @return a sample */ private double edgeSample(long xx) { // Expected frequency = 0.0117188 // Drop the sign bit to create u: long u1 = xx & MAX_INT64; // Extract the sign bit for use later // Use 2 - 1 or 0 - 1 final double signBit = ((xx >>> 62) & 0x2) - 1.0; final int j = selectRegion(); // Four kinds of overhangs: // j = 0 : Sample from tail // 0 < j < J_INFLECTION : Overhang is concave; only sample from Lower-Left triangle // j = J_INFLECTION : Must sample from entire overhang rectangle // j > J_INFLECTION : Overhangs are convex; implicitly accept point in Lower-Left triangle // // Conditional statements are arranged such that the more likely outcomes are first. double x; if (j > J_INFLECTION) { // Convex overhang // Expected frequency: 0.00892899 // Observed loop repeat frequency: 0.389804 for (;;) { x = interpolate(X, j, u1); // u2 = u1 + (u2 - u1) = u1 + uDistance final long uDistance = randomInt63() - u1; if (uDistance >= 0) { // Lower-left triangle break; } if (uDistance >= CONVEX_E_MAX && // Within maximum distance of f(x) from the triangle hypotenuse. // Frequency (per upper-right triangle): 0.431497 // Reject frequency: 0.489630 interpolate(Y, j, u1 + uDistance) < Math.exp(-0.5 * x * x)) { break; } // uDistance < E_MAX (upper-right triangle) or rejected as above the curve u1 = randomInt63(); } } else if (j < J_INFLECTION) { if (j == 0) { // Tail // Expected frequency: 0.000276902 // Note: Although less frequent than the next branch, j == 0 is a subset of // j < J_INFLECTION and must be first. // Observed loop repeat frequency: 0.0634786 do { x = ONE_OVER_X_0 * exponential.sample(); } while (exponential.sample() < 0.5 * x * x); x += X_0; } else { // Concave overhang // Expected frequency: 0.00249694 // Observed loop repeat frequency: 0.0123784 for (;;) { // Create a second uniform deviate (as u1 is recycled). final long u = randomInt63(); // If u2 < u1 then reflect in the hypotenuse by swapping u1 and u2. // Use conditional ternary to avoid a 50/50 branch statement to swap the pair. final long u2 = u1 < u ? u : u1; u1 = u1 < u ? u1 : u; x = interpolate(X, j, u1); if (u2 - u1 > CONCAVE_E_MAX || interpolate(Y, j, u2) < Math.exp(-0.5 * x * x)) { break; } u1 = randomInt63(); } } } else { // Inflection point // Expected frequency: 0.000015914 // Observed loop repeat frequency: 0.500213 for (;;) { x = interpolate(X, j, u1); if (interpolate(Y, j, randomInt63()) < Math.exp(-0.5 * x * x)) { break; } u1 = randomInt63(); } } return signBit * x; } /** * Select the overhang region or the tail using alias sampling. * * @return the region */ private int selectRegion() { final long x = nextLong(); // j in [0, 256) final int j = ((int) x) & MASK_INT8; // map to j in [0, N] with N the number of layers of the ziggurat return x >= IPMF[j] ? MAP[j] & MASK_INT8 : j; } /** {@inheritDoc} */ @Override public NormalizedGaussian withUniformRandomProvider(UniformRandomProvider rng) { return new NormalizedGaussian(rng); } /** * Create a new normalised Gaussian sampler. * * @param rng Generator of uniformly distributed random numbers. * @return the sampler */ public static NormalizedGaussian of(UniformRandomProvider rng) { return new NormalizedGaussian(rng); } } /** * @param rng Generator of uniformly distributed random numbers. */ ZigguratSampler(UniformRandomProvider rng) { this.rng = rng; } /** * Generate a string to represent the sampler. * * @param type Sampler type (e.g. "exponential"). * @return the string */ String toString(String type) { return "Modified ziggurat " + type + " deviate [" + rng.toString() + "]"; } /** * Generates a {@code long}. * * @return the long */ long nextLong() { return rng.nextLong(); } /** * Generates a positive {@code long} in {@code [0, 2^63)}. * * <p>In the c reference implementation RANDOM_INT63() obtains the current random value * and then advances the RNG. This implementation obtains a new value from the RNG. * Thus the java implementation must ensure a previous call to the RNG is cached * if RANDOM_INT63() is called without first advancing the RNG. * * @return the long */ long randomInt63() { return rng.nextLong() >>> 1; } /** * Compute the value of a point using linear interpolation of a data table of values * using the provided uniform deviate. * <pre> * value = v[j] + u * (v[j-1] - v[j]) * </pre> * * <p>This can be used to generate the (x,y) coordinates of a point in a rectangle * with the upper-left corner at {@code j} and lower-right corner at {@code j-1}: * * <pre>{@code * X[j],Y[j] * |\ | * | \| * | \ * | |\ Ziggurat overhang j (with hypotenuse not pdf(x)) * | | \ * | u2 \ * | \ * |-->u1 \ * +-------- X[j-1],Y[j-1] * * x = X[j] + u1 * (X[j-1] - X[j]) * y = Y[j] + u2 * (Y[j-1] - Y[j]) * }</pre> * * @param v Ziggurat data table. Values assumed to be scaled by 2^-63. * @param j Index j. Value assumed to be above zero. * @param u Uniform deviate. Value assumed to be in {@code [0, 2^63)}. * @return value */ static double interpolate(double[] v, int j, long u) { // Note: // The reference code used two methods to interpolate X and Y separately. // The c language exploited declared pointers to X and Y and used a #define construct. // This computed X identically to this method but Y as: // y = Y[j-1] + (1-u2) * (Y[j] - Y[j-1]) // Using a single method here clarifies the code. It avoids generating (1-u). // Tests show the alternative is 1 ULP different with approximately 3% frequency. // It has not been measured more than 1 ULP different. return v[j] * TWO_POW_63 + u * (v[j - 1] - v[j]); } }
2,999