test_randomstate.py 79 KB

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