test_generator_mt19937.py 116 KB

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