test_generator_mt19937.py 103 KB

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