m2m模型翻译
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.

2022 lines
80 KiB

6 months ago
  1. import hashlib
  2. import pickle
  3. import sys
  4. import warnings
  5. import numpy as np
  6. import pytest
  7. from numpy.testing import (
  8. assert_, assert_raises, assert_equal, assert_warns,
  9. assert_no_warnings, assert_array_equal, assert_array_almost_equal,
  10. suppress_warnings
  11. )
  12. from numpy.random import MT19937, PCG64
  13. from numpy import random
  14. INT_FUNCS = {'binomial': (100.0, 0.6),
  15. 'geometric': (.5,),
  16. 'hypergeometric': (20, 20, 10),
  17. 'logseries': (.5,),
  18. 'multinomial': (20, np.ones(6) / 6.0),
  19. 'negative_binomial': (100, .5),
  20. 'poisson': (10.0,),
  21. 'zipf': (2,),
  22. }
  23. if np.iinfo(int).max < 2**32:
  24. # Windows and some 32-bit platforms, e.g., ARM
  25. INT_FUNC_HASHES = {'binomial': '2fbead005fc63942decb5326d36a1f32fe2c9d32c904ee61e46866b88447c263',
  26. 'logseries': '23ead5dcde35d4cfd4ef2c105e4c3d43304b45dc1b1444b7823b9ee4fa144ebb',
  27. 'geometric': '0d764db64f5c3bad48c8c33551c13b4d07a1e7b470f77629bef6c985cac76fcf',
  28. 'hypergeometric': '7b59bf2f1691626c5815cdcd9a49e1dd68697251d4521575219e4d2a1b8b2c67',
  29. 'multinomial': 'd754fa5b92943a38ec07630de92362dd2e02c43577fc147417dc5b9db94ccdd3',
  30. 'negative_binomial': '8eb216f7cb2a63cf55605422845caaff002fddc64a7dc8b2d45acd477a49e824',
  31. 'poisson': '70c891d76104013ebd6f6bcf30d403a9074b886ff62e4e6b8eb605bf1a4673b7',
  32. 'zipf': '01f074f97517cd5d21747148ac6ca4074dde7fcb7acbaec0a936606fecacd93f',
  33. }
  34. else:
  35. INT_FUNC_HASHES = {'binomial': '8626dd9d052cb608e93d8868de0a7b347258b199493871a1dc56e2a26cacb112',
  36. 'geometric': '8edd53d272e49c4fc8fbbe6c7d08d563d62e482921f3131d0a0e068af30f0db9',
  37. 'hypergeometric': '83496cc4281c77b786c9b7ad88b74d42e01603a55c60577ebab81c3ba8d45657',
  38. 'logseries': '65878a38747c176bc00e930ebafebb69d4e1e16cd3a704e264ea8f5e24f548db',
  39. 'multinomial': '7a984ae6dca26fd25374479e118b22f55db0aedccd5a0f2584ceada33db98605',
  40. 'negative_binomial': 'd636d968e6a24ae92ab52fe11c46ac45b0897e98714426764e820a7d77602a61',
  41. 'poisson': '956552176f77e7c9cb20d0118fc9cf690be488d790ed4b4c4747b965e61b0bb4',
  42. 'zipf': 'f84ba7feffda41e606e20b28dfc0f1ea9964a74574513d4a4cbc98433a8bfa45',
  43. }
  44. @pytest.fixture(scope='module', params=INT_FUNCS)
  45. def int_func(request):
  46. return (request.param, INT_FUNCS[request.param],
  47. INT_FUNC_HASHES[request.param])
  48. def assert_mt19937_state_equal(a, b):
  49. assert_equal(a['bit_generator'], b['bit_generator'])
  50. assert_array_equal(a['state']['key'], b['state']['key'])
  51. assert_array_equal(a['state']['pos'], b['state']['pos'])
  52. assert_equal(a['has_gauss'], b['has_gauss'])
  53. assert_equal(a['gauss'], b['gauss'])
  54. class TestSeed:
  55. def test_scalar(self):
  56. s = random.RandomState(0)
  57. assert_equal(s.randint(1000), 684)
  58. s = random.RandomState(4294967295)
  59. assert_equal(s.randint(1000), 419)
  60. def test_array(self):
  61. s = random.RandomState(range(10))
  62. assert_equal(s.randint(1000), 468)
  63. s = random.RandomState(np.arange(10))
  64. assert_equal(s.randint(1000), 468)
  65. s = random.RandomState([0])
  66. assert_equal(s.randint(1000), 973)
  67. s = random.RandomState([4294967295])
  68. assert_equal(s.randint(1000), 265)
  69. def test_invalid_scalar(self):
  70. # seed must be an unsigned 32 bit integer
  71. assert_raises(TypeError, random.RandomState, -0.5)
  72. assert_raises(ValueError, random.RandomState, -1)
  73. def test_invalid_array(self):
  74. # seed must be an unsigned 32 bit integer
  75. assert_raises(TypeError, random.RandomState, [-0.5])
  76. assert_raises(ValueError, random.RandomState, [-1])
  77. assert_raises(ValueError, random.RandomState, [4294967296])
  78. assert_raises(ValueError, random.RandomState, [1, 2, 4294967296])
  79. assert_raises(ValueError, random.RandomState, [1, -2, 4294967296])
  80. def test_invalid_array_shape(self):
  81. # gh-9832
  82. assert_raises(ValueError, random.RandomState, np.array([],
  83. dtype=np.int64))
  84. assert_raises(ValueError, random.RandomState, [[1, 2, 3]])
  85. assert_raises(ValueError, random.RandomState, [[1, 2, 3],
  86. [4, 5, 6]])
  87. def test_cannot_seed(self):
  88. rs = random.RandomState(PCG64(0))
  89. with assert_raises(TypeError):
  90. rs.seed(1234)
  91. def test_invalid_initialization(self):
  92. assert_raises(ValueError, random.RandomState, MT19937)
  93. class TestBinomial:
  94. def test_n_zero(self):
  95. # Tests the corner case of n == 0 for the binomial distribution.
  96. # binomial(0, p) should be zero for any p in [0, 1].
  97. # This test addresses issue #3480.
  98. zeros = np.zeros(2, dtype='int')
  99. for p in [0, .5, 1]:
  100. assert_(random.binomial(0, p) == 0)
  101. assert_array_equal(random.binomial(zeros, p), zeros)
  102. def test_p_is_nan(self):
  103. # Issue #4571.
  104. assert_raises(ValueError, random.binomial, 1, np.nan)
  105. class TestMultinomial:
  106. def test_basic(self):
  107. random.multinomial(100, [0.2, 0.8])
  108. def test_zero_probability(self):
  109. random.multinomial(100, [0.2, 0.8, 0.0, 0.0, 0.0])
  110. def test_int_negative_interval(self):
  111. assert_(-5 <= random.randint(-5, -1) < -1)
  112. x = random.randint(-5, -1, 5)
  113. assert_(np.all(-5 <= x))
  114. assert_(np.all(x < -1))
  115. def test_size(self):
  116. # gh-3173
  117. p = [0.5, 0.5]
  118. assert_equal(random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
  119. assert_equal(random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
  120. assert_equal(random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
  121. assert_equal(random.multinomial(1, p, [2, 2]).shape, (2, 2, 2))
  122. assert_equal(random.multinomial(1, p, (2, 2)).shape, (2, 2, 2))
  123. assert_equal(random.multinomial(1, p, np.array((2, 2))).shape,
  124. (2, 2, 2))
  125. assert_raises(TypeError, random.multinomial, 1, p,
  126. float(1))
  127. def test_invalid_prob(self):
  128. assert_raises(ValueError, random.multinomial, 100, [1.1, 0.2])
  129. assert_raises(ValueError, random.multinomial, 100, [-.1, 0.9])
  130. def test_invalid_n(self):
  131. assert_raises(ValueError, random.multinomial, -1, [0.8, 0.2])
  132. def test_p_non_contiguous(self):
  133. p = np.arange(15.)
  134. p /= np.sum(p[1::3])
  135. pvals = p[1::3]
  136. random.seed(1432985819)
  137. non_contig = random.multinomial(100, pvals=pvals)
  138. random.seed(1432985819)
  139. contig = random.multinomial(100, pvals=np.ascontiguousarray(pvals))
  140. assert_array_equal(non_contig, contig)
  141. def test_multinomial_pvals_float32(self):
  142. x = np.array([9.9e-01, 9.9e-01, 1.0e-09, 1.0e-09, 1.0e-09, 1.0e-09,
  143. 1.0e-09, 1.0e-09, 1.0e-09, 1.0e-09], dtype=np.float32)
  144. pvals = x / x.sum()
  145. match = r"[\w\s]*pvals array is cast to 64-bit floating"
  146. with pytest.raises(ValueError, match=match):
  147. random.multinomial(1, pvals)
  148. class TestSetState:
  149. def setup(self):
  150. self.seed = 1234567890
  151. self.random_state = random.RandomState(self.seed)
  152. self.state = self.random_state.get_state()
  153. def test_basic(self):
  154. old = self.random_state.tomaxint(16)
  155. self.random_state.set_state(self.state)
  156. new = self.random_state.tomaxint(16)
  157. assert_(np.all(old == new))
  158. def test_gaussian_reset(self):
  159. # Make sure the cached every-other-Gaussian is reset.
  160. old = self.random_state.standard_normal(size=3)
  161. self.random_state.set_state(self.state)
  162. new = self.random_state.standard_normal(size=3)
  163. assert_(np.all(old == new))
  164. def test_gaussian_reset_in_media_res(self):
  165. # When the state is saved with a cached Gaussian, make sure the
  166. # cached Gaussian is restored.
  167. self.random_state.standard_normal()
  168. state = self.random_state.get_state()
  169. old = self.random_state.standard_normal(size=3)
  170. self.random_state.set_state(state)
  171. new = self.random_state.standard_normal(size=3)
  172. assert_(np.all(old == new))
  173. def test_backwards_compatibility(self):
  174. # Make sure we can accept old state tuples that do not have the
  175. # cached Gaussian value.
  176. old_state = self.state[:-2]
  177. x1 = self.random_state.standard_normal(size=16)
  178. self.random_state.set_state(old_state)
  179. x2 = self.random_state.standard_normal(size=16)
  180. self.random_state.set_state(self.state)
  181. x3 = self.random_state.standard_normal(size=16)
  182. assert_(np.all(x1 == x2))
  183. assert_(np.all(x1 == x3))
  184. def test_negative_binomial(self):
  185. # Ensure that the negative binomial results take floating point
  186. # arguments without truncation.
  187. self.random_state.negative_binomial(0.5, 0.5)
  188. def test_get_state_warning(self):
  189. rs = random.RandomState(PCG64())
  190. with suppress_warnings() as sup:
  191. w = sup.record(RuntimeWarning)
  192. state = rs.get_state()
  193. assert_(len(w) == 1)
  194. assert isinstance(state, dict)
  195. assert state['bit_generator'] == 'PCG64'
  196. def test_invalid_legacy_state_setting(self):
  197. state = self.random_state.get_state()
  198. new_state = ('Unknown', ) + state[1:]
  199. assert_raises(ValueError, self.random_state.set_state, new_state)
  200. assert_raises(TypeError, self.random_state.set_state,
  201. np.array(new_state, dtype=object))
  202. state = self.random_state.get_state(legacy=False)
  203. del state['bit_generator']
  204. assert_raises(ValueError, self.random_state.set_state, state)
  205. def test_pickle(self):
  206. self.random_state.seed(0)
  207. self.random_state.random_sample(100)
  208. self.random_state.standard_normal()
  209. pickled = self.random_state.get_state(legacy=False)
  210. assert_equal(pickled['has_gauss'], 1)
  211. rs_unpick = pickle.loads(pickle.dumps(self.random_state))
  212. unpickled = rs_unpick.get_state(legacy=False)
  213. assert_mt19937_state_equal(pickled, unpickled)
  214. def test_state_setting(self):
  215. attr_state = self.random_state.__getstate__()
  216. self.random_state.standard_normal()
  217. self.random_state.__setstate__(attr_state)
  218. state = self.random_state.get_state(legacy=False)
  219. assert_mt19937_state_equal(attr_state, state)
  220. def test_repr(self):
  221. assert repr(self.random_state).startswith('RandomState(MT19937)')
  222. class TestRandint:
  223. rfunc = random.randint
  224. # valid integer/boolean types
  225. itype = [np.bool_, np.int8, np.uint8, np.int16, np.uint16,
  226. np.int32, np.uint32, np.int64, np.uint64]
  227. def test_unsupported_type(self):
  228. assert_raises(TypeError, self.rfunc, 1, dtype=float)
  229. def test_bounds_checking(self):
  230. for dt in self.itype:
  231. lbnd = 0 if dt is np.bool_ else np.iinfo(dt).min
  232. ubnd = 2 if dt is np.bool_ else np.iinfo(dt).max + 1
  233. assert_raises(ValueError, self.rfunc, lbnd - 1, ubnd, dtype=dt)
  234. assert_raises(ValueError, self.rfunc, lbnd, ubnd + 1, dtype=dt)
  235. assert_raises(ValueError, self.rfunc, ubnd, lbnd, dtype=dt)
  236. assert_raises(ValueError, self.rfunc, 1, 0, dtype=dt)
  237. def test_rng_zero_and_extremes(self):
  238. for dt in self.itype:
  239. lbnd = 0 if dt is np.bool_ else np.iinfo(dt).min
  240. ubnd = 2 if dt is np.bool_ else np.iinfo(dt).max + 1
  241. tgt = ubnd - 1
  242. assert_equal(self.rfunc(tgt, tgt + 1, size=1000, dtype=dt), tgt)
  243. tgt = lbnd
  244. assert_equal(self.rfunc(tgt, tgt + 1, size=1000, dtype=dt), tgt)
  245. tgt = (lbnd + ubnd)//2
  246. assert_equal(self.rfunc(tgt, tgt + 1, size=1000, dtype=dt), tgt)
  247. def test_full_range(self):
  248. # Test for ticket #1690
  249. for dt in self.itype:
  250. lbnd = 0 if dt is np.bool_ else np.iinfo(dt).min
  251. ubnd = 2 if dt is np.bool_ else np.iinfo(dt).max + 1
  252. try:
  253. self.rfunc(lbnd, ubnd, dtype=dt)
  254. except Exception as e:
  255. raise AssertionError("No error should have been raised, "
  256. "but one was with the following "
  257. "message:\n\n%s" % str(e))
  258. def test_in_bounds_fuzz(self):
  259. # Don't use fixed seed
  260. random.seed()
  261. for dt in self.itype[1:]:
  262. for ubnd in [4, 8, 16]:
  263. vals = self.rfunc(2, ubnd, size=2**16, dtype=dt)
  264. assert_(vals.max() < ubnd)
  265. assert_(vals.min() >= 2)
  266. vals = self.rfunc(0, 2, size=2**16, dtype=np.bool_)
  267. assert_(vals.max() < 2)
  268. assert_(vals.min() >= 0)
  269. def test_repeatability(self):
  270. # We use a sha256 hash of generated sequences of 1000 samples
  271. # in the range [0, 6) for all but bool, where the range
  272. # is [0, 2). Hashes are for little endian numbers.
  273. tgt = {'bool': '509aea74d792fb931784c4b0135392c65aec64beee12b0cc167548a2c3d31e71',
  274. 'int16': '7b07f1a920e46f6d0fe02314155a2330bcfd7635e708da50e536c5ebb631a7d4',
  275. 'int32': 'e577bfed6c935de944424667e3da285012e741892dcb7051a8f1ce68ab05c92f',
  276. 'int64': '0fbead0b06759df2cfb55e43148822d4a1ff953c7eb19a5b08445a63bb64fa9e',
  277. 'int8': '001aac3a5acb935a9b186cbe14a1ca064b8bb2dd0b045d48abeacf74d0203404',
  278. 'uint16': '7b07f1a920e46f6d0fe02314155a2330bcfd7635e708da50e536c5ebb631a7d4',
  279. 'uint32': 'e577bfed6c935de944424667e3da285012e741892dcb7051a8f1ce68ab05c92f',
  280. 'uint64': '0fbead0b06759df2cfb55e43148822d4a1ff953c7eb19a5b08445a63bb64fa9e',
  281. 'uint8': '001aac3a5acb935a9b186cbe14a1ca064b8bb2dd0b045d48abeacf74d0203404'}
  282. for dt in self.itype[1:]:
  283. random.seed(1234)
  284. # view as little endian for hash
  285. if sys.byteorder == 'little':
  286. val = self.rfunc(0, 6, size=1000, dtype=dt)
  287. else:
  288. val = self.rfunc(0, 6, size=1000, dtype=dt).byteswap()
  289. res = hashlib.sha256(val.view(np.int8)).hexdigest()
  290. assert_(tgt[np.dtype(dt).name] == res)
  291. # bools do not depend on endianness
  292. random.seed(1234)
  293. val = self.rfunc(0, 2, size=1000, dtype=bool).view(np.int8)
  294. res = hashlib.sha256(val).hexdigest()
  295. assert_(tgt[np.dtype(bool).name] == res)
  296. @pytest.mark.skipif(np.iinfo('l').max < 2**32,
  297. reason='Cannot test with 32-bit C long')
  298. def test_repeatability_32bit_boundary_broadcasting(self):
  299. desired = np.array([[[3992670689, 2438360420, 2557845020],
  300. [4107320065, 4142558326, 3216529513],
  301. [1605979228, 2807061240, 665605495]],
  302. [[3211410639, 4128781000, 457175120],
  303. [1712592594, 1282922662, 3081439808],
  304. [3997822960, 2008322436, 1563495165]],
  305. [[1398375547, 4269260146, 115316740],
  306. [3414372578, 3437564012, 2112038651],
  307. [3572980305, 2260248732, 3908238631]],
  308. [[2561372503, 223155946, 3127879445],
  309. [ 441282060, 3514786552, 2148440361],
  310. [1629275283, 3479737011, 3003195987]],
  311. [[ 412181688, 940383289, 3047321305],
  312. [2978368172, 764731833, 2282559898],
  313. [ 105711276, 720447391, 3596512484]]])
  314. for size in [None, (5, 3, 3)]:
  315. random.seed(12345)
  316. x = self.rfunc([[-1], [0], [1]], [2**32 - 1, 2**32, 2**32 + 1],
  317. size=size)
  318. assert_array_equal(x, desired if size is not None else desired[0])
  319. def test_int64_uint64_corner_case(self):
  320. # When stored in Numpy arrays, `lbnd` is casted
  321. # as np.int64, and `ubnd` is casted as np.uint64.
  322. # Checking whether `lbnd` >= `ubnd` used to be
  323. # done solely via direct comparison, which is incorrect
  324. # because when Numpy tries to compare both numbers,
  325. # it casts both to np.float64 because there is
  326. # no integer superset of np.int64 and np.uint64. However,
  327. # `ubnd` is too large to be represented in np.float64,
  328. # causing it be round down to np.iinfo(np.int64).max,
  329. # leading to a ValueError because `lbnd` now equals
  330. # the new `ubnd`.
  331. dt = np.int64
  332. tgt = np.iinfo(np.int64).max
  333. lbnd = np.int64(np.iinfo(np.int64).max)
  334. ubnd = np.uint64(np.iinfo(np.int64).max + 1)
  335. # None of these function calls should
  336. # generate a ValueError now.
  337. actual = random.randint(lbnd, ubnd, dtype=dt)
  338. assert_equal(actual, tgt)
  339. def test_respect_dtype_singleton(self):
  340. # See gh-7203
  341. for dt in self.itype:
  342. lbnd = 0 if dt is np.bool_ else np.iinfo(dt).min
  343. ubnd = 2 if dt is np.bool_ else np.iinfo(dt).max + 1
  344. sample = self.rfunc(lbnd, ubnd, dtype=dt)
  345. assert_equal(sample.dtype, np.dtype(dt))
  346. for dt in (bool, int, np.compat.long):
  347. lbnd = 0 if dt is bool else np.iinfo(dt).min
  348. ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
  349. # gh-7284: Ensure that we get Python data types
  350. sample = self.rfunc(lbnd, ubnd, dtype=dt)
  351. assert_(not hasattr(sample, 'dtype'))
  352. assert_equal(type(sample), dt)
  353. class TestRandomDist:
  354. # Make sure the random distribution returns the correct value for a
  355. # given seed
  356. def setup(self):
  357. self.seed = 1234567890
  358. def test_rand(self):
  359. random.seed(self.seed)
  360. actual = random.rand(3, 2)
  361. desired = np.array([[0.61879477158567997, 0.59162362775974664],
  362. [0.88868358904449662, 0.89165480011560816],
  363. [0.4575674820298663, 0.7781880808593471]])
  364. assert_array_almost_equal(actual, desired, decimal=15)
  365. def test_rand_singleton(self):
  366. random.seed(self.seed)
  367. actual = random.rand()
  368. desired = 0.61879477158567997
  369. assert_array_almost_equal(actual, desired, decimal=15)
  370. def test_randn(self):
  371. random.seed(self.seed)
  372. actual = random.randn(3, 2)
  373. desired = np.array([[1.34016345771863121, 1.73759122771936081],
  374. [1.498988344300628, -0.2286433324536169],
  375. [2.031033998682787, 2.17032494605655257]])
  376. assert_array_almost_equal(actual, desired, decimal=15)
  377. random.seed(self.seed)
  378. actual = random.randn()
  379. assert_array_almost_equal(actual, desired[0, 0], decimal=15)
  380. def test_randint(self):
  381. random.seed(self.seed)
  382. actual = random.randint(-99, 99, size=(3, 2))
  383. desired = np.array([[31, 3],
  384. [-52, 41],
  385. [-48, -66]])
  386. assert_array_equal(actual, desired)
  387. def test_random_integers(self):
  388. random.seed(self.seed)
  389. with suppress_warnings() as sup:
  390. w = sup.record(DeprecationWarning)
  391. actual = random.random_integers(-99, 99, size=(3, 2))
  392. assert_(len(w) == 1)
  393. desired = np.array([[31, 3],
  394. [-52, 41],
  395. [-48, -66]])
  396. assert_array_equal(actual, desired)
  397. random.seed(self.seed)
  398. with suppress_warnings() as sup:
  399. w = sup.record(DeprecationWarning)
  400. actual = random.random_integers(198, size=(3, 2))
  401. assert_(len(w) == 1)
  402. assert_array_equal(actual, desired + 100)
  403. def test_tomaxint(self):
  404. random.seed(self.seed)
  405. rs = random.RandomState(self.seed)
  406. actual = rs.tomaxint(size=(3, 2))
  407. if np.iinfo(int).max == 2147483647:
  408. desired = np.array([[1328851649, 731237375],
  409. [1270502067, 320041495],
  410. [1908433478, 499156889]], dtype=np.int64)
  411. else:
  412. desired = np.array([[5707374374421908479, 5456764827585442327],
  413. [8196659375100692377, 8224063923314595285],
  414. [4220315081820346526, 7177518203184491332]],
  415. dtype=np.int64)
  416. assert_equal(actual, desired)
  417. rs.seed(self.seed)
  418. actual = rs.tomaxint()
  419. assert_equal(actual, desired[0, 0])
  420. def test_random_integers_max_int(self):
  421. # Tests whether random_integers can generate the
  422. # maximum allowed Python int that can be converted
  423. # into a C long. Previous implementations of this
  424. # method have thrown an OverflowError when attempting
  425. # to generate this integer.
  426. with suppress_warnings() as sup:
  427. w = sup.record(DeprecationWarning)
  428. actual = random.random_integers(np.iinfo('l').max,
  429. np.iinfo('l').max)
  430. assert_(len(w) == 1)
  431. desired = np.iinfo('l').max
  432. assert_equal(actual, desired)
  433. with suppress_warnings() as sup:
  434. w = sup.record(DeprecationWarning)
  435. typer = np.dtype('l').type
  436. actual = random.random_integers(typer(np.iinfo('l').max),
  437. typer(np.iinfo('l').max))
  438. assert_(len(w) == 1)
  439. assert_equal(actual, desired)
  440. def test_random_integers_deprecated(self):
  441. with warnings.catch_warnings():
  442. warnings.simplefilter("error", DeprecationWarning)
  443. # DeprecationWarning raised with high == None
  444. assert_raises(DeprecationWarning,
  445. random.random_integers,
  446. np.iinfo('l').max)
  447. # DeprecationWarning raised with high != None
  448. assert_raises(DeprecationWarning,
  449. random.random_integers,
  450. np.iinfo('l').max, np.iinfo('l').max)
  451. def test_random_sample(self):
  452. random.seed(self.seed)
  453. actual = random.random_sample((3, 2))
  454. desired = np.array([[0.61879477158567997, 0.59162362775974664],
  455. [0.88868358904449662, 0.89165480011560816],
  456. [0.4575674820298663, 0.7781880808593471]])
  457. assert_array_almost_equal(actual, desired, decimal=15)
  458. random.seed(self.seed)
  459. actual = random.random_sample()
  460. assert_array_almost_equal(actual, desired[0, 0], decimal=15)
  461. def test_choice_uniform_replace(self):
  462. random.seed(self.seed)
  463. actual = random.choice(4, 4)
  464. desired = np.array([2, 3, 2, 3])
  465. assert_array_equal(actual, desired)
  466. def test_choice_nonuniform_replace(self):
  467. random.seed(self.seed)
  468. actual = random.choice(4, 4, p=[0.4, 0.4, 0.1, 0.1])
  469. desired = np.array([1, 1, 2, 2])
  470. assert_array_equal(actual, desired)
  471. def test_choice_uniform_noreplace(self):
  472. random.seed(self.seed)
  473. actual = random.choice(4, 3, replace=False)
  474. desired = np.array([0, 1, 3])
  475. assert_array_equal(actual, desired)
  476. def test_choice_nonuniform_noreplace(self):
  477. random.seed(self.seed)
  478. actual = random.choice(4, 3, replace=False, p=[0.1, 0.3, 0.5, 0.1])
  479. desired = np.array([2, 3, 1])
  480. assert_array_equal(actual, desired)
  481. def test_choice_noninteger(self):
  482. random.seed(self.seed)
  483. actual = random.choice(['a', 'b', 'c', 'd'], 4)
  484. desired = np.array(['c', 'd', 'c', 'd'])
  485. assert_array_equal(actual, desired)
  486. def test_choice_exceptions(self):
  487. sample = random.choice
  488. assert_raises(ValueError, sample, -1, 3)
  489. assert_raises(ValueError, sample, 3., 3)
  490. assert_raises(ValueError, sample, [[1, 2], [3, 4]], 3)
  491. assert_raises(ValueError, sample, [], 3)
  492. assert_raises(ValueError, sample, [1, 2, 3, 4], 3,
  493. p=[[0.25, 0.25], [0.25, 0.25]])
  494. assert_raises(ValueError, sample, [1, 2], 3, p=[0.4, 0.4, 0.2])
  495. assert_raises(ValueError, sample, [1, 2], 3, p=[1.1, -0.1])
  496. assert_raises(ValueError, sample, [1, 2], 3, p=[0.4, 0.4])
  497. assert_raises(ValueError, sample, [1, 2, 3], 4, replace=False)
  498. # gh-13087
  499. assert_raises(ValueError, sample, [1, 2, 3], -2, replace=False)
  500. assert_raises(ValueError, sample, [1, 2, 3], (-1,), replace=False)
  501. assert_raises(ValueError, sample, [1, 2, 3], (-1, 1), replace=False)
  502. assert_raises(ValueError, sample, [1, 2, 3], 2,
  503. replace=False, p=[1, 0, 0])
  504. def test_choice_return_shape(self):
  505. p = [0.1, 0.9]
  506. # Check scalar
  507. assert_(np.isscalar(random.choice(2, replace=True)))
  508. assert_(np.isscalar(random.choice(2, replace=False)))
  509. assert_(np.isscalar(random.choice(2, replace=True, p=p)))
  510. assert_(np.isscalar(random.choice(2, replace=False, p=p)))
  511. assert_(np.isscalar(random.choice([1, 2], replace=True)))
  512. assert_(random.choice([None], replace=True) is None)
  513. a = np.array([1, 2])
  514. arr = np.empty(1, dtype=object)
  515. arr[0] = a
  516. assert_(random.choice(arr, replace=True) is a)
  517. # Check 0-d array
  518. s = tuple()
  519. assert_(not np.isscalar(random.choice(2, s, replace=True)))
  520. assert_(not np.isscalar(random.choice(2, s, replace=False)))
  521. assert_(not np.isscalar(random.choice(2, s, replace=True, p=p)))
  522. assert_(not np.isscalar(random.choice(2, s, replace=False, p=p)))
  523. assert_(not np.isscalar(random.choice([1, 2], s, replace=True)))
  524. assert_(random.choice([None], s, replace=True).ndim == 0)
  525. a = np.array([1, 2])
  526. arr = np.empty(1, dtype=object)
  527. arr[0] = a
  528. assert_(random.choice(arr, s, replace=True).item() is a)
  529. # Check multi dimensional array
  530. s = (2, 3)
  531. p = [0.1, 0.1, 0.1, 0.1, 0.4, 0.2]
  532. assert_equal(random.choice(6, s, replace=True).shape, s)
  533. assert_equal(random.choice(6, s, replace=False).shape, s)
  534. assert_equal(random.choice(6, s, replace=True, p=p).shape, s)
  535. assert_equal(random.choice(6, s, replace=False, p=p).shape, s)
  536. assert_equal(random.choice(np.arange(6), s, replace=True).shape, s)
  537. # Check zero-size
  538. assert_equal(random.randint(0, 0, size=(3, 0, 4)).shape, (3, 0, 4))
  539. assert_equal(random.randint(0, -10, size=0).shape, (0,))
  540. assert_equal(random.randint(10, 10, size=0).shape, (0,))
  541. assert_equal(random.choice(0, size=0).shape, (0,))
  542. assert_equal(random.choice([], size=(0,)).shape, (0,))
  543. assert_equal(random.choice(['a', 'b'], size=(3, 0, 4)).shape,
  544. (3, 0, 4))
  545. assert_raises(ValueError, random.choice, [], 10)
  546. def test_choice_nan_probabilities(self):
  547. a = np.array([42, 1, 2])
  548. p = [None, None, None]
  549. assert_raises(ValueError, random.choice, a, p=p)
  550. def test_choice_p_non_contiguous(self):
  551. p = np.ones(10) / 5
  552. p[1::2] = 3.0
  553. random.seed(self.seed)
  554. non_contig = random.choice(5, 3, p=p[::2])
  555. random.seed(self.seed)
  556. contig = random.choice(5, 3, p=np.ascontiguousarray(p[::2]))
  557. assert_array_equal(non_contig, contig)
  558. def test_bytes(self):
  559. random.seed(self.seed)
  560. actual = random.bytes(10)
  561. desired = b'\x82Ui\x9e\xff\x97+Wf\xa5'
  562. assert_equal(actual, desired)
  563. def test_shuffle(self):
  564. # Test lists, arrays (of various dtypes), and multidimensional versions
  565. # of both, c-contiguous or not:
  566. for conv in [lambda x: np.array([]),
  567. lambda x: x,
  568. lambda x: np.asarray(x).astype(np.int8),
  569. lambda x: np.asarray(x).astype(np.float32),
  570. lambda x: np.asarray(x).astype(np.complex64),
  571. lambda x: np.asarray(x).astype(object),
  572. lambda x: [(i, i) for i in x],
  573. lambda x: np.asarray([[i, i] for i in x]),
  574. lambda x: np.vstack([x, x]).T,
  575. # gh-11442
  576. lambda x: (np.asarray([(i, i) for i in x],
  577. [("a", int), ("b", int)])
  578. .view(np.recarray)),
  579. # gh-4270
  580. lambda x: np.asarray([(i, i) for i in x],
  581. [("a", object, (1,)),
  582. ("b", np.int32, (1,))])]:
  583. random.seed(self.seed)
  584. alist = conv([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])
  585. random.shuffle(alist)
  586. actual = alist
  587. desired = conv([0, 1, 9, 6, 2, 4, 5, 8, 7, 3])
  588. assert_array_equal(actual, desired)
  589. def test_shuffle_masked(self):
  590. # gh-3263
  591. a = np.ma.masked_values(np.reshape(range(20), (5, 4)) % 3 - 1, -1)
  592. b = np.ma.masked_values(np.arange(20) % 3 - 1, -1)
  593. a_orig = a.copy()
  594. b_orig = b.copy()
  595. for i in range(50):
  596. random.shuffle(a)
  597. assert_equal(
  598. sorted(a.data[~a.mask]), sorted(a_orig.data[~a_orig.mask]))
  599. random.shuffle(b)
  600. assert_equal(
  601. sorted(b.data[~b.mask]), sorted(b_orig.data[~b_orig.mask]))
  602. def test_shuffle_invalid_objects(self):
  603. x = np.array(3)
  604. assert_raises(TypeError, random.shuffle, x)
  605. def test_permutation(self):
  606. random.seed(self.seed)
  607. alist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
  608. actual = random.permutation(alist)
  609. desired = [0, 1, 9, 6, 2, 4, 5, 8, 7, 3]
  610. assert_array_equal(actual, desired)
  611. random.seed(self.seed)
  612. arr_2d = np.atleast_2d([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]).T
  613. actual = random.permutation(arr_2d)
  614. assert_array_equal(actual, np.atleast_2d(desired).T)
  615. random.seed(self.seed)
  616. bad_x_str = "abcd"
  617. assert_raises(IndexError, random.permutation, bad_x_str)
  618. random.seed(self.seed)
  619. bad_x_float = 1.2
  620. assert_raises(IndexError, random.permutation, bad_x_float)
  621. integer_val = 10
  622. desired = [9, 0, 8, 5, 1, 3, 4, 7, 6, 2]
  623. random.seed(self.seed)
  624. actual = random.permutation(integer_val)
  625. assert_array_equal(actual, desired)
  626. def test_beta(self):
  627. random.seed(self.seed)
  628. actual = random.beta(.1, .9, size=(3, 2))
  629. desired = np.array(
  630. [[1.45341850513746058e-02, 5.31297615662868145e-04],
  631. [1.85366619058432324e-06, 4.19214516800110563e-03],
  632. [1.58405155108498093e-04, 1.26252891949397652e-04]])
  633. assert_array_almost_equal(actual, desired, decimal=15)
  634. def test_binomial(self):
  635. random.seed(self.seed)
  636. actual = random.binomial(100.123, .456, size=(3, 2))
  637. desired = np.array([[37, 43],
  638. [42, 48],
  639. [46, 45]])
  640. assert_array_equal(actual, desired)
  641. random.seed(self.seed)
  642. actual = random.binomial(100.123, .456)
  643. desired = 37
  644. assert_array_equal(actual, desired)
  645. def test_chisquare(self):
  646. random.seed(self.seed)
  647. actual = random.chisquare(50, size=(3, 2))
  648. desired = np.array([[63.87858175501090585, 68.68407748911370447],
  649. [65.77116116901505904, 47.09686762438974483],
  650. [72.3828403199695174, 74.18408615260374006]])
  651. assert_array_almost_equal(actual, desired, decimal=13)
  652. def test_dirichlet(self):
  653. random.seed(self.seed)
  654. alpha = np.array([51.72840233779265162, 39.74494232180943953])
  655. actual = random.dirichlet(alpha, size=(3, 2))
  656. desired = np.array([[[0.54539444573611562, 0.45460555426388438],
  657. [0.62345816822039413, 0.37654183177960598]],
  658. [[0.55206000085785778, 0.44793999914214233],
  659. [0.58964023305154301, 0.41035976694845688]],
  660. [[0.59266909280647828, 0.40733090719352177],
  661. [0.56974431743975207, 0.43025568256024799]]])
  662. assert_array_almost_equal(actual, desired, decimal=15)
  663. bad_alpha = np.array([5.4e-01, -1.0e-16])
  664. assert_raises(ValueError, random.dirichlet, bad_alpha)
  665. random.seed(self.seed)
  666. alpha = np.array([51.72840233779265162, 39.74494232180943953])
  667. actual = random.dirichlet(alpha)
  668. assert_array_almost_equal(actual, desired[0, 0], decimal=15)
  669. def test_dirichlet_size(self):
  670. # gh-3173
  671. p = np.array([51.72840233779265162, 39.74494232180943953])
  672. assert_equal(random.dirichlet(p, np.uint32(1)).shape, (1, 2))
  673. assert_equal(random.dirichlet(p, np.uint32(1)).shape, (1, 2))
  674. assert_equal(random.dirichlet(p, np.uint32(1)).shape, (1, 2))
  675. assert_equal(random.dirichlet(p, [2, 2]).shape, (2, 2, 2))
  676. assert_equal(random.dirichlet(p, (2, 2)).shape, (2, 2, 2))
  677. assert_equal(random.dirichlet(p, np.array((2, 2))).shape, (2, 2, 2))
  678. assert_raises(TypeError, random.dirichlet, p, float(1))
  679. def test_dirichlet_bad_alpha(self):
  680. # gh-2089
  681. alpha = np.array([5.4e-01, -1.0e-16])
  682. assert_raises(ValueError, random.dirichlet, alpha)
  683. def test_dirichlet_alpha_non_contiguous(self):
  684. a = np.array([51.72840233779265162, -1.0, 39.74494232180943953])
  685. alpha = a[::2]
  686. random.seed(self.seed)
  687. non_contig = random.dirichlet(alpha, size=(3, 2))
  688. random.seed(self.seed)
  689. contig = random.dirichlet(np.ascontiguousarray(alpha),
  690. size=(3, 2))
  691. assert_array_almost_equal(non_contig, contig)
  692. def test_exponential(self):
  693. random.seed(self.seed)
  694. actual = random.exponential(1.1234, size=(3, 2))
  695. desired = np.array([[1.08342649775011624, 1.00607889924557314],
  696. [2.46628830085216721, 2.49668106809923884],
  697. [0.68717433461363442, 1.69175666993575979]])
  698. assert_array_almost_equal(actual, desired, decimal=15)
  699. def test_exponential_0(self):
  700. assert_equal(random.exponential(scale=0), 0)
  701. assert_raises(ValueError, random.exponential, scale=-0.)
  702. def test_f(self):
  703. random.seed(self.seed)
  704. actual = random.f(12, 77, size=(3, 2))
  705. desired = np.array([[1.21975394418575878, 1.75135759791559775],
  706. [1.44803115017146489, 1.22108959480396262],
  707. [1.02176975757740629, 1.34431827623300415]])
  708. assert_array_almost_equal(actual, desired, decimal=15)
  709. def test_gamma(self):
  710. random.seed(self.seed)
  711. actual = random.gamma(5, 3, size=(3, 2))
  712. desired = np.array([[24.60509188649287182, 28.54993563207210627],
  713. [26.13476110204064184, 12.56988482927716078],
  714. [31.71863275789960568, 33.30143302795922011]])
  715. assert_array_almost_equal(actual, desired, decimal=14)
  716. def test_gamma_0(self):
  717. assert_equal(random.gamma(shape=0, scale=0), 0)
  718. assert_raises(ValueError, random.gamma, shape=-0., scale=-0.)
  719. def test_geometric(self):
  720. random.seed(self.seed)
  721. actual = random.geometric(.123456789, size=(3, 2))
  722. desired = np.array([[8, 7],
  723. [17, 17],
  724. [5, 12]])
  725. assert_array_equal(actual, desired)
  726. def test_geometric_exceptions(self):
  727. assert_raises(ValueError, random.geometric, 1.1)
  728. assert_raises(ValueError, random.geometric, [1.1] * 10)
  729. assert_raises(ValueError, random.geometric, -0.1)
  730. assert_raises(ValueError, random.geometric, [-0.1] * 10)
  731. with suppress_warnings() as sup:
  732. sup.record(RuntimeWarning)
  733. assert_raises(ValueError, random.geometric, np.nan)
  734. assert_raises(ValueError, random.geometric, [np.nan] * 10)
  735. def test_gumbel(self):
  736. random.seed(self.seed)
  737. actual = random.gumbel(loc=.123456789, scale=2.0, size=(3, 2))
  738. desired = np.array([[0.19591898743416816, 0.34405539668096674],
  739. [-1.4492522252274278, -1.47374816298446865],
  740. [1.10651090478803416, -0.69535848626236174]])
  741. assert_array_almost_equal(actual, desired, decimal=15)
  742. def test_gumbel_0(self):
  743. assert_equal(random.gumbel(scale=0), 0)
  744. assert_raises(ValueError, random.gumbel, scale=-0.)
  745. def test_hypergeometric(self):
  746. random.seed(self.seed)
  747. actual = random.hypergeometric(10.1, 5.5, 14, size=(3, 2))
  748. desired = np.array([[10, 10],
  749. [10, 10],
  750. [9, 9]])
  751. assert_array_equal(actual, desired)
  752. # Test nbad = 0
  753. actual = random.hypergeometric(5, 0, 3, size=4)
  754. desired = np.array([3, 3, 3, 3])
  755. assert_array_equal(actual, desired)
  756. actual = random.hypergeometric(15, 0, 12, size=4)
  757. desired = np.array([12, 12, 12, 12])
  758. assert_array_equal(actual, desired)
  759. # Test ngood = 0
  760. actual = random.hypergeometric(0, 5, 3, size=4)
  761. desired = np.array([0, 0, 0, 0])
  762. assert_array_equal(actual, desired)
  763. actual = random.hypergeometric(0, 15, 12, size=4)
  764. desired = np.array([0, 0, 0, 0])
  765. assert_array_equal(actual, desired)
  766. def test_laplace(self):
  767. random.seed(self.seed)
  768. actual = random.laplace(loc=.123456789, scale=2.0, size=(3, 2))
  769. desired = np.array([[0.66599721112760157, 0.52829452552221945],
  770. [3.12791959514407125, 3.18202813572992005],
  771. [-0.05391065675859356, 1.74901336242837324]])
  772. assert_array_almost_equal(actual, desired, decimal=15)
  773. def test_laplace_0(self):
  774. assert_equal(random.laplace(scale=0), 0)
  775. assert_raises(ValueError, random.laplace, scale=-0.)
  776. def test_logistic(self):
  777. random.seed(self.seed)
  778. actual = random.logistic(loc=.123456789, scale=2.0, size=(3, 2))
  779. desired = np.array([[1.09232835305011444, 0.8648196662399954],
  780. [4.27818590694950185, 4.33897006346929714],
  781. [-0.21682183359214885, 2.63373365386060332]])
  782. assert_array_almost_equal(actual, desired, decimal=15)
  783. def test_lognormal(self):
  784. random.seed(self.seed)
  785. actual = random.lognormal(mean=.123456789, sigma=2.0, size=(3, 2))
  786. desired = np.array([[16.50698631688883822, 36.54846706092654784],
  787. [22.67886599981281748, 0.71617561058995771],
  788. [65.72798501792723869, 86.84341601437161273]])
  789. assert_array_almost_equal(actual, desired, decimal=13)
  790. def test_lognormal_0(self):
  791. assert_equal(random.lognormal(sigma=0), 1)
  792. assert_raises(ValueError, random.lognormal, sigma=-0.)
  793. def test_logseries(self):
  794. random.seed(self.seed)
  795. actual = random.logseries(p=.923456789, size=(3, 2))
  796. desired = np.array([[2, 2],
  797. [6, 17],
  798. [3, 6]])
  799. assert_array_equal(actual, desired)
  800. def test_logseries_exceptions(self):
  801. with suppress_warnings() as sup:
  802. sup.record(RuntimeWarning)
  803. assert_raises(ValueError, random.logseries, np.nan)
  804. assert_raises(ValueError, random.logseries, [np.nan] * 10)
  805. def test_multinomial(self):
  806. random.seed(self.seed)
  807. actual = random.multinomial(20, [1 / 6.] * 6, size=(3, 2))
  808. desired = np.array([[[4, 3, 5, 4, 2, 2],
  809. [5, 2, 8, 2, 2, 1]],
  810. [[3, 4, 3, 6, 0, 4],
  811. [2, 1, 4, 3, 6, 4]],
  812. [[4, 4, 2, 5, 2, 3],
  813. [4, 3, 4, 2, 3, 4]]])
  814. assert_array_equal(actual, desired)
  815. def test_multivariate_normal(self):
  816. random.seed(self.seed)
  817. mean = (.123456789, 10)
  818. cov = [[1, 0], [0, 1]]
  819. size = (3, 2)
  820. actual = random.multivariate_normal(mean, cov, size)
  821. desired = np.array([[[1.463620246718631, 11.73759122771936],
  822. [1.622445133300628, 9.771356667546383]],
  823. [[2.154490787682787, 12.170324946056553],
  824. [1.719909438201865, 9.230548443648306]],
  825. [[0.689515026297799, 9.880729819607714],
  826. [-0.023054015651998, 9.201096623542879]]])
  827. assert_array_almost_equal(actual, desired, decimal=15)
  828. # Check for default size, was raising deprecation warning
  829. actual = random.multivariate_normal(mean, cov)
  830. desired = np.array([0.895289569463708, 9.17180864067987])
  831. assert_array_almost_equal(actual, desired, decimal=15)
  832. # Check that non positive-semidefinite covariance warns with
  833. # RuntimeWarning
  834. mean = [0, 0]
  835. cov = [[1, 2], [2, 1]]
  836. assert_warns(RuntimeWarning, random.multivariate_normal, mean, cov)
  837. # and that it doesn't warn with RuntimeWarning check_valid='ignore'
  838. assert_no_warnings(random.multivariate_normal, mean, cov,
  839. check_valid='ignore')
  840. # and that it raises with RuntimeWarning check_valid='raises'
  841. assert_raises(ValueError, random.multivariate_normal, mean, cov,
  842. check_valid='raise')
  843. cov = np.array([[1, 0.1], [0.1, 1]], dtype=np.float32)
  844. with suppress_warnings() as sup:
  845. random.multivariate_normal(mean, cov)
  846. w = sup.record(RuntimeWarning)
  847. assert len(w) == 0
  848. mu = np.zeros(2)
  849. cov = np.eye(2)
  850. assert_raises(ValueError, random.multivariate_normal, mean, cov,
  851. check_valid='other')
  852. assert_raises(ValueError, random.multivariate_normal,
  853. np.zeros((2, 1, 1)), cov)
  854. assert_raises(ValueError, random.multivariate_normal,
  855. mu, np.empty((3, 2)))
  856. assert_raises(ValueError, random.multivariate_normal,
  857. mu, np.eye(3))
  858. def test_negative_binomial(self):
  859. random.seed(self.seed)
  860. actual = random.negative_binomial(n=100, p=.12345, size=(3, 2))
  861. desired = np.array([[848, 841],
  862. [892, 611],
  863. [779, 647]])
  864. assert_array_equal(actual, desired)
  865. def test_negative_binomial_exceptions(self):
  866. with suppress_warnings() as sup:
  867. sup.record(RuntimeWarning)
  868. assert_raises(ValueError, random.negative_binomial, 100, np.nan)
  869. assert_raises(ValueError, random.negative_binomial, 100,
  870. [np.nan] * 10)
  871. def test_noncentral_chisquare(self):
  872. random.seed(self.seed)
  873. actual = random.noncentral_chisquare(df=5, nonc=5, size=(3, 2))
  874. desired = np.array([[23.91905354498517511, 13.35324692733826346],
  875. [31.22452661329736401, 16.60047399466177254],
  876. [5.03461598262724586, 17.94973089023519464]])
  877. assert_array_almost_equal(actual, desired, decimal=14)
  878. actual = random.noncentral_chisquare(df=.5, nonc=.2, size=(3, 2))
  879. desired = np.array([[1.47145377828516666, 0.15052899268012659],
  880. [0.00943803056963588, 1.02647251615666169],
  881. [0.332334982684171, 0.15451287602753125]])
  882. assert_array_almost_equal(actual, desired, decimal=14)
  883. random.seed(self.seed)
  884. actual = random.noncentral_chisquare(df=5, nonc=0, size=(3, 2))
  885. desired = np.array([[9.597154162763948, 11.725484450296079],
  886. [10.413711048138335, 3.694475922923986],
  887. [13.484222138963087, 14.377255424602957]])
  888. assert_array_almost_equal(actual, desired, decimal=14)
  889. def test_noncentral_f(self):
  890. random.seed(self.seed)
  891. actual = random.noncentral_f(dfnum=5, dfden=2, nonc=1,
  892. size=(3, 2))
  893. desired = np.array([[1.40598099674926669, 0.34207973179285761],
  894. [3.57715069265772545, 7.92632662577829805],
  895. [0.43741599463544162, 1.1774208752428319]])
  896. assert_array_almost_equal(actual, desired, decimal=14)
  897. def test_noncentral_f_nan(self):
  898. random.seed(self.seed)
  899. actual = random.noncentral_f(dfnum=5, dfden=2, nonc=np.nan)
  900. assert np.isnan(actual)
  901. def test_normal(self):
  902. random.seed(self.seed)
  903. actual = random.normal(loc=.123456789, scale=2.0, size=(3, 2))
  904. desired = np.array([[2.80378370443726244, 3.59863924443872163],
  905. [3.121433477601256, -0.33382987590723379],
  906. [4.18552478636557357, 4.46410668111310471]])
  907. assert_array_almost_equal(actual, desired, decimal=15)
  908. def test_normal_0(self):
  909. assert_equal(random.normal(scale=0), 0)
  910. assert_raises(ValueError, random.normal, scale=-0.)
  911. def test_pareto(self):
  912. random.seed(self.seed)
  913. actual = random.pareto(a=.123456789, size=(3, 2))
  914. desired = np.array(
  915. [[2.46852460439034849e+03, 1.41286880810518346e+03],
  916. [5.28287797029485181e+07, 6.57720981047328785e+07],
  917. [1.40840323350391515e+02, 1.98390255135251704e+05]])
  918. # For some reason on 32-bit x86 Ubuntu 12.10 the [1, 0] entry in this
  919. # matrix differs by 24 nulps. Discussion:
  920. # https://mail.python.org/pipermail/numpy-discussion/2012-September/063801.html
  921. # Consensus is that this is probably some gcc quirk that affects
  922. # rounding but not in any important way, so we just use a looser
  923. # tolerance on this test:
  924. np.testing.assert_array_almost_equal_nulp(actual, desired, nulp=30)
  925. def test_poisson(self):
  926. random.seed(self.seed)
  927. actual = random.poisson(lam=.123456789, size=(3, 2))
  928. desired = np.array([[0, 0],
  929. [1, 0],
  930. [0, 0]])
  931. assert_array_equal(actual, desired)
  932. def test_poisson_exceptions(self):
  933. lambig = np.iinfo('l').max
  934. lamneg = -1
  935. assert_raises(ValueError, random.poisson, lamneg)
  936. assert_raises(ValueError, random.poisson, [lamneg] * 10)
  937. assert_raises(ValueError, random.poisson, lambig)
  938. assert_raises(ValueError, random.poisson, [lambig] * 10)
  939. with suppress_warnings() as sup:
  940. sup.record(RuntimeWarning)
  941. assert_raises(ValueError, random.poisson, np.nan)
  942. assert_raises(ValueError, random.poisson, [np.nan] * 10)
  943. def test_power(self):
  944. random.seed(self.seed)
  945. actual = random.power(a=.123456789, size=(3, 2))
  946. desired = np.array([[0.02048932883240791, 0.01424192241128213],
  947. [0.38446073748535298, 0.39499689943484395],
  948. [0.00177699707563439, 0.13115505880863756]])
  949. assert_array_almost_equal(actual, desired, decimal=15)
  950. def test_rayleigh(self):
  951. random.seed(self.seed)
  952. actual = random.rayleigh(scale=10, size=(3, 2))
  953. desired = np.array([[13.8882496494248393, 13.383318339044731],
  954. [20.95413364294492098, 21.08285015800712614],
  955. [11.06066537006854311, 17.35468505778271009]])
  956. assert_array_almost_equal(actual, desired, decimal=14)
  957. def test_rayleigh_0(self):
  958. assert_equal(random.rayleigh(scale=0), 0)
  959. assert_raises(ValueError, random.rayleigh, scale=-0.)
  960. def test_standard_cauchy(self):
  961. random.seed(self.seed)
  962. actual = random.standard_cauchy(size=(3, 2))
  963. desired = np.array([[0.77127660196445336, -6.55601161955910605],
  964. [0.93582023391158309, -2.07479293013759447],
  965. [-4.74601644297011926, 0.18338989290760804]])
  966. assert_array_almost_equal(actual, desired, decimal=15)
  967. def test_standard_exponential(self):
  968. random.seed(self.seed)
  969. actual = random.standard_exponential(size=(3, 2))
  970. desired = np.array([[0.96441739162374596, 0.89556604882105506],
  971. [2.1953785836319808, 2.22243285392490542],
  972. [0.6116915921431676, 1.50592546727413201]])
  973. assert_array_almost_equal(actual, desired, decimal=15)
  974. def test_standard_gamma(self):
  975. random.seed(self.seed)
  976. actual = random.standard_gamma(shape=3, size=(3, 2))
  977. desired = np.array([[5.50841531318455058, 6.62953470301903103],
  978. [5.93988484943779227, 2.31044849402133989],
  979. [7.54838614231317084, 8.012756093271868]])
  980. assert_array_almost_equal(actual, desired, decimal=14)
  981. def test_standard_gamma_0(self):
  982. assert_equal(random.standard_gamma(shape=0), 0)
  983. assert_raises(ValueError, random.standard_gamma, shape=-0.)
  984. def test_standard_normal(self):
  985. random.seed(self.seed)
  986. actual = random.standard_normal(size=(3, 2))
  987. desired = np.array([[1.34016345771863121, 1.73759122771936081],
  988. [1.498988344300628, -0.2286433324536169],
  989. [2.031033998682787, 2.17032494605655257]])
  990. assert_array_almost_equal(actual, desired, decimal=15)
  991. def test_randn_singleton(self):
  992. random.seed(self.seed)
  993. actual = random.randn()
  994. desired = np.array(1.34016345771863121)
  995. assert_array_almost_equal(actual, desired, decimal=15)
  996. def test_standard_t(self):
  997. random.seed(self.seed)
  998. actual = random.standard_t(df=10, size=(3, 2))
  999. desired = np.array([[0.97140611862659965, -0.08830486548450577],
  1000. [1.36311143689505321, -0.55317463909867071],
  1001. [-0.18473749069684214, 0.61181537341755321]])
  1002. assert_array_almost_equal(actual, desired, decimal=15)
  1003. def test_triangular(self):
  1004. random.seed(self.seed)
  1005. actual = random.triangular(left=5.12, mode=10.23, right=20.34,
  1006. size=(3, 2))
  1007. desired = np.array([[12.68117178949215784, 12.4129206149193152],
  1008. [16.20131377335158263, 16.25692138747600524],
  1009. [11.20400690911820263, 14.4978144835829923]])
  1010. assert_array_almost_equal(actual, desired, decimal=14)
  1011. def test_uniform(self):
  1012. random.seed(self.seed)
  1013. actual = random.uniform(low=1.23, high=10.54, size=(3, 2))
  1014. desired = np.array([[6.99097932346268003, 6.73801597444323974],
  1015. [9.50364421400426274, 9.53130618907631089],
  1016. [5.48995325769805476, 8.47493103280052118]])
  1017. assert_array_almost_equal(actual, desired, decimal=15)
  1018. def test_uniform_range_bounds(self):
  1019. fmin = np.finfo('float').min
  1020. fmax = np.finfo('float').max
  1021. func = random.uniform
  1022. assert_raises(OverflowError, func, -np.inf, 0)
  1023. assert_raises(OverflowError, func, 0, np.inf)
  1024. assert_raises(OverflowError, func, fmin, fmax)
  1025. assert_raises(OverflowError, func, [-np.inf], [0])
  1026. assert_raises(OverflowError, func, [0], [np.inf])
  1027. # (fmax / 1e17) - fmin is within range, so this should not throw
  1028. # account for i386 extended precision DBL_MAX / 1e17 + DBL_MAX >
  1029. # DBL_MAX by increasing fmin a bit
  1030. random.uniform(low=np.nextafter(fmin, 1), high=fmax / 1e17)
  1031. def test_scalar_exception_propagation(self):
  1032. # Tests that exceptions are correctly propagated in distributions
  1033. # when called with objects that throw exceptions when converted to
  1034. # scalars.
  1035. #
  1036. # Regression test for gh: 8865
  1037. class ThrowingFloat(np.ndarray):
  1038. def __float__(self):
  1039. raise TypeError
  1040. throwing_float = np.array(1.0).view(ThrowingFloat)
  1041. assert_raises(TypeError, random.uniform, throwing_float,
  1042. throwing_float)
  1043. class ThrowingInteger(np.ndarray):
  1044. def __int__(self):
  1045. raise TypeError
  1046. throwing_int = np.array(1).view(ThrowingInteger)
  1047. assert_raises(TypeError, random.hypergeometric, throwing_int, 1, 1)
  1048. def test_vonmises(self):
  1049. random.seed(self.seed)
  1050. actual = random.vonmises(mu=1.23, kappa=1.54, size=(3, 2))
  1051. desired = np.array([[2.28567572673902042, 2.89163838442285037],
  1052. [0.38198375564286025, 2.57638023113890746],
  1053. [1.19153771588353052, 1.83509849681825354]])
  1054. assert_array_almost_equal(actual, desired, decimal=15)
  1055. def test_vonmises_small(self):
  1056. # check infinite loop, gh-4720
  1057. random.seed(self.seed)
  1058. r = random.vonmises(mu=0., kappa=1.1e-8, size=10**6)
  1059. assert_(np.isfinite(r).all())
  1060. def test_vonmises_large(self):
  1061. # guard against changes in RandomState when Generator is fixed
  1062. random.seed(self.seed)
  1063. actual = random.vonmises(mu=0., kappa=1e7, size=3)
  1064. desired = np.array([4.634253748521111e-04,
  1065. 3.558873596114509e-04,
  1066. -2.337119622577433e-04])
  1067. assert_array_almost_equal(actual, desired, decimal=8)
  1068. def test_vonmises_nan(self):
  1069. random.seed(self.seed)
  1070. r = random.vonmises(mu=0., kappa=np.nan)
  1071. assert_(np.isnan(r))
  1072. def test_wald(self):
  1073. random.seed(self.seed)
  1074. actual = random.wald(mean=1.23, scale=1.54, size=(3, 2))
  1075. desired = np.array([[3.82935265715889983, 5.13125249184285526],
  1076. [0.35045403618358717, 1.50832396872003538],
  1077. [0.24124319895843183, 0.22031101461955038]])
  1078. assert_array_almost_equal(actual, desired, decimal=14)
  1079. def test_weibull(self):
  1080. random.seed(self.seed)
  1081. actual = random.weibull(a=1.23, size=(3, 2))
  1082. desired = np.array([[0.97097342648766727, 0.91422896443565516],
  1083. [1.89517770034962929, 1.91414357960479564],
  1084. [0.67057783752390987, 1.39494046635066793]])
  1085. assert_array_almost_equal(actual, desired, decimal=15)
  1086. def test_weibull_0(self):
  1087. random.seed(self.seed)
  1088. assert_equal(random.weibull(a=0, size=12), np.zeros(12))
  1089. assert_raises(ValueError, random.weibull, a=-0.)
  1090. def test_zipf(self):
  1091. random.seed(self.seed)
  1092. actual = random.zipf(a=1.23, size=(3, 2))
  1093. desired = np.array([[66, 29],
  1094. [1, 1],
  1095. [3, 13]])
  1096. assert_array_equal(actual, desired)
  1097. class TestBroadcast:
  1098. # tests that functions that broadcast behave
  1099. # correctly when presented with non-scalar arguments
  1100. def setup(self):
  1101. self.seed = 123456789
  1102. def set_seed(self):
  1103. random.seed(self.seed)
  1104. def test_uniform(self):
  1105. low = [0]
  1106. high = [1]
  1107. uniform = random.uniform
  1108. desired = np.array([0.53283302478975902,
  1109. 0.53413660089041659,
  1110. 0.50955303552646702])
  1111. self.set_seed()
  1112. actual = uniform(low * 3, high)
  1113. assert_array_almost_equal(actual, desired, decimal=14)
  1114. self.set_seed()
  1115. actual = uniform(low, high * 3)
  1116. assert_array_almost_equal(actual, desired, decimal=14)
  1117. def test_normal(self):
  1118. loc = [0]
  1119. scale = [1]
  1120. bad_scale = [-1]
  1121. normal = random.normal
  1122. desired = np.array([2.2129019979039612,
  1123. 2.1283977976520019,
  1124. 1.8417114045748335])
  1125. self.set_seed()
  1126. actual = normal(loc * 3, scale)
  1127. assert_array_almost_equal(actual, desired, decimal=14)
  1128. assert_raises(ValueError, normal, loc * 3, bad_scale)
  1129. self.set_seed()
  1130. actual = normal(loc, scale * 3)
  1131. assert_array_almost_equal(actual, desired, decimal=14)
  1132. assert_raises(ValueError, normal, loc, bad_scale * 3)
  1133. def test_beta(self):
  1134. a = [1]
  1135. b = [2]
  1136. bad_a = [-1]
  1137. bad_b = [-2]
  1138. beta = random.beta
  1139. desired = np.array([0.19843558305989056,
  1140. 0.075230336409423643,
  1141. 0.24976865978980844])
  1142. self.set_seed()
  1143. actual = beta(a * 3, b)
  1144. assert_array_almost_equal(actual, desired, decimal=14)
  1145. assert_raises(ValueError, beta, bad_a * 3, b)
  1146. assert_raises(ValueError, beta, a * 3, bad_b)
  1147. self.set_seed()
  1148. actual = beta(a, b * 3)
  1149. assert_array_almost_equal(actual, desired, decimal=14)
  1150. assert_raises(ValueError, beta, bad_a, b * 3)
  1151. assert_raises(ValueError, beta, a, bad_b * 3)
  1152. def test_exponential(self):
  1153. scale = [1]
  1154. bad_scale = [-1]
  1155. exponential = random.exponential
  1156. desired = np.array([0.76106853658845242,
  1157. 0.76386282278691653,
  1158. 0.71243813125891797])
  1159. self.set_seed()
  1160. actual = exponential(scale * 3)
  1161. assert_array_almost_equal(actual, desired, decimal=14)
  1162. assert_raises(ValueError, exponential, bad_scale * 3)
  1163. def test_standard_gamma(self):
  1164. shape = [1]
  1165. bad_shape = [-1]
  1166. std_gamma = random.standard_gamma
  1167. desired = np.array([0.76106853658845242,
  1168. 0.76386282278691653,
  1169. 0.71243813125891797])
  1170. self.set_seed()
  1171. actual = std_gamma(shape * 3)
  1172. assert_array_almost_equal(actual, desired, decimal=14)
  1173. assert_raises(ValueError, std_gamma, bad_shape * 3)
  1174. def test_gamma(self):
  1175. shape = [1]
  1176. scale = [2]
  1177. bad_shape = [-1]
  1178. bad_scale = [-2]
  1179. gamma = random.gamma
  1180. desired = np.array([1.5221370731769048,
  1181. 1.5277256455738331,
  1182. 1.4248762625178359])
  1183. self.set_seed()
  1184. actual = gamma(shape * 3, scale)
  1185. assert_array_almost_equal(actual, desired, decimal=14)
  1186. assert_raises(ValueError, gamma, bad_shape * 3, scale)
  1187. assert_raises(ValueError, gamma, shape * 3, bad_scale)
  1188. self.set_seed()
  1189. actual = gamma(shape, scale * 3)
  1190. assert_array_almost_equal(actual, desired, decimal=14)
  1191. assert_raises(ValueError, gamma, bad_shape, scale * 3)
  1192. assert_raises(ValueError, gamma, shape, bad_scale * 3)
  1193. def test_f(self):
  1194. dfnum = [1]
  1195. dfden = [2]
  1196. bad_dfnum = [-1]
  1197. bad_dfden = [-2]
  1198. f = random.f
  1199. desired = np.array([0.80038951638264799,
  1200. 0.86768719635363512,
  1201. 2.7251095168386801])
  1202. self.set_seed()
  1203. actual = f(dfnum * 3, dfden)
  1204. assert_array_almost_equal(actual, desired, decimal=14)
  1205. assert_raises(ValueError, f, bad_dfnum * 3, dfden)
  1206. assert_raises(ValueError, f, dfnum * 3, bad_dfden)
  1207. self.set_seed()
  1208. actual = f(dfnum, dfden * 3)
  1209. assert_array_almost_equal(actual, desired, decimal=14)
  1210. assert_raises(ValueError, f, bad_dfnum, dfden * 3)
  1211. assert_raises(ValueError, f, dfnum, bad_dfden * 3)
  1212. def test_noncentral_f(self):
  1213. dfnum = [2]
  1214. dfden = [3]
  1215. nonc = [4]
  1216. bad_dfnum = [0]
  1217. bad_dfden = [-1]
  1218. bad_nonc = [-2]
  1219. nonc_f = random.noncentral_f
  1220. desired = np.array([9.1393943263705211,
  1221. 13.025456344595602,
  1222. 8.8018098359100545])
  1223. self.set_seed()
  1224. actual = nonc_f(dfnum * 3, dfden, nonc)
  1225. assert_array_almost_equal(actual, desired, decimal=14)
  1226. assert np.all(np.isnan(nonc_f(dfnum, dfden, [np.nan] * 3)))
  1227. assert_raises(ValueError, nonc_f, bad_dfnum * 3, dfden, nonc)
  1228. assert_raises(ValueError, nonc_f, dfnum * 3, bad_dfden, nonc)
  1229. assert_raises(ValueError, nonc_f, dfnum * 3, dfden, bad_nonc)
  1230. self.set_seed()
  1231. actual = nonc_f(dfnum, dfden * 3, nonc)
  1232. assert_array_almost_equal(actual, desired, decimal=14)
  1233. assert_raises(ValueError, nonc_f, bad_dfnum, dfden * 3, nonc)
  1234. assert_raises(ValueError, nonc_f, dfnum, bad_dfden * 3, nonc)
  1235. assert_raises(ValueError, nonc_f, dfnum, dfden * 3, bad_nonc)
  1236. self.set_seed()
  1237. actual = nonc_f(dfnum, dfden, nonc * 3)
  1238. assert_array_almost_equal(actual, desired, decimal=14)
  1239. assert_raises(ValueError, nonc_f, bad_dfnum, dfden, nonc * 3)
  1240. assert_raises(ValueError, nonc_f, dfnum, bad_dfden, nonc * 3)
  1241. assert_raises(ValueError, nonc_f, dfnum, dfden, bad_nonc * 3)
  1242. def test_noncentral_f_small_df(self):
  1243. self.set_seed()
  1244. desired = np.array([6.869638627492048, 0.785880199263955])
  1245. actual = random.noncentral_f(0.9, 0.9, 2, size=2)
  1246. assert_array_almost_equal(actual, desired, decimal=14)
  1247. def test_chisquare(self):
  1248. df = [1]
  1249. bad_df = [-1]
  1250. chisquare = random.chisquare
  1251. desired = np.array([0.57022801133088286,
  1252. 0.51947702108840776,
  1253. 0.1320969254923558])
  1254. self.set_seed()
  1255. actual = chisquare(df * 3)
  1256. assert_array_almost_equal(actual, desired, decimal=14)
  1257. assert_raises(ValueError, chisquare, bad_df * 3)
  1258. def test_noncentral_chisquare(self):
  1259. df = [1]
  1260. nonc = [2]
  1261. bad_df = [-1]
  1262. bad_nonc = [-2]
  1263. nonc_chi = random.noncentral_chisquare
  1264. desired = np.array([9.0015599467913763,
  1265. 4.5804135049718742,
  1266. 6.0872302432834564])
  1267. self.set_seed()
  1268. actual = nonc_chi(df * 3, nonc)
  1269. assert_array_almost_equal(actual, desired, decimal=14)
  1270. assert_raises(ValueError, nonc_chi, bad_df * 3, nonc)
  1271. assert_raises(ValueError, nonc_chi, df * 3, bad_nonc)
  1272. self.set_seed()
  1273. actual = nonc_chi(df, nonc * 3)
  1274. assert_array_almost_equal(actual, desired, decimal=14)
  1275. assert_raises(ValueError, nonc_chi, bad_df, nonc * 3)
  1276. assert_raises(ValueError, nonc_chi, df, bad_nonc * 3)
  1277. def test_standard_t(self):
  1278. df = [1]
  1279. bad_df = [-1]
  1280. t = random.standard_t
  1281. desired = np.array([3.0702872575217643,
  1282. 5.8560725167361607,
  1283. 1.0274791436474273])
  1284. self.set_seed()
  1285. actual = t(df * 3)
  1286. assert_array_almost_equal(actual, desired, decimal=14)
  1287. assert_raises(ValueError, t, bad_df * 3)
  1288. assert_raises(ValueError, random.standard_t, bad_df * 3)
  1289. def test_vonmises(self):
  1290. mu = [2]
  1291. kappa = [1]
  1292. bad_kappa = [-1]
  1293. vonmises = random.vonmises
  1294. desired = np.array([2.9883443664201312,
  1295. -2.7064099483995943,
  1296. -1.8672476700665914])
  1297. self.set_seed()
  1298. actual = vonmises(mu * 3, kappa)
  1299. assert_array_almost_equal(actual, desired, decimal=14)
  1300. assert_raises(ValueError, vonmises, mu * 3, bad_kappa)
  1301. self.set_seed()
  1302. actual = vonmises(mu, kappa * 3)
  1303. assert_array_almost_equal(actual, desired, decimal=14)
  1304. assert_raises(ValueError, vonmises, mu, bad_kappa * 3)
  1305. def test_pareto(self):
  1306. a = [1]
  1307. bad_a = [-1]
  1308. pareto = random.pareto
  1309. desired = np.array([1.1405622680198362,
  1310. 1.1465519762044529,
  1311. 1.0389564467453547])
  1312. self.set_seed()
  1313. actual = pareto(a * 3)
  1314. assert_array_almost_equal(actual, desired, decimal=14)
  1315. assert_raises(ValueError, pareto, bad_a * 3)
  1316. assert_raises(ValueError, random.pareto, bad_a * 3)
  1317. def test_weibull(self):
  1318. a = [1]
  1319. bad_a = [-1]
  1320. weibull = random.weibull
  1321. desired = np.array([0.76106853658845242,
  1322. 0.76386282278691653,
  1323. 0.71243813125891797])
  1324. self.set_seed()
  1325. actual = weibull(a * 3)
  1326. assert_array_almost_equal(actual, desired, decimal=14)
  1327. assert_raises(ValueError, weibull, bad_a * 3)
  1328. assert_raises(ValueError, random.weibull, bad_a * 3)
  1329. def test_power(self):
  1330. a = [1]
  1331. bad_a = [-1]
  1332. power = random.power
  1333. desired = np.array([0.53283302478975902,
  1334. 0.53413660089041659,
  1335. 0.50955303552646702])
  1336. self.set_seed()
  1337. actual = power(a * 3)
  1338. assert_array_almost_equal(actual, desired, decimal=14)
  1339. assert_raises(ValueError, power, bad_a * 3)
  1340. assert_raises(ValueError, random.power, bad_a * 3)
  1341. def test_laplace(self):
  1342. loc = [0]
  1343. scale = [1]
  1344. bad_scale = [-1]
  1345. laplace = random.laplace
  1346. desired = np.array([0.067921356028507157,
  1347. 0.070715642226971326,
  1348. 0.019290950698972624])
  1349. self.set_seed()
  1350. actual = laplace(loc * 3, scale)
  1351. assert_array_almost_equal(actual, desired, decimal=14)
  1352. assert_raises(ValueError, laplace, loc * 3, bad_scale)
  1353. self.set_seed()
  1354. actual = laplace(loc, scale * 3)
  1355. assert_array_almost_equal(actual, desired, decimal=14)
  1356. assert_raises(ValueError, laplace, loc, bad_scale * 3)
  1357. def test_gumbel(self):
  1358. loc = [0]
  1359. scale = [1]
  1360. bad_scale = [-1]
  1361. gumbel = random.gumbel
  1362. desired = np.array([0.2730318639556768,
  1363. 0.26936705726291116,
  1364. 0.33906220393037939])
  1365. self.set_seed()
  1366. actual = gumbel(loc * 3, scale)
  1367. assert_array_almost_equal(actual, desired, decimal=14)
  1368. assert_raises(ValueError, gumbel, loc * 3, bad_scale)
  1369. self.set_seed()
  1370. actual = gumbel(loc, scale * 3)
  1371. assert_array_almost_equal(actual, desired, decimal=14)
  1372. assert_raises(ValueError, gumbel, loc, bad_scale * 3)
  1373. def test_logistic(self):
  1374. loc = [0]
  1375. scale = [1]
  1376. bad_scale = [-1]
  1377. logistic = random.logistic
  1378. desired = np.array([0.13152135837586171,
  1379. 0.13675915696285773,
  1380. 0.038216792802833396])
  1381. self.set_seed()
  1382. actual = logistic(loc * 3, scale)
  1383. assert_array_almost_equal(actual, desired, decimal=14)
  1384. assert_raises(ValueError, logistic, loc * 3, bad_scale)
  1385. self.set_seed()
  1386. actual = logistic(loc, scale * 3)
  1387. assert_array_almost_equal(actual, desired, decimal=14)
  1388. assert_raises(ValueError, logistic, loc, bad_scale * 3)
  1389. assert_equal(random.logistic(1.0, 0.0), 1.0)
  1390. def test_lognormal(self):
  1391. mean = [0]
  1392. sigma = [1]
  1393. bad_sigma = [-1]
  1394. lognormal = random.lognormal
  1395. desired = np.array([9.1422086044848427,
  1396. 8.4013952870126261,
  1397. 6.3073234116578671])
  1398. self.set_seed()
  1399. actual = lognormal(mean * 3, sigma)
  1400. assert_array_almost_equal(actual, desired, decimal=14)
  1401. assert_raises(ValueError, lognormal, mean * 3, bad_sigma)
  1402. assert_raises(ValueError, random.lognormal, mean * 3, bad_sigma)
  1403. self.set_seed()
  1404. actual = lognormal(mean, sigma * 3)
  1405. assert_array_almost_equal(actual, desired, decimal=14)
  1406. assert_raises(ValueError, lognormal, mean, bad_sigma * 3)
  1407. assert_raises(ValueError, random.lognormal, mean, bad_sigma * 3)
  1408. def test_rayleigh(self):
  1409. scale = [1]
  1410. bad_scale = [-1]
  1411. rayleigh = random.rayleigh
  1412. desired = np.array([1.2337491937897689,
  1413. 1.2360119924878694,
  1414. 1.1936818095781789])
  1415. self.set_seed()
  1416. actual = rayleigh(scale * 3)
  1417. assert_array_almost_equal(actual, desired, decimal=14)
  1418. assert_raises(ValueError, rayleigh, bad_scale * 3)
  1419. def test_wald(self):
  1420. mean = [0.5]
  1421. scale = [1]
  1422. bad_mean = [0]
  1423. bad_scale = [-2]
  1424. wald = random.wald
  1425. desired = np.array([0.11873681120271318,
  1426. 0.12450084820795027,
  1427. 0.9096122728408238])
  1428. self.set_seed()
  1429. actual = wald(mean * 3, scale)
  1430. assert_array_almost_equal(actual, desired, decimal=14)
  1431. assert_raises(ValueError, wald, bad_mean * 3, scale)
  1432. assert_raises(ValueError, wald, mean * 3, bad_scale)
  1433. assert_raises(ValueError, random.wald, bad_mean * 3, scale)
  1434. assert_raises(ValueError, random.wald, mean * 3, bad_scale)
  1435. self.set_seed()
  1436. actual = wald(mean, scale * 3)
  1437. assert_array_almost_equal(actual, desired, decimal=14)
  1438. assert_raises(ValueError, wald, bad_mean, scale * 3)
  1439. assert_raises(ValueError, wald, mean, bad_scale * 3)
  1440. assert_raises(ValueError, wald, 0.0, 1)
  1441. assert_raises(ValueError, wald, 0.5, 0.0)
  1442. def test_triangular(self):
  1443. left = [1]
  1444. right = [3]
  1445. mode = [2]
  1446. bad_left_one = [3]
  1447. bad_mode_one = [4]
  1448. bad_left_two, bad_mode_two = right * 2
  1449. triangular = random.triangular
  1450. desired = np.array([2.03339048710429,
  1451. 2.0347400359389356,
  1452. 2.0095991069536208])
  1453. self.set_seed()
  1454. actual = triangular(left * 3, mode, right)
  1455. assert_array_almost_equal(actual, desired, decimal=14)
  1456. assert_raises(ValueError, triangular, bad_left_one * 3, mode, right)
  1457. assert_raises(ValueError, triangular, left * 3, bad_mode_one, right)
  1458. assert_raises(ValueError, triangular, bad_left_two * 3, bad_mode_two,
  1459. right)
  1460. self.set_seed()
  1461. actual = triangular(left, mode * 3, right)
  1462. assert_array_almost_equal(actual, desired, decimal=14)
  1463. assert_raises(ValueError, triangular, bad_left_one, mode * 3, right)
  1464. assert_raises(ValueError, triangular, left, bad_mode_one * 3, right)
  1465. assert_raises(ValueError, triangular, bad_left_two, bad_mode_two * 3,
  1466. right)
  1467. self.set_seed()
  1468. actual = triangular(left, mode, right * 3)
  1469. assert_array_almost_equal(actual, desired, decimal=14)
  1470. assert_raises(ValueError, triangular, bad_left_one, mode, right * 3)
  1471. assert_raises(ValueError, triangular, left, bad_mode_one, right * 3)
  1472. assert_raises(ValueError, triangular, bad_left_two, bad_mode_two,
  1473. right * 3)
  1474. assert_raises(ValueError, triangular, 10., 0., 20.)
  1475. assert_raises(ValueError, triangular, 10., 25., 20.)
  1476. assert_raises(ValueError, triangular, 10., 10., 10.)
  1477. def test_binomial(self):
  1478. n = [1]
  1479. p = [0.5]
  1480. bad_n = [-1]
  1481. bad_p_one = [-1]
  1482. bad_p_two = [1.5]
  1483. binom = random.binomial
  1484. desired = np.array([1, 1, 1])
  1485. self.set_seed()
  1486. actual = binom(n * 3, p)
  1487. assert_array_equal(actual, desired)
  1488. assert_raises(ValueError, binom, bad_n * 3, p)
  1489. assert_raises(ValueError, binom, n * 3, bad_p_one)
  1490. assert_raises(ValueError, binom, n * 3, bad_p_two)
  1491. self.set_seed()
  1492. actual = binom(n, p * 3)
  1493. assert_array_equal(actual, desired)
  1494. assert_raises(ValueError, binom, bad_n, p * 3)
  1495. assert_raises(ValueError, binom, n, bad_p_one * 3)
  1496. assert_raises(ValueError, binom, n, bad_p_two * 3)
  1497. def test_negative_binomial(self):
  1498. n = [1]
  1499. p = [0.5]
  1500. bad_n = [-1]
  1501. bad_p_one = [-1]
  1502. bad_p_two = [1.5]
  1503. neg_binom = random.negative_binomial
  1504. desired = np.array([1, 0, 1])
  1505. self.set_seed()
  1506. actual = neg_binom(n * 3, p)
  1507. assert_array_equal(actual, desired)
  1508. assert_raises(ValueError, neg_binom, bad_n * 3, p)
  1509. assert_raises(ValueError, neg_binom, n * 3, bad_p_one)
  1510. assert_raises(ValueError, neg_binom, n * 3, bad_p_two)
  1511. self.set_seed()
  1512. actual = neg_binom(n, p * 3)
  1513. assert_array_equal(actual, desired)
  1514. assert_raises(ValueError, neg_binom, bad_n, p * 3)
  1515. assert_raises(ValueError, neg_binom, n, bad_p_one * 3)
  1516. assert_raises(ValueError, neg_binom, n, bad_p_two * 3)
  1517. def test_poisson(self):
  1518. max_lam = random.RandomState()._poisson_lam_max
  1519. lam = [1]
  1520. bad_lam_one = [-1]
  1521. bad_lam_two = [max_lam * 2]
  1522. poisson = random.poisson
  1523. desired = np.array([1, 1, 0])
  1524. self.set_seed()
  1525. actual = poisson(lam * 3)
  1526. assert_array_equal(actual, desired)
  1527. assert_raises(ValueError, poisson, bad_lam_one * 3)
  1528. assert_raises(ValueError, poisson, bad_lam_two * 3)
  1529. def test_zipf(self):
  1530. a = [2]
  1531. bad_a = [0]
  1532. zipf = random.zipf
  1533. desired = np.array([2, 2, 1])
  1534. self.set_seed()
  1535. actual = zipf(a * 3)
  1536. assert_array_equal(actual, desired)
  1537. assert_raises(ValueError, zipf, bad_a * 3)
  1538. with np.errstate(invalid='ignore'):
  1539. assert_raises(ValueError, zipf, np.nan)
  1540. assert_raises(ValueError, zipf, [0, 0, np.nan])
  1541. def test_geometric(self):
  1542. p = [0.5]
  1543. bad_p_one = [-1]
  1544. bad_p_two = [1.5]
  1545. geom = random.geometric
  1546. desired = np.array([2, 2, 2])
  1547. self.set_seed()
  1548. actual = geom(p * 3)
  1549. assert_array_equal(actual, desired)
  1550. assert_raises(ValueError, geom, bad_p_one * 3)
  1551. assert_raises(ValueError, geom, bad_p_two * 3)
  1552. def test_hypergeometric(self):
  1553. ngood = [1]
  1554. nbad = [2]
  1555. nsample = [2]
  1556. bad_ngood = [-1]
  1557. bad_nbad = [-2]
  1558. bad_nsample_one = [0]
  1559. bad_nsample_two = [4]
  1560. hypergeom = random.hypergeometric
  1561. desired = np.array([1, 1, 1])
  1562. self.set_seed()
  1563. actual = hypergeom(ngood * 3, nbad, nsample)
  1564. assert_array_equal(actual, desired)
  1565. assert_raises(ValueError, hypergeom, bad_ngood * 3, nbad, nsample)
  1566. assert_raises(ValueError, hypergeom, ngood * 3, bad_nbad, nsample)
  1567. assert_raises(ValueError, hypergeom, ngood * 3, nbad, bad_nsample_one)
  1568. assert_raises(ValueError, hypergeom, ngood * 3, nbad, bad_nsample_two)
  1569. self.set_seed()
  1570. actual = hypergeom(ngood, nbad * 3, nsample)
  1571. assert_array_equal(actual, desired)
  1572. assert_raises(ValueError, hypergeom, bad_ngood, nbad * 3, nsample)
  1573. assert_raises(ValueError, hypergeom, ngood, bad_nbad * 3, nsample)
  1574. assert_raises(ValueError, hypergeom, ngood, nbad * 3, bad_nsample_one)
  1575. assert_raises(ValueError, hypergeom, ngood, nbad * 3, bad_nsample_two)
  1576. self.set_seed()
  1577. actual = hypergeom(ngood, nbad, nsample * 3)
  1578. assert_array_equal(actual, desired)
  1579. assert_raises(ValueError, hypergeom, bad_ngood, nbad, nsample * 3)
  1580. assert_raises(ValueError, hypergeom, ngood, bad_nbad, nsample * 3)
  1581. assert_raises(ValueError, hypergeom, ngood, nbad, bad_nsample_one * 3)
  1582. assert_raises(ValueError, hypergeom, ngood, nbad, bad_nsample_two * 3)
  1583. assert_raises(ValueError, hypergeom, -1, 10, 20)
  1584. assert_raises(ValueError, hypergeom, 10, -1, 20)
  1585. assert_raises(ValueError, hypergeom, 10, 10, 0)
  1586. assert_raises(ValueError, hypergeom, 10, 10, 25)
  1587. def test_logseries(self):
  1588. p = [0.5]
  1589. bad_p_one = [2]
  1590. bad_p_two = [-1]
  1591. logseries = random.logseries
  1592. desired = np.array([1, 1, 1])
  1593. self.set_seed()
  1594. actual = logseries(p * 3)
  1595. assert_array_equal(actual, desired)
  1596. assert_raises(ValueError, logseries, bad_p_one * 3)
  1597. assert_raises(ValueError, logseries, bad_p_two * 3)
  1598. class TestThread:
  1599. # make sure each state produces the same sequence even in threads
  1600. def setup(self):
  1601. self.seeds = range(4)
  1602. def check_function(self, function, sz):
  1603. from threading import Thread
  1604. out1 = np.empty((len(self.seeds),) + sz)
  1605. out2 = np.empty((len(self.seeds),) + sz)
  1606. # threaded generation
  1607. t = [Thread(target=function, args=(random.RandomState(s), o))
  1608. for s, o in zip(self.seeds, out1)]
  1609. [x.start() for x in t]
  1610. [x.join() for x in t]
  1611. # the same serial
  1612. for s, o in zip(self.seeds, out2):
  1613. function(random.RandomState(s), o)
  1614. # these platforms change x87 fpu precision mode in threads
  1615. if np.intp().dtype.itemsize == 4 and sys.platform == "win32":
  1616. assert_array_almost_equal(out1, out2)
  1617. else:
  1618. assert_array_equal(out1, out2)
  1619. def test_normal(self):
  1620. def gen_random(state, out):
  1621. out[...] = state.normal(size=10000)
  1622. self.check_function(gen_random, sz=(10000,))
  1623. def test_exp(self):
  1624. def gen_random(state, out):
  1625. out[...] = state.exponential(scale=np.ones((100, 1000)))
  1626. self.check_function(gen_random, sz=(100, 1000))
  1627. def test_multinomial(self):
  1628. def gen_random(state, out):
  1629. out[...] = state.multinomial(10, [1 / 6.] * 6, size=10000)
  1630. self.check_function(gen_random, sz=(10000, 6))
  1631. # See Issue #4263
  1632. class TestSingleEltArrayInput:
  1633. def setup(self):
  1634. self.argOne = np.array([2])
  1635. self.argTwo = np.array([3])
  1636. self.argThree = np.array([4])
  1637. self.tgtShape = (1,)
  1638. def test_one_arg_funcs(self):
  1639. funcs = (random.exponential, random.standard_gamma,
  1640. random.chisquare, random.standard_t,
  1641. random.pareto, random.weibull,
  1642. random.power, random.rayleigh,
  1643. random.poisson, random.zipf,
  1644. random.geometric, random.logseries)
  1645. probfuncs = (random.geometric, random.logseries)
  1646. for func in funcs:
  1647. if func in probfuncs: # p < 1.0
  1648. out = func(np.array([0.5]))
  1649. else:
  1650. out = func(self.argOne)
  1651. assert_equal(out.shape, self.tgtShape)
  1652. def test_two_arg_funcs(self):
  1653. funcs = (random.uniform, random.normal,
  1654. random.beta, random.gamma,
  1655. random.f, random.noncentral_chisquare,
  1656. random.vonmises, random.laplace,
  1657. random.gumbel, random.logistic,
  1658. random.lognormal, random.wald,
  1659. random.binomial, random.negative_binomial)
  1660. probfuncs = (random.binomial, random.negative_binomial)
  1661. for func in funcs:
  1662. if func in probfuncs: # p <= 1
  1663. argTwo = np.array([0.5])
  1664. else:
  1665. argTwo = self.argTwo
  1666. out = func(self.argOne, argTwo)
  1667. assert_equal(out.shape, self.tgtShape)
  1668. out = func(self.argOne[0], argTwo)
  1669. assert_equal(out.shape, self.tgtShape)
  1670. out = func(self.argOne, argTwo[0])
  1671. assert_equal(out.shape, self.tgtShape)
  1672. def test_three_arg_funcs(self):
  1673. funcs = [random.noncentral_f, random.triangular,
  1674. random.hypergeometric]
  1675. for func in funcs:
  1676. out = func(self.argOne, self.argTwo, self.argThree)
  1677. assert_equal(out.shape, self.tgtShape)
  1678. out = func(self.argOne[0], self.argTwo, self.argThree)
  1679. assert_equal(out.shape, self.tgtShape)
  1680. out = func(self.argOne, self.argTwo[0], self.argThree)
  1681. assert_equal(out.shape, self.tgtShape)
  1682. # Ensure returned array dtype is correct for platform
  1683. def test_integer_dtype(int_func):
  1684. random.seed(123456789)
  1685. fname, args, sha256 = int_func
  1686. f = getattr(random, fname)
  1687. actual = f(*args, size=2)
  1688. assert_(actual.dtype == np.dtype('l'))
  1689. def test_integer_repeat(int_func):
  1690. random.seed(123456789)
  1691. fname, args, sha256 = int_func
  1692. f = getattr(random, fname)
  1693. val = f(*args, size=1000000)
  1694. if sys.byteorder != 'little':
  1695. val = val.byteswap()
  1696. res = hashlib.sha256(val.view(np.int8)).hexdigest()
  1697. assert_(res == sha256)
  1698. def test_broadcast_size_error():
  1699. # GH-16833
  1700. with pytest.raises(ValueError):
  1701. random.binomial(1, [0.3, 0.7], size=(2, 1))
  1702. with pytest.raises(ValueError):
  1703. random.binomial([1, 2], 0.3, size=(2, 1))
  1704. with pytest.raises(ValueError):
  1705. random.binomial([1, 2], [0.3, 0.7], size=(2, 1))