test_randomstate.py 83 KB

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