test_randomstate.py 83 KB

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