test_randomstate.py 83 KB

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