codekingpro/portable-devtools
115k
1import sys
2
3import pytest
4
5import numpy as np
6from numpy import random
7from numpy.testing import assert_, assert_array_equal, assert_raises
8
9
10class TestRegression:
11
12 def test_VonMises_range(self):
13 # Make sure generated random variables are in [-pi, pi].
14 # Regression test for ticket #986.
15 for mu in np.linspace(-7., 7., 5):
16 r = random.vonmises(mu, 1, 50)
17 assert_(np.all(r > -np.pi) and np.all(r <= np.pi))
18
19 def test_hypergeometric_range(self):
20 # Test for ticket #921
21 assert_(np.all(random.hypergeometric(3, 18, 11, size=10) < 4))
22 assert_(np.all(random.hypergeometric(18, 3, 11, size=10) > 0))
23
24 # Test for ticket #5623
25 args = [
26 (2**20 - 2, 2**20 - 2, 2**20 - 2), # Check for 32-bit systems
27 ]
28 is_64bits = sys.maxsize > 2**32
29 if is_64bits and sys.platform != 'win32':
30 # Check for 64-bit systems
31 args.append((2**40 - 2, 2**40 - 2, 2**40 - 2))
32 for arg in args:
33 assert_(random.hypergeometric(*arg) > 0)
34
35 def test_logseries_convergence(self):
36 # Test for ticket #923
37 N = 1000
38 random.seed(0)
39 rvsn = random.logseries(0.8, size=N)
40 # these two frequency counts should be close to theoretical
41 # numbers with this large sample
42 # theoretical large N result is 0.49706795
43 freq = np.sum(rvsn == 1) / N
44 msg = f'Frequency was {freq:f}, should be > 0.45'
45 assert_(freq > 0.45, msg)
46 # theoretical large N result is 0.19882718
47 freq = np.sum(rvsn == 2) / N
48 msg = f'Frequency was {freq:f}, should be < 0.23'
49 assert_(freq < 0.23, msg)
50
51 def test_shuffle_mixed_dimension(self):
52 # Test for trac ticket #2074
53 for t in [[1, 2, 3, None],
54 [(1, 1), (2, 2), (3, 3), None],
55 [1, (2, 2), (3, 3), None],
56 [(1, 1), 2, 3, None]]:
57 rng = random.RandomState(12345)
58 shuffled = list(t)
59 rng.shuffle(shuffled)
60 expected = np.array([t[0], t[3], t[1], t[2]], dtype=object)
61 assert_array_equal(np.array(shuffled, dtype=object), expected)
62
63 def test_call_within_randomstate(self):
64 # Check that custom RandomState does not call into global state
65 m = random.RandomState()
66 res = np.array([0, 8, 7, 2, 1, 9, 4, 7, 0, 3])
67 for i in range(3):
68 random.seed(i)
69 m.seed(4321)
70 # If m.state is not honored, the result will change
71 assert_array_equal(m.choice(10, size=10, p=np.ones(10) / 10.), res)
72
73 def test_multivariate_normal_size_types(self):
74 # Test for multivariate_normal issue with 'size' argument.
75 # Check that the multivariate_normal size argument can be a
76 # numpy integer.
77 random.multivariate_normal([0], [[0]], size=1)
78 random.multivariate_normal([0], [[0]], size=np.int_(1))
79 random.multivariate_normal([0], [[0]], size=np.int64(1))
80
81 def test_beta_small_parameters(self):
82 # Test that beta with small a and b parameters does not produce
83 # NaNs due to roundoff errors causing 0 / 0, gh-5851
84 random.seed(1234567890)
85 x = random.beta(0.0001, 0.0001, size=100)
86 assert_(not np.any(np.isnan(x)), 'Nans in random.beta')
87
88 def test_choice_sum_of_probs_tolerance(self):
89 # The sum of probs should be 1.0 with some tolerance.
90 # For low precision dtypes the tolerance was too tight.
91 # See numpy github issue 6123.
92 random.seed(1234)
93 a = [1, 2, 3]
94 counts = [4, 4, 2]
95 for dt in np.float16, np.float32, np.float64:
96 probs = np.array(counts, dtype=dt) / sum(counts)
97 c = random.choice(a, p=probs)
98 assert_(c in a)
99 assert_raises(ValueError, random.choice, a, p=probs * 0.9)
100
101 def test_shuffle_of_array_of_different_length_strings(self):
102 # Test that permuting an array of different length strings
103 # will not cause a segfault on garbage collection
104 # Tests gh-7710
105 random.seed(1234)
106
107 a = np.array(['a', 'a' * 1000])
108
109 for _ in range(100):
110 random.shuffle(a)
111
112 # Force Garbage Collection - should not segfault.
113 import gc
114 gc.collect()
115
116 def test_shuffle_of_array_of_objects(self):
117 # Test that permuting an array of objects will not cause
118 # a segfault on garbage collection.
119 # See gh-7719
120 random.seed(1234)
121 a = np.array([np.arange(1), np.arange(4)], dtype=object)
122
123 for _ in range(1000):
124 random.shuffle(a)
125
126 # Force Garbage Collection - should not segfault.
127 import gc
128 gc.collect()
129
130 def test_permutation_subclass(self):
131 class N(np.ndarray):
132 pass
133
134 rng = random.RandomState(1)
135 orig = np.arange(3).view(N)
136 perm = rng.permutation(orig)
137 assert_array_equal(perm, np.array([0, 2, 1]))
138 assert_array_equal(orig, np.arange(3).view(N))
139
140 class M:
141 a = np.arange(5)
142
143 def __array__(self, dtype=None, copy=None):
144 return self.a
145
146 rng = random.RandomState(1)
147 m = M()
148 perm = rng.permutation(m)
149 assert_array_equal(perm, np.array([2, 1, 4, 0, 3]))
150 assert_array_equal(m.__array__(), np.arange(5))
151
152 def test_warns_byteorder(self):
153 # GH 13159
154 other_byteord_dt = '<i4' if sys.byteorder == 'big' else '>i4'
155 with pytest.deprecated_call(match='non-native byteorder is not'):
156 random.randint(0, 200, size=10, dtype=other_byteord_dt)
157
158 def test_named_argument_initialization(self):
159 # GH 13669
160 rs1 = np.random.RandomState(123456789)
161 rs2 = np.random.RandomState(seed=123456789)
162 assert rs1.randint(0, 100) == rs2.randint(0, 100)
163
164 def test_choice_retun_dtype(self):
165 # GH 9867, now long since the NumPy default changed.
166 c = np.random.choice(10, p=[.1] * 10, size=2)
167 assert c.dtype == np.dtype(np.long)
168 c = np.random.choice(10, p=[.1] * 10, replace=False, size=2)
169 assert c.dtype == np.dtype(np.long)
170 c = np.random.choice(10, size=2)
171 assert c.dtype == np.dtype(np.long)
172 c = np.random.choice(10, replace=False, size=2)
173 assert c.dtype == np.dtype(np.long)
174
175 @pytest.mark.skipif(np.iinfo('l').max < 2**32,
176 reason='Cannot test with 32-bit C long')
177 def test_randint_117(self):
178 # GH 14189
179 rng = random.RandomState(0)
180 expected = np.array([2357136044, 2546248239, 3071714933, 3626093760,
181 2588848963, 3684848379, 2340255427, 3638918503,
182 1819583497, 2678185683], dtype='int64')
183 actual = rng.randint(2**32, size=10)
184 assert_array_equal(actual, expected)
185
186 def test_p_zero_stream(self):
187 # Regression test for gh-14522. Ensure that future versions
188 # generate the same variates as version 1.16.
189 rng = random.RandomState(12345)
190 assert_array_equal(rng.binomial(1, [0, 0.25, 0.5, 0.75, 1]),
191 [0, 0, 0, 1, 1])
192
193 def test_n_zero_stream(self):
194 # Regression test for gh-14522. Ensure that future versions
195 # generate the same variates as version 1.16.
196 rng = random.RandomState(8675309)
197 expected = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
198 [3, 4, 2, 3, 3, 1, 5, 3, 1, 3]])
199 assert_array_equal(rng.binomial([[0], [10]], 0.25, size=(2, 10)),
200 expected)
201
202
203def test_multinomial_empty():
204 # gh-20483
205 # Ensure that empty p-vals are correctly handled
206 assert random.multinomial(10, []).shape == (0,)
207 assert random.multinomial(3, [], size=(7, 5, 3)).shape == (7, 5, 3, 0)
208
209
210def test_multinomial_1d_pval():
211 # gh-20483
212 with pytest.raises(TypeError, match="pvals must be a 1-d"):
213 random.multinomial(10, 0.3)
214 