Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
test_regression.py176 linesDownload Raw Back to tests
1import inspect
2import sys
3
4import pytest
5
6import numpy as np
7from numpy import random
8from numpy.testing import IS_PYPY, assert_, assert_array_equal, assert_raises
9
10
11class TestRegression:
12
13    def test_VonMises_range(self):
14        # Make sure generated random variables are in [-pi, pi].
15        # Regression test for ticket #986.
16        for mu in np.linspace(-7., 7., 5):
17            r = random.mtrand.vonmises(mu, 1, 50)
18            assert_(np.all(r > -np.pi) and np.all(r <= np.pi))
19
20    def test_hypergeometric_range(self):
21        # Test for ticket #921
22        assert_(np.all(np.random.hypergeometric(3, 18, 11, size=10) < 4))
23        assert_(np.all(np.random.hypergeometric(18, 3, 11, size=10) > 0))
24
25        # Test for ticket #5623
26        args = [
27            (2**20 - 2, 2**20 - 2, 2**20 - 2),  # Check for 32-bit systems
28        ]
29        is_64bits = sys.maxsize > 2**32
30        if is_64bits and sys.platform != 'win32':
31            # Check for 64-bit systems
32            args.append((2**40 - 2, 2**40 - 2, 2**40 - 2))
33        for arg in args:
34            assert_(np.random.hypergeometric(*arg) > 0)
35
36    def test_logseries_convergence(self):
37        # Test for ticket #923
38        N = 1000
39        np.random.seed(0)
40        rvsn = np.random.logseries(0.8, size=N)
41        # these two frequency counts should be close to theoretical
42        # numbers with this large sample
43        # theoretical large N result is 0.49706795
44        freq = np.sum(rvsn == 1) / N
45        msg = f'Frequency was {freq:f}, should be > 0.45'
46        assert_(freq > 0.45, msg)
47        # theoretical large N result is 0.19882718
48        freq = np.sum(rvsn == 2) / N
49        msg = f'Frequency was {freq:f}, should be < 0.23'
50        assert_(freq < 0.23, msg)
51
52    def test_shuffle_mixed_dimension(self):
53        # Test for trac ticket #2074
54        for t in [[1, 2, 3, None],
55                  [(1, 1), (2, 2), (3, 3), None],
56                  [1, (2, 2), (3, 3), None],
57                  [(1, 1), 2, 3, None]]:
58            rng = np.random.RandomState(12345)
59            shuffled = list(t)
60            rng.shuffle(shuffled)
61            expected = np.array([t[0], t[3], t[1], t[2]], dtype=object)
62            assert_array_equal(np.array(shuffled, dtype=object), expected)
63
64    def test_call_within_randomstate(self):
65        # Check that custom RandomState does not call into global state
66        m = np.random.RandomState()
67        res = np.array([0, 8, 7, 2, 1, 9, 4, 7, 0, 3])
68        for i in range(3):
69            np.random.seed(i)
70            m.seed(4321)
71            # If m.state is not honored, the result will change
72            assert_array_equal(m.choice(10, size=10, p=np.ones(10) / 10.), res)
73
74    def test_multivariate_normal_size_types(self):
75        # Test for multivariate_normal issue with 'size' argument.
76        # Check that the multivariate_normal size argument can be a
77        # numpy integer.
78        np.random.multivariate_normal([0], [[0]], size=1)
79        np.random.multivariate_normal([0], [[0]], size=np.int_(1))
80        np.random.multivariate_normal([0], [[0]], size=np.int64(1))
81
82    def test_beta_small_parameters(self):
83        # Test that beta with small a and b parameters does not produce
84        # NaNs due to roundoff errors causing 0 / 0, gh-5851
85        np.random.seed(1234567890)
86        x = np.random.beta(0.0001, 0.0001, size=100)
87        assert_(not np.any(np.isnan(x)), 'Nans in np.random.beta')
88
89    def test_choice_sum_of_probs_tolerance(self):
90        # The sum of probs should be 1.0 with some tolerance.
91        # For low precision dtypes the tolerance was too tight.
92        # See numpy github issue 6123.
93        np.random.seed(1234)
94        a = [1, 2, 3]
95        counts = [4, 4, 2]
96        for dt in np.float16, np.float32, np.float64:
97            probs = np.array(counts, dtype=dt) / sum(counts)
98            c = np.random.choice(a, p=probs)
99            assert_(c in a)
100            assert_raises(ValueError, np.random.choice, a, p=probs * 0.9)
101
102    def test_shuffle_of_array_of_different_length_strings(self):
103        # Test that permuting an array of different length strings
104        # will not cause a segfault on garbage collection
105        # Tests gh-7710
106        np.random.seed(1234)
107
108        a = np.array(['a', 'a' * 1000])
109
110        for _ in range(100):
111            np.random.shuffle(a)
112
113        # Force Garbage Collection - should not segfault.
114        import gc
115        gc.collect()
116
117    def test_shuffle_of_array_of_objects(self):
118        # Test that permuting an array of objects will not cause
119        # a segfault on garbage collection.
120        # See gh-7719
121        np.random.seed(1234)
122        a = np.array([np.arange(1), np.arange(4)], dtype=object)
123
124        for _ in range(1000):
125            np.random.shuffle(a)
126
127        # Force Garbage Collection - should not segfault.
128        import gc
129        gc.collect()
130
131    def test_permutation_subclass(self):
132        class N(np.ndarray):
133            pass
134
135        rng = np.random.RandomState(1)
136        orig = np.arange(3).view(N)
137        perm = rng.permutation(orig)
138        assert_array_equal(perm, np.array([0, 2, 1]))
139        assert_array_equal(orig, np.arange(3).view(N))
140
141        class M:
142            a = np.arange(5)
143
144            def __array__(self, dtype=None, copy=None):
145                return self.a
146
147        rng = np.random.RandomState(1)
148        m = M()
149        perm = rng.permutation(m)
150        assert_array_equal(perm, np.array([2, 1, 4, 0, 3]))
151        assert_array_equal(m.__array__(), np.arange(5))
152
153    @pytest.mark.skipif(sys.flags.optimize == 2, reason="Python running -OO")
154    @pytest.mark.skipif(IS_PYPY, reason="PyPy does not modify tp_doc")
155    @pytest.mark.parametrize(
156        "cls",
157        [
158            random.Generator,
159            random.MT19937,
160            random.PCG64,
161            random.PCG64DXSM,
162            random.Philox,
163            random.RandomState,
164            random.SFC64,
165            random.BitGenerator,
166            random.SeedSequence,
167            random.bit_generator.SeedlessSeedSequence,
168        ],
169    )
170    def test_inspect_signature(self, cls: type) -> None:
171        assert hasattr(cls, "__text_signature__")
172        try:
173            inspect.signature(cls)
174        except ValueError:
175            pytest.fail(f"invalid signature: {cls.__module__}.{cls.__qualname__}")
176 
codekingpro/portable-devtools · Team Ai