test_generator_mt19937.py 115 KB

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