Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes15kdownloads
test_randomstate.py2100 linesDownload Raw Back to tests
1import hashlib
2import pickle
3import sys
4import warnings
5
6import pytest
7
8import numpy as np
9from numpy import random
10from numpy.random import MT19937, PCG64
11from numpy.testing import (
12    IS_WASM,
13    assert_,
14    assert_array_almost_equal,
15    assert_array_equal,
16    assert_equal,
17    assert_no_warnings,
18    assert_raises,
19)
20
21INT_FUNCS = {'binomial': (100.0, 0.6),
22             'geometric': (.5,),
23             'hypergeometric': (20, 20, 10),
24             'logseries': (.5,),
25             'multinomial': (20, np.ones(6) / 6.0),
26             'negative_binomial': (100, .5),
27             'poisson': (10.0,),
28             'zipf': (2,),
29             }
30
31if np.iinfo(np.long).max < 2**32:
32    # Windows and some 32-bit platforms, e.g., ARM
33    INT_FUNC_HASHES = {'binomial':          '2fbead005fc63942decb5326d36a1f32fe2c9d32c904ee61e46866b88447c263',  # noqa: E501
34                       'logseries':         '23ead5dcde35d4cfd4ef2c105e4c3d43304b45dc1b1444b7823b9ee4fa144ebb',  # noqa: E501
35                       'geometric':         '0d764db64f5c3bad48c8c33551c13b4d07a1e7b470f77629bef6c985cac76fcf',  # noqa: E501
36                       'hypergeometric':    '7b59bf2f1691626c5815cdcd9a49e1dd68697251d4521575219e4d2a1b8b2c67',  # noqa: E501
37                       'multinomial':       'd754fa5b92943a38ec07630de92362dd2e02c43577fc147417dc5b9db94ccdd3',  # noqa: E501
38                       'negative_binomial': '8eb216f7cb2a63cf55605422845caaff002fddc64a7dc8b2d45acd477a49e824',  # noqa: E501
39                       'poisson':           '70c891d76104013ebd6f6bcf30d403a9074b886ff62e4e6b8eb605bf1a4673b7',  # noqa: E501
40                       'zipf':              '01f074f97517cd5d21747148ac6ca4074dde7fcb7acbaec0a936606fecacd93f',  # noqa: E501
41                       }
42else:
43    INT_FUNC_HASHES = {'binomial':          '8626dd9d052cb608e93d8868de0a7b347258b199493871a1dc56e2a26cacb112',  # noqa: E501
44                       'geometric':         '8edd53d272e49c4fc8fbbe6c7d08d563d62e482921f3131d0a0e068af30f0db9',  # noqa: E501
45                       'hypergeometric':    '83496cc4281c77b786c9b7ad88b74d42e01603a55c60577ebab81c3ba8d45657',  # noqa: E501
46                       'logseries':         '65878a38747c176bc00e930ebafebb69d4e1e16cd3a704e264ea8f5e24f548db',  # noqa: E501
47                       'multinomial':       '7a984ae6dca26fd25374479e118b22f55db0aedccd5a0f2584ceada33db98605',  # noqa: E501
48                       'negative_binomial': 'd636d968e6a24ae92ab52fe11c46ac45b0897e98714426764e820a7d77602a61',  # noqa: E501
49                       'poisson':           '956552176f77e7c9cb20d0118fc9cf690be488d790ed4b4c4747b965e61b0bb4',  # noqa: E501
50                       'zipf':              'f84ba7feffda41e606e20b28dfc0f1ea9964a74574513d4a4cbc98433a8bfa45',  # noqa: E501
51                       }
52
53
54@pytest.fixture(scope='module', params=INT_FUNCS)
55def int_func(request):
56    return (request.param, INT_FUNCS[request.param],
57            INT_FUNC_HASHES[request.param])
58
59
60@pytest.fixture
61def restore_singleton_bitgen():
62    """Ensures that the singleton bitgen is restored after a test"""
63    orig_bitgen = np.random.get_bit_generator()
64    yield
65    np.random.set_bit_generator(orig_bitgen)
66
67
68def assert_mt19937_state_equal(a, b):
69    assert_equal(a['bit_generator'], b['bit_generator'])
70    assert_array_equal(a['state']['key'], b['state']['key'])
71    assert_array_equal(a['state']['pos'], b['state']['pos'])
72    assert_equal(a['has_gauss'], b['has_gauss'])
73    assert_equal(a['gauss'], b['gauss'])
74
75
76class TestSeed:
77    def test_scalar(self):
78        s = random.RandomState(0)
79        assert_equal(s.randint(1000), 684)
80        s = random.RandomState(4294967295)
81        assert_equal(s.randint(1000), 419)
82
83    def test_array(self):
84        s = random.RandomState(range(10))
85        assert_equal(s.randint(1000), 468)
86        s = random.RandomState(np.arange(10))
87        assert_equal(s.randint(1000), 468)
88        s = random.RandomState([0])
89        assert_equal(s.randint(1000), 973)
90        s = random.RandomState([4294967295])
91        assert_equal(s.randint(1000), 265)
92
93    def test_invalid_scalar(self):
94        # seed must be an unsigned 32 bit integer
95        assert_raises(TypeError, random.RandomState, -0.5)
96        assert_raises(ValueError, random.RandomState, -1)
97
98    def test_invalid_array(self):
99        # seed must be an unsigned 32 bit integer
100        assert_raises(TypeError, random.RandomState, [-0.5])
101        assert_raises(ValueError, random.RandomState, [-1])
102        assert_raises(ValueError, random.RandomState, [4294967296])
103        assert_raises(ValueError, random.RandomState, [1, 2, 4294967296])
104        assert_raises(ValueError, random.RandomState, [1, -2, 4294967296])
105
106    def test_invalid_array_shape(self):
107        # gh-9832
108        assert_raises(ValueError, random.RandomState, np.array([],
109                                                               dtype=np.int64))
110        assert_raises(ValueError, random.RandomState, [[1, 2, 3]])
111        assert_raises(ValueError, random.RandomState, [[1, 2, 3],
112                                                       [4, 5, 6]])
113
114    def test_cannot_seed(self):
115        rs = random.RandomState(PCG64(0))
116        with assert_raises(TypeError):
117            rs.seed(1234)
118
119    def test_invalid_initialization(self):
120        assert_raises(ValueError, random.RandomState, MT19937)
121
122
123class TestBinomial:
124    def test_n_zero(self):
125        # Tests the corner case of n == 0 for the binomial distribution.
126        # binomial(0, p) should be zero for any p in [0, 1].
127        # This test addresses issue #3480.
128        zeros = np.zeros(2, dtype='int')
129        for p in [0, .5, 1]:
130            assert_(random.binomial(0, p) == 0)
131            assert_array_equal(random.binomial(zeros, p), zeros)
132
133    def test_p_is_nan(self):
134        # Issue #4571.
135        assert_raises(ValueError, random.binomial, 1, np.nan)
136
137
138class TestMultinomial:
139    def test_basic(self):
140        random.multinomial(100, [0.2, 0.8])
141
142    def test_zero_probability(self):
143        random.multinomial(100, [0.2, 0.8, 0.0, 0.0, 0.0])
144
145    def test_int_negative_interval(self):
146        assert_(-5 <= random.randint(-5, -1) < -1)
147        x = random.randint(-5, -1, 5)
148        assert_(np.all(-5 <= x))
149        assert_(np.all(x < -1))
150
151    def test_size(self):
152        # gh-3173
153        p = [0.5, 0.5]
154        assert_equal(random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
155        assert_equal(random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
156        assert_equal(random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
157        assert_equal(random.multinomial(1, p, [2, 2]).shape, (2, 2, 2))
158        assert_equal(random.multinomial(1, p, (2, 2)).shape, (2, 2, 2))
159        assert_equal(random.multinomial(1, p, np.array((2, 2))).shape,
160                     (2, 2, 2))
161
162        assert_raises(TypeError, random.multinomial, 1, p,
163                      float(1))
164
165    def test_invalid_prob(self):
166        assert_raises(ValueError, random.multinomial, 100, [1.1, 0.2])
167        assert_raises(ValueError, random.multinomial, 100, [-.1, 0.9])
168
169    def test_invalid_n(self):
170        assert_raises(ValueError, random.multinomial, -1, [0.8, 0.2])
171
172    def test_p_non_contiguous(self):
173        p = np.arange(15.)
174        p /= np.sum(p[1::3])
175        pvals = p[1::3]
176        rng = random.RandomState(1432985819)
177        non_contig = rng.multinomial(100, pvals=pvals)
178        rng = random.RandomState(1432985819)
179        contig = rng.multinomial(100, pvals=np.ascontiguousarray(pvals))
180        assert_array_equal(non_contig, contig)
181
182    def test_multinomial_pvals_float32(self):
183        x = np.array([9.9e-01, 9.9e-01, 1.0e-09, 1.0e-09, 1.0e-09, 1.0e-09,
184                      1.0e-09, 1.0e-09, 1.0e-09, 1.0e-09], dtype=np.float32)
185        pvals = x / x.sum()
186        match = r"[\w\s]*pvals array is cast to 64-bit floating"
187        with pytest.raises(ValueError, match=match):
188            random.multinomial(1, pvals)
189
190    def test_multinomial_n_float(self):
191        # Non-index integer types should gracefully truncate floats
192        random.multinomial(100.5, [0.2, 0.8])
193
194
195class TestSetState:
196    def _create_state(self):
197        seed = 1234567890
198        random_state = random.RandomState(seed)
199        state = random_state.get_state()
200        return random_state, state
201
202    def test_basic(self):
203        random_state, state = self._create_state()
204        old = random_state.tomaxint(16)
205        random_state.set_state(state)
206        new = random_state.tomaxint(16)
207        assert_(np.all(old == new))
208
209    def test_gaussian_reset(self):
210        # Make sure the cached every-other-Gaussian is reset.
211        random_state, state = self._create_state()
212        old = random_state.standard_normal(size=3)
213        random_state.set_state(state)
214        new = random_state.standard_normal(size=3)
215        assert_(np.all(old == new))
216
217    def test_gaussian_reset_in_media_res(self):
218        # When the state is saved with a cached Gaussian, make sure the
219        # cached Gaussian is restored.
220        random_state, state = self._create_state()
221        random_state.standard_normal()
222        state = random_state.get_state()
223        old = random_state.standard_normal(size=3)
224        random_state.set_state(state)
225        new = random_state.standard_normal(size=3)
226        assert_(np.all(old == new))
227
228    def test_backwards_compatibility(self):
229        # Make sure we can accept old state tuples that do not have the
230        # cached Gaussian value.
231        random_state, state = self._create_state()
232        old_state = state[:-2]
233        x1 = random_state.standard_normal(size=16)
234        random_state.set_state(old_state)
235        x2 = random_state.standard_normal(size=16)
236        random_state.set_state(state)
237        x3 = random_state.standard_normal(size=16)
238        assert_(np.all(x1 == x2))
239        assert_(np.all(x1 == x3))
240
241    def test_negative_binomial(self):
242        # Ensure that the negative binomial results take floating point
243        # arguments without truncation.
244        random_state, _ = self._create_state()
245        random_state.negative_binomial(0.5, 0.5)
246
247    def test_get_state_warning(self):
248        rs = random.RandomState(PCG64())
249        with pytest.warns(RuntimeWarning):
250            state = rs.get_state()
251        assert isinstance(state, dict)
252        assert state['bit_generator'] == 'PCG64'
253
254    def test_invalid_legacy_state_setting(self):
255        random_state, state = self._create_state()
256        state = random_state.get_state()
257        new_state = ('Unknown', ) + state[1:]
258        assert_raises(ValueError, random_state.set_state, new_state)
259        assert_raises(TypeError, random_state.set_state,
260                      np.array(new_state, dtype=object))
261        state = random_state.get_state(legacy=False)
262        del state['bit_generator']
263        assert_raises(ValueError, random_state.set_state, state)
264
265    def test_pickle(self):
266        random_state, _ = self._create_state()
267        random_state.seed(0)
268        random_state.random_sample(100)
269        random_state.standard_normal()
270        pickled = random_state.get_state(legacy=False)
271        assert_equal(pickled['has_gauss'], 1)
272        rs_unpick = pickle.loads(pickle.dumps(random_state))
273        unpickled = rs_unpick.get_state(legacy=False)
274        assert_mt19937_state_equal(pickled, unpickled)
275
276    def test_state_setting(self):
277        random_state, state = self._create_state()
278        attr_state = random_state.__getstate__()
279        random_state.standard_normal()
280        random_state.__setstate__(attr_state)
281        state = random_state.get_state(legacy=False)
282        assert_mt19937_state_equal(attr_state, state)
283
284    def test_repr(self):
285        random_state, _ = self._create_state()
286        assert repr(random_state).startswith('RandomState(MT19937)')
287
288
289class TestRandint:
290
291    # valid integer/boolean types
292    itype = [np.bool, np.int8, np.uint8, np.int16, np.uint16,
293             np.int32, np.uint32, np.int64, np.uint64]
294
295    def test_unsupported_type(self):
296        rng = np.random.RandomState()
297        assert_raises(TypeError, rng.randint, 1, dtype=float)
298
299    def test_bounds_checking(self):
300        rng = np.random.RandomState()
301        for dt in self.itype:
302            lbnd = 0 if dt is np.bool else np.iinfo(dt).min
303            ubnd = 2 if dt is np.bool else np.iinfo(dt).max + 1
304            assert_raises(ValueError, rng.randint, lbnd - 1, ubnd, dtype=dt)
305            assert_raises(ValueError, rng.randint, lbnd, ubnd + 1, dtype=dt)
306            assert_raises(ValueError, rng.randint, ubnd, lbnd, dtype=dt)
307            assert_raises(ValueError, rng.randint, 1, 0, dtype=dt)
308
309    def test_rng_zero_and_extremes(self):
310        rng = np.random.RandomState()
311        for dt in self.itype:
312            lbnd = 0 if dt is np.bool else np.iinfo(dt).min
313            ubnd = 2 if dt is np.bool else np.iinfo(dt).max + 1
314
315            tgt = ubnd - 1
316            assert_equal(rng.randint(tgt, tgt + 1, size=1000, dtype=dt), tgt)
317
318            tgt = lbnd
319            assert_equal(rng.randint(tgt, tgt + 1, size=1000, dtype=dt), tgt)
320
321            tgt = (lbnd + ubnd) // 2
322            assert_equal(rng.randint(tgt, tgt + 1, size=1000, dtype=dt), tgt)
323
324    def test_full_range(self):
325        # Test for ticket #1690
326        rng = np.random.RandomState()
327
328        for dt in self.itype:
329            lbnd = 0 if dt is np.bool else np.iinfo(dt).min
330            ubnd = 2 if dt is np.bool else np.iinfo(dt).max + 1
331
332            try:
333                rng.randint(lbnd, ubnd, dtype=dt)
334            except Exception as e:
335                raise AssertionError("No error should have been raised, "
336                                     "but one was with the following "
337                                     "message:\n\n%s" % str(e))
338
339    def test_in_bounds_fuzz(self):
340        # Don't use fixed seed
341        rng = np.random.RandomState()
342
343        for dt in self.itype[1:]:
344            for ubnd in [4, 8, 16]:
345                vals = rng.randint(2, ubnd, size=2**16, dtype=dt)
346                assert_(vals.max() < ubnd)
347                assert_(vals.min() >= 2)
348
349        vals = rng.randint(0, 2, size=2**16, dtype=np.bool)
350
351        assert_(vals.max() < 2)
352        assert_(vals.min() >= 0)
353
354    def test_repeatability(self):
355        # We use a sha256 hash of generated sequences of 1000 samples
356        # in the range [0, 6) for all but bool, where the range
357        # is [0, 2). Hashes are for little endian numbers.
358        tgt = {'bool':   '509aea74d792fb931784c4b0135392c65aec64beee12b0cc167548a2c3d31e71',  # noqa: E501
359               'int16':  '7b07f1a920e46f6d0fe02314155a2330bcfd7635e708da50e536c5ebb631a7d4',  # noqa: E501
360               'int32':  'e577bfed6c935de944424667e3da285012e741892dcb7051a8f1ce68ab05c92f',  # noqa: E501
361               'int64':  '0fbead0b06759df2cfb55e43148822d4a1ff953c7eb19a5b08445a63bb64fa9e',  # noqa: E501
362               'int8':   '001aac3a5acb935a9b186cbe14a1ca064b8bb2dd0b045d48abeacf74d0203404',  # noqa: E501
363               'uint16': '7b07f1a920e46f6d0fe02314155a2330bcfd7635e708da50e536c5ebb631a7d4',  # noqa: E501
364               'uint32': 'e577bfed6c935de944424667e3da285012e741892dcb7051a8f1ce68ab05c92f',  # noqa: E501
365               'uint64': '0fbead0b06759df2cfb55e43148822d4a1ff953c7eb19a5b08445a63bb64fa9e',  # noqa: E501
366               'uint8':  '001aac3a5acb935a9b186cbe14a1ca064b8bb2dd0b045d48abeacf74d0203404'}  # noqa: E501
367
368        for dt in self.itype[1:]:
369            rng = random.RandomState(1234)
370
371            # view as little endian for hash
372            if sys.byteorder == 'little':
373                val = rng.randint(0, 6, size=1000, dtype=dt)
374            else:
375                val = rng.randint(0, 6, size=1000, dtype=dt).byteswap()
376
377            res = hashlib.sha256(val.view(np.int8)).hexdigest()
378            assert_(tgt[np.dtype(dt).name] == res)
379
380        # bools do not depend on endianness
381        rng = random.RandomState(1234)
382        val = rng.randint(0, 2, size=1000, dtype=bool).view(np.int8)
383        res = hashlib.sha256(val).hexdigest()
384        assert_(tgt[np.dtype(bool).name] == res)
385
386    @pytest.mark.skipif(np.iinfo('l').max < 2**32,
387                        reason='Cannot test with 32-bit C long')
388    def test_repeatability_32bit_boundary_broadcasting(self):
389        desired = np.array([[[3992670689, 2438360420, 2557845020],
390                             [4107320065, 4142558326, 3216529513],
391                             [1605979228, 2807061240,  665605495]],
392                            [[3211410639, 4128781000,  457175120],
393                             [1712592594, 1282922662, 3081439808],
394                             [3997822960, 2008322436, 1563495165]],
395                            [[1398375547, 4269260146,  115316740],
396                             [3414372578, 3437564012, 2112038651],
397                             [3572980305, 2260248732, 3908238631]],
398                            [[2561372503,  223155946, 3127879445],
399                             [ 441282060, 3514786552, 2148440361],
400                             [1629275283, 3479737011, 3003195987]],
401                            [[ 412181688,  940383289, 3047321305],
402                             [2978368172,  764731833, 2282559898],
403                             [ 105711276,  720447391, 3596512484]]])
404        for size in [None, (5, 3, 3)]:
405            rng = random.RandomState(12345)
406            x = rng.randint([[-1], [0], [1]], [2**32 - 1, 2**32, 2**32 + 1],
407                           size=size)
408            assert_array_equal(x, desired if size is not None else desired[0])
409
410    def test_int64_uint64_corner_case(self):
411        # When stored in Numpy arrays, `lbnd` is casted
412        # as np.int64, and `ubnd` is casted as np.uint64.
413        # Checking whether `lbnd` >= `ubnd` used to be
414        # done solely via direct comparison, which is incorrect
415        # because when Numpy tries to compare both numbers,
416        # it casts both to np.float64 because there is
417        # no integer superset of np.int64 and np.uint64. However,
418        # `ubnd` is too large to be represented in np.float64,
419        # causing it be round down to np.iinfo(np.int64).max,
420        # leading to a ValueError because `lbnd` now equals
421        # the new `ubnd`.
422
423        dt = np.int64
424        tgt = np.iinfo(np.int64).max
425        lbnd = np.int64(np.iinfo(np.int64).max)
426        ubnd = np.uint64(np.iinfo(np.int64).max + 1)
427
428        # None of these function calls should
429        # generate a ValueError now.
430        actual = random.randint(lbnd, ubnd, dtype=dt)
431        assert_equal(actual, tgt)
432
433    def test_respect_dtype_singleton(self):
434        # See gh-7203
435        rng = np.random.RandomState()
436
437        for dt in self.itype:
438            lbnd = 0 if dt is np.bool else np.iinfo(dt).min
439            ubnd = 2 if dt is np.bool else np.iinfo(dt).max + 1
440
441            sample = rng.randint(lbnd, ubnd, dtype=dt)
442            assert_equal(sample.dtype, np.dtype(dt))
443
444        for dt in (bool, int):
445            # The legacy random generation forces the use of "long" on this
446            # branch even when the input is `int` and the default dtype
447            # for int changed (dtype=int is also the functions default)
448            op_dtype = "long" if dt is int else "bool"
449            lbnd = 0 if dt is bool else np.iinfo(op_dtype).min
450            ubnd = 2 if dt is bool else np.iinfo(op_dtype).max + 1
451
452            sample = rng.randint(lbnd, ubnd, dtype=dt)
453            assert_(not hasattr(sample, 'dtype'))
454            assert_equal(type(sample), dt)
455
456
457class TestRandomDist:
458    # Make sure the random distribution returns the correct value for a
459    # given seed
460    seed = 1234567890
461
462    def test_rand(self):
463        rng = random.RandomState(self.seed)
464        actual = rng.rand(3, 2)
465        desired = np.array([[0.61879477158567997, 0.59162362775974664],
466                            [0.88868358904449662, 0.89165480011560816],
467                            [0.4575674820298663, 0.7781880808593471]])
468        assert_array_almost_equal(actual, desired, decimal=15)
469
470    def test_rand_singleton(self):
471        rng = random.RandomState(self.seed)
472        actual = rng.rand()
473        desired = 0.61879477158567997
474        assert_array_almost_equal(actual, desired, decimal=15)
475
476    def test_randn(self):
477        rng = random.RandomState(self.seed)
478        actual = rng.randn(3, 2)
479        desired = np.array([[1.34016345771863121, 1.73759122771936081],
480                           [1.498988344300628, -0.2286433324536169],
481                           [2.031033998682787, 2.17032494605655257]])
482        assert_array_almost_equal(actual, desired, decimal=15)
483
484        rng = random.RandomState(self.seed)
485        actual = rng.randn()
486        assert_array_almost_equal(actual, desired[0, 0], decimal=15)
487
488    def test_randint(self):
489        rng = random.RandomState(self.seed)
490        actual = rng.randint(-99, 99, size=(3, 2))
491        desired = np.array([[31, 3],
492                            [-52, 41],
493                            [-48, -66]])
494        assert_array_equal(actual, desired)
495
496    def test_random_integers(self):
497        rng = random.RandomState(self.seed)
498        with pytest.warns(DeprecationWarning):
499            actual = rng.random_integers(-99, 99, size=(3, 2))
500        desired = np.array([[31, 3],
501                            [-52, 41],
502                            [-48, -66]])
503        assert_array_equal(actual, desired)
504
505        rng = random.RandomState(self.seed)
506        with pytest.warns(DeprecationWarning):
507            actual = rng.random_integers(198, size=(3, 2))
508        assert_array_equal(actual, desired + 100)
509
510    def test_tomaxint(self):
511        rs = random.RandomState(self.seed)
512        actual = rs.tomaxint(size=(3, 2))
513        if np.iinfo(np.long).max == 2147483647:
514            desired = np.array([[1328851649,  731237375],
515                                [1270502067,  320041495],
516                                [1908433478,  499156889]], dtype=np.int64)
517        else:
518            desired = np.array([[5707374374421908479, 5456764827585442327],
519                                [8196659375100692377, 8224063923314595285],
520                                [4220315081820346526, 7177518203184491332]],
521                               dtype=np.int64)
522
523        assert_equal(actual, desired)
524
525        rs.seed(self.seed)
526        actual = rs.tomaxint()
527        assert_equal(actual, desired[0, 0])
528
529    def test_random_integers_max_int(self):
530        # Tests whether random_integers can generate the
531        # maximum allowed Python int that can be converted
532        # into a C long. Previous implementations of this
533        # method have thrown an OverflowError when attempting
534        # to generate this integer.
535        with pytest.warns(DeprecationWarning):
536            actual = random.random_integers(np.iinfo('l').max,
537                                            np.iinfo('l').max)
538
539        desired = np.iinfo('l').max
540        assert_equal(actual, desired)
541        with pytest.warns(DeprecationWarning):
542            typer = np.dtype('l').type
543            actual = random.random_integers(typer(np.iinfo('l').max),
544                                            typer(np.iinfo('l').max))
545        assert_equal(actual, desired)
546
547    def test_random_integers_deprecated(self):
548        with warnings.catch_warnings():
549            warnings.simplefilter("error", DeprecationWarning)
550
551            # DeprecationWarning raised with high == None
552            assert_raises(DeprecationWarning,
553                          random.random_integers,
554                          np.iinfo('l').max)
555
556            # DeprecationWarning raised with high != None
557            assert_raises(DeprecationWarning,
558                          random.random_integers,
559                          np.iinfo('l').max, np.iinfo('l').max)
560
561    def test_random_sample(self):
562        rng = random.RandomState(self.seed)
563        actual = rng.random_sample((3, 2))
564        desired = np.array([[0.61879477158567997, 0.59162362775974664],
565                            [0.88868358904449662, 0.89165480011560816],
566                            [0.4575674820298663, 0.7781880808593471]])
567        assert_array_almost_equal(actual, desired, decimal=15)
568
569        rng = random.RandomState(self.seed)
570        actual = rng.random_sample()
571        assert_array_almost_equal(actual, desired[0, 0], decimal=15)
572
573    def test_choice_uniform_replace(self):
574        rng = random.RandomState(self.seed)
575        actual = rng.choice(4, 4)
576        desired = np.array([2, 3, 2, 3])
577        assert_array_equal(actual, desired)
578
579    def test_choice_nonuniform_replace(self):
580        rng = random.RandomState(self.seed)
581        actual = rng.choice(4, 4, p=[0.4, 0.4, 0.1, 0.1])
582        desired = np.array([1, 1, 2, 2])
583        assert_array_equal(actual, desired)
584
585    def test_choice_uniform_noreplace(self):
586        rng = random.RandomState(self.seed)
587        actual = rng.choice(4, 3, replace=False)
588        desired = np.array([0, 1, 3])
589        assert_array_equal(actual, desired)
590
591    def test_choice_nonuniform_noreplace(self):
592        rng = random.RandomState(self.seed)
593        actual = rng.choice(4, 3, replace=False, p=[0.1, 0.3, 0.5, 0.1])
594        desired = np.array([2, 3, 1])
595        assert_array_equal(actual, desired)
596
597    def test_choice_noninteger(self):
598        rng = random.RandomState(self.seed)
599        actual = rng.choice(['a', 'b', 'c', 'd'], 4)
600        desired = np.array(['c', 'd', 'c', 'd'])
601        assert_array_equal(actual, desired)
602
603    def test_choice_exceptions(self):
604        sample = random.choice
605        assert_raises(ValueError, sample, -1, 3)
606        assert_raises(ValueError, sample, 3., 3)
607        assert_raises(ValueError, sample, [[1, 2], [3, 4]], 3)
608        assert_raises(ValueError, sample, [], 3)
609        assert_raises(ValueError, sample, [1, 2, 3, 4], 3,
610                      p=[[0.25, 0.25], [0.25, 0.25]])
611        assert_raises(ValueError, sample, [1, 2], 3, p=[0.4, 0.4, 0.2])
612        assert_raises(ValueError, sample, [1, 2], 3, p=[1.1, -0.1])
613        assert_raises(ValueError, sample, [1, 2], 3, p=[0.4, 0.4])
614        assert_raises(ValueError, sample, [1, 2, 3], 4, replace=False)
615        # gh-13087
616        assert_raises(ValueError, sample, [1, 2, 3], -2, replace=False)
617        assert_raises(ValueError, sample, [1, 2, 3], (-1,), replace=False)
618        assert_raises(ValueError, sample, [1, 2, 3], (-1, 1), replace=False)
619        assert_raises(ValueError, sample, [1, 2, 3], 2,
620                      replace=False, p=[1, 0, 0])
621
622    def test_choice_return_shape(self):
623        p = [0.1, 0.9]
624        # Check scalar
625        assert_(np.isscalar(random.choice(2, replace=True)))
626        assert_(np.isscalar(random.choice(2, replace=False)))
627        assert_(np.isscalar(random.choice(2, replace=True, p=p)))
628        assert_(np.isscalar(random.choice(2, replace=False, p=p)))
629        assert_(np.isscalar(random.choice([1, 2], replace=True)))
630        assert_(random.choice([None], replace=True) is None)
631        a = np.array([1, 2])
632        arr = np.empty(1, dtype=object)
633        arr[0] = a
634        assert_(random.choice(arr, replace=True) is a)
635
636        # Check 0-d array
637        s = ()
638        assert_(not np.isscalar(random.choice(2, s, replace=True)))
639        assert_(not np.isscalar(random.choice(2, s, replace=False)))
640        assert_(not np.isscalar(random.choice(2, s, replace=True, p=p)))
641        assert_(not np.isscalar(random.choice(2, s, replace=False, p=p)))
642        assert_(not np.isscalar(random.choice([1, 2], s, replace=True)))
643        assert_(random.choice([None], s, replace=True).ndim == 0)
644        a = np.array([1, 2])
645        arr = np.empty(1, dtype=object)
646        arr[0] = a
647        assert_(random.choice(arr, s, replace=True).item() is a)
648
649        # Check multi dimensional array
650        s = (2, 3)
651        p = [0.1, 0.1, 0.1, 0.1, 0.4, 0.2]
652        assert_equal(random.choice(6, s, replace=True).shape, s)
653        assert_equal(random.choice(6, s, replace=False).shape, s)
654        assert_equal(random.choice(6, s, replace=True, p=p).shape, s)
655        assert_equal(random.choice(6, s, replace=False, p=p).shape, s)
656        assert_equal(random.choice(np.arange(6), s, replace=True).shape, s)
657
658        # Check zero-size
659        assert_equal(random.randint(0, 0, size=(3, 0, 4)).shape, (3, 0, 4))
660        assert_equal(random.randint(0, -10, size=0).shape, (0,))
661        assert_equal(random.randint(10, 10, size=0).shape, (0,))
662        assert_equal(random.choice(0, size=0).shape, (0,))
663        assert_equal(random.choice([], size=(0,)).shape, (0,))
664        assert_equal(random.choice(['a', 'b'], size=(3, 0, 4)).shape,
665                     (3, 0, 4))
666        assert_raises(ValueError, random.choice, [], 10)
667
668    def test_choice_nan_probabilities(self):
669        a = np.array([42, 1, 2])
670        p = [None, None, None]
671        assert_raises(ValueError, random.choice, a, p=p)
672
673    def test_choice_p_non_contiguous(self):
674        p = np.ones(10) / 5
675        p[1::2] = 3.0
676        rng = random.RandomState(self.seed)
677        non_contig = rng.choice(5, 3, p=p[::2])
678        rng = random.RandomState(self.seed)
679        contig = rng.choice(5, 3, p=np.ascontiguousarray(p[::2]))
680        assert_array_equal(non_contig, contig)
681
682    def test_bytes(self):
683        rng = random.RandomState(self.seed)
684        actual = rng.bytes(10)
685        desired = b'\x82Ui\x9e\xff\x97+Wf\xa5'
686        assert_equal(actual, desired)
687
688    def test_shuffle(self):
689        # Test lists, arrays (of various dtypes), and multidimensional versions
690        # of both, c-contiguous or not:
691        for conv in [lambda x: np.array([]),
692                     lambda x: x,
693                     lambda x: np.asarray(x).astype(np.int8),
694                     lambda x: np.asarray(x).astype(np.float32),
695                     lambda x: np.asarray(x).astype(np.complex64),
696                     lambda x: np.asarray(x).astype(object),
697                     lambda x: [(i, i) for i in x],
698                     lambda x: np.asarray([[i, i] for i in x]),
699                     lambda x: np.vstack([x, x]).T,
700                     # gh-11442
701                     lambda x: (np.asarray([(i, i) for i in x],
702                                           [("a", int), ("b", int)])
703                                .view(np.recarray)),
704                     # gh-4270
705                     lambda x: np.asarray([(i, i) for i in x],
706                                          [("a", object, (1,)),
707                                           ("b", np.int32, (1,))])]:
708            rng = random.RandomState(self.seed)
709            alist = conv([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])
710            rng.shuffle(alist)
711            actual = alist
712            desired = conv([0, 1, 9, 6, 2, 4, 5, 8, 7, 3])
713            assert_array_equal(actual, desired)
714
715    def test_shuffle_masked(self):
716        # gh-3263
717        a = np.ma.masked_values(np.reshape(range(20), (5, 4)) % 3 - 1, -1)
718        b = np.ma.masked_values(np.arange(20) % 3 - 1, -1)
719        a_orig = a.copy()
720        b_orig = b.copy()
721        for i in range(50):
722            random.shuffle(a)
723            assert_equal(
724                sorted(a.data[~a.mask]), sorted(a_orig.data[~a_orig.mask]))
725            random.shuffle(b)
726            assert_equal(
727                sorted(b.data[~b.mask]), sorted(b_orig.data[~b_orig.mask]))
728
729        def test_shuffle_invalid_objects(self):
730            x = np.array(3)
731            assert_raises(TypeError, random.shuffle, x)
732
733    def test_permutation(self):
734        rng = random.RandomState(self.seed)
735        alist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
736        actual = rng.permutation(alist)
737        desired = [0, 1, 9, 6, 2, 4, 5, 8, 7, 3]
738        assert_array_equal(actual, desired)
739
740        rng = random.RandomState(self.seed)
741        arr_2d = np.atleast_2d([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]).T
742        actual = rng.permutation(arr_2d)
743        assert_array_equal(actual, np.atleast_2d(desired).T)
744
745        rng = random.RandomState(self.seed)
746        bad_x_str = "abcd"
747        assert_raises(IndexError, random.permutation, bad_x_str)
748
749        rng = random.RandomState(self.seed)
750        bad_x_float = 1.2
751        assert_raises(IndexError, random.permutation, bad_x_float)
752
753        integer_val = 10
754        desired = [9, 0, 8, 5, 1, 3, 4, 7, 6, 2]
755
756        rng = random.RandomState(self.seed)
757        actual = rng.permutation(integer_val)
758        assert_array_equal(actual, desired)
759
760    def test_beta(self):
761        rng = random.RandomState(self.seed)
762        actual = rng.beta(.1, .9, size=(3, 2))
763        desired = np.array(
764                [[1.45341850513746058e-02, 5.31297615662868145e-04],
765                 [1.85366619058432324e-06, 4.19214516800110563e-03],
766                 [1.58405155108498093e-04, 1.26252891949397652e-04]])
767        assert_array_almost_equal(actual, desired, decimal=15)
768
769    def test_binomial(self):
770        rng = random.RandomState(self.seed)
771        actual = rng.binomial(100.123, .456, size=(3, 2))
772        desired = np.array([[37, 43],
773                            [42, 48],
774                            [46, 45]])
775        assert_array_equal(actual, desired)
776
777        rng = random.RandomState(self.seed)
778        actual = rng.binomial(100.123, .456)
779        desired = 37
780        assert_array_equal(actual, desired)
781
782    def test_chisquare(self):
783        rng = random.RandomState(self.seed)
784        actual = rng.chisquare(50, size=(3, 2))
785        desired = np.array([[63.87858175501090585, 68.68407748911370447],
786                            [65.77116116901505904, 47.09686762438974483],
787                            [72.3828403199695174, 74.18408615260374006]])
788        assert_array_almost_equal(actual, desired, decimal=13)
789
790    def test_dirichlet(self):
791        rng = random.RandomState(self.seed)
792        alpha = np.array([51.72840233779265162, 39.74494232180943953])
793        actual = rng.dirichlet(alpha, size=(3, 2))
794        desired = np.array([[[0.54539444573611562, 0.45460555426388438],
795                             [0.62345816822039413, 0.37654183177960598]],
796                            [[0.55206000085785778, 0.44793999914214233],
797                             [0.58964023305154301, 0.41035976694845688]],
798                            [[0.59266909280647828, 0.40733090719352177],
799                             [0.56974431743975207, 0.43025568256024799]]])
800        assert_array_almost_equal(actual, desired, decimal=15)
801        bad_alpha = np.array([5.4e-01, -1.0e-16])
802        assert_raises(ValueError, random.dirichlet, bad_alpha)
803
804        rng = random.RandomState(self.seed)
805        alpha = np.array([51.72840233779265162, 39.74494232180943953])
806        actual = rng.dirichlet(alpha)
807        assert_array_almost_equal(actual, desired[0, 0], decimal=15)
808
809    def test_dirichlet_size(self):
810        # gh-3173
811        p = np.array([51.72840233779265162, 39.74494232180943953])
812        assert_equal(random.dirichlet(p, np.uint32(1)).shape, (1, 2))
813        assert_equal(random.dirichlet(p, np.uint32(1)).shape, (1, 2))
814        assert_equal(random.dirichlet(p, np.uint32(1)).shape, (1, 2))
815        assert_equal(random.dirichlet(p, [2, 2]).shape, (2, 2, 2))
816        assert_equal(random.dirichlet(p, (2, 2)).shape, (2, 2, 2))
817        assert_equal(random.dirichlet(p, np.array((2, 2))).shape, (2, 2, 2))
818
819        assert_raises(TypeError, random.dirichlet, p, float(1))
820
821    def test_dirichlet_bad_alpha(self):
822        # gh-2089
823        alpha = np.array([5.4e-01, -1.0e-16])
824        assert_raises(ValueError, random.dirichlet, alpha)
825
826    def test_dirichlet_alpha_non_contiguous(self):
827        a = np.array([51.72840233779265162, -1.0, 39.74494232180943953])
828        alpha = a[::2]
829        rng = random.RandomState(self.seed)
830        non_contig = rng.dirichlet(alpha, size=(3, 2))
831        rng = random.RandomState(self.seed)
832        contig = rng.dirichlet(np.ascontiguousarray(alpha),
833                                  size=(3, 2))
834        assert_array_almost_equal(non_contig, contig)
835
836    def test_exponential(self):
837        rng = random.RandomState(self.seed)
838        actual = rng.exponential(1.1234, size=(3, 2))
839        desired = np.array([[1.08342649775011624, 1.00607889924557314],
840                            [2.46628830085216721, 2.49668106809923884],
841                            [0.68717433461363442, 1.69175666993575979]])
842        assert_array_almost_equal(actual, desired, decimal=15)
843
844    def test_exponential_0(self):
845        assert_equal(random.exponential(scale=0), 0)
846        assert_raises(ValueError, random.exponential, scale=-0.)
847
848    def test_f(self):
849        rng = random.RandomState(self.seed)
850        actual = rng.f(12, 77, size=(3, 2))
851        desired = np.array([[1.21975394418575878, 1.75135759791559775],
852                            [1.44803115017146489, 1.22108959480396262],
853                            [1.02176975757740629, 1.34431827623300415]])
854        assert_array_almost_equal(actual, desired, decimal=15)
855
856    def test_gamma(self):
857        rng = random.RandomState(self.seed)
858        actual = rng.gamma(5, 3, size=(3, 2))
859        desired = np.array([[24.60509188649287182, 28.54993563207210627],
860                            [26.13476110204064184, 12.56988482927716078],
861                            [31.71863275789960568, 33.30143302795922011]])
862        assert_array_almost_equal(actual, desired, decimal=14)
863
864    def test_gamma_0(self):
865        assert_equal(random.gamma(shape=0, scale=0), 0)
866        assert_raises(ValueError, random.gamma, shape=-0., scale=-0.)
867
868    def test_geometric(self):
869        rng = random.RandomState(self.seed)
870        actual = rng.geometric(.123456789, size=(3, 2))
871        desired = np.array([[8, 7],
872                            [17, 17],
873                            [5, 12]])
874        assert_array_equal(actual, desired)
875
876    def test_geometric_exceptions(self):
877        assert_raises(ValueError, random.geometric, 1.1)
878        assert_raises(ValueError, random.geometric, [1.1] * 10)
879        assert_raises(ValueError, random.geometric, -0.1)
880        assert_raises(ValueError, random.geometric, [-0.1] * 10)
881        with warnings.catch_warnings():
882            warnings.simplefilter('ignore', RuntimeWarning)
883            assert_raises(ValueError, random.geometric, np.nan)
884            assert_raises(ValueError, random.geometric, [np.nan] * 10)
885
886    def test_gumbel(self):
887        rng = random.RandomState(self.seed)
888        actual = rng.gumbel(loc=.123456789, scale=2.0, size=(3, 2))
889        desired = np.array([[0.19591898743416816, 0.34405539668096674],
890                            [-1.4492522252274278, -1.47374816298446865],
891                            [1.10651090478803416, -0.69535848626236174]])
892        assert_array_almost_equal(actual, desired, decimal=15)
893
894    def test_gumbel_0(self):
895        assert_equal(random.gumbel(scale=0), 0)
896        assert_raises(ValueError, random.gumbel, scale=-0.)
897
898    def test_hypergeometric(self):
899        rng = random.RandomState(self.seed)
900        actual = rng.hypergeometric(10.1, 5.5, 14, size=(3, 2))
901        desired = np.array([[10, 10],
902                            [10, 10],
903                            [9, 9]])
904        assert_array_equal(actual, desired)
905
906        # Test nbad = 0
907        actual = rng.hypergeometric(5, 0, 3, size=4)
908        desired = np.array([3, 3, 3, 3])
909        assert_array_equal(actual, desired)
910
911        actual = rng.hypergeometric(15, 0, 12, size=4)
912        desired = np.array([12, 12, 12, 12])
913        assert_array_equal(actual, desired)
914
915        # Test ngood = 0
916        actual = rng.hypergeometric(0, 5, 3, size=4)
917        desired = np.array([0, 0, 0, 0])
918        assert_array_equal(actual, desired)
919
920        actual = rng.hypergeometric(0, 15, 12, size=4)
921        desired = np.array([0, 0, 0, 0])
922        assert_array_equal(actual, desired)
923
924    def test_laplace(self):
925        rng = random.RandomState(self.seed)
926        actual = rng.laplace(loc=.123456789, scale=2.0, size=(3, 2))
927        desired = np.array([[0.66599721112760157, 0.52829452552221945],
928                            [3.12791959514407125, 3.18202813572992005],
929                            [-0.05391065675859356, 1.74901336242837324]])
930        assert_array_almost_equal(actual, desired, decimal=15)
931
932    def test_laplace_0(self):
933        assert_equal(random.laplace(scale=0), 0)
934        assert_raises(ValueError, random.laplace, scale=-0.)
935
936    def test_logistic(self):
937        rng = random.RandomState(self.seed)
938        actual = rng.logistic(loc=.123456789, scale=2.0, size=(3, 2))
939        desired = np.array([[1.09232835305011444, 0.8648196662399954],
940                            [4.27818590694950185, 4.33897006346929714],
941                            [-0.21682183359214885, 2.63373365386060332]])
942        assert_array_almost_equal(actual, desired, decimal=15)
943
944    def test_lognormal(self):
945        rng = random.RandomState(self.seed)
946        actual = rng.lognormal(mean=.123456789, sigma=2.0, size=(3, 2))
947        desired = np.array([[16.50698631688883822, 36.54846706092654784],
948                            [22.67886599981281748, 0.71617561058995771],
949                            [65.72798501792723869, 86.84341601437161273]])
950        assert_array_almost_equal(actual, desired, decimal=13)
951
952    def test_lognormal_0(self):
953        assert_equal(random.lognormal(sigma=0), 1)
954        assert_raises(ValueError, random.lognormal, sigma=-0.)
955
956    def test_logseries(self):
957        rng = random.RandomState(self.seed)
958        actual = rng.logseries(p=.923456789, size=(3, 2))
959        desired = np.array([[2, 2],
960                            [6, 17],
961                            [3, 6]])
962        assert_array_equal(actual, desired)
963
964    def test_logseries_zero(self):
965        assert random.logseries(0) == 1
966
967    @pytest.mark.parametrize("value", [np.nextafter(0., -1), 1., np.nan, 5.])
968    def test_logseries_exceptions(self, value):
969        with np.errstate(invalid="ignore"):
970            with pytest.raises(ValueError):
971                random.logseries(value)
972            with pytest.raises(ValueError):
973                # contiguous path:
974                random.logseries(np.array([value] * 10))
975            with pytest.raises(ValueError):
976                # non-contiguous path:
977                random.logseries(np.array([value] * 10)[::2])
978
979    def test_multinomial(self):
980        rng = random.RandomState(self.seed)
981        actual = rng.multinomial(20, [1 / 6.] * 6, size=(3, 2))
982        desired = np.array([[[4, 3, 5, 4, 2, 2],
983                             [5, 2, 8, 2, 2, 1]],
984                            [[3, 4, 3, 6, 0, 4],
985                             [2, 1, 4, 3, 6, 4]],
986                            [[4, 4, 2, 5, 2, 3],
987                             [4, 3, 4, 2, 3, 4]]])
988        assert_array_equal(actual, desired)
989
990    def test_multivariate_normal(self):
991        rng = random.RandomState(self.seed)
992        mean = (.123456789, 10)
993        cov = [[1, 0], [0, 1]]
994        size = (3, 2)
995        actual = rng.multivariate_normal(mean, cov, size)
996        desired = np.array([[[1.463620246718631, 11.73759122771936],
997                             [1.622445133300628, 9.771356667546383]],
998                            [[2.154490787682787, 12.170324946056553],
999                             [1.719909438201865, 9.230548443648306]],
1000                            [[0.689515026297799, 9.880729819607714],
1001                             [-0.023054015651998, 9.201096623542879]]])
1002
1003        assert_array_almost_equal(actual, desired, decimal=15)
1004
1005        # Check for default size, was raising deprecation warning
1006        actual = rng.multivariate_normal(mean, cov)
1007        desired = np.array([0.895289569463708, 9.17180864067987])
1008        assert_array_almost_equal(actual, desired, decimal=15)
1009
1010        # Check that non positive-semidefinite covariance warns with
1011        # RuntimeWarning
1012        mean = [0, 0]
1013        cov = [[1, 2], [2, 1]]
1014        pytest.warns(RuntimeWarning, rng.multivariate_normal, mean, cov)
1015
1016        # and that it doesn't warn with RuntimeWarning check_valid='ignore'
1017        assert_no_warnings(rng.multivariate_normal, mean, cov,
1018                           check_valid='ignore')
1019
1020        # and that it raises with RuntimeWarning check_valid='raises'
1021        assert_raises(ValueError, rng.multivariate_normal, mean, cov,
1022                      check_valid='raise')
1023
1024        cov = np.array([[1, 0.1], [0.1, 1]], dtype=np.float32)
1025        with warnings.catch_warnings():
1026            warnings.simplefilter('error', RuntimeWarning)
1027            rng.multivariate_normal(mean, cov)
1028
1029        mu = np.zeros(2)
1030        cov = np.eye(2)
1031        assert_raises(ValueError, rng.multivariate_normal, mean, cov,
1032                      check_valid='other')
1033        assert_raises(ValueError, rng.multivariate_normal,
1034                      np.zeros((2, 1, 1)), cov)
1035        assert_raises(ValueError, rng.multivariate_normal,
1036                      mu, np.empty((3, 2)))
1037        assert_raises(ValueError, rng.multivariate_normal,
1038                      mu, np.eye(3))
1039
1040    def test_negative_binomial(self):
1041        rng = random.RandomState(self.seed)
1042        actual = rng.negative_binomial(n=100, p=.12345, size=(3, 2))
1043        desired = np.array([[848, 841],
1044                            [892, 611],
1045                            [779, 647]])
1046        assert_array_equal(actual, desired)
1047
1048    def test_negative_binomial_exceptions(self):
1049        with warnings.catch_warnings():
1050            warnings.simplefilter('ignore', RuntimeWarning)
1051            assert_raises(ValueError, random.negative_binomial, 100, np.nan)
1052            assert_raises(ValueError, random.negative_binomial, 100,
1053                          [np.nan] * 10)
1054
1055    def test_noncentral_chisquare(self):
1056        rng = random.RandomState(self.seed)
1057        actual = rng.noncentral_chisquare(df=5, nonc=5, size=(3, 2))
1058        desired = np.array([[23.91905354498517511, 13.35324692733826346],
1059                            [31.22452661329736401, 16.60047399466177254],
1060                            [5.03461598262724586, 17.94973089023519464]])
1061        assert_array_almost_equal(actual, desired, decimal=14)
1062
1063        actual = rng.noncentral_chisquare(df=.5, nonc=.2, size=(3, 2))
1064        desired = np.array([[1.47145377828516666,  0.15052899268012659],
1065                            [0.00943803056963588,  1.02647251615666169],
1066                            [0.332334982684171,  0.15451287602753125]])
1067        assert_array_almost_equal(actual, desired, decimal=14)
1068
1069        rng = random.RandomState(self.seed)
1070        actual = rng.noncentral_chisquare(df=5, nonc=0, size=(3, 2))
1071        desired = np.array([[9.597154162763948, 11.725484450296079],
1072                            [10.413711048138335, 3.694475922923986],
1073                            [13.484222138963087, 14.377255424602957]])
1074        assert_array_almost_equal(actual, desired, decimal=14)
1075
1076    def test_noncentral_f(self):
1077        rng = random.RandomState(self.seed)
1078        actual = rng.noncentral_f(dfnum=5, dfden=2, nonc=1,
1079                                     size=(3, 2))
1080        desired = np.array([[1.40598099674926669, 0.34207973179285761],
1081                            [3.57715069265772545, 7.92632662577829805],
1082                            [0.43741599463544162, 1.1774208752428319]])
1083        assert_array_almost_equal(actual, desired, decimal=14)
1084
1085    def test_noncentral_f_nan(self):
1086        random.seed(self.seed)
1087        actual = random.noncentral_f(dfnum=5, dfden=2, nonc=np.nan)
1088        assert np.isnan(actual)
1089
1090    def test_normal(self):
1091        rng = random.RandomState(self.seed)
1092        actual = rng.normal(loc=.123456789, scale=2.0, size=(3, 2))
1093        desired = np.array([[2.80378370443726244, 3.59863924443872163],
1094                            [3.121433477601256, -0.33382987590723379],
1095                            [4.18552478636557357, 4.46410668111310471]])
1096        assert_array_almost_equal(actual, desired, decimal=15)
1097
1098    def test_normal_0(self):
1099        assert_equal(random.normal(scale=0), 0)
1100        assert_raises(ValueError, random.normal, scale=-0.)
1101
1102    def test_pareto(self):
1103        rng = random.RandomState(self.seed)
1104        actual = rng.pareto(a=.123456789, size=(3, 2))
1105        desired = np.array(
1106                [[2.46852460439034849e+03, 1.41286880810518346e+03],
1107                 [5.28287797029485181e+07, 6.57720981047328785e+07],
1108                 [1.40840323350391515e+02, 1.98390255135251704e+05]])
1109        # For some reason on 32-bit x86 Ubuntu 12.10 the [1, 0] entry in this
1110        # matrix differs by 24 nulps. Discussion:
1111        #   https://mail.python.org/pipermail/numpy-discussion/2012-September/063801.html
1112        # Consensus is that this is probably some gcc quirk that affects
1113        # rounding but not in any important way, so we just use a looser
1114        # tolerance on this test:
1115        np.testing.assert_array_almost_equal_nulp(actual, desired, nulp=30)
1116
1117    def test_poisson(self):
1118        rng = random.RandomState(self.seed)
1119        actual = rng.poisson(lam=.123456789, size=(3, 2))
1120        desired = np.array([[0, 0],
1121                            [1, 0],
1122                            [0, 0]])
1123        assert_array_equal(actual, desired)
1124
1125    def test_poisson_exceptions(self):
1126        lambig = np.iinfo('l').max
1127        lamneg = -1
1128        assert_raises(ValueError, random.poisson, lamneg)
1129        assert_raises(ValueError, random.poisson, [lamneg] * 10)
1130        assert_raises(ValueError, random.poisson, lambig)
1131        assert_raises(ValueError, random.poisson, [lambig] * 10)
1132        with warnings.catch_warnings():
1133            warnings.simplefilter('ignore', RuntimeWarning)
1134            assert_raises(ValueError, random.poisson, np.nan)
1135            assert_raises(ValueError, random.poisson, [np.nan] * 10)
1136
1137    def test_power(self):
1138        rng = random.RandomState(self.seed)
1139        actual = rng.power(a=.123456789, size=(3, 2))
1140        desired = np.array([[0.02048932883240791, 0.01424192241128213],
1141                            [0.38446073748535298, 0.39499689943484395],
1142                            [0.00177699707563439, 0.13115505880863756]])
1143        assert_array_almost_equal(actual, desired, decimal=15)
1144
1145    def test_rayleigh(self):
1146        rng = random.RandomState(self.seed)
1147        actual = rng.rayleigh(scale=10, size=(3, 2))
1148        desired = np.array([[13.8882496494248393, 13.383318339044731],
1149                            [20.95413364294492098, 21.08285015800712614],
1150                            [11.06066537006854311, 17.35468505778271009]])
1151        assert_array_almost_equal(actual, desired, decimal=14)
1152
1153    def test_rayleigh_0(self):
1154        assert_equal(random.rayleigh(scale=0), 0)
1155        assert_raises(ValueError, random.rayleigh, scale=-0.)
1156
1157    def test_standard_cauchy(self):
1158        rng = random.RandomState(self.seed)
1159        actual = rng.standard_cauchy(size=(3, 2))
1160        desired = np.array([[0.77127660196445336, -6.55601161955910605],
1161                            [0.93582023391158309, -2.07479293013759447],
1162                            [-4.74601644297011926, 0.18338989290760804]])
1163        assert_array_almost_equal(actual, desired, decimal=15)
1164
1165    def test_standard_exponential(self):
1166        rng = random.RandomState(self.seed)
1167        actual = rng.standard_exponential(size=(3, 2))
1168        desired = np.array([[0.96441739162374596, 0.89556604882105506],
1169                            [2.1953785836319808, 2.22243285392490542],
1170                            [0.6116915921431676, 1.50592546727413201]])
1171        assert_array_almost_equal(actual, desired, decimal=15)
1172
1173    def test_standard_gamma(self):
1174        rng = random.RandomState(self.seed)
1175        actual = rng.standard_gamma(shape=3, size=(3, 2))
1176        desired = np.array([[5.50841531318455058, 6.62953470301903103],
1177                            [5.93988484943779227, 2.31044849402133989],
1178                            [7.54838614231317084, 8.012756093271868]])
1179        assert_array_almost_equal(actual, desired, decimal=14)
1180
1181    def test_standard_gamma_0(self):
1182        assert_equal(random.standard_gamma(shape=0), 0)
1183        assert_raises(ValueError, random.standard_gamma, shape=-0.)
1184
1185    def test_standard_normal(self):
1186        rng = random.RandomState(self.seed)
1187        actual = rng.standard_normal(size=(3, 2))
1188        desired = np.array([[1.34016345771863121, 1.73759122771936081],
1189                            [1.498988344300628, -0.2286433324536169],
1190                            [2.031033998682787, 2.17032494605655257]])
1191        assert_array_almost_equal(actual, desired, decimal=15)
1192
1193    def test_randn_singleton(self):
1194        rng = random.RandomState(self.seed)
1195        actual = rng.randn()
1196        desired = np.array(1.34016345771863121)
1197        assert_array_almost_equal(actual, desired, decimal=15)
1198
1199    def test_standard_t(self):
1200        rng = random.RandomState(self.seed)

Showing the first 1,200 of 2100 lines. Download the file for the rest.

codekingpro/portable-devtools · Team Ai