comparison DEPENDENCIES/mingw32/Python27/Lib/site-packages/numpy/testing/tests/test_utils.py @ 87:2a2c65a20a8b

Add Python libs and headers
author Chris Cannam
date Wed, 25 Feb 2015 14:05:22 +0000
parents
children
comparison
equal deleted inserted replaced
86:413a9d26189e 87:2a2c65a20a8b
1 from __future__ import division, absolute_import, print_function
2
3 import warnings
4 import sys
5
6 import numpy as np
7 from numpy.testing import *
8 import unittest
9
10 class _GenericTest(object):
11 def _test_equal(self, a, b):
12 self._assert_func(a, b)
13
14 def _test_not_equal(self, a, b):
15 try:
16 self._assert_func(a, b)
17 passed = True
18 except AssertionError:
19 pass
20 else:
21 raise AssertionError("a and b are found equal but are not")
22
23 def test_array_rank1_eq(self):
24 """Test two equal array of rank 1 are found equal."""
25 a = np.array([1, 2])
26 b = np.array([1, 2])
27
28 self._test_equal(a, b)
29
30 def test_array_rank1_noteq(self):
31 """Test two different array of rank 1 are found not equal."""
32 a = np.array([1, 2])
33 b = np.array([2, 2])
34
35 self._test_not_equal(a, b)
36
37 def test_array_rank2_eq(self):
38 """Test two equal array of rank 2 are found equal."""
39 a = np.array([[1, 2], [3, 4]])
40 b = np.array([[1, 2], [3, 4]])
41
42 self._test_equal(a, b)
43
44 def test_array_diffshape(self):
45 """Test two arrays with different shapes are found not equal."""
46 a = np.array([1, 2])
47 b = np.array([[1, 2], [1, 2]])
48
49 self._test_not_equal(a, b)
50
51 def test_objarray(self):
52 """Test object arrays."""
53 a = np.array([1, 1], dtype=np.object)
54 self._test_equal(a, 1)
55
56 def test_array_likes(self):
57 self._test_equal([1, 2, 3], (1, 2, 3))
58
59 class TestArrayEqual(_GenericTest, unittest.TestCase):
60 def setUp(self):
61 self._assert_func = assert_array_equal
62
63 def test_generic_rank1(self):
64 """Test rank 1 array for all dtypes."""
65 def foo(t):
66 a = np.empty(2, t)
67 a.fill(1)
68 b = a.copy()
69 c = a.copy()
70 c.fill(0)
71 self._test_equal(a, b)
72 self._test_not_equal(c, b)
73
74 # Test numeric types and object
75 for t in '?bhilqpBHILQPfdgFDG':
76 foo(t)
77
78 # Test strings
79 for t in ['S1', 'U1']:
80 foo(t)
81
82 def test_generic_rank3(self):
83 """Test rank 3 array for all dtypes."""
84 def foo(t):
85 a = np.empty((4, 2, 3), t)
86 a.fill(1)
87 b = a.copy()
88 c = a.copy()
89 c.fill(0)
90 self._test_equal(a, b)
91 self._test_not_equal(c, b)
92
93 # Test numeric types and object
94 for t in '?bhilqpBHILQPfdgFDG':
95 foo(t)
96
97 # Test strings
98 for t in ['S1', 'U1']:
99 foo(t)
100
101 def test_nan_array(self):
102 """Test arrays with nan values in them."""
103 a = np.array([1, 2, np.nan])
104 b = np.array([1, 2, np.nan])
105
106 self._test_equal(a, b)
107
108 c = np.array([1, 2, 3])
109 self._test_not_equal(c, b)
110
111 def test_string_arrays(self):
112 """Test two arrays with different shapes are found not equal."""
113 a = np.array(['floupi', 'floupa'])
114 b = np.array(['floupi', 'floupa'])
115
116 self._test_equal(a, b)
117
118 c = np.array(['floupipi', 'floupa'])
119
120 self._test_not_equal(c, b)
121
122 def test_recarrays(self):
123 """Test record arrays."""
124 a = np.empty(2, [('floupi', np.float), ('floupa', np.float)])
125 a['floupi'] = [1, 2]
126 a['floupa'] = [1, 2]
127 b = a.copy()
128
129 self._test_equal(a, b)
130
131 c = np.empty(2, [('floupipi', np.float), ('floupa', np.float)])
132 c['floupipi'] = a['floupi'].copy()
133 c['floupa'] = a['floupa'].copy()
134
135 self._test_not_equal(c, b)
136
137 class TestBuildErrorMessage(unittest.TestCase):
138 def test_build_err_msg_defaults(self):
139 x = np.array([1.00001, 2.00002, 3.00003])
140 y = np.array([1.00002, 2.00003, 3.00004])
141 err_msg = 'There is a mismatch'
142
143 a = build_err_msg([x, y], err_msg)
144 b = ('\nItems are not equal: There is a mismatch\n ACTUAL: array([ '
145 '1.00001, 2.00002, 3.00003])\n DESIRED: array([ 1.00002, '
146 '2.00003, 3.00004])')
147 self.assertEqual(a, b)
148
149 def test_build_err_msg_no_verbose(self):
150 x = np.array([1.00001, 2.00002, 3.00003])
151 y = np.array([1.00002, 2.00003, 3.00004])
152 err_msg = 'There is a mismatch'
153
154 a = build_err_msg([x, y], err_msg, verbose=False)
155 b = '\nItems are not equal: There is a mismatch'
156 self.assertEqual(a, b)
157
158 def test_build_err_msg_custom_names(self):
159 x = np.array([1.00001, 2.00002, 3.00003])
160 y = np.array([1.00002, 2.00003, 3.00004])
161 err_msg = 'There is a mismatch'
162
163 a = build_err_msg([x, y], err_msg, names=('FOO', 'BAR'))
164 b = ('\nItems are not equal: There is a mismatch\n FOO: array([ '
165 '1.00001, 2.00002, 3.00003])\n BAR: array([ 1.00002, 2.00003, '
166 '3.00004])')
167 self.assertEqual(a, b)
168
169 def test_build_err_msg_custom_precision(self):
170 x = np.array([1.000000001, 2.00002, 3.00003])
171 y = np.array([1.000000002, 2.00003, 3.00004])
172 err_msg = 'There is a mismatch'
173
174 a = build_err_msg([x, y], err_msg, precision=10)
175 b = ('\nItems are not equal: There is a mismatch\n ACTUAL: array([ '
176 '1.000000001, 2.00002 , 3.00003 ])\n DESIRED: array([ '
177 '1.000000002, 2.00003 , 3.00004 ])')
178 self.assertEqual(a, b)
179
180 class TestEqual(TestArrayEqual):
181 def setUp(self):
182 self._assert_func = assert_equal
183
184 def test_nan_items(self):
185 self._assert_func(np.nan, np.nan)
186 self._assert_func([np.nan], [np.nan])
187 self._test_not_equal(np.nan, [np.nan])
188 self._test_not_equal(np.nan, 1)
189
190 def test_inf_items(self):
191 self._assert_func(np.inf, np.inf)
192 self._assert_func([np.inf], [np.inf])
193 self._test_not_equal(np.inf, [np.inf])
194
195 def test_non_numeric(self):
196 self._assert_func('ab', 'ab')
197 self._test_not_equal('ab', 'abb')
198
199 def test_complex_item(self):
200 self._assert_func(complex(1, 2), complex(1, 2))
201 self._assert_func(complex(1, np.nan), complex(1, np.nan))
202 self._test_not_equal(complex(1, np.nan), complex(1, 2))
203 self._test_not_equal(complex(np.nan, 1), complex(1, np.nan))
204 self._test_not_equal(complex(np.nan, np.inf), complex(np.nan, 2))
205
206 def test_negative_zero(self):
207 self._test_not_equal(np.PZERO, np.NZERO)
208
209 def test_complex(self):
210 x = np.array([complex(1, 2), complex(1, np.nan)])
211 y = np.array([complex(1, 2), complex(1, 2)])
212 self._assert_func(x, x)
213 self._test_not_equal(x, y)
214
215 class TestArrayAlmostEqual(_GenericTest, unittest.TestCase):
216 def setUp(self):
217 self._assert_func = assert_array_almost_equal
218
219 def test_simple(self):
220 x = np.array([1234.2222])
221 y = np.array([1234.2223])
222
223 self._assert_func(x, y, decimal=3)
224 self._assert_func(x, y, decimal=4)
225 self.assertRaises(AssertionError,
226 lambda: self._assert_func(x, y, decimal=5))
227
228 def test_nan(self):
229 anan = np.array([np.nan])
230 aone = np.array([1])
231 ainf = np.array([np.inf])
232 self._assert_func(anan, anan)
233 self.assertRaises(AssertionError,
234 lambda : self._assert_func(anan, aone))
235 self.assertRaises(AssertionError,
236 lambda : self._assert_func(anan, ainf))
237 self.assertRaises(AssertionError,
238 lambda : self._assert_func(ainf, anan))
239
240 def test_inf(self):
241 a = np.array([[1., 2.], [3., 4.]])
242 b = a.copy()
243 a[0, 0] = np.inf
244 self.assertRaises(AssertionError,
245 lambda : self._assert_func(a, b))
246
247 def test_subclass(self):
248 a = np.array([[1., 2.], [3., 4.]])
249 b = np.ma.masked_array([[1., 2.], [0., 4.]],
250 [[False, False], [True, False]])
251 assert_array_almost_equal(a, b)
252 assert_array_almost_equal(b, a)
253 assert_array_almost_equal(b, b)
254
255 class TestAlmostEqual(_GenericTest, unittest.TestCase):
256 def setUp(self):
257 self._assert_func = assert_almost_equal
258
259 def test_nan_item(self):
260 self._assert_func(np.nan, np.nan)
261 self.assertRaises(AssertionError,
262 lambda : self._assert_func(np.nan, 1))
263 self.assertRaises(AssertionError,
264 lambda : self._assert_func(np.nan, np.inf))
265 self.assertRaises(AssertionError,
266 lambda : self._assert_func(np.inf, np.nan))
267
268 def test_inf_item(self):
269 self._assert_func(np.inf, np.inf)
270 self._assert_func(-np.inf, -np.inf)
271 self.assertRaises(AssertionError,
272 lambda : self._assert_func(np.inf, 1))
273
274 def test_simple_item(self):
275 self._test_not_equal(1, 2)
276
277 def test_complex_item(self):
278 self._assert_func(complex(1, 2), complex(1, 2))
279 self._assert_func(complex(1, np.nan), complex(1, np.nan))
280 self._assert_func(complex(np.inf, np.nan), complex(np.inf, np.nan))
281 self._test_not_equal(complex(1, np.nan), complex(1, 2))
282 self._test_not_equal(complex(np.nan, 1), complex(1, np.nan))
283 self._test_not_equal(complex(np.nan, np.inf), complex(np.nan, 2))
284
285 def test_complex(self):
286 x = np.array([complex(1, 2), complex(1, np.nan)])
287 z = np.array([complex(1, 2), complex(np.nan, 1)])
288 y = np.array([complex(1, 2), complex(1, 2)])
289 self._assert_func(x, x)
290 self._test_not_equal(x, y)
291 self._test_not_equal(x, z)
292
293 def test_error_message(self):
294 """Check the message is formatted correctly for the decimal value"""
295 x = np.array([1.00000000001, 2.00000000002, 3.00003])
296 y = np.array([1.00000000002, 2.00000000003, 3.00004])
297
298 # test with a different amount of decimal digits
299 # note that we only check for the formatting of the arrays themselves
300 b = ('x: array([ 1.00000000001, 2.00000000002, 3.00003 '
301 ' ])\n y: array([ 1.00000000002, 2.00000000003, 3.00004 ])')
302 try:
303 self._assert_func(x, y, decimal=12)
304 except AssertionError as e:
305 # remove anything that's not the array string
306 self.assertEqual(str(e).split('%)\n ')[1], b)
307
308 # with the default value of decimal digits, only the 3rd element differs
309 # note that we only check for the formatting of the arrays themselves
310 b = ('x: array([ 1. , 2. , 3.00003])\n y: array([ 1. , '
311 '2. , 3.00004])')
312 try:
313 self._assert_func(x, y)
314 except AssertionError as e:
315 # remove anything that's not the array string
316 self.assertEqual(str(e).split('%)\n ')[1], b)
317
318 class TestApproxEqual(unittest.TestCase):
319 def setUp(self):
320 self._assert_func = assert_approx_equal
321
322 def test_simple_arrays(self):
323 x = np.array([1234.22])
324 y = np.array([1234.23])
325
326 self._assert_func(x, y, significant=5)
327 self._assert_func(x, y, significant=6)
328 self.assertRaises(AssertionError,
329 lambda: self._assert_func(x, y, significant=7))
330
331 def test_simple_items(self):
332 x = 1234.22
333 y = 1234.23
334
335 self._assert_func(x, y, significant=4)
336 self._assert_func(x, y, significant=5)
337 self._assert_func(x, y, significant=6)
338 self.assertRaises(AssertionError,
339 lambda: self._assert_func(x, y, significant=7))
340
341 def test_nan_array(self):
342 anan = np.array(np.nan)
343 aone = np.array(1)
344 ainf = np.array(np.inf)
345 self._assert_func(anan, anan)
346 self.assertRaises(AssertionError,
347 lambda : self._assert_func(anan, aone))
348 self.assertRaises(AssertionError,
349 lambda : self._assert_func(anan, ainf))
350 self.assertRaises(AssertionError,
351 lambda : self._assert_func(ainf, anan))
352
353 def test_nan_items(self):
354 anan = np.array(np.nan)
355 aone = np.array(1)
356 ainf = np.array(np.inf)
357 self._assert_func(anan, anan)
358 self.assertRaises(AssertionError,
359 lambda : self._assert_func(anan, aone))
360 self.assertRaises(AssertionError,
361 lambda : self._assert_func(anan, ainf))
362 self.assertRaises(AssertionError,
363 lambda : self._assert_func(ainf, anan))
364
365 class TestRaises(unittest.TestCase):
366 def setUp(self):
367 class MyException(Exception):
368 pass
369
370 self.e = MyException
371
372 def raises_exception(self, e):
373 raise e
374
375 def does_not_raise_exception(self):
376 pass
377
378 def test_correct_catch(self):
379 f = raises(self.e)(self.raises_exception)(self.e)
380
381 def test_wrong_exception(self):
382 try:
383 f = raises(self.e)(self.raises_exception)(RuntimeError)
384 except RuntimeError:
385 return
386 else:
387 raise AssertionError("should have caught RuntimeError")
388
389 def test_catch_no_raise(self):
390 try:
391 f = raises(self.e)(self.does_not_raise_exception)()
392 except AssertionError:
393 return
394 else:
395 raise AssertionError("should have raised an AssertionError")
396
397 class TestWarns(unittest.TestCase):
398 def test_warn(self):
399 def f():
400 warnings.warn("yo")
401 return 3
402
403 before_filters = sys.modules['warnings'].filters[:]
404 assert_equal(assert_warns(UserWarning, f), 3)
405 after_filters = sys.modules['warnings'].filters
406
407 assert_raises(AssertionError, assert_no_warnings, f)
408 assert_equal(assert_no_warnings(lambda x: x, 1), 1)
409
410 # Check that the warnings state is unchanged
411 assert_equal(before_filters, after_filters,
412 "assert_warns does not preserver warnings state")
413
414 def test_warn_wrong_warning(self):
415 def f():
416 warnings.warn("yo", DeprecationWarning)
417
418 failed = False
419 filters = sys.modules['warnings'].filters[:]
420 try:
421 try:
422 # Should raise an AssertionError
423 assert_warns(UserWarning, f)
424 failed = True
425 except AssertionError:
426 pass
427 finally:
428 sys.modules['warnings'].filters = filters
429
430 if failed:
431 raise AssertionError("wrong warning caught by assert_warn")
432
433 class TestAssertAllclose(unittest.TestCase):
434 def test_simple(self):
435 x = 1e-3
436 y = 1e-9
437
438 assert_allclose(x, y, atol=1)
439 self.assertRaises(AssertionError, assert_allclose, x, y)
440
441 a = np.array([x, y, x, y])
442 b = np.array([x, y, x, x])
443
444 assert_allclose(a, b, atol=1)
445 self.assertRaises(AssertionError, assert_allclose, a, b)
446
447 b[-1] = y * (1 + 1e-8)
448 assert_allclose(a, b)
449 self.assertRaises(AssertionError, assert_allclose, a, b,
450 rtol=1e-9)
451
452 assert_allclose(6, 10, rtol=0.5)
453 self.assertRaises(AssertionError, assert_allclose, 10, 6, rtol=0.5)
454
455 def test_min_int(self):
456 a = np.array([np.iinfo(np.int_).min], dtype=np.int_)
457 # Should not raise:
458 assert_allclose(a, a)
459
460
461 class TestArrayAlmostEqualNulp(unittest.TestCase):
462 @dec.knownfailureif(True, "Github issue #347")
463 def test_simple(self):
464 np.random.seed(12345)
465 for i in range(100):
466 dev = np.random.randn(10)
467 x = np.ones(10)
468 y = x + dev * np.finfo(np.float64).eps
469 assert_array_almost_equal_nulp(x, y, nulp=2 * np.max(dev))
470
471 def test_simple2(self):
472 x = np.random.randn(10)
473 y = 2 * x
474 def failure():
475 return assert_array_almost_equal_nulp(x, y,
476 nulp=1000)
477 self.assertRaises(AssertionError, failure)
478
479 def test_big_float32(self):
480 x = (1e10 * np.random.randn(10)).astype(np.float32)
481 y = x + 1
482 assert_array_almost_equal_nulp(x, y, nulp=1000)
483
484 def test_big_float64(self):
485 x = 1e10 * np.random.randn(10)
486 y = x + 1
487 def failure():
488 assert_array_almost_equal_nulp(x, y, nulp=1000)
489 self.assertRaises(AssertionError, failure)
490
491 def test_complex(self):
492 x = np.random.randn(10) + 1j * np.random.randn(10)
493 y = x + 1
494 def failure():
495 assert_array_almost_equal_nulp(x, y, nulp=1000)
496 self.assertRaises(AssertionError, failure)
497
498 def test_complex2(self):
499 x = np.random.randn(10)
500 y = np.array(x, np.complex) + 1e-16 * np.random.randn(10)
501
502 assert_array_almost_equal_nulp(x, y, nulp=1000)
503
504 class TestULP(unittest.TestCase):
505 def test_equal(self):
506 x = np.random.randn(10)
507 assert_array_max_ulp(x, x, maxulp=0)
508
509 def test_single(self):
510 # Generate 1 + small deviation, check that adding eps gives a few UNL
511 x = np.ones(10).astype(np.float32)
512 x += 0.01 * np.random.randn(10).astype(np.float32)
513 eps = np.finfo(np.float32).eps
514 assert_array_max_ulp(x, x+eps, maxulp=20)
515
516 def test_double(self):
517 # Generate 1 + small deviation, check that adding eps gives a few UNL
518 x = np.ones(10).astype(np.float64)
519 x += 0.01 * np.random.randn(10).astype(np.float64)
520 eps = np.finfo(np.float64).eps
521 assert_array_max_ulp(x, x+eps, maxulp=200)
522
523 def test_inf(self):
524 for dt in [np.float32, np.float64]:
525 inf = np.array([np.inf]).astype(dt)
526 big = np.array([np.finfo(dt).max])
527 assert_array_max_ulp(inf, big, maxulp=200)
528
529 def test_nan(self):
530 # Test that nan is 'far' from small, tiny, inf, max and min
531 for dt in [np.float32, np.float64]:
532 if dt == np.float32:
533 maxulp = 1e6
534 else:
535 maxulp = 1e12
536 inf = np.array([np.inf]).astype(dt)
537 nan = np.array([np.nan]).astype(dt)
538 big = np.array([np.finfo(dt).max])
539 tiny = np.array([np.finfo(dt).tiny])
540 zero = np.array([np.PZERO]).astype(dt)
541 nzero = np.array([np.NZERO]).astype(dt)
542 self.assertRaises(AssertionError,
543 lambda: assert_array_max_ulp(nan, inf,
544 maxulp=maxulp))
545 self.assertRaises(AssertionError,
546 lambda: assert_array_max_ulp(nan, big,
547 maxulp=maxulp))
548 self.assertRaises(AssertionError,
549 lambda: assert_array_max_ulp(nan, tiny,
550 maxulp=maxulp))
551 self.assertRaises(AssertionError,
552 lambda: assert_array_max_ulp(nan, zero,
553 maxulp=maxulp))
554 self.assertRaises(AssertionError,
555 lambda: assert_array_max_ulp(nan, nzero,
556 maxulp=maxulp))
557 if __name__ == '__main__':
558 run_module_suite()