test_generator_mt19937.py 112 KB

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