图片解析应用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2606 lines
107 KiB

  1. import sys
  2. import hashlib
  3. import pytest
  4. import numpy as np
  5. from numpy.linalg import LinAlgError
  6. from numpy.testing import (
  7. assert_, assert_raises, assert_equal, assert_allclose,
  8. assert_warns, assert_no_warnings, assert_array_equal,
  9. assert_array_almost_equal, suppress_warnings)
  10. from numpy.random import Generator, MT19937, SeedSequence, RandomState
  11. random = Generator(MT19937())
  12. JUMP_TEST_DATA = [
  13. {
  14. "seed": 0,
  15. "steps": 10,
  16. "initial": {"key_sha256": "bb1636883c2707b51c5b7fc26c6927af4430f2e0785a8c7bc886337f919f9edf", "pos": 9},
  17. "jumped": {"key_sha256": "ff682ac12bb140f2d72fba8d3506cf4e46817a0db27aae1683867629031d8d55", "pos": 598},
  18. },
  19. {
  20. "seed":384908324,
  21. "steps":312,
  22. "initial": {"key_sha256": "16b791a1e04886ccbbb4d448d6ff791267dc458ae599475d08d5cced29d11614", "pos": 311},
  23. "jumped": {"key_sha256": "a0110a2cf23b56be0feaed8f787a7fc84bef0cb5623003d75b26bdfa1c18002c", "pos": 276},
  24. },
  25. {
  26. "seed": [839438204, 980239840, 859048019, 821],
  27. "steps": 511,
  28. "initial": {"key_sha256": "d306cf01314d51bd37892d874308200951a35265ede54d200f1e065004c3e9ea", "pos": 510},
  29. "jumped": {"key_sha256": "0e00ab449f01a5195a83b4aee0dfbc2ce8d46466a640b92e33977d2e42f777f8", "pos": 475},
  30. },
  31. ]
  32. @pytest.fixture(scope='module', params=[True, False])
  33. def endpoint(request):
  34. return request.param
  35. class TestSeed:
  36. def test_scalar(self):
  37. s = Generator(MT19937(0))
  38. assert_equal(s.integers(1000), 479)
  39. s = Generator(MT19937(4294967295))
  40. assert_equal(s.integers(1000), 324)
  41. def test_array(self):
  42. s = Generator(MT19937(range(10)))
  43. assert_equal(s.integers(1000), 465)
  44. s = Generator(MT19937(np.arange(10)))
  45. assert_equal(s.integers(1000), 465)
  46. s = Generator(MT19937([0]))
  47. assert_equal(s.integers(1000), 479)
  48. s = Generator(MT19937([4294967295]))
  49. assert_equal(s.integers(1000), 324)
  50. def test_seedsequence(self):
  51. s = MT19937(SeedSequence(0))
  52. assert_equal(s.random_raw(1), 2058676884)
  53. def test_invalid_scalar(self):
  54. # seed must be an unsigned 32 bit integer
  55. assert_raises(TypeError, MT19937, -0.5)
  56. assert_raises(ValueError, MT19937, -1)
  57. def test_invalid_array(self):
  58. # seed must be an unsigned integer
  59. assert_raises(TypeError, MT19937, [-0.5])
  60. assert_raises(ValueError, MT19937, [-1])
  61. assert_raises(ValueError, MT19937, [1, -2, 4294967296])
  62. def test_noninstantized_bitgen(self):
  63. assert_raises(ValueError, Generator, MT19937)
  64. class TestBinomial:
  65. def test_n_zero(self):
  66. # Tests the corner case of n == 0 for the binomial distribution.
  67. # binomial(0, p) should be zero for any p in [0, 1].
  68. # This test addresses issue #3480.
  69. zeros = np.zeros(2, dtype='int')
  70. for p in [0, .5, 1]:
  71. assert_(random.binomial(0, p) == 0)
  72. assert_array_equal(random.binomial(zeros, p), zeros)
  73. def test_p_is_nan(self):
  74. # Issue #4571.
  75. assert_raises(ValueError, random.binomial, 1, np.nan)
  76. class TestMultinomial:
  77. def test_basic(self):
  78. random.multinomial(100, [0.2, 0.8])
  79. def test_zero_probability(self):
  80. random.multinomial(100, [0.2, 0.8, 0.0, 0.0, 0.0])
  81. def test_int_negative_interval(self):
  82. assert_(-5 <= random.integers(-5, -1) < -1)
  83. x = random.integers(-5, -1, 5)
  84. assert_(np.all(-5 <= x))
  85. assert_(np.all(x < -1))
  86. def test_size(self):
  87. # gh-3173
  88. p = [0.5, 0.5]
  89. assert_equal(random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
  90. assert_equal(random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
  91. assert_equal(random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
  92. assert_equal(random.multinomial(1, p, [2, 2]).shape, (2, 2, 2))
  93. assert_equal(random.multinomial(1, p, (2, 2)).shape, (2, 2, 2))
  94. assert_equal(random.multinomial(1, p, np.array((2, 2))).shape,
  95. (2, 2, 2))
  96. assert_raises(TypeError, random.multinomial, 1, p,
  97. float(1))
  98. def test_invalid_prob(self):
  99. assert_raises(ValueError, random.multinomial, 100, [1.1, 0.2])
  100. assert_raises(ValueError, random.multinomial, 100, [-.1, 0.9])
  101. def test_invalid_n(self):
  102. assert_raises(ValueError, random.multinomial, -1, [0.8, 0.2])
  103. assert_raises(ValueError, random.multinomial, [-1] * 10, [0.8, 0.2])
  104. def test_p_non_contiguous(self):
  105. p = np.arange(15.)
  106. p /= np.sum(p[1::3])
  107. pvals = p[1::3]
  108. random = Generator(MT19937(1432985819))
  109. non_contig = random.multinomial(100, pvals=pvals)
  110. random = Generator(MT19937(1432985819))
  111. contig = random.multinomial(100, pvals=np.ascontiguousarray(pvals))
  112. assert_array_equal(non_contig, contig)
  113. def test_multidimensional_pvals(self):
  114. assert_raises(ValueError, random.multinomial, 10, [[0, 1]])
  115. assert_raises(ValueError, random.multinomial, 10, [[0], [1]])
  116. assert_raises(ValueError, random.multinomial, 10, [[[0], [1]], [[1], [0]]])
  117. assert_raises(ValueError, random.multinomial, 10, np.array([[0, 1], [1, 0]]))
  118. def test_multinomial_pvals_float32(self):
  119. x = np.array([9.9e-01, 9.9e-01, 1.0e-09, 1.0e-09, 1.0e-09, 1.0e-09,
  120. 1.0e-09, 1.0e-09, 1.0e-09, 1.0e-09], dtype=np.float32)
  121. pvals = x / x.sum()
  122. random = Generator(MT19937(1432985819))
  123. match = r"[\w\s]*pvals array is cast to 64-bit floating"
  124. with pytest.raises(ValueError, match=match):
  125. random.multinomial(1, pvals)
  126. class TestMultivariateHypergeometric:
  127. def setup(self):
  128. self.seed = 8675309
  129. def test_argument_validation(self):
  130. # Error cases...
  131. # `colors` must be a 1-d sequence
  132. assert_raises(ValueError, random.multivariate_hypergeometric,
  133. 10, 4)
  134. # Negative nsample
  135. assert_raises(ValueError, random.multivariate_hypergeometric,
  136. [2, 3, 4], -1)
  137. # Negative color
  138. assert_raises(ValueError, random.multivariate_hypergeometric,
  139. [-1, 2, 3], 2)
  140. # nsample exceeds sum(colors)
  141. assert_raises(ValueError, random.multivariate_hypergeometric,
  142. [2, 3, 4], 10)
  143. # nsample exceeds sum(colors) (edge case of empty colors)
  144. assert_raises(ValueError, random.multivariate_hypergeometric,
  145. [], 1)
  146. # Validation errors associated with very large values in colors.
  147. assert_raises(ValueError, random.multivariate_hypergeometric,
  148. [999999999, 101], 5, 1, 'marginals')
  149. int64_info = np.iinfo(np.int64)
  150. max_int64 = int64_info.max
  151. max_int64_index = max_int64 // int64_info.dtype.itemsize
  152. assert_raises(ValueError, random.multivariate_hypergeometric,
  153. [max_int64_index - 100, 101], 5, 1, 'count')
  154. @pytest.mark.parametrize('method', ['count', 'marginals'])
  155. def test_edge_cases(self, method):
  156. # Set the seed, but in fact, all the results in this test are
  157. # deterministic, so we don't really need this.
  158. random = Generator(MT19937(self.seed))
  159. x = random.multivariate_hypergeometric([0, 0, 0], 0, method=method)
  160. assert_array_equal(x, [0, 0, 0])
  161. x = random.multivariate_hypergeometric([], 0, method=method)
  162. assert_array_equal(x, [])
  163. x = random.multivariate_hypergeometric([], 0, size=1, method=method)
  164. assert_array_equal(x, np.empty((1, 0), dtype=np.int64))
  165. x = random.multivariate_hypergeometric([1, 2, 3], 0, method=method)
  166. assert_array_equal(x, [0, 0, 0])
  167. x = random.multivariate_hypergeometric([9, 0, 0], 3, method=method)
  168. assert_array_equal(x, [3, 0, 0])
  169. colors = [1, 1, 0, 1, 1]
  170. x = random.multivariate_hypergeometric(colors, sum(colors),
  171. method=method)
  172. assert_array_equal(x, colors)
  173. x = random.multivariate_hypergeometric([3, 4, 5], 12, size=3,
  174. method=method)
  175. assert_array_equal(x, [[3, 4, 5]]*3)
  176. # Cases for nsample:
  177. # nsample < 10
  178. # 10 <= nsample < colors.sum()/2
  179. # colors.sum()/2 < nsample < colors.sum() - 10
  180. # colors.sum() - 10 < nsample < colors.sum()
  181. @pytest.mark.parametrize('nsample', [8, 25, 45, 55])
  182. @pytest.mark.parametrize('method', ['count', 'marginals'])
  183. @pytest.mark.parametrize('size', [5, (2, 3), 150000])
  184. def test_typical_cases(self, nsample, method, size):
  185. random = Generator(MT19937(self.seed))
  186. colors = np.array([10, 5, 20, 25])
  187. sample = random.multivariate_hypergeometric(colors, nsample, size,
  188. method=method)
  189. if isinstance(size, int):
  190. expected_shape = (size,) + colors.shape
  191. else:
  192. expected_shape = size + colors.shape
  193. assert_equal(sample.shape, expected_shape)
  194. assert_((sample >= 0).all())
  195. assert_((sample <= colors).all())
  196. assert_array_equal(sample.sum(axis=-1),
  197. np.full(size, fill_value=nsample, dtype=int))
  198. if isinstance(size, int) and size >= 100000:
  199. # This sample is large enough to compare its mean to
  200. # the expected values.
  201. assert_allclose(sample.mean(axis=0),
  202. nsample * colors / colors.sum(),
  203. rtol=1e-3, atol=0.005)
  204. def test_repeatability1(self):
  205. random = Generator(MT19937(self.seed))
  206. sample = random.multivariate_hypergeometric([3, 4, 5], 5, size=5,
  207. method='count')
  208. expected = np.array([[2, 1, 2],
  209. [2, 1, 2],
  210. [1, 1, 3],
  211. [2, 0, 3],
  212. [2, 1, 2]])
  213. assert_array_equal(sample, expected)
  214. def test_repeatability2(self):
  215. random = Generator(MT19937(self.seed))
  216. sample = random.multivariate_hypergeometric([20, 30, 50], 50,
  217. size=5,
  218. method='marginals')
  219. expected = np.array([[ 9, 17, 24],
  220. [ 7, 13, 30],
  221. [ 9, 15, 26],
  222. [ 9, 17, 24],
  223. [12, 14, 24]])
  224. assert_array_equal(sample, expected)
  225. def test_repeatability3(self):
  226. random = Generator(MT19937(self.seed))
  227. sample = random.multivariate_hypergeometric([20, 30, 50], 12,
  228. size=5,
  229. method='marginals')
  230. expected = np.array([[2, 3, 7],
  231. [5, 3, 4],
  232. [2, 5, 5],
  233. [5, 3, 4],
  234. [1, 5, 6]])
  235. assert_array_equal(sample, expected)
  236. class TestSetState:
  237. def setup(self):
  238. self.seed = 1234567890
  239. self.rg = Generator(MT19937(self.seed))
  240. self.bit_generator = self.rg.bit_generator
  241. self.state = self.bit_generator.state
  242. self.legacy_state = (self.state['bit_generator'],
  243. self.state['state']['key'],
  244. self.state['state']['pos'])
  245. def test_gaussian_reset(self):
  246. # Make sure the cached every-other-Gaussian is reset.
  247. old = self.rg.standard_normal(size=3)
  248. self.bit_generator.state = self.state
  249. new = self.rg.standard_normal(size=3)
  250. assert_(np.all(old == new))
  251. def test_gaussian_reset_in_media_res(self):
  252. # When the state is saved with a cached Gaussian, make sure the
  253. # cached Gaussian is restored.
  254. self.rg.standard_normal()
  255. state = self.bit_generator.state
  256. old = self.rg.standard_normal(size=3)
  257. self.bit_generator.state = state
  258. new = self.rg.standard_normal(size=3)
  259. assert_(np.all(old == new))
  260. def test_negative_binomial(self):
  261. # Ensure that the negative binomial results take floating point
  262. # arguments without truncation.
  263. self.rg.negative_binomial(0.5, 0.5)
  264. class TestIntegers:
  265. rfunc = random.integers
  266. # valid integer/boolean types
  267. itype = [bool, np.int8, np.uint8, np.int16, np.uint16,
  268. np.int32, np.uint32, np.int64, np.uint64]
  269. def test_unsupported_type(self, endpoint):
  270. assert_raises(TypeError, self.rfunc, 1, endpoint=endpoint, dtype=float)
  271. def test_bounds_checking(self, endpoint):
  272. for dt in self.itype:
  273. lbnd = 0 if dt is bool else np.iinfo(dt).min
  274. ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
  275. ubnd = ubnd - 1 if endpoint else ubnd
  276. assert_raises(ValueError, self.rfunc, lbnd - 1, ubnd,
  277. endpoint=endpoint, dtype=dt)
  278. assert_raises(ValueError, self.rfunc, lbnd, ubnd + 1,
  279. endpoint=endpoint, dtype=dt)
  280. assert_raises(ValueError, self.rfunc, ubnd, lbnd,
  281. endpoint=endpoint, dtype=dt)
  282. assert_raises(ValueError, self.rfunc, 1, 0, endpoint=endpoint,
  283. dtype=dt)
  284. assert_raises(ValueError, self.rfunc, [lbnd - 1], ubnd,
  285. endpoint=endpoint, dtype=dt)
  286. assert_raises(ValueError, self.rfunc, [lbnd], [ubnd + 1],
  287. endpoint=endpoint, dtype=dt)
  288. assert_raises(ValueError, self.rfunc, [ubnd], [lbnd],
  289. endpoint=endpoint, dtype=dt)
  290. assert_raises(ValueError, self.rfunc, 1, [0],
  291. endpoint=endpoint, dtype=dt)
  292. def test_bounds_checking_array(self, endpoint):
  293. for dt in self.itype:
  294. lbnd = 0 if dt is bool else np.iinfo(dt).min
  295. ubnd = 2 if dt is bool else np.iinfo(dt).max + (not endpoint)
  296. assert_raises(ValueError, self.rfunc, [lbnd - 1] * 2, [ubnd] * 2,
  297. endpoint=endpoint, dtype=dt)
  298. assert_raises(ValueError, self.rfunc, [lbnd] * 2,
  299. [ubnd + 1] * 2, endpoint=endpoint, dtype=dt)
  300. assert_raises(ValueError, self.rfunc, ubnd, [lbnd] * 2,
  301. endpoint=endpoint, dtype=dt)
  302. assert_raises(ValueError, self.rfunc, [1] * 2, 0,
  303. endpoint=endpoint, dtype=dt)
  304. def test_rng_zero_and_extremes(self, endpoint):
  305. for dt in self.itype:
  306. lbnd = 0 if dt is bool else np.iinfo(dt).min
  307. ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
  308. ubnd = ubnd - 1 if endpoint else ubnd
  309. is_open = not endpoint
  310. tgt = ubnd - 1
  311. assert_equal(self.rfunc(tgt, tgt + is_open, size=1000,
  312. endpoint=endpoint, dtype=dt), tgt)
  313. assert_equal(self.rfunc([tgt], tgt + is_open, size=1000,
  314. endpoint=endpoint, dtype=dt), tgt)
  315. tgt = lbnd
  316. assert_equal(self.rfunc(tgt, tgt + is_open, size=1000,
  317. endpoint=endpoint, dtype=dt), tgt)
  318. assert_equal(self.rfunc(tgt, [tgt + is_open], size=1000,
  319. endpoint=endpoint, dtype=dt), tgt)
  320. tgt = (lbnd + ubnd) // 2
  321. assert_equal(self.rfunc(tgt, tgt + is_open, size=1000,
  322. endpoint=endpoint, dtype=dt), tgt)
  323. assert_equal(self.rfunc([tgt], [tgt + is_open],
  324. size=1000, endpoint=endpoint, dtype=dt),
  325. tgt)
  326. def test_rng_zero_and_extremes_array(self, endpoint):
  327. size = 1000
  328. for dt in self.itype:
  329. lbnd = 0 if dt is bool else np.iinfo(dt).min
  330. ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
  331. ubnd = ubnd - 1 if endpoint else ubnd
  332. tgt = ubnd - 1
  333. assert_equal(self.rfunc([tgt], [tgt + 1],
  334. size=size, dtype=dt), tgt)
  335. assert_equal(self.rfunc(
  336. [tgt] * size, [tgt + 1] * size, dtype=dt), tgt)
  337. assert_equal(self.rfunc(
  338. [tgt] * size, [tgt + 1] * size, size=size, dtype=dt), tgt)
  339. tgt = lbnd
  340. assert_equal(self.rfunc([tgt], [tgt + 1],
  341. size=size, dtype=dt), tgt)
  342. assert_equal(self.rfunc(
  343. [tgt] * size, [tgt + 1] * size, dtype=dt), tgt)
  344. assert_equal(self.rfunc(
  345. [tgt] * size, [tgt + 1] * size, size=size, dtype=dt), tgt)
  346. tgt = (lbnd + ubnd) // 2
  347. assert_equal(self.rfunc([tgt], [tgt + 1],
  348. size=size, dtype=dt), tgt)
  349. assert_equal(self.rfunc(
  350. [tgt] * size, [tgt + 1] * size, dtype=dt), tgt)
  351. assert_equal(self.rfunc(
  352. [tgt] * size, [tgt + 1] * size, size=size, dtype=dt), tgt)
  353. def test_full_range(self, endpoint):
  354. # Test for ticket #1690
  355. for dt in self.itype:
  356. lbnd = 0 if dt is bool else np.iinfo(dt).min
  357. ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
  358. ubnd = ubnd - 1 if endpoint else ubnd
  359. try:
  360. self.rfunc(lbnd, ubnd, endpoint=endpoint, dtype=dt)
  361. except Exception as e:
  362. raise AssertionError("No error should have been raised, "
  363. "but one was with the following "
  364. "message:\n\n%s" % str(e))
  365. def test_full_range_array(self, endpoint):
  366. # Test for ticket #1690
  367. for dt in self.itype:
  368. lbnd = 0 if dt is bool else np.iinfo(dt).min
  369. ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
  370. ubnd = ubnd - 1 if endpoint else ubnd
  371. try:
  372. self.rfunc([lbnd] * 2, [ubnd], endpoint=endpoint, dtype=dt)
  373. except Exception as e:
  374. raise AssertionError("No error should have been raised, "
  375. "but one was with the following "
  376. "message:\n\n%s" % str(e))
  377. def test_in_bounds_fuzz(self, endpoint):
  378. # Don't use fixed seed
  379. random = Generator(MT19937())
  380. for dt in self.itype[1:]:
  381. for ubnd in [4, 8, 16]:
  382. vals = self.rfunc(2, ubnd - endpoint, size=2 ** 16,
  383. endpoint=endpoint, dtype=dt)
  384. assert_(vals.max() < ubnd)
  385. assert_(vals.min() >= 2)
  386. vals = self.rfunc(0, 2 - endpoint, size=2 ** 16, endpoint=endpoint,
  387. dtype=bool)
  388. assert_(vals.max() < 2)
  389. assert_(vals.min() >= 0)
  390. def test_scalar_array_equiv(self, endpoint):
  391. for dt in self.itype:
  392. lbnd = 0 if dt is bool else np.iinfo(dt).min
  393. ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
  394. ubnd = ubnd - 1 if endpoint else ubnd
  395. size = 1000
  396. random = Generator(MT19937(1234))
  397. scalar = random.integers(lbnd, ubnd, size=size, endpoint=endpoint,
  398. dtype=dt)
  399. random = Generator(MT19937(1234))
  400. scalar_array = random.integers([lbnd], [ubnd], size=size,
  401. endpoint=endpoint, dtype=dt)
  402. random = Generator(MT19937(1234))
  403. array = random.integers([lbnd] * size, [ubnd] *
  404. size, size=size, endpoint=endpoint, dtype=dt)
  405. assert_array_equal(scalar, scalar_array)
  406. assert_array_equal(scalar, array)
  407. def test_repeatability(self, endpoint):
  408. # We use a sha256 hash of generated sequences of 1000 samples
  409. # in the range [0, 6) for all but bool, where the range
  410. # is [0, 2). Hashes are for little endian numbers.
  411. tgt = {'bool': '053594a9b82d656f967c54869bc6970aa0358cf94ad469c81478459c6a90eee3',
  412. 'int16': '54de9072b6ee9ff7f20b58329556a46a447a8a29d67db51201bf88baa6e4e5d4',
  413. 'int32': 'd3a0d5efb04542b25ac712e50d21f39ac30f312a5052e9bbb1ad3baa791ac84b',
  414. 'int64': '14e224389ac4580bfbdccb5697d6190b496f91227cf67df60989de3d546389b1',
  415. 'int8': '0e203226ff3fbbd1580f15da4621e5f7164d0d8d6b51696dd42d004ece2cbec1',
  416. 'uint16': '54de9072b6ee9ff7f20b58329556a46a447a8a29d67db51201bf88baa6e4e5d4',
  417. 'uint32': 'd3a0d5efb04542b25ac712e50d21f39ac30f312a5052e9bbb1ad3baa791ac84b',
  418. 'uint64': '14e224389ac4580bfbdccb5697d6190b496f91227cf67df60989de3d546389b1',
  419. 'uint8': '0e203226ff3fbbd1580f15da4621e5f7164d0d8d6b51696dd42d004ece2cbec1'}
  420. for dt in self.itype[1:]:
  421. random = Generator(MT19937(1234))
  422. # view as little endian for hash
  423. if sys.byteorder == 'little':
  424. val = random.integers(0, 6 - endpoint, size=1000, endpoint=endpoint,
  425. dtype=dt)
  426. else:
  427. val = random.integers(0, 6 - endpoint, size=1000, endpoint=endpoint,
  428. dtype=dt).byteswap()
  429. res = hashlib.sha256(val).hexdigest()
  430. assert_(tgt[np.dtype(dt).name] == res)
  431. # bools do not depend on endianness
  432. random = Generator(MT19937(1234))
  433. val = random.integers(0, 2 - endpoint, size=1000, endpoint=endpoint,
  434. dtype=bool).view(np.int8)
  435. res = hashlib.sha256(val).hexdigest()
  436. assert_(tgt[np.dtype(bool).name] == res)
  437. def test_repeatability_broadcasting(self, endpoint):
  438. for dt in self.itype:
  439. lbnd = 0 if dt in (bool, np.bool_) else np.iinfo(dt).min
  440. ubnd = 2 if dt in (bool, np.bool_) else np.iinfo(dt).max + 1
  441. ubnd = ubnd - 1 if endpoint else ubnd
  442. # view as little endian for hash
  443. random = Generator(MT19937(1234))
  444. val = random.integers(lbnd, ubnd, size=1000, endpoint=endpoint,
  445. dtype=dt)
  446. random = Generator(MT19937(1234))
  447. val_bc = random.integers([lbnd] * 1000, ubnd, endpoint=endpoint,
  448. dtype=dt)
  449. assert_array_equal(val, val_bc)
  450. random = Generator(MT19937(1234))
  451. val_bc = random.integers([lbnd] * 1000, [ubnd] * 1000,
  452. endpoint=endpoint, dtype=dt)
  453. assert_array_equal(val, val_bc)
  454. @pytest.mark.parametrize(
  455. 'bound, expected',
  456. [(2**32 - 1, np.array([517043486, 1364798665, 1733884389, 1353720612,
  457. 3769704066, 1170797179, 4108474671])),
  458. (2**32, np.array([517043487, 1364798666, 1733884390, 1353720613,
  459. 3769704067, 1170797180, 4108474672])),
  460. (2**32 + 1, np.array([517043487, 1733884390, 3769704068, 4108474673,
  461. 1831631863, 1215661561, 3869512430]))]
  462. )
  463. def test_repeatability_32bit_boundary(self, bound, expected):
  464. for size in [None, len(expected)]:
  465. random = Generator(MT19937(1234))
  466. x = random.integers(bound, size=size)
  467. assert_equal(x, expected if size is not None else expected[0])
  468. def test_repeatability_32bit_boundary_broadcasting(self):
  469. desired = np.array([[[1622936284, 3620788691, 1659384060],
  470. [1417365545, 760222891, 1909653332],
  471. [3788118662, 660249498, 4092002593]],
  472. [[3625610153, 2979601262, 3844162757],
  473. [ 685800658, 120261497, 2694012896],
  474. [1207779440, 1586594375, 3854335050]],
  475. [[3004074748, 2310761796, 3012642217],
  476. [2067714190, 2786677879, 1363865881],
  477. [ 791663441, 1867303284, 2169727960]],
  478. [[1939603804, 1250951100, 298950036],
  479. [1040128489, 3791912209, 3317053765],
  480. [3155528714, 61360675, 2305155588]],
  481. [[ 817688762, 1335621943, 3288952434],
  482. [1770890872, 1102951817, 1957607470],
  483. [3099996017, 798043451, 48334215]]])
  484. for size in [None, (5, 3, 3)]:
  485. random = Generator(MT19937(12345))
  486. x = random.integers([[-1], [0], [1]],
  487. [2**32 - 1, 2**32, 2**32 + 1],
  488. size=size)
  489. assert_array_equal(x, desired if size is not None else desired[0])
  490. def test_int64_uint64_broadcast_exceptions(self, endpoint):
  491. configs = {np.uint64: ((0, 2**65), (-1, 2**62), (10, 9), (0, 0)),
  492. np.int64: ((0, 2**64), (-(2**64), 2**62), (10, 9), (0, 0),
  493. (-2**63-1, -2**63-1))}
  494. for dtype in configs:
  495. for config in configs[dtype]:
  496. low, high = config
  497. high = high - endpoint
  498. low_a = np.array([[low]*10])
  499. high_a = np.array([high] * 10)
  500. assert_raises(ValueError, random.integers, low, high,
  501. endpoint=endpoint, dtype=dtype)
  502. assert_raises(ValueError, random.integers, low_a, high,
  503. endpoint=endpoint, dtype=dtype)
  504. assert_raises(ValueError, random.integers, low, high_a,
  505. endpoint=endpoint, dtype=dtype)
  506. assert_raises(ValueError, random.integers, low_a, high_a,
  507. endpoint=endpoint, dtype=dtype)
  508. low_o = np.array([[low]*10], dtype=object)
  509. high_o = np.array([high] * 10, dtype=object)
  510. assert_raises(ValueError, random.integers, low_o, high,
  511. endpoint=endpoint, dtype=dtype)
  512. assert_raises(ValueError, random.integers, low, high_o,
  513. endpoint=endpoint, dtype=dtype)
  514. assert_raises(ValueError, random.integers, low_o, high_o,
  515. endpoint=endpoint, dtype=dtype)
  516. def test_int64_uint64_corner_case(self, endpoint):
  517. # When stored in Numpy arrays, `lbnd` is casted
  518. # as np.int64, and `ubnd` is casted as np.uint64.
  519. # Checking whether `lbnd` >= `ubnd` used to be
  520. # done solely via direct comparison, which is incorrect
  521. # because when Numpy tries to compare both numbers,
  522. # it casts both to np.float64 because there is
  523. # no integer superset of np.int64 and np.uint64. However,
  524. # `ubnd` is too large to be represented in np.float64,
  525. # causing it be round down to np.iinfo(np.int64).max,
  526. # leading to a ValueError because `lbnd` now equals
  527. # the new `ubnd`.
  528. dt = np.int64
  529. tgt = np.iinfo(np.int64).max
  530. lbnd = np.int64(np.iinfo(np.int64).max)
  531. ubnd = np.uint64(np.iinfo(np.int64).max + 1 - endpoint)
  532. # None of these function calls should
  533. # generate a ValueError now.
  534. actual = random.integers(lbnd, ubnd, endpoint=endpoint, dtype=dt)
  535. assert_equal(actual, tgt)
  536. def test_respect_dtype_singleton(self, endpoint):
  537. # See gh-7203
  538. for dt in self.itype:
  539. lbnd = 0 if dt is bool else np.iinfo(dt).min
  540. ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
  541. ubnd = ubnd - 1 if endpoint else ubnd
  542. dt = np.bool_ if dt is bool else dt
  543. sample = self.rfunc(lbnd, ubnd, endpoint=endpoint, dtype=dt)
  544. assert_equal(sample.dtype, dt)
  545. for dt in (bool, int, np.compat.long):
  546. lbnd = 0 if dt is bool else np.iinfo(dt).min
  547. ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
  548. ubnd = ubnd - 1 if endpoint else ubnd
  549. # gh-7284: Ensure that we get Python data types
  550. sample = self.rfunc(lbnd, ubnd, endpoint=endpoint, dtype=dt)
  551. assert not hasattr(sample, 'dtype')
  552. assert_equal(type(sample), dt)
  553. def test_respect_dtype_array(self, endpoint):
  554. # See gh-7203
  555. for dt in self.itype:
  556. lbnd = 0 if dt is bool else np.iinfo(dt).min
  557. ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
  558. ubnd = ubnd - 1 if endpoint else ubnd
  559. dt = np.bool_ if dt is bool else dt
  560. sample = self.rfunc([lbnd], [ubnd], endpoint=endpoint, dtype=dt)
  561. assert_equal(sample.dtype, dt)
  562. sample = self.rfunc([lbnd] * 2, [ubnd] * 2, endpoint=endpoint,
  563. dtype=dt)
  564. assert_equal(sample.dtype, dt)
  565. def test_zero_size(self, endpoint):
  566. # See gh-7203
  567. for dt in self.itype:
  568. sample = self.rfunc(0, 0, (3, 0, 4), endpoint=endpoint, dtype=dt)
  569. assert sample.shape == (3, 0, 4)
  570. assert sample.dtype == dt
  571. assert self.rfunc(0, -10, 0, endpoint=endpoint,
  572. dtype=dt).shape == (0,)
  573. assert_equal(random.integers(0, 0, size=(3, 0, 4)).shape,
  574. (3, 0, 4))
  575. assert_equal(random.integers(0, -10, size=0).shape, (0,))
  576. assert_equal(random.integers(10, 10, size=0).shape, (0,))
  577. def test_error_byteorder(self):
  578. other_byteord_dt = '<i4' if sys.byteorder == 'big' else '>i4'
  579. with pytest.raises(ValueError):
  580. random.integers(0, 200, size=10, dtype=other_byteord_dt)
  581. # chi2max is the maximum acceptable chi-squared value.
  582. @pytest.mark.slow
  583. @pytest.mark.parametrize('sample_size,high,dtype,chi2max',
  584. [(5000000, 5, np.int8, 125.0), # p-value ~4.6e-25
  585. (5000000, 7, np.uint8, 150.0), # p-value ~7.7e-30
  586. (10000000, 2500, np.int16, 3300.0), # p-value ~3.0e-25
  587. (50000000, 5000, np.uint16, 6500.0), # p-value ~3.5e-25
  588. ])
  589. def test_integers_small_dtype_chisquared(self, sample_size, high,
  590. dtype, chi2max):
  591. # Regression test for gh-14774.
  592. samples = random.integers(high, size=sample_size, dtype=dtype)
  593. values, counts = np.unique(samples, return_counts=True)
  594. expected = sample_size / high
  595. chi2 = ((counts - expected)**2 / expected).sum()
  596. assert chi2 < chi2max
  597. class TestRandomDist:
  598. # Make sure the random distribution returns the correct value for a
  599. # given seed
  600. def setup(self):
  601. self.seed = 1234567890
  602. def test_integers(self):
  603. random = Generator(MT19937(self.seed))
  604. actual = random.integers(-99, 99, size=(3, 2))
  605. desired = np.array([[-80, -56], [41, 37], [-83, -16]])
  606. assert_array_equal(actual, desired)
  607. def test_integers_masked(self):
  608. # Test masked rejection sampling algorithm to generate array of
  609. # uint32 in an interval.
  610. random = Generator(MT19937(self.seed))
  611. actual = random.integers(0, 99, size=(3, 2), dtype=np.uint32)
  612. desired = np.array([[9, 21], [70, 68], [8, 41]], dtype=np.uint32)
  613. assert_array_equal(actual, desired)
  614. def test_integers_closed(self):
  615. random = Generator(MT19937(self.seed))
  616. actual = random.integers(-99, 99, size=(3, 2), endpoint=True)
  617. desired = np.array([[-80, -56], [ 41, 38], [-83, -15]])
  618. assert_array_equal(actual, desired)
  619. def test_integers_max_int(self):
  620. # Tests whether integers with closed=True can generate the
  621. # maximum allowed Python int that can be converted
  622. # into a C long. Previous implementations of this
  623. # method have thrown an OverflowError when attempting
  624. # to generate this integer.
  625. actual = random.integers(np.iinfo('l').max, np.iinfo('l').max,
  626. endpoint=True)
  627. desired = np.iinfo('l').max
  628. assert_equal(actual, desired)
  629. def test_random(self):
  630. random = Generator(MT19937(self.seed))
  631. actual = random.random((3, 2))
  632. desired = np.array([[0.096999199829214, 0.707517457682192],
  633. [0.084364834598269, 0.767731206553125],
  634. [0.665069021359413, 0.715487190596693]])
  635. assert_array_almost_equal(actual, desired, decimal=15)
  636. random = Generator(MT19937(self.seed))
  637. actual = random.random()
  638. assert_array_almost_equal(actual, desired[0, 0], decimal=15)
  639. def test_random_float(self):
  640. random = Generator(MT19937(self.seed))
  641. actual = random.random((3, 2))
  642. desired = np.array([[0.0969992 , 0.70751746],
  643. [0.08436483, 0.76773121],
  644. [0.66506902, 0.71548719]])
  645. assert_array_almost_equal(actual, desired, decimal=7)
  646. def test_random_float_scalar(self):
  647. random = Generator(MT19937(self.seed))
  648. actual = random.random(dtype=np.float32)
  649. desired = 0.0969992
  650. assert_array_almost_equal(actual, desired, decimal=7)
  651. def test_random_unsupported_type(self):
  652. assert_raises(TypeError, random.random, dtype='int32')
  653. def test_choice_uniform_replace(self):
  654. random = Generator(MT19937(self.seed))
  655. actual = random.choice(4, 4)
  656. desired = np.array([0, 0, 2, 2], dtype=np.int64)
  657. assert_array_equal(actual, desired)
  658. def test_choice_nonuniform_replace(self):
  659. random = Generator(MT19937(self.seed))
  660. actual = random.choice(4, 4, p=[0.4, 0.4, 0.1, 0.1])
  661. desired = np.array([0, 1, 0, 1], dtype=np.int64)
  662. assert_array_equal(actual, desired)
  663. def test_choice_uniform_noreplace(self):
  664. random = Generator(MT19937(self.seed))
  665. actual = random.choice(4, 3, replace=False)
  666. desired = np.array([2, 0, 3], dtype=np.int64)
  667. assert_array_equal(actual, desired)
  668. actual = random.choice(4, 4, replace=False, shuffle=False)
  669. desired = np.arange(4, dtype=np.int64)
  670. assert_array_equal(actual, desired)
  671. def test_choice_nonuniform_noreplace(self):
  672. random = Generator(MT19937(self.seed))
  673. actual = random.choice(4, 3, replace=False, p=[0.1, 0.3, 0.5, 0.1])
  674. desired = np.array([0, 2, 3], dtype=np.int64)
  675. assert_array_equal(actual, desired)
  676. def test_choice_noninteger(self):
  677. random = Generator(MT19937(self.seed))
  678. actual = random.choice(['a', 'b', 'c', 'd'], 4)
  679. desired = np.array(['a', 'a', 'c', 'c'])
  680. assert_array_equal(actual, desired)
  681. def test_choice_multidimensional_default_axis(self):
  682. random = Generator(MT19937(self.seed))
  683. actual = random.choice([[0, 1], [2, 3], [4, 5], [6, 7]], 3)
  684. desired = np.array([[0, 1], [0, 1], [4, 5]])
  685. assert_array_equal(actual, desired)
  686. def test_choice_multidimensional_custom_axis(self):
  687. random = Generator(MT19937(self.seed))
  688. actual = random.choice([[0, 1], [2, 3], [4, 5], [6, 7]], 1, axis=1)
  689. desired = np.array([[0], [2], [4], [6]])
  690. assert_array_equal(actual, desired)
  691. def test_choice_exceptions(self):
  692. sample = random.choice
  693. assert_raises(ValueError, sample, -1, 3)
  694. assert_raises(ValueError, sample, 3., 3)
  695. assert_raises(ValueError, sample, [], 3)
  696. assert_raises(ValueError, sample, [1, 2, 3, 4], 3,
  697. p=[[0.25, 0.25], [0.25, 0.25]])
  698. assert_raises(ValueError, sample, [1, 2], 3, p=[0.4, 0.4, 0.2])
  699. assert_raises(ValueError, sample, [1, 2], 3, p=[1.1, -0.1])
  700. assert_raises(ValueError, sample, [1, 2], 3, p=[0.4, 0.4])
  701. assert_raises(ValueError, sample, [1, 2, 3], 4, replace=False)
  702. # gh-13087
  703. assert_raises(ValueError, sample, [1, 2, 3], -2, replace=False)
  704. assert_raises(ValueError, sample, [1, 2, 3], (-1,), replace=False)
  705. assert_raises(ValueError, sample, [1, 2, 3], (-1, 1), replace=False)
  706. assert_raises(ValueError, sample, [1, 2, 3], 2,
  707. replace=False, p=[1, 0, 0])
  708. def test_choice_return_shape(self):
  709. p = [0.1, 0.9]
  710. # Check scalar
  711. assert_(np.isscalar(random.choice(2, replace=True)))
  712. assert_(np.isscalar(random.choice(2, replace=False)))
  713. assert_(np.isscalar(random.choice(2, replace=True, p=p)))
  714. assert_(np.isscalar(random.choice(2, replace=False, p=p)))
  715. assert_(np.isscalar(random.choice([1, 2], replace=True)))
  716. assert_(random.choice([None], replace=True) is None)
  717. a = np.array([1, 2])
  718. arr = np.empty(1, dtype=object)
  719. arr[0] = a
  720. assert_(random.choice(arr, replace=True) is a)
  721. # Check 0-d array
  722. s = tuple()
  723. assert_(not np.isscalar(random.choice(2, s, replace=True)))
  724. assert_(not np.isscalar(random.choice(2, s, replace=False)))
  725. assert_(not np.isscalar(random.choice(2, s, replace=True, p=p)))
  726. assert_(not np.isscalar(random.choice(2, s, replace=False, p=p)))
  727. assert_(not np.isscalar(random.choice([1, 2], s, replace=True)))
  728. assert_(random.choice([None], s, replace=True).ndim == 0)
  729. a = np.array([1, 2])
  730. arr = np.empty(1, dtype=object)
  731. arr[0] = a
  732. assert_(random.choice(arr, s, replace=True).item() is a)
  733. # Check multi dimensional array
  734. s = (2, 3)
  735. p = [0.1, 0.1, 0.1, 0.1, 0.4, 0.2]
  736. assert_equal(random.choice(6, s, replace=True).shape, s)
  737. assert_equal(random.choice(6, s, replace=False).shape, s)
  738. assert_equal(random.choice(6, s, replace=True, p=p).shape, s)
  739. assert_equal(random.choice(6, s, replace=False, p=p).shape, s)
  740. assert_equal(random.choice(np.arange(6), s, replace=True).shape, s)
  741. # Check zero-size
  742. assert_equal(random.integers(0, 0, size=(3, 0, 4)).shape, (3, 0, 4))
  743. assert_equal(random.integers(0, -10, size=0).shape, (0,))
  744. assert_equal(random.integers(10, 10, size=0).shape, (0,))
  745. assert_equal(random.choice(0, size=0).shape, (0,))
  746. assert_equal(random.choice([], size=(0,)).shape, (0,))
  747. assert_equal(random.choice(['a', 'b'], size=(3, 0, 4)).shape,
  748. (3, 0, 4))
  749. assert_raises(ValueError, random.choice, [], 10)
  750. def test_choice_nan_probabilities(self):
  751. a = np.array([42, 1, 2])
  752. p = [None, None, None]
  753. assert_raises(ValueError, random.choice, a, p=p)
  754. def test_choice_p_non_contiguous(self):
  755. p = np.ones(10) / 5
  756. p[1::2] = 3.0
  757. random = Generator(MT19937(self.seed))
  758. non_contig = random.choice(5, 3, p=p[::2])
  759. random = Generator(MT19937(self.seed))
  760. contig = random.choice(5, 3, p=np.ascontiguousarray(p[::2]))
  761. assert_array_equal(non_contig, contig)
  762. def test_choice_return_type(self):
  763. # gh 9867
  764. p = np.ones(4) / 4.
  765. actual = random.choice(4, 2)
  766. assert actual.dtype == np.int64
  767. actual = random.choice(4, 2, replace=False)
  768. assert actual.dtype == np.int64
  769. actual = random.choice(4, 2, p=p)
  770. assert actual.dtype == np.int64
  771. actual = random.choice(4, 2, p=p, replace=False)
  772. assert actual.dtype == np.int64
  773. def test_choice_large_sample(self):
  774. choice_hash = '4266599d12bfcfb815213303432341c06b4349f5455890446578877bb322e222'
  775. random = Generator(MT19937(self.seed))
  776. actual = random.choice(10000, 5000, replace=False)
  777. if sys.byteorder != 'little':
  778. actual = actual.byteswap()
  779. res = hashlib.sha256(actual.view(np.int8)).hexdigest()
  780. assert_(choice_hash == res)
  781. def test_bytes(self):
  782. random = Generator(MT19937(self.seed))
  783. actual = random.bytes(10)
  784. desired = b'\x86\xf0\xd4\x18\xe1\x81\t8%\xdd'
  785. assert_equal(actual, desired)
  786. def test_shuffle(self):
  787. # Test lists, arrays (of various dtypes), and multidimensional versions
  788. # of both, c-contiguous or not:
  789. for conv in [lambda x: np.array([]),
  790. lambda x: x,
  791. lambda x: np.asarray(x).astype(np.int8),
  792. lambda x: np.asarray(x).astype(np.float32),
  793. lambda x: np.asarray(x).astype(np.complex64),
  794. lambda x: np.asarray(x).astype(object),
  795. lambda x: [(i, i) for i in x],
  796. lambda x: np.asarray([[i, i] for i in x]),
  797. lambda x: np.vstack([x, x]).T,
  798. # gh-11442
  799. lambda x: (np.asarray([(i, i) for i in x],
  800. [("a", int), ("b", int)])
  801. .view(np.recarray)),
  802. # gh-4270
  803. lambda x: np.asarray([(i, i) for i in x],
  804. [("a", object, (1,)),
  805. ("b", np.int32, (1,))])]:
  806. random = Generator(MT19937(self.seed))
  807. alist = conv([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])
  808. random.shuffle(alist)
  809. actual = alist
  810. desired = conv([4, 1, 9, 8, 0, 5, 3, 6, 2, 7])
  811. assert_array_equal(actual, desired)
  812. def test_shuffle_custom_axis(self):
  813. random = Generator(MT19937(self.seed))
  814. actual = np.arange(16).reshape((4, 4))
  815. random.shuffle(actual, axis=1)
  816. desired = np.array([[ 0, 3, 1, 2],
  817. [ 4, 7, 5, 6],
  818. [ 8, 11, 9, 10],
  819. [12, 15, 13, 14]])
  820. assert_array_equal(actual, desired)
  821. random = Generator(MT19937(self.seed))
  822. actual = np.arange(16).reshape((4, 4))
  823. random.shuffle(actual, axis=-1)
  824. assert_array_equal(actual, desired)
  825. def test_shuffle_custom_axis_empty(self):
  826. random = Generator(MT19937(self.seed))
  827. desired = np.array([]).reshape((0, 6))
  828. for axis in (0, 1):
  829. actual = np.array([]).reshape((0, 6))
  830. random.shuffle(actual, axis=axis)
  831. assert_array_equal(actual, desired)
  832. def test_shuffle_axis_nonsquare(self):
  833. y1 = np.arange(20).reshape(2, 10)
  834. y2 = y1.copy()
  835. random = Generator(MT19937(self.seed))
  836. random.shuffle(y1, axis=1)
  837. random = Generator(MT19937(self.seed))
  838. random.shuffle(y2.T)
  839. assert_array_equal(y1, y2)
  840. def test_shuffle_masked(self):
  841. # gh-3263
  842. a = np.ma.masked_values(np.reshape(range(20), (5, 4)) % 3 - 1, -1)
  843. b = np.ma.masked_values(np.arange(20) % 3 - 1, -1)
  844. a_orig = a.copy()
  845. b_orig = b.copy()
  846. for i in range(50):
  847. random.shuffle(a)
  848. assert_equal(
  849. sorted(a.data[~a.mask]), sorted(a_orig.data[~a_orig.mask]))
  850. random.shuffle(b)
  851. assert_equal(
  852. sorted(b.data[~b.mask]), sorted(b_orig.data[~b_orig.mask]))
  853. def test_shuffle_exceptions(self):
  854. random = Generator(MT19937(self.seed))
  855. arr = np.arange(10)
  856. assert_raises(np.AxisError, random.shuffle, arr, 1)
  857. arr = np.arange(9).reshape((3, 3))
  858. assert_raises(np.AxisError, random.shuffle, arr, 3)
  859. assert_raises(TypeError, random.shuffle, arr, slice(1, 2, None))
  860. arr = [[1, 2, 3], [4, 5, 6]]
  861. assert_raises(NotImplementedError, random.shuffle, arr, 1)
  862. arr = np.array(3)
  863. assert_raises(TypeError, random.shuffle, arr)
  864. arr = np.ones((3, 2))
  865. assert_raises(np.AxisError, random.shuffle, arr, 2)
  866. def test_permutation(self):
  867. random = Generator(MT19937(self.seed))
  868. alist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
  869. actual = random.permutation(alist)
  870. desired = [4, 1, 9, 8, 0, 5, 3, 6, 2, 7]
  871. assert_array_equal(actual, desired)
  872. random = Generator(MT19937(self.seed))
  873. arr_2d = np.atleast_2d([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]).T
  874. actual = random.permutation(arr_2d)
  875. assert_array_equal(actual, np.atleast_2d(desired).T)
  876. bad_x_str = "abcd"
  877. assert_raises(np.AxisError, random.permutation, bad_x_str)
  878. bad_x_float = 1.2
  879. assert_raises(np.AxisError, random.permutation, bad_x_float)
  880. random = Generator(MT19937(self.seed))
  881. integer_val = 10
  882. desired = [3, 0, 8, 7, 9, 4, 2, 5, 1, 6]
  883. actual = random.permutation(integer_val)
  884. assert_array_equal(actual, desired)
  885. def test_permutation_custom_axis(self):
  886. a = np.arange(16).reshape((4, 4))
  887. desired = np.array([[ 0, 3, 1, 2],
  888. [ 4, 7, 5, 6],
  889. [ 8, 11, 9, 10],
  890. [12, 15, 13, 14]])
  891. random = Generator(MT19937(self.seed))
  892. actual = random.permutation(a, axis=1)
  893. assert_array_equal(actual, desired)
  894. random = Generator(MT19937(self.seed))
  895. actual = random.permutation(a, axis=-1)
  896. assert_array_equal(actual, desired)
  897. def test_permutation_exceptions(self):
  898. random = Generator(MT19937(self.seed))
  899. arr = np.arange(10)
  900. assert_raises(np.AxisError, random.permutation, arr, 1)
  901. arr = np.arange(9).reshape((3, 3))
  902. assert_raises(np.AxisError, random.permutation, arr, 3)
  903. assert_raises(TypeError, random.permutation, arr, slice(1, 2, None))
  904. @pytest.mark.parametrize("dtype", [int, object])
  905. @pytest.mark.parametrize("axis, expected",
  906. [(None, np.array([[3, 7, 0, 9, 10, 11],
  907. [8, 4, 2, 5, 1, 6]])),
  908. (0, np.array([[6, 1, 2, 9, 10, 11],
  909. [0, 7, 8, 3, 4, 5]])),
  910. (1, np.array([[ 5, 3, 4, 0, 2, 1],
  911. [11, 9, 10, 6, 8, 7]]))])
  912. def test_permuted(self, dtype, axis, expected):
  913. random = Generator(MT19937(self.seed))
  914. x = np.arange(12).reshape(2, 6).astype(dtype)
  915. random.permuted(x, axis=axis, out=x)
  916. assert_array_equal(x, expected)
  917. random = Generator(MT19937(self.seed))
  918. x = np.arange(12).reshape(2, 6).astype(dtype)
  919. y = random.permuted(x, axis=axis)
  920. assert y.dtype == dtype
  921. assert_array_equal(y, expected)
  922. def test_permuted_with_strides(self):
  923. random = Generator(MT19937(self.seed))
  924. x0 = np.arange(22).reshape(2, 11)
  925. x1 = x0.copy()
  926. x = x0[:, ::3]
  927. y = random.permuted(x, axis=1, out=x)
  928. expected = np.array([[0, 9, 3, 6],
  929. [14, 20, 11, 17]])
  930. assert_array_equal(y, expected)
  931. x1[:, ::3] = expected
  932. # Verify that the original x0 was modified in-place as expected.
  933. assert_array_equal(x1, x0)
  934. def test_permuted_empty(self):
  935. y = random.permuted([])
  936. assert_array_equal(y, [])
  937. @pytest.mark.parametrize('outshape', [(2, 3), 5])
  938. def test_permuted_out_with_wrong_shape(self, outshape):
  939. a = np.array([1, 2, 3])
  940. out = np.zeros(outshape, dtype=a.dtype)
  941. with pytest.raises(ValueError, match='same shape'):
  942. random.permuted(a, out=out)
  943. def test_permuted_out_with_wrong_type(self):
  944. out = np.zeros((3, 5), dtype=np.int32)
  945. x = np.ones((3, 5))
  946. with pytest.raises(TypeError, match='Cannot cast'):
  947. random.permuted(x, axis=1, out=out)
  948. def test_beta(self):
  949. random = Generator(MT19937(self.seed))
  950. actual = random.beta(.1, .9, size=(3, 2))
  951. desired = np.array(
  952. [[1.083029353267698e-10, 2.449965303168024e-11],
  953. [2.397085162969853e-02, 3.590779671820755e-08],
  954. [2.830254190078299e-04, 1.744709918330393e-01]])
  955. assert_array_almost_equal(actual, desired, decimal=15)
  956. def test_binomial(self):
  957. random = Generator(MT19937(self.seed))
  958. actual = random.binomial(100.123, .456, size=(3, 2))
  959. desired = np.array([[42, 41],
  960. [42, 48],
  961. [44, 50]])
  962. assert_array_equal(actual, desired)
  963. random = Generator(MT19937(self.seed))
  964. actual = random.binomial(100.123, .456)
  965. desired = 42
  966. assert_array_equal(actual, desired)
  967. def test_chisquare(self):
  968. random = Generator(MT19937(self.seed))
  969. actual = random.chisquare(50, size=(3, 2))
  970. desired = np.array([[32.9850547060149, 39.0219480493301],
  971. [56.2006134779419, 57.3474165711485],
  972. [55.4243733880198, 55.4209797925213]])
  973. assert_array_almost_equal(actual, desired, decimal=13)
  974. def test_dirichlet(self):
  975. random = Generator(MT19937(self.seed))
  976. alpha = np.array([51.72840233779265162, 39.74494232180943953])
  977. actual = random.dirichlet(alpha, size=(3, 2))
  978. desired = np.array([[[0.5439892869558927, 0.45601071304410745],
  979. [0.5588917345860708, 0.4411082654139292 ]],
  980. [[0.5632074165063435, 0.43679258349365657],
  981. [0.54862581112627, 0.45137418887373015]],
  982. [[0.49961831357047226, 0.5003816864295278 ],
  983. [0.52374806183482, 0.47625193816517997]]])
  984. assert_array_almost_equal(actual, desired, decimal=15)
  985. bad_alpha = np.array([5.4e-01, -1.0e-16])
  986. assert_raises(ValueError, random.dirichlet, bad_alpha)
  987. random = Generator(MT19937(self.seed))
  988. alpha = np.array([51.72840233779265162, 39.74494232180943953])
  989. actual = random.dirichlet(alpha)
  990. assert_array_almost_equal(actual, desired[0, 0], decimal=15)
  991. def test_dirichlet_size(self):
  992. # gh-3173
  993. p = np.array([51.72840233779265162, 39.74494232180943953])
  994. assert_equal(random.dirichlet(p, np.uint32(1)).shape, (1, 2))
  995. assert_equal(random.dirichlet(p, np.uint32(1)).shape, (1, 2))
  996. assert_equal(random.dirichlet(p, np.uint32(1)).shape, (1, 2))
  997. assert_equal(random.dirichlet(p, [2, 2]).shape, (2, 2, 2))
  998. assert_equal(random.dirichlet(p, (2, 2)).shape, (2, 2, 2))
  999. assert_equal(random.dirichlet(p, np.array((2, 2))).shape, (2, 2, 2))
  1000. assert_raises(TypeError, random.dirichlet, p, float(1))
  1001. def test_dirichlet_bad_alpha(self):
  1002. # gh-2089
  1003. alpha = np.array([5.4e-01, -1.0e-16])
  1004. assert_raises(ValueError, random.dirichlet, alpha)
  1005. # gh-15876
  1006. assert_raises(ValueError, random.dirichlet, [[5, 1]])
  1007. assert_raises(ValueError, random.dirichlet, [[5], [1]])
  1008. assert_raises(ValueError, random.dirichlet, [[[5], [1]], [[1], [5]]])
  1009. assert_raises(ValueError, random.dirichlet, np.array([[5, 1], [1, 5]]))
  1010. def test_dirichlet_alpha_non_contiguous(self):
  1011. a = np.array([51.72840233779265162, -1.0, 39.74494232180943953])
  1012. alpha = a[::2]
  1013. random = Generator(MT19937(self.seed))
  1014. non_contig = random.dirichlet(alpha, size=(3, 2))
  1015. random = Generator(MT19937(self.seed))
  1016. contig = random.dirichlet(np.ascontiguousarray(alpha),
  1017. size=(3, 2))
  1018. assert_array_almost_equal(non_contig, contig)
  1019. def test_dirichlet_small_alpha(self):
  1020. eps = 1.0e-9 # 1.0e-10 -> runtime x 10; 1e-11 -> runtime x 200, etc.
  1021. alpha = eps * np.array([1., 1.0e-3])
  1022. random = Generator(MT19937(self.seed))
  1023. actual = random.dirichlet(alpha, size=(3, 2))
  1024. expected = np.array([
  1025. [[1., 0.],
  1026. [1., 0.]],
  1027. [[1., 0.],
  1028. [1., 0.]],
  1029. [[1., 0.],
  1030. [1., 0.]]
  1031. ])
  1032. assert_array_almost_equal(actual, expected, decimal=15)
  1033. @pytest.mark.slow
  1034. def test_dirichlet_moderately_small_alpha(self):
  1035. # Use alpha.max() < 0.1 to trigger stick breaking code path
  1036. alpha = np.array([0.02, 0.04, 0.03])
  1037. exact_mean = alpha / alpha.sum()
  1038. random = Generator(MT19937(self.seed))
  1039. sample = random.dirichlet(alpha, size=20000000)
  1040. sample_mean = sample.mean(axis=0)
  1041. assert_allclose(sample_mean, exact_mean, rtol=1e-3)
  1042. def test_exponential(self):
  1043. random = Generator(MT19937(self.seed))
  1044. actual = random.exponential(1.1234, size=(3, 2))
  1045. desired = np.array([[0.098845481066258, 1.560752510746964],
  1046. [0.075730916041636, 1.769098974710777],
  1047. [1.488602544592235, 2.49684815275751 ]])
  1048. assert_array_almost_equal(actual, desired, decimal=15)
  1049. def test_exponential_0(self):
  1050. assert_equal(random.exponential(scale=0), 0)
  1051. assert_raises(ValueError, random.exponential, scale=-0.)
  1052. def test_f(self):
  1053. random = Generator(MT19937(self.seed))
  1054. actual = random.f(12, 77, size=(3, 2))
  1055. desired = np.array([[0.461720027077085, 1.100441958872451],
  1056. [1.100337455217484, 0.91421736740018 ],
  1057. [0.500811891303113, 0.826802454552058]])
  1058. assert_array_almost_equal(actual, desired, decimal=15)
  1059. def test_gamma(self):
  1060. random = Generator(MT19937(self.seed))
  1061. actual = random.gamma(5, 3, size=(3, 2))
  1062. desired = np.array([[ 5.03850858902096, 7.9228656732049 ],
  1063. [18.73983605132985, 19.57961681699238],
  1064. [18.17897755150825, 18.17653912505234]])
  1065. assert_array_almost_equal(actual, desired, decimal=14)
  1066. def test_gamma_0(self):
  1067. assert_equal(random.gamma(shape=0, scale=0), 0)
  1068. assert_raises(ValueError, random.gamma, shape=-0., scale=-0.)
  1069. def test_geometric(self):
  1070. random = Generator(MT19937(self.seed))
  1071. actual = random.geometric(.123456789, size=(3, 2))
  1072. desired = np.array([[1, 11],
  1073. [1, 12],
  1074. [11, 17]])
  1075. assert_array_equal(actual, desired)
  1076. def test_geometric_exceptions(self):
  1077. assert_raises(ValueError, random.geometric, 1.1)
  1078. assert_raises(ValueError, random.geometric, [1.1] * 10)
  1079. assert_raises(ValueError, random.geometric, -0.1)
  1080. assert_raises(ValueError, random.geometric, [-0.1] * 10)
  1081. with np.errstate(invalid='ignore'):
  1082. assert_raises(ValueError, random.geometric, np.nan)
  1083. assert_raises(ValueError, random.geometric, [np.nan] * 10)
  1084. def test_gumbel(self):
  1085. random = Generator(MT19937(self.seed))
  1086. actual = random.gumbel(loc=.123456789, scale=2.0, size=(3, 2))
  1087. desired = np.array([[ 4.688397515056245, -0.289514845417841],
  1088. [ 4.981176042584683, -0.633224272589149],
  1089. [-0.055915275687488, -0.333962478257953]])
  1090. assert_array_almost_equal(actual, desired, decimal=15)
  1091. def test_gumbel_0(self):
  1092. assert_equal(random.gumbel(scale=0), 0)
  1093. assert_raises(ValueError, random.gumbel, scale=-0.)
  1094. def test_hypergeometric(self):
  1095. random = Generator(MT19937(self.seed))
  1096. actual = random.hypergeometric(10.1, 5.5, 14, size=(3, 2))
  1097. desired = np.array([[ 9, 9],
  1098. [ 9, 9],
  1099. [10, 9]])
  1100. assert_array_equal(actual, desired)
  1101. # Test nbad = 0
  1102. actual = random.hypergeometric(5, 0, 3, size=4)
  1103. desired = np.array([3, 3, 3, 3])
  1104. assert_array_equal(actual, desired)
  1105. actual = random.hypergeometric(15, 0, 12, size=4)
  1106. desired = np.array([12, 12, 12, 12])
  1107. assert_array_equal(actual, desired)
  1108. # Test ngood = 0
  1109. actual = random.hypergeometric(0, 5, 3, size=4)
  1110. desired = np.array([0, 0, 0, 0])
  1111. assert_array_equal(actual, desired)
  1112. actual = random.hypergeometric(0, 15, 12, size=4)
  1113. desired = np.array([0, 0, 0, 0])
  1114. assert_array_equal(actual, desired)
  1115. def test_laplace(self):
  1116. random = Generator(MT19937(self.seed))
  1117. actual = random.laplace(loc=.123456789, scale=2.0, size=(3, 2))
  1118. desired = np.array([[-3.156353949272393, 1.195863024830054],
  1119. [-3.435458081645966, 1.656882398925444],
  1120. [ 0.924824032467446, 1.251116432209336]])
  1121. assert_array_almost_equal(actual, desired, decimal=15)
  1122. def test_laplace_0(self):
  1123. assert_equal(random.laplace(scale=0), 0)
  1124. assert_raises(ValueError, random.laplace, scale=-0.)
  1125. def test_logistic(self):
  1126. random = Generator(MT19937(self.seed))
  1127. actual = random.logistic(loc=.123456789, scale=2.0, size=(3, 2))
  1128. desired = np.array([[-4.338584631510999, 1.890171436749954],
  1129. [-4.64547787337966 , 2.514545562919217],
  1130. [ 1.495389489198666, 1.967827627577474]])
  1131. assert_array_almost_equal(actual, desired, decimal=15)
  1132. def test_lognormal(self):
  1133. random = Generator(MT19937(self.seed))
  1134. actual = random.lognormal(mean=.123456789, sigma=2.0, size=(3, 2))
  1135. desired = np.array([[ 0.0268252166335, 13.9534486483053],
  1136. [ 0.1204014788936, 2.2422077497792],
  1137. [ 4.2484199496128, 12.0093343977523]])
  1138. assert_array_almost_equal(actual, desired, decimal=13)
  1139. def test_lognormal_0(self):
  1140. assert_equal(random.lognormal(sigma=0), 1)
  1141. assert_raises(ValueError, random.lognormal, sigma=-0.)
  1142. def test_logseries(self):
  1143. random = Generator(MT19937(self.seed))
  1144. actual = random.logseries(p=.923456789, size=(3, 2))
  1145. desired = np.array([[14, 17],
  1146. [3, 18],
  1147. [5, 1]])
  1148. assert_array_equal(actual, desired)
  1149. def test_logseries_exceptions(self):
  1150. with np.errstate(invalid='ignore'):
  1151. assert_raises(ValueError, random.logseries, np.nan)
  1152. assert_raises(ValueError, random.logseries, [np.nan] * 10)
  1153. def test_multinomial(self):
  1154. random = Generator(MT19937(self.seed))
  1155. actual = random.multinomial(20, [1 / 6.] * 6, size=(3, 2))
  1156. desired = np.array([[[1, 5, 1, 6, 4, 3],
  1157. [4, 2, 6, 2, 4, 2]],
  1158. [[5, 3, 2, 6, 3, 1],
  1159. [4, 4, 0, 2, 3, 7]],
  1160. [[6, 3, 1, 5, 3, 2],
  1161. [5, 5, 3, 1, 2, 4]]])
  1162. assert_array_equal(actual, desired)
  1163. @pytest.mark.parametrize("method", ["svd", "eigh", "cholesky"])
  1164. def test_multivariate_normal(self, method):
  1165. random = Generator(MT19937(self.seed))
  1166. mean = (.123456789, 10)
  1167. cov = [[1, 0], [0, 1]]
  1168. size = (3, 2)
  1169. actual = random.multivariate_normal(mean, cov, size, method=method)
  1170. desired = np.array([[[-1.747478062846581, 11.25613495182354 ],
  1171. [-0.9967333370066214, 10.342002097029821 ]],
  1172. [[ 0.7850019631242964, 11.181113712443013 ],
  1173. [ 0.8901349653255224, 8.873825399642492 ]],
  1174. [[ 0.7130260107430003, 9.551628690083056 ],
  1175. [ 0.7127098726541128, 11.991709234143173 ]]])
  1176. assert_array_almost_equal(actual, desired, decimal=15)
  1177. # Check for default size, was raising deprecation warning
  1178. actual = random.multivariate_normal(mean, cov, method=method)
  1179. desired = np.array([0.233278563284287, 9.424140804347195])
  1180. assert_array_almost_equal(actual, desired, decimal=15)
  1181. # Check that non symmetric covariance input raises exception when
  1182. # check_valid='raises' if using default svd method.
  1183. mean = [0, 0]
  1184. cov = [[1, 2], [1, 2]]
  1185. assert_raises(ValueError, random.multivariate_normal, mean, cov,
  1186. check_valid='raise')
  1187. # Check that non positive-semidefinite covariance warns with
  1188. # RuntimeWarning
  1189. cov = [[1, 2], [2, 1]]
  1190. assert_warns(RuntimeWarning, random.multivariate_normal, mean, cov)
  1191. assert_warns(RuntimeWarning, random.multivariate_normal, mean, cov,
  1192. method='eigh')
  1193. assert_raises(LinAlgError, random.multivariate_normal, mean, cov,
  1194. method='cholesky')
  1195. # and that it doesn't warn with RuntimeWarning check_valid='ignore'
  1196. assert_no_warnings(random.multivariate_normal, mean, cov,
  1197. check_valid='ignore')
  1198. # and that it raises with RuntimeWarning check_valid='raises'
  1199. assert_raises(ValueError, random.multivariate_normal, mean, cov,
  1200. check_valid='raise')
  1201. assert_raises(ValueError, random.multivariate_normal, mean, cov,
  1202. check_valid='raise', method='eigh')
  1203. # check degenerate samples from singular covariance matrix
  1204. cov = [[1, 1], [1, 1]]
  1205. if method in ('svd', 'eigh'):
  1206. samples = random.multivariate_normal(mean, cov, size=(3, 2),
  1207. method=method)
  1208. assert_array_almost_equal(samples[..., 0], samples[..., 1],
  1209. decimal=6)
  1210. else:
  1211. assert_raises(LinAlgError, random.multivariate_normal, mean, cov,
  1212. method='cholesky')
  1213. cov = np.array([[1, 0.1], [0.1, 1]], dtype=np.float32)
  1214. with suppress_warnings() as sup:
  1215. random.multivariate_normal(mean, cov, method=method)
  1216. w = sup.record(RuntimeWarning)
  1217. assert len(w) == 0
  1218. mu = np.zeros(2)
  1219. cov = np.eye(2)
  1220. assert_raises(ValueError, random.multivariate_normal, mean, cov,
  1221. check_valid='other')
  1222. assert_raises(ValueError, random.multivariate_normal,
  1223. np.zeros((2, 1, 1)), cov)
  1224. assert_raises(ValueError, random.multivariate_normal,
  1225. mu, np.empty((3, 2)))
  1226. assert_raises(ValueError, random.multivariate_normal,
  1227. mu, np.eye(3))
  1228. @pytest.mark.parametrize("method", ["svd", "eigh", "cholesky"])
  1229. def test_multivariate_normal_basic_stats(self, method):
  1230. random = Generator(MT19937(self.seed))
  1231. n_s = 1000
  1232. mean = np.array([1, 2])
  1233. cov = np.array([[2, 1], [1, 2]])
  1234. s = random.multivariate_normal(mean, cov, size=(n_s,), method=method)
  1235. s_center = s - mean
  1236. cov_emp = (s_center.T @ s_center) / (n_s - 1)
  1237. # these are pretty loose and are only designed to detect major errors
  1238. assert np.all(np.abs(s_center.mean(-2)) < 0.1)
  1239. assert np.all(np.abs(cov_emp - cov) < 0.2)
  1240. def test_negative_binomial(self):
  1241. random = Generator(MT19937(self.seed))
  1242. actual = random.negative_binomial(n=100, p=.12345, size=(3, 2))
  1243. desired = np.array([[543, 727],
  1244. [775, 760],
  1245. [600, 674]])
  1246. assert_array_equal(actual, desired)
  1247. def test_negative_binomial_exceptions(self):
  1248. with np.errstate(invalid='ignore'):
  1249. assert_raises(ValueError, random.negative_binomial, 100, np.nan)
  1250. assert_raises(ValueError, random.negative_binomial, 100,
  1251. [np.nan] * 10)
  1252. def test_negative_binomial_p0_exception(self):
  1253. # Verify that p=0 raises an exception.
  1254. with assert_raises(ValueError):
  1255. x = random.negative_binomial(1, 0)
  1256. def test_noncentral_chisquare(self):
  1257. random = Generator(MT19937(self.seed))
  1258. actual = random.noncentral_chisquare(df=5, nonc=5, size=(3, 2))
  1259. desired = np.array([[ 1.70561552362133, 15.97378184942111],
  1260. [13.71483425173724, 20.17859633310629],
  1261. [11.3615477156643 , 3.67891108738029]])
  1262. assert_array_almost_equal(actual, desired, decimal=14)
  1263. actual = random.noncentral_chisquare(df=.5, nonc=.2, size=(3, 2))
  1264. desired = np.array([[9.41427665607629e-04, 1.70473157518850e-04],
  1265. [1.14554372041263e+00, 1.38187755933435e-03],
  1266. [1.90659181905387e+00, 1.21772577941822e+00]])
  1267. assert_array_almost_equal(actual, desired, decimal=14)
  1268. random = Generator(MT19937(self.seed))
  1269. actual = random.noncentral_chisquare(df=5, nonc=0, size=(3, 2))
  1270. desired = np.array([[0.82947954590419, 1.80139670767078],
  1271. [6.58720057417794, 7.00491463609814],
  1272. [6.31101879073157, 6.30982307753005]])
  1273. assert_array_almost_equal(actual, desired, decimal=14)
  1274. def test_noncentral_f(self):
  1275. random = Generator(MT19937(self.seed))
  1276. actual = random.noncentral_f(dfnum=5, dfden=2, nonc=1,
  1277. size=(3, 2))
  1278. desired = np.array([[0.060310671139 , 0.23866058175939],
  1279. [0.86860246709073, 0.2668510459738 ],
  1280. [0.23375780078364, 1.88922102885943]])
  1281. assert_array_almost_equal(actual, desired, decimal=14)
  1282. def test_noncentral_f_nan(self):
  1283. random = Generator(MT19937(self.seed))
  1284. actual = random.noncentral_f(dfnum=5, dfden=2, nonc=np.nan)
  1285. assert np.isnan(actual)
  1286. def test_normal(self):
  1287. random = Generator(MT19937(self.seed))
  1288. actual = random.normal(loc=.123456789, scale=2.0, size=(3, 2))
  1289. desired = np.array([[-3.618412914693162, 2.635726692647081],
  1290. [-2.116923463013243, 0.807460983059643],
  1291. [ 1.446547137248593, 2.485684213886024]])
  1292. assert_array_almost_equal(actual, desired, decimal=15)
  1293. def test_normal_0(self):
  1294. assert_equal(random.normal(scale=0), 0)
  1295. assert_raises(ValueError, random.normal, scale=-0.)
  1296. def test_pareto(self):
  1297. random = Generator(MT19937(self.seed))
  1298. actual = random.pareto(a=.123456789, size=(3, 2))
  1299. desired = np.array([[1.0394926776069018e+00, 7.7142534343505773e+04],
  1300. [7.2640150889064703e-01, 3.4650454783825594e+05],
  1301. [4.5852344481994740e+04, 6.5851383009539105e+07]])
  1302. # For some reason on 32-bit x86 Ubuntu 12.10 the [1, 0] entry in this
  1303. # matrix differs by 24 nulps. Discussion:
  1304. # https://mail.python.org/pipermail/numpy-discussion/2012-September/063801.html
  1305. # Consensus is that this is probably some gcc quirk that affects
  1306. # rounding but not in any important way, so we just use a looser
  1307. # tolerance on this test:
  1308. np.testing.assert_array_almost_equal_nulp(actual, desired, nulp=30)
  1309. def test_poisson(self):
  1310. random = Generator(MT19937(self.seed))
  1311. actual = random.poisson(lam=.123456789, size=(3, 2))
  1312. desired = np.array([[0, 0],
  1313. [0, 0],
  1314. [0, 0]])
  1315. assert_array_equal(actual, desired)
  1316. def test_poisson_exceptions(self):
  1317. lambig = np.iinfo('int64').max
  1318. lamneg = -1
  1319. assert_raises(ValueError, random.poisson, lamneg)
  1320. assert_raises(ValueError, random.poisson, [lamneg] * 10)
  1321. assert_raises(ValueError, random.poisson, lambig)
  1322. assert_raises(ValueError, random.poisson, [lambig] * 10)
  1323. with np.errstate(invalid='ignore'):
  1324. assert_raises(ValueError, random.poisson, np.nan)
  1325. assert_raises(ValueError, random.poisson, [np.nan] * 10)
  1326. def test_power(self):
  1327. random = Generator(MT19937(self.seed))
  1328. actual = random.power(a=.123456789, size=(3, 2))
  1329. desired = np.array([[1.977857368842754e-09, 9.806792196620341e-02],
  1330. [2.482442984543471e-10, 1.527108843266079e-01],
  1331. [8.188283434244285e-02, 3.950547209346948e-01]])
  1332. assert_array_almost_equal(actual, desired, decimal=15)
  1333. def test_rayleigh(self):
  1334. random = Generator(MT19937(self.seed))
  1335. actual = random.rayleigh(scale=10, size=(3, 2))
  1336. desired = np.array([[4.19494429102666, 16.66920198906598],
  1337. [3.67184544902662, 17.74695521962917],
  1338. [16.27935397855501, 21.08355560691792]])
  1339. assert_array_almost_equal(actual, desired, decimal=14)
  1340. def test_rayleigh_0(self):
  1341. assert_equal(random.rayleigh(scale=0), 0)
  1342. assert_raises(ValueError, random.rayleigh, scale=-0.)
  1343. def test_standard_cauchy(self):
  1344. random = Generator(MT19937(self.seed))
  1345. actual = random.standard_cauchy(size=(3, 2))
  1346. desired = np.array([[-1.489437778266206, -3.275389641569784],
  1347. [ 0.560102864910406, -0.680780916282552],
  1348. [-1.314912905226277, 0.295852965660225]])
  1349. assert_array_almost_equal(actual, desired, decimal=15)
  1350. def test_standard_exponential(self):
  1351. random = Generator(MT19937(self.seed))
  1352. actual = random.standard_exponential(size=(3, 2), method='inv')
  1353. desired = np.array([[0.102031839440643, 1.229350298474972],
  1354. [0.088137284693098, 1.459859985522667],
  1355. [1.093830802293668, 1.256977002164613]])
  1356. assert_array_almost_equal(actual, desired, decimal=15)
  1357. def test_standard_expoential_type_error(self):
  1358. assert_raises(TypeError, random.standard_exponential, dtype=np.int32)
  1359. def test_standard_gamma(self):
  1360. random = Generator(MT19937(self.seed))
  1361. actual = random.standard_gamma(shape=3, size=(3, 2))
  1362. desired = np.array([[0.62970724056362, 1.22379851271008],
  1363. [3.899412530884 , 4.12479964250139],
  1364. [3.74994102464584, 3.74929307690815]])
  1365. assert_array_almost_equal(actual, desired, decimal=14)
  1366. def test_standard_gammma_scalar_float(self):
  1367. random = Generator(MT19937(self.seed))
  1368. actual = random.standard_gamma(3, dtype=np.float32)
  1369. desired = 2.9242148399353027
  1370. assert_array_almost_equal(actual, desired, decimal=6)
  1371. def test_standard_gamma_float(self):
  1372. random = Generator(MT19937(self.seed))
  1373. actual = random.standard_gamma(shape=3, size=(3, 2))
  1374. desired = np.array([[0.62971, 1.2238 ],
  1375. [3.89941, 4.1248 ],
  1376. [3.74994, 3.74929]])
  1377. assert_array_almost_equal(actual, desired, decimal=5)
  1378. def test_standard_gammma_float_out(self):
  1379. actual = np.zeros((3, 2), dtype=np.float32)
  1380. random = Generator(MT19937(self.seed))
  1381. random.standard_gamma(10.0, out=actual, dtype=np.float32)
  1382. desired = np.array([[10.14987, 7.87012],
  1383. [ 9.46284, 12.56832],
  1384. [13.82495, 7.81533]], dtype=np.float32)
  1385. assert_array_almost_equal(actual, desired, decimal=5)
  1386. random = Generator(MT19937(self.seed))
  1387. random.standard_gamma(10.0, out=actual, size=(3, 2), dtype=np.float32)
  1388. assert_array_almost_equal(actual, desired, decimal=5)
  1389. def test_standard_gamma_unknown_type(self):
  1390. assert_raises(TypeError, random.standard_gamma, 1.,
  1391. dtype='int32')
  1392. def test_out_size_mismatch(self):
  1393. out = np.zeros(10)
  1394. assert_raises(ValueError, random.standard_gamma, 10.0, size=20,
  1395. out=out)
  1396. assert_raises(ValueError, random.standard_gamma, 10.0, size=(10, 1),
  1397. out=out)
  1398. def test_standard_gamma_0(self):
  1399. assert_equal(random.standard_gamma(shape=0), 0)
  1400. assert_raises(ValueError, random.standard_gamma, shape=-0.)
  1401. def test_standard_normal(self):
  1402. random = Generator(MT19937(self.seed))
  1403. actual = random.standard_normal(size=(3, 2))
  1404. desired = np.array([[-1.870934851846581, 1.25613495182354 ],
  1405. [-1.120190126006621, 0.342002097029821],
  1406. [ 0.661545174124296, 1.181113712443012]])
  1407. assert_array_almost_equal(actual, desired, decimal=15)
  1408. def test_standard_normal_unsupported_type(self):
  1409. assert_raises(TypeError, random.standard_normal, dtype=np.int32)
  1410. def test_standard_t(self):
  1411. random = Generator(MT19937(self.seed))
  1412. actual = random.standard_t(df=10, size=(3, 2))
  1413. desired = np.array([[-1.484666193042647, 0.30597891831161 ],
  1414. [ 1.056684299648085, -0.407312602088507],
  1415. [ 0.130704414281157, -2.038053410490321]])
  1416. assert_array_almost_equal(actual, desired, decimal=15)
  1417. def test_triangular(self):
  1418. random = Generator(MT19937(self.seed))
  1419. actual = random.triangular(left=5.12, mode=10.23, right=20.34,
  1420. size=(3, 2))
  1421. desired = np.array([[ 7.86664070590917, 13.6313848513185 ],
  1422. [ 7.68152445215983, 14.36169131136546],
  1423. [13.16105603911429, 13.72341621856971]])
  1424. assert_array_almost_equal(actual, desired, decimal=14)
  1425. def test_uniform(self):
  1426. random = Generator(MT19937(self.seed))
  1427. actual = random.uniform(low=1.23, high=10.54, size=(3, 2))
  1428. desired = np.array([[2.13306255040998 , 7.816987531021207],
  1429. [2.015436610109887, 8.377577533009589],
  1430. [7.421792588856135, 7.891185744455209]])
  1431. assert_array_almost_equal(actual, desired, decimal=15)
  1432. def test_uniform_range_bounds(self):
  1433. fmin = np.finfo('float').min
  1434. fmax = np.finfo('float').max
  1435. func = random.uniform
  1436. assert_raises(OverflowError, func, -np.inf, 0)
  1437. assert_raises(OverflowError, func, 0, np.inf)
  1438. assert_raises(OverflowError, func, fmin, fmax)
  1439. assert_raises(OverflowError, func, [-np.inf], [0])
  1440. assert_raises(OverflowError, func, [0], [np.inf])
  1441. # (fmax / 1e17) - fmin is within range, so this should not throw
  1442. # account for i386 extended precision DBL_MAX / 1e17 + DBL_MAX >
  1443. # DBL_MAX by increasing fmin a bit
  1444. random.uniform(low=np.nextafter(fmin, 1), high=fmax / 1e17)
  1445. def test_uniform_zero_range(self):
  1446. func = random.uniform
  1447. result = func(1.5, 1.5)
  1448. assert_allclose(result, 1.5)
  1449. result = func([0.0, np.pi], [0.0, np.pi])
  1450. assert_allclose(result, [0.0, np.pi])
  1451. result = func([[2145.12], [2145.12]], [2145.12, 2145.12])
  1452. assert_allclose(result, 2145.12 + np.zeros((2, 2)))
  1453. def test_uniform_neg_range(self):
  1454. func = random.uniform
  1455. assert_raises(ValueError, func, 2, 1)
  1456. assert_raises(ValueError, func, [1, 2], [1, 1])
  1457. assert_raises(ValueError, func, [[0, 1],[2, 3]], 2)
  1458. def test_scalar_exception_propagation(self):
  1459. # Tests that exceptions are correctly propagated in distributions
  1460. # when called with objects that throw exceptions when converted to
  1461. # scalars.
  1462. #
  1463. # Regression test for gh: 8865
  1464. class ThrowingFloat(np.ndarray):
  1465. def __float__(self):
  1466. raise TypeError
  1467. throwing_float = np.array(1.0).view(ThrowingFloat)
  1468. assert_raises(TypeError, random.uniform, throwing_float,
  1469. throwing_float)
  1470. class ThrowingInteger(np.ndarray):
  1471. def __int__(self):
  1472. raise TypeError
  1473. throwing_int = np.array(1).view(ThrowingInteger)
  1474. assert_raises(TypeError, random.hypergeometric, throwing_int, 1, 1)
  1475. def test_vonmises(self):
  1476. random = Generator(MT19937(self.seed))
  1477. actual = random.vonmises(mu=1.23, kappa=1.54, size=(3, 2))
  1478. desired = np.array([[ 1.107972248690106, 2.841536476232361],
  1479. [ 1.832602376042457, 1.945511926976032],
  1480. [-0.260147475776542, 2.058047492231698]])
  1481. assert_array_almost_equal(actual, desired, decimal=15)
  1482. def test_vonmises_small(self):
  1483. # check infinite loop, gh-4720
  1484. random = Generator(MT19937(self.seed))
  1485. r = random.vonmises(mu=0., kappa=1.1e-8, size=10**6)
  1486. assert_(np.isfinite(r).all())
  1487. def test_vonmises_nan(self):
  1488. random = Generator(MT19937(self.seed))
  1489. r = random.vonmises(mu=0., kappa=np.nan)
  1490. assert_(np.isnan(r))
  1491. @pytest.mark.parametrize("kappa", [1e4, 1e15])
  1492. def test_vonmises_large_kappa(self, kappa):
  1493. random = Generator(MT19937(self.seed))
  1494. rs = RandomState(random.bit_generator)
  1495. state = random.bit_generator.state
  1496. random_state_vals = rs.vonmises(0, kappa, size=10)
  1497. random.bit_generator.state = state
  1498. gen_vals = random.vonmises(0, kappa, size=10)
  1499. if kappa < 1e6:
  1500. assert_allclose(random_state_vals, gen_vals)
  1501. else:
  1502. assert np.all(random_state_vals != gen_vals)
  1503. @pytest.mark.parametrize("mu", [-7., -np.pi, -3.1, np.pi, 3.2])
  1504. @pytest.mark.parametrize("kappa", [1e-9, 1e-6, 1, 1e3, 1e15])
  1505. def test_vonmises_large_kappa_range(self, mu, kappa):
  1506. r = random.vonmises(mu, kappa, 50)
  1507. assert_(np.all(r > -np.pi) and np.all(r <= np.pi))
  1508. def test_wald(self):
  1509. random = Generator(MT19937(self.seed))
  1510. actual = random.wald(mean=1.23, scale=1.54, size=(3, 2))
  1511. desired = np.array([[0.26871721804551, 3.2233942732115 ],
  1512. [2.20328374987066, 2.40958405189353],
  1513. [2.07093587449261, 0.73073890064369]])
  1514. assert_array_almost_equal(actual, desired, decimal=14)
  1515. def test_weibull(self):
  1516. random = Generator(MT19937(self.seed))
  1517. actual = random.weibull(a=1.23, size=(3, 2))
  1518. desired = np.array([[0.138613914769468, 1.306463419753191],
  1519. [0.111623365934763, 1.446570494646721],
  1520. [1.257145775276011, 1.914247725027957]])
  1521. assert_array_almost_equal(actual, desired, decimal=15)
  1522. def test_weibull_0(self):
  1523. random = Generator(MT19937(self.seed))
  1524. assert_equal(random.weibull(a=0, size=12), np.zeros(12))
  1525. assert_raises(ValueError, random.weibull, a=-0.)
  1526. def test_zipf(self):
  1527. random = Generator(MT19937(self.seed))
  1528. actual = random.zipf(a=1.23, size=(3, 2))
  1529. desired = np.array([[ 1, 1],
  1530. [ 10, 867],
  1531. [354, 2]])
  1532. assert_array_equal(actual, desired)
  1533. class TestBroadcast:
  1534. # tests that functions that broadcast behave
  1535. # correctly when presented with non-scalar arguments
  1536. def setup(self):
  1537. self.seed = 123456789
  1538. def test_uniform(self):
  1539. random = Generator(MT19937(self.seed))
  1540. low = [0]
  1541. high = [1]
  1542. uniform = random.uniform
  1543. desired = np.array([0.16693771389729, 0.19635129550675, 0.75563050964095])
  1544. random = Generator(MT19937(self.seed))
  1545. actual = random.uniform(low * 3, high)
  1546. assert_array_almost_equal(actual, desired, decimal=14)
  1547. random = Generator(MT19937(self.seed))
  1548. actual = random.uniform(low, high * 3)
  1549. assert_array_almost_equal(actual, desired, decimal=14)
  1550. def test_normal(self):
  1551. loc = [0]
  1552. scale = [1]
  1553. bad_scale = [-1]
  1554. random = Generator(MT19937(self.seed))
  1555. desired = np.array([-0.38736406738527, 0.79594375042255, 0.0197076236097])
  1556. random = Generator(MT19937(self.seed))
  1557. actual = random.normal(loc * 3, scale)
  1558. assert_array_almost_equal(actual, desired, decimal=14)
  1559. assert_raises(ValueError, random.normal, loc * 3, bad_scale)
  1560. random = Generator(MT19937(self.seed))
  1561. normal = random.normal
  1562. actual = normal(loc, scale * 3)
  1563. assert_array_almost_equal(actual, desired, decimal=14)
  1564. assert_raises(ValueError, normal, loc, bad_scale * 3)
  1565. def test_beta(self):
  1566. a = [1]
  1567. b = [2]
  1568. bad_a = [-1]
  1569. bad_b = [-2]
  1570. desired = np.array([0.18719338682602, 0.73234824491364, 0.17928615186455])
  1571. random = Generator(MT19937(self.seed))
  1572. beta = random.beta
  1573. actual = beta(a * 3, b)
  1574. assert_array_almost_equal(actual, desired, decimal=14)
  1575. assert_raises(ValueError, beta, bad_a * 3, b)
  1576. assert_raises(ValueError, beta, a * 3, bad_b)
  1577. random = Generator(MT19937(self.seed))
  1578. actual = random.beta(a, b * 3)
  1579. assert_array_almost_equal(actual, desired, decimal=14)
  1580. def test_exponential(self):
  1581. scale = [1]
  1582. bad_scale = [-1]
  1583. desired = np.array([0.67245993212806, 0.21380495318094, 0.7177848928629])
  1584. random = Generator(MT19937(self.seed))
  1585. actual = random.exponential(scale * 3)
  1586. assert_array_almost_equal(actual, desired, decimal=14)
  1587. assert_raises(ValueError, random.exponential, bad_scale * 3)
  1588. def test_standard_gamma(self):
  1589. shape = [1]
  1590. bad_shape = [-1]
  1591. desired = np.array([0.67245993212806, 0.21380495318094, 0.7177848928629])
  1592. random = Generator(MT19937(self.seed))
  1593. std_gamma = random.standard_gamma
  1594. actual = std_gamma(shape * 3)
  1595. assert_array_almost_equal(actual, desired, decimal=14)
  1596. assert_raises(ValueError, std_gamma, bad_shape * 3)
  1597. def test_gamma(self):
  1598. shape = [1]
  1599. scale = [2]
  1600. bad_shape = [-1]
  1601. bad_scale = [-2]
  1602. desired = np.array([1.34491986425611, 0.42760990636187, 1.4355697857258])
  1603. random = Generator(MT19937(self.seed))
  1604. gamma = random.gamma
  1605. actual = gamma(shape * 3, scale)
  1606. assert_array_almost_equal(actual, desired, decimal=14)
  1607. assert_raises(ValueError, gamma, bad_shape * 3, scale)
  1608. assert_raises(ValueError, gamma, shape * 3, bad_scale)
  1609. random = Generator(MT19937(self.seed))
  1610. gamma = random.gamma
  1611. actual = gamma(shape, scale * 3)
  1612. assert_array_almost_equal(actual, desired, decimal=14)
  1613. assert_raises(ValueError, gamma, bad_shape, scale * 3)
  1614. assert_raises(ValueError, gamma, shape, bad_scale * 3)
  1615. def test_f(self):
  1616. dfnum = [1]
  1617. dfden = [2]
  1618. bad_dfnum = [-1]
  1619. bad_dfden = [-2]
  1620. desired = np.array([0.07765056244107, 7.72951397913186, 0.05786093891763])
  1621. random = Generator(MT19937(self.seed))
  1622. f = random.f
  1623. actual = f(dfnum * 3, dfden)
  1624. assert_array_almost_equal(actual, desired, decimal=14)
  1625. assert_raises(ValueError, f, bad_dfnum * 3, dfden)
  1626. assert_raises(ValueError, f, dfnum * 3, bad_dfden)
  1627. random = Generator(MT19937(self.seed))
  1628. f = random.f
  1629. actual = f(dfnum, dfden * 3)
  1630. assert_array_almost_equal(actual, desired, decimal=14)
  1631. assert_raises(ValueError, f, bad_dfnum, dfden * 3)
  1632. assert_raises(ValueError, f, dfnum, bad_dfden * 3)
  1633. def test_noncentral_f(self):
  1634. dfnum = [2]
  1635. dfden = [3]
  1636. nonc = [4]
  1637. bad_dfnum = [0]
  1638. bad_dfden = [-1]
  1639. bad_nonc = [-2]
  1640. desired = np.array([2.02434240411421, 12.91838601070124, 1.24395160354629])
  1641. random = Generator(MT19937(self.seed))
  1642. nonc_f = random.noncentral_f
  1643. actual = nonc_f(dfnum * 3, dfden, nonc)
  1644. assert_array_almost_equal(actual, desired, decimal=14)
  1645. assert np.all(np.isnan(nonc_f(dfnum, dfden, [np.nan] * 3)))
  1646. assert_raises(ValueError, nonc_f, bad_dfnum * 3, dfden, nonc)
  1647. assert_raises(ValueError, nonc_f, dfnum * 3, bad_dfden, nonc)
  1648. assert_raises(ValueError, nonc_f, dfnum * 3, dfden, bad_nonc)
  1649. random = Generator(MT19937(self.seed))
  1650. nonc_f = random.noncentral_f
  1651. actual = nonc_f(dfnum, dfden * 3, nonc)
  1652. assert_array_almost_equal(actual, desired, decimal=14)
  1653. assert_raises(ValueError, nonc_f, bad_dfnum, dfden * 3, nonc)
  1654. assert_raises(ValueError, nonc_f, dfnum, bad_dfden * 3, nonc)
  1655. assert_raises(ValueError, nonc_f, dfnum, dfden * 3, bad_nonc)
  1656. random = Generator(MT19937(self.seed))
  1657. nonc_f = random.noncentral_f
  1658. actual = nonc_f(dfnum, dfden, nonc * 3)
  1659. assert_array_almost_equal(actual, desired, decimal=14)
  1660. assert_raises(ValueError, nonc_f, bad_dfnum, dfden, nonc * 3)
  1661. assert_raises(ValueError, nonc_f, dfnum, bad_dfden, nonc * 3)
  1662. assert_raises(ValueError, nonc_f, dfnum, dfden, bad_nonc * 3)
  1663. def test_noncentral_f_small_df(self):
  1664. random = Generator(MT19937(self.seed))
  1665. desired = np.array([0.04714867120827, 0.1239390327694])
  1666. actual = random.noncentral_f(0.9, 0.9, 2, size=2)
  1667. assert_array_almost_equal(actual, desired, decimal=14)
  1668. def test_chisquare(self):
  1669. df = [1]
  1670. bad_df = [-1]
  1671. desired = np.array([0.05573640064251, 1.47220224353539, 2.9469379318589])
  1672. random = Generator(MT19937(self.seed))
  1673. actual = random.chisquare(df * 3)
  1674. assert_array_almost_equal(actual, desired, decimal=14)
  1675. assert_raises(ValueError, random.chisquare, bad_df * 3)
  1676. def test_noncentral_chisquare(self):
  1677. df = [1]
  1678. nonc = [2]
  1679. bad_df = [-1]
  1680. bad_nonc = [-2]
  1681. desired = np.array([0.07710766249436, 5.27829115110304, 0.630732147399])
  1682. random = Generator(MT19937(self.seed))
  1683. nonc_chi = random.noncentral_chisquare
  1684. actual = nonc_chi(df * 3, nonc)
  1685. assert_array_almost_equal(actual, desired, decimal=14)
  1686. assert_raises(ValueError, nonc_chi, bad_df * 3, nonc)
  1687. assert_raises(ValueError, nonc_chi, df * 3, bad_nonc)
  1688. random = Generator(MT19937(self.seed))
  1689. nonc_chi = random.noncentral_chisquare
  1690. actual = nonc_chi(df, nonc * 3)
  1691. assert_array_almost_equal(actual, desired, decimal=14)
  1692. assert_raises(ValueError, nonc_chi, bad_df, nonc * 3)
  1693. assert_raises(ValueError, nonc_chi, df, bad_nonc * 3)
  1694. def test_standard_t(self):
  1695. df = [1]
  1696. bad_df = [-1]
  1697. desired = np.array([-1.39498829447098, -1.23058658835223, 0.17207021065983])
  1698. random = Generator(MT19937(self.seed))
  1699. actual = random.standard_t(df * 3)
  1700. assert_array_almost_equal(actual, desired, decimal=14)
  1701. assert_raises(ValueError, random.standard_t, bad_df * 3)
  1702. def test_vonmises(self):
  1703. mu = [2]
  1704. kappa = [1]
  1705. bad_kappa = [-1]
  1706. desired = np.array([2.25935584988528, 2.23326261461399, -2.84152146503326])
  1707. random = Generator(MT19937(self.seed))
  1708. actual = random.vonmises(mu * 3, kappa)
  1709. assert_array_almost_equal(actual, desired, decimal=14)
  1710. assert_raises(ValueError, random.vonmises, mu * 3, bad_kappa)
  1711. random = Generator(MT19937(self.seed))
  1712. actual = random.vonmises(mu, kappa * 3)
  1713. assert_array_almost_equal(actual, desired, decimal=14)
  1714. assert_raises(ValueError, random.vonmises, mu, bad_kappa * 3)
  1715. def test_pareto(self):
  1716. a = [1]
  1717. bad_a = [-1]
  1718. desired = np.array([0.95905052946317, 0.2383810889437 , 1.04988745750013])
  1719. random = Generator(MT19937(self.seed))
  1720. actual = random.pareto(a * 3)
  1721. assert_array_almost_equal(actual, desired, decimal=14)
  1722. assert_raises(ValueError, random.pareto, bad_a * 3)
  1723. def test_weibull(self):
  1724. a = [1]
  1725. bad_a = [-1]
  1726. desired = np.array([0.67245993212806, 0.21380495318094, 0.7177848928629])
  1727. random = Generator(MT19937(self.seed))
  1728. actual = random.weibull(a * 3)
  1729. assert_array_almost_equal(actual, desired, decimal=14)
  1730. assert_raises(ValueError, random.weibull, bad_a * 3)
  1731. def test_power(self):
  1732. a = [1]
  1733. bad_a = [-1]
  1734. desired = np.array([0.48954864361052, 0.19249412888486, 0.51216834058807])
  1735. random = Generator(MT19937(self.seed))
  1736. actual = random.power(a * 3)
  1737. assert_array_almost_equal(actual, desired, decimal=14)
  1738. assert_raises(ValueError, random.power, bad_a * 3)
  1739. def test_laplace(self):
  1740. loc = [0]
  1741. scale = [1]
  1742. bad_scale = [-1]
  1743. desired = np.array([-1.09698732625119, -0.93470271947368, 0.71592671378202])
  1744. random = Generator(MT19937(self.seed))
  1745. laplace = random.laplace
  1746. actual = laplace(loc * 3, scale)
  1747. assert_array_almost_equal(actual, desired, decimal=14)
  1748. assert_raises(ValueError, laplace, loc * 3, bad_scale)
  1749. random = Generator(MT19937(self.seed))
  1750. laplace = random.laplace
  1751. actual = laplace(loc, scale * 3)
  1752. assert_array_almost_equal(actual, desired, decimal=14)
  1753. assert_raises(ValueError, laplace, loc, bad_scale * 3)
  1754. def test_gumbel(self):
  1755. loc = [0]
  1756. scale = [1]
  1757. bad_scale = [-1]
  1758. desired = np.array([1.70020068231762, 1.52054354273631, -0.34293267607081])
  1759. random = Generator(MT19937(self.seed))
  1760. gumbel = random.gumbel
  1761. actual = gumbel(loc * 3, scale)
  1762. assert_array_almost_equal(actual, desired, decimal=14)
  1763. assert_raises(ValueError, gumbel, loc * 3, bad_scale)
  1764. random = Generator(MT19937(self.seed))
  1765. gumbel = random.gumbel
  1766. actual = gumbel(loc, scale * 3)
  1767. assert_array_almost_equal(actual, desired, decimal=14)
  1768. assert_raises(ValueError, gumbel, loc, bad_scale * 3)
  1769. def test_logistic(self):
  1770. loc = [0]
  1771. scale = [1]
  1772. bad_scale = [-1]
  1773. desired = np.array([-1.607487640433, -1.40925686003678, 1.12887112820397])
  1774. random = Generator(MT19937(self.seed))
  1775. actual = random.logistic(loc * 3, scale)
  1776. assert_array_almost_equal(actual, desired, decimal=14)
  1777. assert_raises(ValueError, random.logistic, loc * 3, bad_scale)
  1778. random = Generator(MT19937(self.seed))
  1779. actual = random.logistic(loc, scale * 3)
  1780. assert_array_almost_equal(actual, desired, decimal=14)
  1781. assert_raises(ValueError, random.logistic, loc, bad_scale * 3)
  1782. assert_equal(random.logistic(1.0, 0.0), 1.0)
  1783. def test_lognormal(self):
  1784. mean = [0]
  1785. sigma = [1]
  1786. bad_sigma = [-1]
  1787. desired = np.array([0.67884390500697, 2.21653186290321, 1.01990310084276])
  1788. random = Generator(MT19937(self.seed))
  1789. lognormal = random.lognormal
  1790. actual = lognormal(mean * 3, sigma)
  1791. assert_array_almost_equal(actual, desired, decimal=14)
  1792. assert_raises(ValueError, lognormal, mean * 3, bad_sigma)
  1793. random = Generator(MT19937(self.seed))
  1794. actual = random.lognormal(mean, sigma * 3)
  1795. assert_raises(ValueError, random.lognormal, mean, bad_sigma * 3)
  1796. def test_rayleigh(self):
  1797. scale = [1]
  1798. bad_scale = [-1]
  1799. desired = np.array(
  1800. [1.1597068009872629,
  1801. 0.6539188836253857,
  1802. 1.1981526554349398]
  1803. )
  1804. random = Generator(MT19937(self.seed))
  1805. actual = random.rayleigh(scale * 3)
  1806. assert_array_almost_equal(actual, desired, decimal=14)
  1807. assert_raises(ValueError, random.rayleigh, bad_scale * 3)
  1808. def test_wald(self):
  1809. mean = [0.5]
  1810. scale = [1]
  1811. bad_mean = [0]
  1812. bad_scale = [-2]
  1813. desired = np.array([0.38052407392905, 0.50701641508592, 0.484935249864])
  1814. random = Generator(MT19937(self.seed))
  1815. actual = random.wald(mean * 3, scale)
  1816. assert_array_almost_equal(actual, desired, decimal=14)
  1817. assert_raises(ValueError, random.wald, bad_mean * 3, scale)
  1818. assert_raises(ValueError, random.wald, mean * 3, bad_scale)
  1819. random = Generator(MT19937(self.seed))
  1820. actual = random.wald(mean, scale * 3)
  1821. assert_array_almost_equal(actual, desired, decimal=14)
  1822. assert_raises(ValueError, random.wald, bad_mean, scale * 3)
  1823. assert_raises(ValueError, random.wald, mean, bad_scale * 3)
  1824. def test_triangular(self):
  1825. left = [1]
  1826. right = [3]
  1827. mode = [2]
  1828. bad_left_one = [3]
  1829. bad_mode_one = [4]
  1830. bad_left_two, bad_mode_two = right * 2
  1831. desired = np.array([1.57781954604754, 1.62665986867957, 2.30090130831326])
  1832. random = Generator(MT19937(self.seed))
  1833. triangular = random.triangular
  1834. actual = triangular(left * 3, mode, right)
  1835. assert_array_almost_equal(actual, desired, decimal=14)
  1836. assert_raises(ValueError, triangular, bad_left_one * 3, mode, right)
  1837. assert_raises(ValueError, triangular, left * 3, bad_mode_one, right)
  1838. assert_raises(ValueError, triangular, bad_left_two * 3, bad_mode_two,
  1839. right)
  1840. random = Generator(MT19937(self.seed))
  1841. triangular = random.triangular
  1842. actual = triangular(left, mode * 3, right)
  1843. assert_array_almost_equal(actual, desired, decimal=14)
  1844. assert_raises(ValueError, triangular, bad_left_one, mode * 3, right)
  1845. assert_raises(ValueError, triangular, left, bad_mode_one * 3, right)
  1846. assert_raises(ValueError, triangular, bad_left_two, bad_mode_two * 3,
  1847. right)
  1848. random = Generator(MT19937(self.seed))
  1849. triangular = random.triangular
  1850. actual = triangular(left, mode, right * 3)
  1851. assert_array_almost_equal(actual, desired, decimal=14)
  1852. assert_raises(ValueError, triangular, bad_left_one, mode, right * 3)
  1853. assert_raises(ValueError, triangular, left, bad_mode_one, right * 3)
  1854. assert_raises(ValueError, triangular, bad_left_two, bad_mode_two,
  1855. right * 3)
  1856. assert_raises(ValueError, triangular, 10., 0., 20.)
  1857. assert_raises(ValueError, triangular, 10., 25., 20.)
  1858. assert_raises(ValueError, triangular, 10., 10., 10.)
  1859. def test_binomial(self):
  1860. n = [1]
  1861. p = [0.5]
  1862. bad_n = [-1]
  1863. bad_p_one = [-1]
  1864. bad_p_two = [1.5]
  1865. desired = np.array([0, 0, 1])
  1866. random = Generator(MT19937(self.seed))
  1867. binom = random.binomial
  1868. actual = binom(n * 3, p)
  1869. assert_array_equal(actual, desired)
  1870. assert_raises(ValueError, binom, bad_n * 3, p)
  1871. assert_raises(ValueError, binom, n * 3, bad_p_one)
  1872. assert_raises(ValueError, binom, n * 3, bad_p_two)
  1873. random = Generator(MT19937(self.seed))
  1874. actual = random.binomial(n, p * 3)
  1875. assert_array_equal(actual, desired)
  1876. assert_raises(ValueError, binom, bad_n, p * 3)
  1877. assert_raises(ValueError, binom, n, bad_p_one * 3)
  1878. assert_raises(ValueError, binom, n, bad_p_two * 3)
  1879. def test_negative_binomial(self):
  1880. n = [1]
  1881. p = [0.5]
  1882. bad_n = [-1]
  1883. bad_p_one = [-1]
  1884. bad_p_two = [1.5]
  1885. desired = np.array([0, 2, 1], dtype=np.int64)
  1886. random = Generator(MT19937(self.seed))
  1887. neg_binom = random.negative_binomial
  1888. actual = neg_binom(n * 3, p)
  1889. assert_array_equal(actual, desired)
  1890. assert_raises(ValueError, neg_binom, bad_n * 3, p)
  1891. assert_raises(ValueError, neg_binom, n * 3, bad_p_one)
  1892. assert_raises(ValueError, neg_binom, n * 3, bad_p_two)
  1893. random = Generator(MT19937(self.seed))
  1894. neg_binom = random.negative_binomial
  1895. actual = neg_binom(n, p * 3)
  1896. assert_array_equal(actual, desired)
  1897. assert_raises(ValueError, neg_binom, bad_n, p * 3)
  1898. assert_raises(ValueError, neg_binom, n, bad_p_one * 3)
  1899. assert_raises(ValueError, neg_binom, n, bad_p_two * 3)
  1900. def test_poisson(self):
  1901. lam = [1]
  1902. bad_lam_one = [-1]
  1903. desired = np.array([0, 0, 3])
  1904. random = Generator(MT19937(self.seed))
  1905. max_lam = random._poisson_lam_max
  1906. bad_lam_two = [max_lam * 2]
  1907. poisson = random.poisson
  1908. actual = poisson(lam * 3)
  1909. assert_array_equal(actual, desired)
  1910. assert_raises(ValueError, poisson, bad_lam_one * 3)
  1911. assert_raises(ValueError, poisson, bad_lam_two * 3)
  1912. def test_zipf(self):
  1913. a = [2]
  1914. bad_a = [0]
  1915. desired = np.array([1, 8, 1])
  1916. random = Generator(MT19937(self.seed))
  1917. zipf = random.zipf
  1918. actual = zipf(a * 3)
  1919. assert_array_equal(actual, desired)
  1920. assert_raises(ValueError, zipf, bad_a * 3)
  1921. with np.errstate(invalid='ignore'):
  1922. assert_raises(ValueError, zipf, np.nan)
  1923. assert_raises(ValueError, zipf, [0, 0, np.nan])
  1924. def test_geometric(self):
  1925. p = [0.5]
  1926. bad_p_one = [-1]
  1927. bad_p_two = [1.5]
  1928. desired = np.array([1, 1, 3])
  1929. random = Generator(MT19937(self.seed))
  1930. geometric = random.geometric
  1931. actual = geometric(p * 3)
  1932. assert_array_equal(actual, desired)
  1933. assert_raises(ValueError, geometric, bad_p_one * 3)
  1934. assert_raises(ValueError, geometric, bad_p_two * 3)
  1935. def test_hypergeometric(self):
  1936. ngood = [1]
  1937. nbad = [2]
  1938. nsample = [2]
  1939. bad_ngood = [-1]
  1940. bad_nbad = [-2]
  1941. bad_nsample_one = [-1]
  1942. bad_nsample_two = [4]
  1943. desired = np.array([0, 0, 1])
  1944. random = Generator(MT19937(self.seed))
  1945. actual = random.hypergeometric(ngood * 3, nbad, nsample)
  1946. assert_array_equal(actual, desired)
  1947. assert_raises(ValueError, random.hypergeometric, bad_ngood * 3, nbad, nsample)
  1948. assert_raises(ValueError, random.hypergeometric, ngood * 3, bad_nbad, nsample)
  1949. assert_raises(ValueError, random.hypergeometric, ngood * 3, nbad, bad_nsample_one)
  1950. assert_raises(ValueError, random.hypergeometric, ngood * 3, nbad, bad_nsample_two)
  1951. random = Generator(MT19937(self.seed))
  1952. actual = random.hypergeometric(ngood, nbad * 3, nsample)
  1953. assert_array_equal(actual, desired)
  1954. assert_raises(ValueError, random.hypergeometric, bad_ngood, nbad * 3, nsample)
  1955. assert_raises(ValueError, random.hypergeometric, ngood, bad_nbad * 3, nsample)
  1956. assert_raises(ValueError, random.hypergeometric, ngood, nbad * 3, bad_nsample_one)
  1957. assert_raises(ValueError, random.hypergeometric, ngood, nbad * 3, bad_nsample_two)
  1958. random = Generator(MT19937(self.seed))
  1959. hypergeom = random.hypergeometric
  1960. actual = hypergeom(ngood, nbad, nsample * 3)
  1961. assert_array_equal(actual, desired)
  1962. assert_raises(ValueError, hypergeom, bad_ngood, nbad, nsample * 3)
  1963. assert_raises(ValueError, hypergeom, ngood, bad_nbad, nsample * 3)
  1964. assert_raises(ValueError, hypergeom, ngood, nbad, bad_nsample_one * 3)
  1965. assert_raises(ValueError, hypergeom, ngood, nbad, bad_nsample_two * 3)
  1966. assert_raises(ValueError, hypergeom, -1, 10, 20)
  1967. assert_raises(ValueError, hypergeom, 10, -1, 20)
  1968. assert_raises(ValueError, hypergeom, 10, 10, -1)
  1969. assert_raises(ValueError, hypergeom, 10, 10, 25)
  1970. # ValueError for arguments that are too big.
  1971. assert_raises(ValueError, hypergeom, 2**30, 10, 20)
  1972. assert_raises(ValueError, hypergeom, 999, 2**31, 50)
  1973. assert_raises(ValueError, hypergeom, 999, [2**29, 2**30], 1000)
  1974. def test_logseries(self):
  1975. p = [0.5]
  1976. bad_p_one = [2]
  1977. bad_p_two = [-1]
  1978. desired = np.array([1, 1, 1])
  1979. random = Generator(MT19937(self.seed))
  1980. logseries = random.logseries
  1981. actual = logseries(p * 3)
  1982. assert_array_equal(actual, desired)
  1983. assert_raises(ValueError, logseries, bad_p_one * 3)
  1984. assert_raises(ValueError, logseries, bad_p_two * 3)
  1985. def test_multinomial(self):
  1986. random = Generator(MT19937(self.seed))
  1987. actual = random.multinomial([5, 20], [1 / 6.] * 6, size=(3, 2))
  1988. desired = np.array([[[0, 0, 2, 1, 2, 0],
  1989. [2, 3, 6, 4, 2, 3]],
  1990. [[1, 0, 1, 0, 2, 1],
  1991. [7, 2, 2, 1, 4, 4]],
  1992. [[0, 2, 0, 1, 2, 0],
  1993. [3, 2, 3, 3, 4, 5]]], dtype=np.int64)
  1994. assert_array_equal(actual, desired)
  1995. random = Generator(MT19937(self.seed))
  1996. actual = random.multinomial([5, 20], [1 / 6.] * 6)
  1997. desired = np.array([[0, 0, 2, 1, 2, 0],
  1998. [2, 3, 6, 4, 2, 3]], dtype=np.int64)
  1999. assert_array_equal(actual, desired)
  2000. class TestThread:
  2001. # make sure each state produces the same sequence even in threads
  2002. def setup(self):
  2003. self.seeds = range(4)
  2004. def check_function(self, function, sz):
  2005. from threading import Thread
  2006. out1 = np.empty((len(self.seeds),) + sz)
  2007. out2 = np.empty((len(self.seeds),) + sz)
  2008. # threaded generation
  2009. t = [Thread(target=function, args=(Generator(MT19937(s)), o))
  2010. for s, o in zip(self.seeds, out1)]
  2011. [x.start() for x in t]
  2012. [x.join() for x in t]
  2013. # the same serial
  2014. for s, o in zip(self.seeds, out2):
  2015. function(Generator(MT19937(s)), o)
  2016. # these platforms change x87 fpu precision mode in threads
  2017. if np.intp().dtype.itemsize == 4 and sys.platform == "win32":
  2018. assert_array_almost_equal(out1, out2)
  2019. else:
  2020. assert_array_equal(out1, out2)
  2021. def test_normal(self):
  2022. def gen_random(state, out):
  2023. out[...] = state.normal(size=10000)
  2024. self.check_function(gen_random, sz=(10000,))
  2025. def test_exp(self):
  2026. def gen_random(state, out):
  2027. out[...] = state.exponential(scale=np.ones((100, 1000)))
  2028. self.check_function(gen_random, sz=(100, 1000))
  2029. def test_multinomial(self):
  2030. def gen_random(state, out):
  2031. out[...] = state.multinomial(10, [1 / 6.] * 6, size=10000)
  2032. self.check_function(gen_random, sz=(10000, 6))
  2033. # See Issue #4263
  2034. class TestSingleEltArrayInput:
  2035. def setup(self):
  2036. self.argOne = np.array([2])
  2037. self.argTwo = np.array([3])
  2038. self.argThree = np.array([4])
  2039. self.tgtShape = (1,)
  2040. def test_one_arg_funcs(self):
  2041. funcs = (random.exponential, random.standard_gamma,
  2042. random.chisquare, random.standard_t,
  2043. random.pareto, random.weibull,
  2044. random.power, random.rayleigh,
  2045. random.poisson, random.zipf,
  2046. random.geometric, random.logseries)
  2047. probfuncs = (random.geometric, random.logseries)
  2048. for func in funcs:
  2049. if func in probfuncs: # p < 1.0
  2050. out = func(np.array([0.5]))
  2051. else:
  2052. out = func(self.argOne)
  2053. assert_equal(out.shape, self.tgtShape)
  2054. def test_two_arg_funcs(self):
  2055. funcs = (random.uniform, random.normal,
  2056. random.beta, random.gamma,
  2057. random.f, random.noncentral_chisquare,
  2058. random.vonmises, random.laplace,
  2059. random.gumbel, random.logistic,
  2060. random.lognormal, random.wald,
  2061. random.binomial, random.negative_binomial)
  2062. probfuncs = (random.binomial, random.negative_binomial)
  2063. for func in funcs:
  2064. if func in probfuncs: # p <= 1
  2065. argTwo = np.array([0.5])
  2066. else:
  2067. argTwo = self.argTwo
  2068. out = func(self.argOne, argTwo)
  2069. assert_equal(out.shape, self.tgtShape)
  2070. out = func(self.argOne[0], argTwo)
  2071. assert_equal(out.shape, self.tgtShape)
  2072. out = func(self.argOne, argTwo[0])
  2073. assert_equal(out.shape, self.tgtShape)
  2074. def test_integers(self, endpoint):
  2075. itype = [np.bool_, np.int8, np.uint8, np.int16, np.uint16,
  2076. np.int32, np.uint32, np.int64, np.uint64]
  2077. func = random.integers
  2078. high = np.array([1])
  2079. low = np.array([0])
  2080. for dt in itype:
  2081. out = func(low, high, endpoint=endpoint, dtype=dt)
  2082. assert_equal(out.shape, self.tgtShape)
  2083. out = func(low[0], high, endpoint=endpoint, dtype=dt)
  2084. assert_equal(out.shape, self.tgtShape)
  2085. out = func(low, high[0], endpoint=endpoint, dtype=dt)
  2086. assert_equal(out.shape, self.tgtShape)
  2087. def test_three_arg_funcs(self):
  2088. funcs = [random.noncentral_f, random.triangular,
  2089. random.hypergeometric]
  2090. for func in funcs:
  2091. out = func(self.argOne, self.argTwo, self.argThree)
  2092. assert_equal(out.shape, self.tgtShape)
  2093. out = func(self.argOne[0], self.argTwo, self.argThree)
  2094. assert_equal(out.shape, self.tgtShape)
  2095. out = func(self.argOne, self.argTwo[0], self.argThree)
  2096. assert_equal(out.shape, self.tgtShape)
  2097. @pytest.mark.parametrize("config", JUMP_TEST_DATA)
  2098. def test_jumped(config):
  2099. # Each config contains the initial seed, a number of raw steps
  2100. # the sha256 hashes of the initial and the final states' keys and
  2101. # the position of of the initial and the final state.
  2102. # These were produced using the original C implementation.
  2103. seed = config["seed"]
  2104. steps = config["steps"]
  2105. mt19937 = MT19937(seed)
  2106. # Burn step
  2107. mt19937.random_raw(steps)
  2108. key = mt19937.state["state"]["key"]
  2109. if sys.byteorder == 'big':
  2110. key = key.byteswap()
  2111. sha256 = hashlib.sha256(key)
  2112. assert mt19937.state["state"]["pos"] == config["initial"]["pos"]
  2113. assert sha256.hexdigest() == config["initial"]["key_sha256"]
  2114. jumped = mt19937.jumped()
  2115. key = jumped.state["state"]["key"]
  2116. if sys.byteorder == 'big':
  2117. key = key.byteswap()
  2118. sha256 = hashlib.sha256(key)
  2119. assert jumped.state["state"]["pos"] == config["jumped"]["pos"]
  2120. assert sha256.hexdigest() == config["jumped"]["key_sha256"]
  2121. def test_broadcast_size_error():
  2122. mu = np.ones(3)
  2123. sigma = np.ones((4, 3))
  2124. size = (10, 4, 2)
  2125. assert random.normal(mu, sigma, size=(5, 4, 3)).shape == (5, 4, 3)
  2126. with pytest.raises(ValueError):
  2127. random.normal(mu, sigma, size=size)
  2128. with pytest.raises(ValueError):
  2129. random.normal(mu, sigma, size=(1, 3))
  2130. with pytest.raises(ValueError):
  2131. random.normal(mu, sigma, size=(4, 1, 1))
  2132. # 1 arg
  2133. shape = np.ones((4, 3))
  2134. with pytest.raises(ValueError):
  2135. random.standard_gamma(shape, size=size)
  2136. with pytest.raises(ValueError):
  2137. random.standard_gamma(shape, size=(3,))
  2138. with pytest.raises(ValueError):
  2139. random.standard_gamma(shape, size=3)
  2140. # Check out
  2141. out = np.empty(size)
  2142. with pytest.raises(ValueError):
  2143. random.standard_gamma(shape, out=out)
  2144. # 2 arg
  2145. with pytest.raises(ValueError):
  2146. random.binomial(1, [0.3, 0.7], size=(2, 1))
  2147. with pytest.raises(ValueError):
  2148. random.binomial([1, 2], 0.3, size=(2, 1))
  2149. with pytest.raises(ValueError):
  2150. random.binomial([1, 2], [0.3, 0.7], size=(2, 1))
  2151. with pytest.raises(ValueError):
  2152. random.multinomial([2, 2], [.3, .7], size=(2, 1))
  2153. # 3 arg
  2154. a = random.chisquare(5, size=3)
  2155. b = random.chisquare(5, size=(4, 3))
  2156. c = random.chisquare(5, size=(5, 4, 3))
  2157. assert random.noncentral_f(a, b, c).shape == (5, 4, 3)
  2158. with pytest.raises(ValueError, match=r"Output size \(6, 5, 1, 1\) is"):
  2159. random.noncentral_f(a, b, c, size=(6, 5, 1, 1))
  2160. def test_broadcast_size_scalar():
  2161. mu = np.ones(3)
  2162. sigma = np.ones(3)
  2163. random.normal(mu, sigma, size=3)
  2164. with pytest.raises(ValueError):
  2165. random.normal(mu, sigma, size=2)
  2166. def test_ragged_shuffle():
  2167. # GH 18142
  2168. seq = [[], [], 1]
  2169. gen = Generator(MT19937(0))
  2170. assert_no_warnings(gen.shuffle, seq)
  2171. assert seq == [1, [], []]
  2172. @pytest.mark.parametrize("high", [-2, [-2]])
  2173. @pytest.mark.parametrize("endpoint", [True, False])
  2174. def test_single_arg_integer_exception(high, endpoint):
  2175. # GH 14333
  2176. gen = Generator(MT19937(0))
  2177. msg = 'high < 0' if endpoint else 'high <= 0'
  2178. with pytest.raises(ValueError, match=msg):
  2179. gen.integers(high, endpoint=endpoint)
  2180. msg = 'low > high' if endpoint else 'low >= high'
  2181. with pytest.raises(ValueError, match=msg):
  2182. gen.integers(-1, high, endpoint=endpoint)
  2183. with pytest.raises(ValueError, match=msg):
  2184. gen.integers([-1], high, endpoint=endpoint)
  2185. @pytest.mark.parametrize("dtype", ["f4", "f8"])
  2186. def test_c_contig_req_out(dtype):
  2187. # GH 18704
  2188. out = np.empty((2, 3), order="F", dtype=dtype)
  2189. shape = [1, 2, 3]
  2190. with pytest.raises(ValueError, match="Supplied output array"):
  2191. random.standard_gamma(shape, out=out, dtype=dtype)
  2192. with pytest.raises(ValueError, match="Supplied output array"):
  2193. random.standard_gamma(shape, out=out, size=out.shape, dtype=dtype)
  2194. @pytest.mark.parametrize("dtype", ["f4", "f8"])
  2195. @pytest.mark.parametrize("order", ["F", "C"])
  2196. @pytest.mark.parametrize("dist", [random.standard_normal, random.random])
  2197. def test_contig_req_out(dist, order, dtype):
  2198. # GH 18704
  2199. out = np.empty((2, 3), dtype=dtype, order=order)
  2200. variates = dist(out=out, dtype=dtype)
  2201. assert variates is out
  2202. variates = dist(out=out, dtype=dtype, size=out.shape)
  2203. assert variates is out