test_support.py 13.8 KB
Newer Older
dugupeiwen's avatar
dugupeiwen committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
import itertools

import numpy as np

from numba import jit
from numba.core import utils
from numba.tests.support import TestCase, forbid_codegen
from .enum_usecases import *
import unittest

DBL_EPSILON = 2**-52
FLT_EPSILON = 2**-23

INF = float('inf')
NAN = float('nan')


class TestAssertPreciseEqual(TestCase):
    """
    Tests for TestCase.assertPreciseEqual().
    """

    int_types = [int]
    np_float_types = [np.float32, np.float64]
    float_types = [float] + np_float_types
    np_complex_types = [np.complex64, np.complex128]
    complex_types = [complex] + np_complex_types
    bool_types = [bool, np.bool_]

    def eq(self, left, right, **kwargs):
        def assert_succeed(left, right):
            self.assertPreciseEqual(left, right, **kwargs)
            self.assertPreciseEqual(right, left, **kwargs)
        assert_succeed(left, right)
        assert_succeed((left, left), (right, right))
        assert_succeed([left, left], [right, right])

    def ne(self, left, right, **kwargs):
        def assert_fail(left, right):
            try:
                self.assertPreciseEqual(left, right, **kwargs)
            except AssertionError:
                pass
            else:
                self.fail("%s and %s unexpectedly considered equal" % (left, right))
        assert_fail(left, right)
        assert_fail(right, left)
        assert_fail((left, left), (right, right))
        assert_fail((right, right), (left, left))
        assert_fail([left, left], [right, right])
        assert_fail([right, right], [left, left])

    def test_types(self):
        # assertPreciseEqual() should test for type compatibility
        # int-like, float-like, complex-like are not compatible
        for i, f, c in itertools.product(self.int_types, self.float_types,
                                         self.complex_types):
            self.ne(i(1), f(1))
            self.ne(f(1), c(1))
            self.ne(i(1), c(1))
        # int and long are compatible between each other
        for u, v in itertools.product(self.int_types, self.int_types):
            self.eq(u(1), v(1))
        # int and bool are not compatible between each other
        for u, v in itertools.product(self.int_types, self.bool_types):
            self.ne(u(1), v(1))
        # NumPy float types are not compatible between each other
        for u, v in itertools.product(self.np_float_types, self.np_float_types):
            if u is v:
                self.eq(u(1), v(1))
            else:
                self.ne(u(1), v(1))
        # NumPy complex types are not compatible between each other
        for u, v in itertools.product(self.np_complex_types, self.np_complex_types):
            if u is v:
                self.eq(u(1), v(1))
            else:
                self.ne(u(1), v(1))

    def test_int_values(self):
        for tp in self.int_types:
            for prec in ['exact', 'single', 'double']:
                self.eq(tp(0), tp(0), prec=prec)
                self.ne(tp(0), tp(1), prec=prec)
                self.ne(tp(-1), tp(1), prec=prec)
                self.ne(tp(2**80), tp(1+2**80), prec=prec)

    def test_bool_values(self):
        for tpa, tpb in itertools.product(self.bool_types, self.bool_types):
            self.eq(tpa(True), tpb(True))
            self.eq(tpa(False), tpb(False))
            self.ne(tpa(True), tpb(False))

    def test_abs_tol_parse(self):
        # check invalid values in abs_tol kwarg raises
        with self.assertRaises(ValueError):
            self.eq(np.float64(1e-17), np.float64(1e-17), abs_tol="invalid")
        with self.assertRaises(ValueError):
            self.eq(np.float64(1), np.float64(2), abs_tol=int(7))

    def test_float_values(self):
        for tp in self.float_types:
            for prec in ['exact', 'single', 'double']:
                self.eq(tp(1.5), tp(1.5), prec=prec)
                # Signed zeros
                self.eq(tp(0.0), tp(0.0), prec=prec)
                self.eq(tp(-0.0), tp(-0.0), prec=prec)
                self.ne(tp(0.0), tp(-0.0), prec=prec)
                self.eq(tp(0.0), tp(-0.0), prec=prec, ignore_sign_on_zero=True)
                # Infinities
                self.eq(tp(INF), tp(INF), prec=prec)
                self.ne(tp(INF), tp(1e38), prec=prec)
                self.eq(tp(-INF), tp(-INF), prec=prec)
                self.ne(tp(INF), tp(-INF), prec=prec)
                # NaNs
                self.eq(tp(NAN), tp(NAN), prec=prec)
                self.ne(tp(NAN), tp(0), prec=prec)
                self.ne(tp(NAN), tp(INF), prec=prec)
                self.ne(tp(NAN), tp(-INF), prec=prec)

    def test_float64_values(self):
        for tp in [float, np.float64]:
            self.ne(tp(1.0 + DBL_EPSILON), tp(1.0))

    def test_float32_values(self):
        tp = np.float32
        self.ne(tp(1.0 + FLT_EPSILON), tp(1.0))

    def test_float64_values_inexact(self):
        for tp in [float, np.float64]:
            for scale in [1.0, -2**3, 2**-4, -2**-20]:
                a = scale * 1.0
                b = scale * (1.0 + DBL_EPSILON)
                c = scale * (1.0 + DBL_EPSILON * 2)
                d = scale * (1.0 + DBL_EPSILON * 4)
                self.ne(tp(a), tp(b))
                self.ne(tp(a), tp(b), prec='exact')
                self.eq(tp(a), tp(b), prec='double')
                self.eq(tp(a), tp(b), prec='double', ulps=1)
                self.ne(tp(a), tp(c), prec='double')
                self.eq(tp(a), tp(c), prec='double', ulps=2)
                self.ne(tp(a), tp(d), prec='double', ulps=2)
                self.eq(tp(a), tp(c), prec='double', ulps=3)
                self.eq(tp(a), tp(d), prec='double', ulps=3)
            # test absolute tolerance based on eps
            self.eq(tp(1e-16), tp(3e-16), prec='double', abs_tol="eps")
            self.ne(tp(1e-16), tp(4e-16), prec='double', abs_tol="eps")
            # test absolute tolerance based on value
            self.eq(tp(1e-17), tp(1e-18), prec='double', abs_tol=1e-17)
            self.ne(tp(1e-17), tp(3e-17), prec='double', abs_tol=1e-17)

    def test_float32_values_inexact(self):
        tp = np.float32
        for scale in [1.0, -2**3, 2**-4, -2**-20]:
            # About the choice of 0.9: there seem to be issues when
            # converting
            a = scale * 1.0
            b = scale * (1.0 + FLT_EPSILON)
            c = scale * (1.0 + FLT_EPSILON * 2)
            d = scale * (1.0 + FLT_EPSILON * 4)
            self.ne(tp(a), tp(b))
            self.ne(tp(a), tp(b), prec='exact')
            self.ne(tp(a), tp(b), prec='double')
            self.eq(tp(a), tp(b), prec='single')
            self.ne(tp(a), tp(c), prec='single')
            self.eq(tp(a), tp(c), prec='single', ulps=2)
            self.ne(tp(a), tp(d), prec='single', ulps=2)
            self.eq(tp(a), tp(c), prec='single', ulps=3)
            self.eq(tp(a), tp(d), prec='single', ulps=3)
        # test absolute tolerance based on eps
        self.eq(tp(1e-7), tp(2e-7), prec='single', abs_tol="eps")
        self.ne(tp(1e-7), tp(3e-7), prec='single', abs_tol="eps")
        # test absolute tolerance based on value
        self.eq(tp(1e-7), tp(1e-8), prec='single', abs_tol=1e-7)
        self.ne(tp(1e-7), tp(3e-7), prec='single', abs_tol=1e-7)

    def test_complex_values(self):
        # Complex literals with signed zeros are confusing, better use
        # the explicit constructor.
        c_pp, c_pn, c_np, c_nn = [complex(0.0, 0.0), complex(0.0, -0.0),
                                  complex(-0.0, 0.0), complex(-0.0, -0.0)]
        for tp in self.complex_types:
            for prec in ['exact', 'single', 'double']:
                self.eq(tp(1 + 2j), tp(1 + 2j), prec=prec)
                self.ne(tp(1 + 1j), tp(1 + 2j), prec=prec)
                self.ne(tp(2 + 2j), tp(1 + 2j), prec=prec)
                # Signed zeros
                self.eq(tp(c_pp), tp(c_pp), prec=prec)
                self.eq(tp(c_np), tp(c_np), prec=prec)
                self.eq(tp(c_nn), tp(c_nn), prec=prec)
                self.ne(tp(c_pp), tp(c_pn), prec=prec)
                self.ne(tp(c_pn), tp(c_nn), prec=prec)
                # Infinities
                self.eq(tp(complex(INF, INF)), tp(complex(INF, INF)), prec=prec)
                self.eq(tp(complex(INF, -INF)), tp(complex(INF, -INF)), prec=prec)
                self.eq(tp(complex(-INF, -INF)), tp(complex(-INF, -INF)), prec=prec)
                self.ne(tp(complex(INF, INF)), tp(complex(INF, -INF)), prec=prec)
                self.ne(tp(complex(INF, INF)), tp(complex(-INF, INF)), prec=prec)
                self.eq(tp(complex(INF, 0)), tp(complex(INF, 0)), prec=prec)
                # NaNs
                self.eq(tp(complex(NAN, 0)), tp(complex(NAN, 0)), prec=prec)
                self.eq(tp(complex(0, NAN)), tp(complex(0, NAN)), prec=prec)
                self.eq(tp(complex(NAN, NAN)), tp(complex(NAN, NAN)), prec=prec)
                self.eq(tp(complex(INF, NAN)), tp(complex(INF, NAN)), prec=prec)
                self.eq(tp(complex(NAN, -INF)), tp(complex(NAN, -INF)), prec=prec)
                # FIXME
                #self.ne(tp(complex(NAN, INF)), tp(complex(NAN, -INF)))
                #self.ne(tp(complex(NAN, 0)), tp(complex(NAN, 1)))
                #self.ne(tp(complex(INF, NAN)), tp(complex(-INF, NAN)))
                #self.ne(tp(complex(0, NAN)), tp(complex(1, NAN)))
                #self.ne(tp(complex(NAN, 0)), tp(complex(0, NAN)))
            # XXX should work with other precisions as well?
            self.ne(tp(complex(INF, 0)), tp(complex(INF, 1)), prec='exact')

    def test_complex128_values_inexact(self):
        for tp in [complex, np.complex128]:
            for scale in [1.0, -2**3, 2**-4, -2**-20]:
                a = scale * 1.0
                b = scale * (1.0 + DBL_EPSILON)
                c = scale * (1.0 + DBL_EPSILON * 2)
                aa = tp(complex(a, a))
                ab = tp(complex(a, b))
                bb = tp(complex(b, b))
                self.ne(tp(aa), tp(ab))
                self.eq(tp(aa), tp(ab), prec='double')
                self.eq(tp(ab), tp(bb), prec='double')
                self.eq(tp(aa), tp(bb), prec='double')
                ac = tp(complex(a, c))
                cc = tp(complex(c, c))
                self.ne(tp(aa), tp(ac), prec='double')
                self.ne(tp(ac), tp(cc), prec='double')
                self.eq(tp(aa), tp(ac), prec='double', ulps=2)
                self.eq(tp(ac), tp(cc), prec='double', ulps=2)
                self.eq(tp(aa), tp(cc), prec='double', ulps=2)
                self.eq(tp(aa), tp(cc), prec='single')

    def test_complex64_values_inexact(self):
        tp = np.complex64
        for scale in [1.0, -2**3, 2**-4, -2**-20]:
            a = scale * 1.0
            b = scale * (1.0 + FLT_EPSILON)
            c = scale * (1.0 + FLT_EPSILON * 2)
            aa = tp(complex(a, a))
            ab = tp(complex(a, b))
            bb = tp(complex(b, b))
            self.ne(tp(aa), tp(ab))
            self.ne(tp(aa), tp(ab), prec='double')
            self.eq(tp(aa), tp(ab), prec='single')
            self.eq(tp(ab), tp(bb), prec='single')
            self.eq(tp(aa), tp(bb), prec='single')
            ac = tp(complex(a, c))
            cc = tp(complex(c, c))
            self.ne(tp(aa), tp(ac), prec='single')
            self.ne(tp(ac), tp(cc), prec='single')
            self.eq(tp(aa), tp(ac), prec='single', ulps=2)
            self.eq(tp(ac), tp(cc), prec='single', ulps=2)
            self.eq(tp(aa), tp(cc), prec='single', ulps=2)

    def test_enums(self):
        values = [Color.red, Color.green, Color.blue, Shake.mint,
                  Shape.circle, Shape.square, Planet.EARTH, Planet.MERCURY]
        for val in values:
            self.eq(val, val)
            self.ne(val, val.value)
        for a, b in itertools.combinations(values, 2):
            self.ne(a, b)

    def test_arrays(self):
        a = np.arange(1, 7, dtype=np.int16).reshape((2, 3))
        b = a.copy()
        self.eq(a, b)
        # Different values
        self.ne(a, b + 1)
        self.ne(a, b[:-1])
        self.ne(a, b.T)
        # Different dtypes
        self.ne(a, b.astype(np.int32))
        # Different layout
        self.ne(a, b.T.copy().T)
        # Different ndim
        self.ne(a, b.flatten())
        # Different writeability
        b.flags.writeable = False
        self.ne(a, b)
        # Precision
        a = np.arange(1, 3, dtype=np.float64)
        b = a * (1.0 + DBL_EPSILON)
        c = a * (1.0 + DBL_EPSILON * 2)
        self.ne(a, b)
        self.eq(a, b, prec='double')
        self.ne(a, c, prec='double')

    def test_npdatetime(self):
        a = np.datetime64('1900', 'Y')
        b = np.datetime64('1900', 'Y')
        c = np.datetime64('1900-01-01', 'D')
        d = np.datetime64('1901', 'Y')
        self.eq(a, b)
        # Different unit
        self.ne(a, c)
        # Different value
        self.ne(a, d)

    def test_nptimedelta(self):
        a = np.timedelta64(1, 'h')
        b = np.timedelta64(1, 'h')
        c = np.timedelta64(60, 'm')
        d = np.timedelta64(2, 'h')
        self.eq(a, b)
        # Different unit
        self.ne(a, c)
        # Different value
        self.ne(a, d)


class TestMisc(TestCase):

    def test_assertRefCount(self):
        # Use floats to avoid integer interning
        x = 55.
        y = 66.
        l = []
        with self.assertRefCount(x, y):
            pass
        with self.assertRaises(AssertionError) as cm:
            # y gains a reference
            with self.assertRefCount(x, y):
                l.append(y)
        self.assertIn("66", str(cm.exception))

    def test_forbid_codegen(self):
        """
        Test that forbid_codegen() prevents code generation using the @jit
        decorator.
        """
        def f():
            return 1
        with forbid_codegen():
            with self.assertRaises(RuntimeError) as raises:
                cfunc = jit(nopython=True)(f)
                cfunc()
        self.assertIn("codegen forbidden by test case", str(raises.exception))


if __name__ == '__main__':
    unittest.main()