test_randomstate.py 78 KB

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