test_randomstate_regression.py 7.9 KB

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