m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2521 lines
83 KiB

6 months ago
  1. """
  2. Utility function to facilitate testing.
  3. """
  4. import os
  5. import sys
  6. import platform
  7. import re
  8. import gc
  9. import operator
  10. import warnings
  11. from functools import partial, wraps
  12. import shutil
  13. import contextlib
  14. from tempfile import mkdtemp, mkstemp
  15. from unittest.case import SkipTest
  16. from warnings import WarningMessage
  17. import pprint
  18. import numpy as np
  19. from numpy.core import(
  20. intp, float32, empty, arange, array_repr, ndarray, isnat, array)
  21. import numpy.linalg.lapack_lite
  22. from io import StringIO
  23. __all__ = [
  24. 'assert_equal', 'assert_almost_equal', 'assert_approx_equal',
  25. 'assert_array_equal', 'assert_array_less', 'assert_string_equal',
  26. 'assert_array_almost_equal', 'assert_raises', 'build_err_msg',
  27. 'decorate_methods', 'jiffies', 'memusage', 'print_assert_equal',
  28. 'raises', 'rundocs', 'runstring', 'verbose', 'measure',
  29. 'assert_', 'assert_array_almost_equal_nulp', 'assert_raises_regex',
  30. 'assert_array_max_ulp', 'assert_warns', 'assert_no_warnings',
  31. 'assert_allclose', 'IgnoreException', 'clear_and_catch_warnings',
  32. 'SkipTest', 'KnownFailureException', 'temppath', 'tempdir', 'IS_PYPY',
  33. 'HAS_REFCOUNT', 'suppress_warnings', 'assert_array_compare',
  34. '_assert_valid_refcount', '_gen_alignment_data', 'assert_no_gc_cycles',
  35. 'break_cycles', 'HAS_LAPACK64'
  36. ]
  37. class KnownFailureException(Exception):
  38. '''Raise this exception to mark a test as a known failing test.'''
  39. pass
  40. KnownFailureTest = KnownFailureException # backwards compat
  41. verbose = 0
  42. IS_PYPY = platform.python_implementation() == 'PyPy'
  43. HAS_REFCOUNT = getattr(sys, 'getrefcount', None) is not None
  44. HAS_LAPACK64 = numpy.linalg.lapack_lite._ilp64
  45. def import_nose():
  46. """ Import nose only when needed.
  47. """
  48. nose_is_good = True
  49. minimum_nose_version = (1, 0, 0)
  50. try:
  51. import nose
  52. except ImportError:
  53. nose_is_good = False
  54. else:
  55. if nose.__versioninfo__ < minimum_nose_version:
  56. nose_is_good = False
  57. if not nose_is_good:
  58. msg = ('Need nose >= %d.%d.%d for tests - see '
  59. 'https://nose.readthedocs.io' %
  60. minimum_nose_version)
  61. raise ImportError(msg)
  62. return nose
  63. def assert_(val, msg=''):
  64. """
  65. Assert that works in release mode.
  66. Accepts callable msg to allow deferring evaluation until failure.
  67. The Python built-in ``assert`` does not work when executing code in
  68. optimized mode (the ``-O`` flag) - no byte-code is generated for it.
  69. For documentation on usage, refer to the Python documentation.
  70. """
  71. __tracebackhide__ = True # Hide traceback for py.test
  72. if not val:
  73. try:
  74. smsg = msg()
  75. except TypeError:
  76. smsg = msg
  77. raise AssertionError(smsg)
  78. def gisnan(x):
  79. """like isnan, but always raise an error if type not supported instead of
  80. returning a TypeError object.
  81. Notes
  82. -----
  83. isnan and other ufunc sometimes return a NotImplementedType object instead
  84. of raising any exception. This function is a wrapper to make sure an
  85. exception is always raised.
  86. This should be removed once this problem is solved at the Ufunc level."""
  87. from numpy.core import isnan
  88. st = isnan(x)
  89. if isinstance(st, type(NotImplemented)):
  90. raise TypeError("isnan not supported for this type")
  91. return st
  92. def gisfinite(x):
  93. """like isfinite, but always raise an error if type not supported instead
  94. of returning a TypeError object.
  95. Notes
  96. -----
  97. isfinite and other ufunc sometimes return a NotImplementedType object
  98. instead of raising any exception. This function is a wrapper to make sure
  99. an exception is always raised.
  100. This should be removed once this problem is solved at the Ufunc level."""
  101. from numpy.core import isfinite, errstate
  102. with errstate(invalid='ignore'):
  103. st = isfinite(x)
  104. if isinstance(st, type(NotImplemented)):
  105. raise TypeError("isfinite not supported for this type")
  106. return st
  107. def gisinf(x):
  108. """like isinf, but always raise an error if type not supported instead of
  109. returning a TypeError object.
  110. Notes
  111. -----
  112. isinf and other ufunc sometimes return a NotImplementedType object instead
  113. of raising any exception. This function is a wrapper to make sure an
  114. exception is always raised.
  115. This should be removed once this problem is solved at the Ufunc level."""
  116. from numpy.core import isinf, errstate
  117. with errstate(invalid='ignore'):
  118. st = isinf(x)
  119. if isinstance(st, type(NotImplemented)):
  120. raise TypeError("isinf not supported for this type")
  121. return st
  122. if os.name == 'nt':
  123. # Code "stolen" from enthought/debug/memusage.py
  124. def GetPerformanceAttributes(object, counter, instance=None,
  125. inum=-1, format=None, machine=None):
  126. # NOTE: Many counters require 2 samples to give accurate results,
  127. # including "% Processor Time" (as by definition, at any instant, a
  128. # thread's CPU usage is either 0 or 100). To read counters like this,
  129. # you should copy this function, but keep the counter open, and call
  130. # CollectQueryData() each time you need to know.
  131. # See http://msdn.microsoft.com/library/en-us/dnperfmo/html/perfmonpt2.asp (dead link)
  132. # My older explanation for this was that the "AddCounter" process
  133. # forced the CPU to 100%, but the above makes more sense :)
  134. import win32pdh
  135. if format is None:
  136. format = win32pdh.PDH_FMT_LONG
  137. path = win32pdh.MakeCounterPath( (machine, object, instance, None,
  138. inum, counter))
  139. hq = win32pdh.OpenQuery()
  140. try:
  141. hc = win32pdh.AddCounter(hq, path)
  142. try:
  143. win32pdh.CollectQueryData(hq)
  144. type, val = win32pdh.GetFormattedCounterValue(hc, format)
  145. return val
  146. finally:
  147. win32pdh.RemoveCounter(hc)
  148. finally:
  149. win32pdh.CloseQuery(hq)
  150. def memusage(processName="python", instance=0):
  151. # from win32pdhutil, part of the win32all package
  152. import win32pdh
  153. return GetPerformanceAttributes("Process", "Virtual Bytes",
  154. processName, instance,
  155. win32pdh.PDH_FMT_LONG, None)
  156. elif sys.platform[:5] == 'linux':
  157. def memusage(_proc_pid_stat=f'/proc/{os.getpid()}/stat'):
  158. """
  159. Return virtual memory size in bytes of the running python.
  160. """
  161. try:
  162. with open(_proc_pid_stat, 'r') as f:
  163. l = f.readline().split(' ')
  164. return int(l[22])
  165. except Exception:
  166. return
  167. else:
  168. def memusage():
  169. """
  170. Return memory usage of running python. [Not implemented]
  171. """
  172. raise NotImplementedError
  173. if sys.platform[:5] == 'linux':
  174. def jiffies(_proc_pid_stat=f'/proc/{os.getpid()}/stat', _load_time=[]):
  175. """
  176. Return number of jiffies elapsed.
  177. Return number of jiffies (1/100ths of a second) that this
  178. process has been scheduled in user mode. See man 5 proc.
  179. """
  180. import time
  181. if not _load_time:
  182. _load_time.append(time.time())
  183. try:
  184. with open(_proc_pid_stat, 'r') as f:
  185. l = f.readline().split(' ')
  186. return int(l[13])
  187. except Exception:
  188. return int(100*(time.time()-_load_time[0]))
  189. else:
  190. # os.getpid is not in all platforms available.
  191. # Using time is safe but inaccurate, especially when process
  192. # was suspended or sleeping.
  193. def jiffies(_load_time=[]):
  194. """
  195. Return number of jiffies elapsed.
  196. Return number of jiffies (1/100ths of a second) that this
  197. process has been scheduled in user mode. See man 5 proc.
  198. """
  199. import time
  200. if not _load_time:
  201. _load_time.append(time.time())
  202. return int(100*(time.time()-_load_time[0]))
  203. def build_err_msg(arrays, err_msg, header='Items are not equal:',
  204. verbose=True, names=('ACTUAL', 'DESIRED'), precision=8):
  205. msg = ['\n' + header]
  206. if err_msg:
  207. if err_msg.find('\n') == -1 and len(err_msg) < 79-len(header):
  208. msg = [msg[0] + ' ' + err_msg]
  209. else:
  210. msg.append(err_msg)
  211. if verbose:
  212. for i, a in enumerate(arrays):
  213. if isinstance(a, ndarray):
  214. # precision argument is only needed if the objects are ndarrays
  215. r_func = partial(array_repr, precision=precision)
  216. else:
  217. r_func = repr
  218. try:
  219. r = r_func(a)
  220. except Exception as exc:
  221. r = f'[repr failed for <{type(a).__name__}>: {exc}]'
  222. if r.count('\n') > 3:
  223. r = '\n'.join(r.splitlines()[:3])
  224. r += '...'
  225. msg.append(f' {names[i]}: {r}')
  226. return '\n'.join(msg)
  227. def assert_equal(actual, desired, err_msg='', verbose=True):
  228. """
  229. Raises an AssertionError if two objects are not equal.
  230. Given two objects (scalars, lists, tuples, dictionaries or numpy arrays),
  231. check that all elements of these objects are equal. An exception is raised
  232. at the first conflicting values.
  233. When one of `actual` and `desired` is a scalar and the other is array_like,
  234. the function checks that each element of the array_like object is equal to
  235. the scalar.
  236. This function handles NaN comparisons as if NaN was a "normal" number.
  237. That is, AssertionError is not raised if both objects have NaNs in the same
  238. positions. This is in contrast to the IEEE standard on NaNs, which says
  239. that NaN compared to anything must return False.
  240. Parameters
  241. ----------
  242. actual : array_like
  243. The object to check.
  244. desired : array_like
  245. The expected object.
  246. err_msg : str, optional
  247. The error message to be printed in case of failure.
  248. verbose : bool, optional
  249. If True, the conflicting values are appended to the error message.
  250. Raises
  251. ------
  252. AssertionError
  253. If actual and desired are not equal.
  254. Examples
  255. --------
  256. >>> np.testing.assert_equal([4,5], [4,6])
  257. Traceback (most recent call last):
  258. ...
  259. AssertionError:
  260. Items are not equal:
  261. item=1
  262. ACTUAL: 5
  263. DESIRED: 6
  264. The following comparison does not raise an exception. There are NaNs
  265. in the inputs, but they are in the same positions.
  266. >>> np.testing.assert_equal(np.array([1.0, 2.0, np.nan]), [1, 2, np.nan])
  267. """
  268. __tracebackhide__ = True # Hide traceback for py.test
  269. if isinstance(desired, dict):
  270. if not isinstance(actual, dict):
  271. raise AssertionError(repr(type(actual)))
  272. assert_equal(len(actual), len(desired), err_msg, verbose)
  273. for k, i in desired.items():
  274. if k not in actual:
  275. raise AssertionError(repr(k))
  276. assert_equal(actual[k], desired[k], f'key={k!r}\n{err_msg}',
  277. verbose)
  278. return
  279. if isinstance(desired, (list, tuple)) and isinstance(actual, (list, tuple)):
  280. assert_equal(len(actual), len(desired), err_msg, verbose)
  281. for k in range(len(desired)):
  282. assert_equal(actual[k], desired[k], f'item={k!r}\n{err_msg}',
  283. verbose)
  284. return
  285. from numpy.core import ndarray, isscalar, signbit
  286. from numpy.lib import iscomplexobj, real, imag
  287. if isinstance(actual, ndarray) or isinstance(desired, ndarray):
  288. return assert_array_equal(actual, desired, err_msg, verbose)
  289. msg = build_err_msg([actual, desired], err_msg, verbose=verbose)
  290. # Handle complex numbers: separate into real/imag to handle
  291. # nan/inf/negative zero correctly
  292. # XXX: catch ValueError for subclasses of ndarray where iscomplex fail
  293. try:
  294. usecomplex = iscomplexobj(actual) or iscomplexobj(desired)
  295. except (ValueError, TypeError):
  296. usecomplex = False
  297. if usecomplex:
  298. if iscomplexobj(actual):
  299. actualr = real(actual)
  300. actuali = imag(actual)
  301. else:
  302. actualr = actual
  303. actuali = 0
  304. if iscomplexobj(desired):
  305. desiredr = real(desired)
  306. desiredi = imag(desired)
  307. else:
  308. desiredr = desired
  309. desiredi = 0
  310. try:
  311. assert_equal(actualr, desiredr)
  312. assert_equal(actuali, desiredi)
  313. except AssertionError:
  314. raise AssertionError(msg)
  315. # isscalar test to check cases such as [np.nan] != np.nan
  316. if isscalar(desired) != isscalar(actual):
  317. raise AssertionError(msg)
  318. try:
  319. isdesnat = isnat(desired)
  320. isactnat = isnat(actual)
  321. dtypes_match = (np.asarray(desired).dtype.type ==
  322. np.asarray(actual).dtype.type)
  323. if isdesnat and isactnat:
  324. # If both are NaT (and have the same dtype -- datetime or
  325. # timedelta) they are considered equal.
  326. if dtypes_match:
  327. return
  328. else:
  329. raise AssertionError(msg)
  330. except (TypeError, ValueError, NotImplementedError):
  331. pass
  332. # Inf/nan/negative zero handling
  333. try:
  334. isdesnan = gisnan(desired)
  335. isactnan = gisnan(actual)
  336. if isdesnan and isactnan:
  337. return # both nan, so equal
  338. # handle signed zero specially for floats
  339. array_actual = np.asarray(actual)
  340. array_desired = np.asarray(desired)
  341. if (array_actual.dtype.char in 'Mm' or
  342. array_desired.dtype.char in 'Mm'):
  343. # version 1.18
  344. # until this version, gisnan failed for datetime64 and timedelta64.
  345. # Now it succeeds but comparison to scalar with a different type
  346. # emits a DeprecationWarning.
  347. # Avoid that by skipping the next check
  348. raise NotImplementedError('cannot compare to a scalar '
  349. 'with a different type')
  350. if desired == 0 and actual == 0:
  351. if not signbit(desired) == signbit(actual):
  352. raise AssertionError(msg)
  353. except (TypeError, ValueError, NotImplementedError):
  354. pass
  355. try:
  356. # Explicitly use __eq__ for comparison, gh-2552
  357. if not (desired == actual):
  358. raise AssertionError(msg)
  359. except (DeprecationWarning, FutureWarning) as e:
  360. # this handles the case when the two types are not even comparable
  361. if 'elementwise == comparison' in e.args[0]:
  362. raise AssertionError(msg)
  363. else:
  364. raise
  365. def print_assert_equal(test_string, actual, desired):
  366. """
  367. Test if two objects are equal, and print an error message if test fails.
  368. The test is performed with ``actual == desired``.
  369. Parameters
  370. ----------
  371. test_string : str
  372. The message supplied to AssertionError.
  373. actual : object
  374. The object to test for equality against `desired`.
  375. desired : object
  376. The expected result.
  377. Examples
  378. --------
  379. >>> np.testing.print_assert_equal('Test XYZ of func xyz', [0, 1], [0, 1])
  380. >>> np.testing.print_assert_equal('Test XYZ of func xyz', [0, 1], [0, 2])
  381. Traceback (most recent call last):
  382. ...
  383. AssertionError: Test XYZ of func xyz failed
  384. ACTUAL:
  385. [0, 1]
  386. DESIRED:
  387. [0, 2]
  388. """
  389. __tracebackhide__ = True # Hide traceback for py.test
  390. import pprint
  391. if not (actual == desired):
  392. msg = StringIO()
  393. msg.write(test_string)
  394. msg.write(' failed\nACTUAL: \n')
  395. pprint.pprint(actual, msg)
  396. msg.write('DESIRED: \n')
  397. pprint.pprint(desired, msg)
  398. raise AssertionError(msg.getvalue())
  399. def assert_almost_equal(actual,desired,decimal=7,err_msg='',verbose=True):
  400. """
  401. Raises an AssertionError if two items are not equal up to desired
  402. precision.
  403. .. note:: It is recommended to use one of `assert_allclose`,
  404. `assert_array_almost_equal_nulp` or `assert_array_max_ulp`
  405. instead of this function for more consistent floating point
  406. comparisons.
  407. The test verifies that the elements of `actual` and `desired` satisfy.
  408. ``abs(desired-actual) < 1.5 * 10**(-decimal)``
  409. That is a looser test than originally documented, but agrees with what the
  410. actual implementation in `assert_array_almost_equal` did up to rounding
  411. vagaries. An exception is raised at conflicting values. For ndarrays this
  412. delegates to assert_array_almost_equal
  413. Parameters
  414. ----------
  415. actual : array_like
  416. The object to check.
  417. desired : array_like
  418. The expected object.
  419. decimal : int, optional
  420. Desired precision, default is 7.
  421. err_msg : str, optional
  422. The error message to be printed in case of failure.
  423. verbose : bool, optional
  424. If True, the conflicting values are appended to the error message.
  425. Raises
  426. ------
  427. AssertionError
  428. If actual and desired are not equal up to specified precision.
  429. See Also
  430. --------
  431. assert_allclose: Compare two array_like objects for equality with desired
  432. relative and/or absolute precision.
  433. assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
  434. Examples
  435. --------
  436. >>> from numpy.testing import assert_almost_equal
  437. >>> assert_almost_equal(2.3333333333333, 2.33333334)
  438. >>> assert_almost_equal(2.3333333333333, 2.33333334, decimal=10)
  439. Traceback (most recent call last):
  440. ...
  441. AssertionError:
  442. Arrays are not almost equal to 10 decimals
  443. ACTUAL: 2.3333333333333
  444. DESIRED: 2.33333334
  445. >>> assert_almost_equal(np.array([1.0,2.3333333333333]),
  446. ... np.array([1.0,2.33333334]), decimal=9)
  447. Traceback (most recent call last):
  448. ...
  449. AssertionError:
  450. Arrays are not almost equal to 9 decimals
  451. <BLANKLINE>
  452. Mismatched elements: 1 / 2 (50%)
  453. Max absolute difference: 6.66669964e-09
  454. Max relative difference: 2.85715698e-09
  455. x: array([1. , 2.333333333])
  456. y: array([1. , 2.33333334])
  457. """
  458. __tracebackhide__ = True # Hide traceback for py.test
  459. from numpy.core import ndarray
  460. from numpy.lib import iscomplexobj, real, imag
  461. # Handle complex numbers: separate into real/imag to handle
  462. # nan/inf/negative zero correctly
  463. # XXX: catch ValueError for subclasses of ndarray where iscomplex fail
  464. try:
  465. usecomplex = iscomplexobj(actual) or iscomplexobj(desired)
  466. except ValueError:
  467. usecomplex = False
  468. def _build_err_msg():
  469. header = ('Arrays are not almost equal to %d decimals' % decimal)
  470. return build_err_msg([actual, desired], err_msg, verbose=verbose,
  471. header=header)
  472. if usecomplex:
  473. if iscomplexobj(actual):
  474. actualr = real(actual)
  475. actuali = imag(actual)
  476. else:
  477. actualr = actual
  478. actuali = 0
  479. if iscomplexobj(desired):
  480. desiredr = real(desired)
  481. desiredi = imag(desired)
  482. else:
  483. desiredr = desired
  484. desiredi = 0
  485. try:
  486. assert_almost_equal(actualr, desiredr, decimal=decimal)
  487. assert_almost_equal(actuali, desiredi, decimal=decimal)
  488. except AssertionError:
  489. raise AssertionError(_build_err_msg())
  490. if isinstance(actual, (ndarray, tuple, list)) \
  491. or isinstance(desired, (ndarray, tuple, list)):
  492. return assert_array_almost_equal(actual, desired, decimal, err_msg)
  493. try:
  494. # If one of desired/actual is not finite, handle it specially here:
  495. # check that both are nan if any is a nan, and test for equality
  496. # otherwise
  497. if not (gisfinite(desired) and gisfinite(actual)):
  498. if gisnan(desired) or gisnan(actual):
  499. if not (gisnan(desired) and gisnan(actual)):
  500. raise AssertionError(_build_err_msg())
  501. else:
  502. if not desired == actual:
  503. raise AssertionError(_build_err_msg())
  504. return
  505. except (NotImplementedError, TypeError):
  506. pass
  507. if abs(desired - actual) >= 1.5 * 10.0**(-decimal):
  508. raise AssertionError(_build_err_msg())
  509. def assert_approx_equal(actual,desired,significant=7,err_msg='',verbose=True):
  510. """
  511. Raises an AssertionError if two items are not equal up to significant
  512. digits.
  513. .. note:: It is recommended to use one of `assert_allclose`,
  514. `assert_array_almost_equal_nulp` or `assert_array_max_ulp`
  515. instead of this function for more consistent floating point
  516. comparisons.
  517. Given two numbers, check that they are approximately equal.
  518. Approximately equal is defined as the number of significant digits
  519. that agree.
  520. Parameters
  521. ----------
  522. actual : scalar
  523. The object to check.
  524. desired : scalar
  525. The expected object.
  526. significant : int, optional
  527. Desired precision, default is 7.
  528. err_msg : str, optional
  529. The error message to be printed in case of failure.
  530. verbose : bool, optional
  531. If True, the conflicting values are appended to the error message.
  532. Raises
  533. ------
  534. AssertionError
  535. If actual and desired are not equal up to specified precision.
  536. See Also
  537. --------
  538. assert_allclose: Compare two array_like objects for equality with desired
  539. relative and/or absolute precision.
  540. assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
  541. Examples
  542. --------
  543. >>> np.testing.assert_approx_equal(0.12345677777777e-20, 0.1234567e-20)
  544. >>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345671e-20,
  545. ... significant=8)
  546. >>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345672e-20,
  547. ... significant=8)
  548. Traceback (most recent call last):
  549. ...
  550. AssertionError:
  551. Items are not equal to 8 significant digits:
  552. ACTUAL: 1.234567e-21
  553. DESIRED: 1.2345672e-21
  554. the evaluated condition that raises the exception is
  555. >>> abs(0.12345670e-20/1e-21 - 0.12345672e-20/1e-21) >= 10**-(8-1)
  556. True
  557. """
  558. __tracebackhide__ = True # Hide traceback for py.test
  559. import numpy as np
  560. (actual, desired) = map(float, (actual, desired))
  561. if desired == actual:
  562. return
  563. # Normalized the numbers to be in range (-10.0,10.0)
  564. # scale = float(pow(10,math.floor(math.log10(0.5*(abs(desired)+abs(actual))))))
  565. with np.errstate(invalid='ignore'):
  566. scale = 0.5*(np.abs(desired) + np.abs(actual))
  567. scale = np.power(10, np.floor(np.log10(scale)))
  568. try:
  569. sc_desired = desired/scale
  570. except ZeroDivisionError:
  571. sc_desired = 0.0
  572. try:
  573. sc_actual = actual/scale
  574. except ZeroDivisionError:
  575. sc_actual = 0.0
  576. msg = build_err_msg(
  577. [actual, desired], err_msg,
  578. header='Items are not equal to %d significant digits:' % significant,
  579. verbose=verbose)
  580. try:
  581. # If one of desired/actual is not finite, handle it specially here:
  582. # check that both are nan if any is a nan, and test for equality
  583. # otherwise
  584. if not (gisfinite(desired) and gisfinite(actual)):
  585. if gisnan(desired) or gisnan(actual):
  586. if not (gisnan(desired) and gisnan(actual)):
  587. raise AssertionError(msg)
  588. else:
  589. if not desired == actual:
  590. raise AssertionError(msg)
  591. return
  592. except (TypeError, NotImplementedError):
  593. pass
  594. if np.abs(sc_desired - sc_actual) >= np.power(10., -(significant-1)):
  595. raise AssertionError(msg)
  596. def assert_array_compare(comparison, x, y, err_msg='', verbose=True, header='',
  597. precision=6, equal_nan=True, equal_inf=True):
  598. __tracebackhide__ = True # Hide traceback for py.test
  599. from numpy.core import array, array2string, isnan, inf, bool_, errstate, all, max, object_
  600. x = np.asanyarray(x)
  601. y = np.asanyarray(y)
  602. # original array for output formatting
  603. ox, oy = x, y
  604. def isnumber(x):
  605. return x.dtype.char in '?bhilqpBHILQPefdgFDG'
  606. def istime(x):
  607. return x.dtype.char in "Mm"
  608. def func_assert_same_pos(x, y, func=isnan, hasval='nan'):
  609. """Handling nan/inf.
  610. Combine results of running func on x and y, checking that they are True
  611. at the same locations.
  612. """
  613. __tracebackhide__ = True # Hide traceback for py.test
  614. x_id = func(x)
  615. y_id = func(y)
  616. # We include work-arounds here to handle three types of slightly
  617. # pathological ndarray subclasses:
  618. # (1) all() on `masked` array scalars can return masked arrays, so we
  619. # use != True
  620. # (2) __eq__ on some ndarray subclasses returns Python booleans
  621. # instead of element-wise comparisons, so we cast to bool_() and
  622. # use isinstance(..., bool) checks
  623. # (3) subclasses with bare-bones __array_function__ implementations may
  624. # not implement np.all(), so favor using the .all() method
  625. # We are not committed to supporting such subclasses, but it's nice to
  626. # support them if possible.
  627. if bool_(x_id == y_id).all() != True:
  628. msg = build_err_msg([x, y],
  629. err_msg + '\nx and y %s location mismatch:'
  630. % (hasval), verbose=verbose, header=header,
  631. names=('x', 'y'), precision=precision)
  632. raise AssertionError(msg)
  633. # If there is a scalar, then here we know the array has the same
  634. # flag as it everywhere, so we should return the scalar flag.
  635. if isinstance(x_id, bool) or x_id.ndim == 0:
  636. return bool_(x_id)
  637. elif isinstance(y_id, bool) or y_id.ndim == 0:
  638. return bool_(y_id)
  639. else:
  640. return y_id
  641. try:
  642. cond = (x.shape == () or y.shape == ()) or x.shape == y.shape
  643. if not cond:
  644. msg = build_err_msg([x, y],
  645. err_msg
  646. + f'\n(shapes {x.shape}, {y.shape} mismatch)',
  647. verbose=verbose, header=header,
  648. names=('x', 'y'), precision=precision)
  649. raise AssertionError(msg)
  650. flagged = bool_(False)
  651. if isnumber(x) and isnumber(y):
  652. if equal_nan:
  653. flagged = func_assert_same_pos(x, y, func=isnan, hasval='nan')
  654. if equal_inf:
  655. flagged |= func_assert_same_pos(x, y,
  656. func=lambda xy: xy == +inf,
  657. hasval='+inf')
  658. flagged |= func_assert_same_pos(x, y,
  659. func=lambda xy: xy == -inf,
  660. hasval='-inf')
  661. elif istime(x) and istime(y):
  662. # If one is datetime64 and the other timedelta64 there is no point
  663. if equal_nan and x.dtype.type == y.dtype.type:
  664. flagged = func_assert_same_pos(x, y, func=isnat, hasval="NaT")
  665. if flagged.ndim > 0:
  666. x, y = x[~flagged], y[~flagged]
  667. # Only do the comparison if actual values are left
  668. if x.size == 0:
  669. return
  670. elif flagged:
  671. # no sense doing comparison if everything is flagged.
  672. return
  673. val = comparison(x, y)
  674. if isinstance(val, bool):
  675. cond = val
  676. reduced = array([val])
  677. else:
  678. reduced = val.ravel()
  679. cond = reduced.all()
  680. # The below comparison is a hack to ensure that fully masked
  681. # results, for which val.ravel().all() returns np.ma.masked,
  682. # do not trigger a failure (np.ma.masked != True evaluates as
  683. # np.ma.masked, which is falsy).
  684. if cond != True:
  685. n_mismatch = reduced.size - reduced.sum(dtype=intp)
  686. n_elements = flagged.size if flagged.ndim != 0 else reduced.size
  687. percent_mismatch = 100 * n_mismatch / n_elements
  688. remarks = [
  689. 'Mismatched elements: {} / {} ({:.3g}%)'.format(
  690. n_mismatch, n_elements, percent_mismatch)]
  691. with errstate(invalid='ignore', divide='ignore'):
  692. # ignore errors for non-numeric types
  693. with contextlib.suppress(TypeError):
  694. error = abs(x - y)
  695. max_abs_error = max(error)
  696. if getattr(error, 'dtype', object_) == object_:
  697. remarks.append('Max absolute difference: '
  698. + str(max_abs_error))
  699. else:
  700. remarks.append('Max absolute difference: '
  701. + array2string(max_abs_error))
  702. # note: this definition of relative error matches that one
  703. # used by assert_allclose (found in np.isclose)
  704. # Filter values where the divisor would be zero
  705. nonzero = bool_(y != 0)
  706. if all(~nonzero):
  707. max_rel_error = array(inf)
  708. else:
  709. max_rel_error = max(error[nonzero] / abs(y[nonzero]))
  710. if getattr(error, 'dtype', object_) == object_:
  711. remarks.append('Max relative difference: '
  712. + str(max_rel_error))
  713. else:
  714. remarks.append('Max relative difference: '
  715. + array2string(max_rel_error))
  716. err_msg += '\n' + '\n'.join(remarks)
  717. msg = build_err_msg([ox, oy], err_msg,
  718. verbose=verbose, header=header,
  719. names=('x', 'y'), precision=precision)
  720. raise AssertionError(msg)
  721. except ValueError:
  722. import traceback
  723. efmt = traceback.format_exc()
  724. header = f'error during assertion:\n\n{efmt}\n\n{header}'
  725. msg = build_err_msg([x, y], err_msg, verbose=verbose, header=header,
  726. names=('x', 'y'), precision=precision)
  727. raise ValueError(msg)
  728. def assert_array_equal(x, y, err_msg='', verbose=True):
  729. """
  730. Raises an AssertionError if two array_like objects are not equal.
  731. Given two array_like objects, check that the shape is equal and all
  732. elements of these objects are equal (but see the Notes for the special
  733. handling of a scalar). An exception is raised at shape mismatch or
  734. conflicting values. In contrast to the standard usage in numpy, NaNs
  735. are compared like numbers, no assertion is raised if both objects have
  736. NaNs in the same positions.
  737. The usual caution for verifying equality with floating point numbers is
  738. advised.
  739. Parameters
  740. ----------
  741. x : array_like
  742. The actual object to check.
  743. y : array_like
  744. The desired, expected object.
  745. err_msg : str, optional
  746. The error message to be printed in case of failure.
  747. verbose : bool, optional
  748. If True, the conflicting values are appended to the error message.
  749. Raises
  750. ------
  751. AssertionError
  752. If actual and desired objects are not equal.
  753. See Also
  754. --------
  755. assert_allclose: Compare two array_like objects for equality with desired
  756. relative and/or absolute precision.
  757. assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
  758. Notes
  759. -----
  760. When one of `x` and `y` is a scalar and the other is array_like, the
  761. function checks that each element of the array_like object is equal to
  762. the scalar.
  763. Examples
  764. --------
  765. The first assert does not raise an exception:
  766. >>> np.testing.assert_array_equal([1.0,2.33333,np.nan],
  767. ... [np.exp(0),2.33333, np.nan])
  768. Assert fails with numerical imprecision with floats:
  769. >>> np.testing.assert_array_equal([1.0,np.pi,np.nan],
  770. ... [1, np.sqrt(np.pi)**2, np.nan])
  771. Traceback (most recent call last):
  772. ...
  773. AssertionError:
  774. Arrays are not equal
  775. <BLANKLINE>
  776. Mismatched elements: 1 / 3 (33.3%)
  777. Max absolute difference: 4.4408921e-16
  778. Max relative difference: 1.41357986e-16
  779. x: array([1. , 3.141593, nan])
  780. y: array([1. , 3.141593, nan])
  781. Use `assert_allclose` or one of the nulp (number of floating point values)
  782. functions for these cases instead:
  783. >>> np.testing.assert_allclose([1.0,np.pi,np.nan],
  784. ... [1, np.sqrt(np.pi)**2, np.nan],
  785. ... rtol=1e-10, atol=0)
  786. As mentioned in the Notes section, `assert_array_equal` has special
  787. handling for scalars. Here the test checks that each value in `x` is 3:
  788. >>> x = np.full((2, 5), fill_value=3)
  789. >>> np.testing.assert_array_equal(x, 3)
  790. """
  791. __tracebackhide__ = True # Hide traceback for py.test
  792. assert_array_compare(operator.__eq__, x, y, err_msg=err_msg,
  793. verbose=verbose, header='Arrays are not equal')
  794. def assert_array_almost_equal(x, y, decimal=6, err_msg='', verbose=True):
  795. """
  796. Raises an AssertionError if two objects are not equal up to desired
  797. precision.
  798. .. note:: It is recommended to use one of `assert_allclose`,
  799. `assert_array_almost_equal_nulp` or `assert_array_max_ulp`
  800. instead of this function for more consistent floating point
  801. comparisons.
  802. The test verifies identical shapes and that the elements of ``actual`` and
  803. ``desired`` satisfy.
  804. ``abs(desired-actual) < 1.5 * 10**(-decimal)``
  805. That is a looser test than originally documented, but agrees with what the
  806. actual implementation did up to rounding vagaries. An exception is raised
  807. at shape mismatch or conflicting values. In contrast to the standard usage
  808. in numpy, NaNs are compared like numbers, no assertion is raised if both
  809. objects have NaNs in the same positions.
  810. Parameters
  811. ----------
  812. x : array_like
  813. The actual object to check.
  814. y : array_like
  815. The desired, expected object.
  816. decimal : int, optional
  817. Desired precision, default is 6.
  818. err_msg : str, optional
  819. The error message to be printed in case of failure.
  820. verbose : bool, optional
  821. If True, the conflicting values are appended to the error message.
  822. Raises
  823. ------
  824. AssertionError
  825. If actual and desired are not equal up to specified precision.
  826. See Also
  827. --------
  828. assert_allclose: Compare two array_like objects for equality with desired
  829. relative and/or absolute precision.
  830. assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
  831. Examples
  832. --------
  833. the first assert does not raise an exception
  834. >>> np.testing.assert_array_almost_equal([1.0,2.333,np.nan],
  835. ... [1.0,2.333,np.nan])
  836. >>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan],
  837. ... [1.0,2.33339,np.nan], decimal=5)
  838. Traceback (most recent call last):
  839. ...
  840. AssertionError:
  841. Arrays are not almost equal to 5 decimals
  842. <BLANKLINE>
  843. Mismatched elements: 1 / 3 (33.3%)
  844. Max absolute difference: 6.e-05
  845. Max relative difference: 2.57136612e-05
  846. x: array([1. , 2.33333, nan])
  847. y: array([1. , 2.33339, nan])
  848. >>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan],
  849. ... [1.0,2.33333, 5], decimal=5)
  850. Traceback (most recent call last):
  851. ...
  852. AssertionError:
  853. Arrays are not almost equal to 5 decimals
  854. <BLANKLINE>
  855. x and y nan location mismatch:
  856. x: array([1. , 2.33333, nan])
  857. y: array([1. , 2.33333, 5. ])
  858. """
  859. __tracebackhide__ = True # Hide traceback for py.test
  860. from numpy.core import number, float_, result_type, array
  861. from numpy.core.numerictypes import issubdtype
  862. from numpy.core.fromnumeric import any as npany
  863. def compare(x, y):
  864. try:
  865. if npany(gisinf(x)) or npany( gisinf(y)):
  866. xinfid = gisinf(x)
  867. yinfid = gisinf(y)
  868. if not (xinfid == yinfid).all():
  869. return False
  870. # if one item, x and y is +- inf
  871. if x.size == y.size == 1:
  872. return x == y
  873. x = x[~xinfid]
  874. y = y[~yinfid]
  875. except (TypeError, NotImplementedError):
  876. pass
  877. # make sure y is an inexact type to avoid abs(MIN_INT); will cause
  878. # casting of x later.
  879. dtype = result_type(y, 1.)
  880. y = np.asanyarray(y, dtype)
  881. z = abs(x - y)
  882. if not issubdtype(z.dtype, number):
  883. z = z.astype(float_) # handle object arrays
  884. return z < 1.5 * 10.0**(-decimal)
  885. assert_array_compare(compare, x, y, err_msg=err_msg, verbose=verbose,
  886. header=('Arrays are not almost equal to %d decimals' % decimal),
  887. precision=decimal)
  888. def assert_array_less(x, y, err_msg='', verbose=True):
  889. """
  890. Raises an AssertionError if two array_like objects are not ordered by less
  891. than.
  892. Given two array_like objects, check that the shape is equal and all
  893. elements of the first object are strictly smaller than those of the
  894. second object. An exception is raised at shape mismatch or incorrectly
  895. ordered values. Shape mismatch does not raise if an object has zero
  896. dimension. In contrast to the standard usage in numpy, NaNs are
  897. compared, no assertion is raised if both objects have NaNs in the same
  898. positions.
  899. Parameters
  900. ----------
  901. x : array_like
  902. The smaller object to check.
  903. y : array_like
  904. The larger object to compare.
  905. err_msg : string
  906. The error message to be printed in case of failure.
  907. verbose : bool
  908. If True, the conflicting values are appended to the error message.
  909. Raises
  910. ------
  911. AssertionError
  912. If actual and desired objects are not equal.
  913. See Also
  914. --------
  915. assert_array_equal: tests objects for equality
  916. assert_array_almost_equal: test objects for equality up to precision
  917. Examples
  918. --------
  919. >>> np.testing.assert_array_less([1.0, 1.0, np.nan], [1.1, 2.0, np.nan])
  920. >>> np.testing.assert_array_less([1.0, 1.0, np.nan], [1, 2.0, np.nan])
  921. Traceback (most recent call last):
  922. ...
  923. AssertionError:
  924. Arrays are not less-ordered
  925. <BLANKLINE>
  926. Mismatched elements: 1 / 3 (33.3%)
  927. Max absolute difference: 1.
  928. Max relative difference: 0.5
  929. x: array([ 1., 1., nan])
  930. y: array([ 1., 2., nan])
  931. >>> np.testing.assert_array_less([1.0, 4.0], 3)
  932. Traceback (most recent call last):
  933. ...
  934. AssertionError:
  935. Arrays are not less-ordered
  936. <BLANKLINE>
  937. Mismatched elements: 1 / 2 (50%)
  938. Max absolute difference: 2.
  939. Max relative difference: 0.66666667
  940. x: array([1., 4.])
  941. y: array(3)
  942. >>> np.testing.assert_array_less([1.0, 2.0, 3.0], [4])
  943. Traceback (most recent call last):
  944. ...
  945. AssertionError:
  946. Arrays are not less-ordered
  947. <BLANKLINE>
  948. (shapes (3,), (1,) mismatch)
  949. x: array([1., 2., 3.])
  950. y: array([4])
  951. """
  952. __tracebackhide__ = True # Hide traceback for py.test
  953. assert_array_compare(operator.__lt__, x, y, err_msg=err_msg,
  954. verbose=verbose,
  955. header='Arrays are not less-ordered',
  956. equal_inf=False)
  957. def runstring(astr, dict):
  958. exec(astr, dict)
  959. def assert_string_equal(actual, desired):
  960. """
  961. Test if two strings are equal.
  962. If the given strings are equal, `assert_string_equal` does nothing.
  963. If they are not equal, an AssertionError is raised, and the diff
  964. between the strings is shown.
  965. Parameters
  966. ----------
  967. actual : str
  968. The string to test for equality against the expected string.
  969. desired : str
  970. The expected string.
  971. Examples
  972. --------
  973. >>> np.testing.assert_string_equal('abc', 'abc')
  974. >>> np.testing.assert_string_equal('abc', 'abcd')
  975. Traceback (most recent call last):
  976. File "<stdin>", line 1, in <module>
  977. ...
  978. AssertionError: Differences in strings:
  979. - abc+ abcd? +
  980. """
  981. # delay import of difflib to reduce startup time
  982. __tracebackhide__ = True # Hide traceback for py.test
  983. import difflib
  984. if not isinstance(actual, str):
  985. raise AssertionError(repr(type(actual)))
  986. if not isinstance(desired, str):
  987. raise AssertionError(repr(type(desired)))
  988. if desired == actual:
  989. return
  990. diff = list(difflib.Differ().compare(actual.splitlines(True),
  991. desired.splitlines(True)))
  992. diff_list = []
  993. while diff:
  994. d1 = diff.pop(0)
  995. if d1.startswith(' '):
  996. continue
  997. if d1.startswith('- '):
  998. l = [d1]
  999. d2 = diff.pop(0)
  1000. if d2.startswith('? '):
  1001. l.append(d2)
  1002. d2 = diff.pop(0)
  1003. if not d2.startswith('+ '):
  1004. raise AssertionError(repr(d2))
  1005. l.append(d2)
  1006. if diff:
  1007. d3 = diff.pop(0)
  1008. if d3.startswith('? '):
  1009. l.append(d3)
  1010. else:
  1011. diff.insert(0, d3)
  1012. if d2[2:] == d1[2:]:
  1013. continue
  1014. diff_list.extend(l)
  1015. continue
  1016. raise AssertionError(repr(d1))
  1017. if not diff_list:
  1018. return
  1019. msg = f"Differences in strings:\n{''.join(diff_list).rstrip()}"
  1020. if actual != desired:
  1021. raise AssertionError(msg)
  1022. def rundocs(filename=None, raise_on_error=True):
  1023. """
  1024. Run doctests found in the given file.
  1025. By default `rundocs` raises an AssertionError on failure.
  1026. Parameters
  1027. ----------
  1028. filename : str
  1029. The path to the file for which the doctests are run.
  1030. raise_on_error : bool
  1031. Whether to raise an AssertionError when a doctest fails. Default is
  1032. True.
  1033. Notes
  1034. -----
  1035. The doctests can be run by the user/developer by adding the ``doctests``
  1036. argument to the ``test()`` call. For example, to run all tests (including
  1037. doctests) for `numpy.lib`:
  1038. >>> np.lib.test(doctests=True) # doctest: +SKIP
  1039. """
  1040. from numpy.distutils.misc_util import exec_mod_from_location
  1041. import doctest
  1042. if filename is None:
  1043. f = sys._getframe(1)
  1044. filename = f.f_globals['__file__']
  1045. name = os.path.splitext(os.path.basename(filename))[0]
  1046. m = exec_mod_from_location(name, filename)
  1047. tests = doctest.DocTestFinder().find(m)
  1048. runner = doctest.DocTestRunner(verbose=False)
  1049. msg = []
  1050. if raise_on_error:
  1051. out = lambda s: msg.append(s)
  1052. else:
  1053. out = None
  1054. for test in tests:
  1055. runner.run(test, out=out)
  1056. if runner.failures > 0 and raise_on_error:
  1057. raise AssertionError("Some doctests failed:\n%s" % "\n".join(msg))
  1058. def raises(*args):
  1059. """Decorator to check for raised exceptions.
  1060. The decorated test function must raise one of the passed exceptions to
  1061. pass. If you want to test many assertions about exceptions in a single
  1062. test, you may want to use `assert_raises` instead.
  1063. .. warning::
  1064. This decorator is nose specific, do not use it if you are using a
  1065. different test framework.
  1066. Parameters
  1067. ----------
  1068. args : exceptions
  1069. The test passes if any of the passed exceptions is raised.
  1070. Raises
  1071. ------
  1072. AssertionError
  1073. Examples
  1074. --------
  1075. Usage::
  1076. @raises(TypeError, ValueError)
  1077. def test_raises_type_error():
  1078. raise TypeError("This test passes")
  1079. @raises(Exception)
  1080. def test_that_fails_by_passing():
  1081. pass
  1082. """
  1083. nose = import_nose()
  1084. return nose.tools.raises(*args)
  1085. #
  1086. # assert_raises and assert_raises_regex are taken from unittest.
  1087. #
  1088. import unittest
  1089. class _Dummy(unittest.TestCase):
  1090. def nop(self):
  1091. pass
  1092. _d = _Dummy('nop')
  1093. def assert_raises(*args, **kwargs):
  1094. """
  1095. assert_raises(exception_class, callable, *args, **kwargs)
  1096. assert_raises(exception_class)
  1097. Fail unless an exception of class exception_class is thrown
  1098. by callable when invoked with arguments args and keyword
  1099. arguments kwargs. If a different type of exception is
  1100. thrown, it will not be caught, and the test case will be
  1101. deemed to have suffered an error, exactly as for an
  1102. unexpected exception.
  1103. Alternatively, `assert_raises` can be used as a context manager:
  1104. >>> from numpy.testing import assert_raises
  1105. >>> with assert_raises(ZeroDivisionError):
  1106. ... 1 / 0
  1107. is equivalent to
  1108. >>> def div(x, y):
  1109. ... return x / y
  1110. >>> assert_raises(ZeroDivisionError, div, 1, 0)
  1111. """
  1112. __tracebackhide__ = True # Hide traceback for py.test
  1113. return _d.assertRaises(*args,**kwargs)
  1114. def assert_raises_regex(exception_class, expected_regexp, *args, **kwargs):
  1115. """
  1116. assert_raises_regex(exception_class, expected_regexp, callable, *args,
  1117. **kwargs)
  1118. assert_raises_regex(exception_class, expected_regexp)
  1119. Fail unless an exception of class exception_class and with message that
  1120. matches expected_regexp is thrown by callable when invoked with arguments
  1121. args and keyword arguments kwargs.
  1122. Alternatively, can be used as a context manager like `assert_raises`.
  1123. Name of this function adheres to Python 3.2+ reference, but should work in
  1124. all versions down to 2.6.
  1125. Notes
  1126. -----
  1127. .. versionadded:: 1.9.0
  1128. """
  1129. __tracebackhide__ = True # Hide traceback for py.test
  1130. return _d.assertRaisesRegex(exception_class, expected_regexp, *args, **kwargs)
  1131. def decorate_methods(cls, decorator, testmatch=None):
  1132. """
  1133. Apply a decorator to all methods in a class matching a regular expression.
  1134. The given decorator is applied to all public methods of `cls` that are
  1135. matched by the regular expression `testmatch`
  1136. (``testmatch.search(methodname)``). Methods that are private, i.e. start
  1137. with an underscore, are ignored.
  1138. Parameters
  1139. ----------
  1140. cls : class
  1141. Class whose methods to decorate.
  1142. decorator : function
  1143. Decorator to apply to methods
  1144. testmatch : compiled regexp or str, optional
  1145. The regular expression. Default value is None, in which case the
  1146. nose default (``re.compile(r'(?:^|[\\b_\\.%s-])[Tt]est' % os.sep)``)
  1147. is used.
  1148. If `testmatch` is a string, it is compiled to a regular expression
  1149. first.
  1150. """
  1151. if testmatch is None:
  1152. testmatch = re.compile(r'(?:^|[\\b_\\.%s-])[Tt]est' % os.sep)
  1153. else:
  1154. testmatch = re.compile(testmatch)
  1155. cls_attr = cls.__dict__
  1156. # delayed import to reduce startup time
  1157. from inspect import isfunction
  1158. methods = [_m for _m in cls_attr.values() if isfunction(_m)]
  1159. for function in methods:
  1160. try:
  1161. if hasattr(function, 'compat_func_name'):
  1162. funcname = function.compat_func_name
  1163. else:
  1164. funcname = function.__name__
  1165. except AttributeError:
  1166. # not a function
  1167. continue
  1168. if testmatch.search(funcname) and not funcname.startswith('_'):
  1169. setattr(cls, funcname, decorator(function))
  1170. return
  1171. def measure(code_str, times=1, label=None):
  1172. """
  1173. Return elapsed time for executing code in the namespace of the caller.
  1174. The supplied code string is compiled with the Python builtin ``compile``.
  1175. The precision of the timing is 10 milli-seconds. If the code will execute
  1176. fast on this timescale, it can be executed many times to get reasonable
  1177. timing accuracy.
  1178. Parameters
  1179. ----------
  1180. code_str : str
  1181. The code to be timed.
  1182. times : int, optional
  1183. The number of times the code is executed. Default is 1. The code is
  1184. only compiled once.
  1185. label : str, optional
  1186. A label to identify `code_str` with. This is passed into ``compile``
  1187. as the second argument (for run-time error messages).
  1188. Returns
  1189. -------
  1190. elapsed : float
  1191. Total elapsed time in seconds for executing `code_str` `times` times.
  1192. Examples
  1193. --------
  1194. >>> times = 10
  1195. >>> etime = np.testing.measure('for i in range(1000): np.sqrt(i**2)', times=times)
  1196. >>> print("Time for a single execution : ", etime / times, "s") # doctest: +SKIP
  1197. Time for a single execution : 0.005 s
  1198. """
  1199. frame = sys._getframe(1)
  1200. locs, globs = frame.f_locals, frame.f_globals
  1201. code = compile(code_str, f'Test name: {label} ', 'exec')
  1202. i = 0
  1203. elapsed = jiffies()
  1204. while i < times:
  1205. i += 1
  1206. exec(code, globs, locs)
  1207. elapsed = jiffies() - elapsed
  1208. return 0.01*elapsed
  1209. def _assert_valid_refcount(op):
  1210. """
  1211. Check that ufuncs don't mishandle refcount of object `1`.
  1212. Used in a few regression tests.
  1213. """
  1214. if not HAS_REFCOUNT:
  1215. return True
  1216. import gc
  1217. import numpy as np
  1218. b = np.arange(100*100).reshape(100, 100)
  1219. c = b
  1220. i = 1
  1221. gc.disable()
  1222. try:
  1223. rc = sys.getrefcount(i)
  1224. for j in range(15):
  1225. d = op(b, c)
  1226. assert_(sys.getrefcount(i) >= rc)
  1227. finally:
  1228. gc.enable()
  1229. del d # for pyflakes
  1230. def assert_allclose(actual, desired, rtol=1e-7, atol=0, equal_nan=True,
  1231. err_msg='', verbose=True):
  1232. """
  1233. Raises an AssertionError if two objects are not equal up to desired
  1234. tolerance.
  1235. The test is equivalent to ``allclose(actual, desired, rtol, atol)`` (note
  1236. that ``allclose`` has different default values). It compares the difference
  1237. between `actual` and `desired` to ``atol + rtol * abs(desired)``.
  1238. .. versionadded:: 1.5.0
  1239. Parameters
  1240. ----------
  1241. actual : array_like
  1242. Array obtained.
  1243. desired : array_like
  1244. Array desired.
  1245. rtol : float, optional
  1246. Relative tolerance.
  1247. atol : float, optional
  1248. Absolute tolerance.
  1249. equal_nan : bool, optional.
  1250. If True, NaNs will compare equal.
  1251. err_msg : str, optional
  1252. The error message to be printed in case of failure.
  1253. verbose : bool, optional
  1254. If True, the conflicting values are appended to the error message.
  1255. Raises
  1256. ------
  1257. AssertionError
  1258. If actual and desired are not equal up to specified precision.
  1259. See Also
  1260. --------
  1261. assert_array_almost_equal_nulp, assert_array_max_ulp
  1262. Examples
  1263. --------
  1264. >>> x = [1e-5, 1e-3, 1e-1]
  1265. >>> y = np.arccos(np.cos(x))
  1266. >>> np.testing.assert_allclose(x, y, rtol=1e-5, atol=0)
  1267. """
  1268. __tracebackhide__ = True # Hide traceback for py.test
  1269. import numpy as np
  1270. def compare(x, y):
  1271. return np.core.numeric.isclose(x, y, rtol=rtol, atol=atol,
  1272. equal_nan=equal_nan)
  1273. actual, desired = np.asanyarray(actual), np.asanyarray(desired)
  1274. header = f'Not equal to tolerance rtol={rtol:g}, atol={atol:g}'
  1275. assert_array_compare(compare, actual, desired, err_msg=str(err_msg),
  1276. verbose=verbose, header=header, equal_nan=equal_nan)
  1277. def assert_array_almost_equal_nulp(x, y, nulp=1):
  1278. """
  1279. Compare two arrays relatively to their spacing.
  1280. This is a relatively robust method to compare two arrays whose amplitude
  1281. is variable.
  1282. Parameters
  1283. ----------
  1284. x, y : array_like
  1285. Input arrays.
  1286. nulp : int, optional
  1287. The maximum number of unit in the last place for tolerance (see Notes).
  1288. Default is 1.
  1289. Returns
  1290. -------
  1291. None
  1292. Raises
  1293. ------
  1294. AssertionError
  1295. If the spacing between `x` and `y` for one or more elements is larger
  1296. than `nulp`.
  1297. See Also
  1298. --------
  1299. assert_array_max_ulp : Check that all items of arrays differ in at most
  1300. N Units in the Last Place.
  1301. spacing : Return the distance between x and the nearest adjacent number.
  1302. Notes
  1303. -----
  1304. An assertion is raised if the following condition is not met::
  1305. abs(x - y) <= nulps * spacing(maximum(abs(x), abs(y)))
  1306. Examples
  1307. --------
  1308. >>> x = np.array([1., 1e-10, 1e-20])
  1309. >>> eps = np.finfo(x.dtype).eps
  1310. >>> np.testing.assert_array_almost_equal_nulp(x, x*eps/2 + x)
  1311. >>> np.testing.assert_array_almost_equal_nulp(x, x*eps + x)
  1312. Traceback (most recent call last):
  1313. ...
  1314. AssertionError: X and Y are not equal to 1 ULP (max is 2)
  1315. """
  1316. __tracebackhide__ = True # Hide traceback for py.test
  1317. import numpy as np
  1318. ax = np.abs(x)
  1319. ay = np.abs(y)
  1320. ref = nulp * np.spacing(np.where(ax > ay, ax, ay))
  1321. if not np.all(np.abs(x-y) <= ref):
  1322. if np.iscomplexobj(x) or np.iscomplexobj(y):
  1323. msg = "X and Y are not equal to %d ULP" % nulp
  1324. else:
  1325. max_nulp = np.max(nulp_diff(x, y))
  1326. msg = "X and Y are not equal to %d ULP (max is %g)" % (nulp, max_nulp)
  1327. raise AssertionError(msg)
  1328. def assert_array_max_ulp(a, b, maxulp=1, dtype=None):
  1329. """
  1330. Check that all items of arrays differ in at most N Units in the Last Place.
  1331. Parameters
  1332. ----------
  1333. a, b : array_like
  1334. Input arrays to be compared.
  1335. maxulp : int, optional
  1336. The maximum number of units in the last place that elements of `a` and
  1337. `b` can differ. Default is 1.
  1338. dtype : dtype, optional
  1339. Data-type to convert `a` and `b` to if given. Default is None.
  1340. Returns
  1341. -------
  1342. ret : ndarray
  1343. Array containing number of representable floating point numbers between
  1344. items in `a` and `b`.
  1345. Raises
  1346. ------
  1347. AssertionError
  1348. If one or more elements differ by more than `maxulp`.
  1349. Notes
  1350. -----
  1351. For computing the ULP difference, this API does not differentiate between
  1352. various representations of NAN (ULP difference between 0x7fc00000 and 0xffc00000
  1353. is zero).
  1354. See Also
  1355. --------
  1356. assert_array_almost_equal_nulp : Compare two arrays relatively to their
  1357. spacing.
  1358. Examples
  1359. --------
  1360. >>> a = np.linspace(0., 1., 100)
  1361. >>> res = np.testing.assert_array_max_ulp(a, np.arcsin(np.sin(a)))
  1362. """
  1363. __tracebackhide__ = True # Hide traceback for py.test
  1364. import numpy as np
  1365. ret = nulp_diff(a, b, dtype)
  1366. if not np.all(ret <= maxulp):
  1367. raise AssertionError("Arrays are not almost equal up to %g "
  1368. "ULP (max difference is %g ULP)" %
  1369. (maxulp, np.max(ret)))
  1370. return ret
  1371. def nulp_diff(x, y, dtype=None):
  1372. """For each item in x and y, return the number of representable floating
  1373. points between them.
  1374. Parameters
  1375. ----------
  1376. x : array_like
  1377. first input array
  1378. y : array_like
  1379. second input array
  1380. dtype : dtype, optional
  1381. Data-type to convert `x` and `y` to if given. Default is None.
  1382. Returns
  1383. -------
  1384. nulp : array_like
  1385. number of representable floating point numbers between each item in x
  1386. and y.
  1387. Notes
  1388. -----
  1389. For computing the ULP difference, this API does not differentiate between
  1390. various representations of NAN (ULP difference between 0x7fc00000 and 0xffc00000
  1391. is zero).
  1392. Examples
  1393. --------
  1394. # By definition, epsilon is the smallest number such as 1 + eps != 1, so
  1395. # there should be exactly one ULP between 1 and 1 + eps
  1396. >>> nulp_diff(1, 1 + np.finfo(x.dtype).eps)
  1397. 1.0
  1398. """
  1399. import numpy as np
  1400. if dtype:
  1401. x = np.asarray(x, dtype=dtype)
  1402. y = np.asarray(y, dtype=dtype)
  1403. else:
  1404. x = np.asarray(x)
  1405. y = np.asarray(y)
  1406. t = np.common_type(x, y)
  1407. if np.iscomplexobj(x) or np.iscomplexobj(y):
  1408. raise NotImplementedError("_nulp not implemented for complex array")
  1409. x = np.array([x], dtype=t)
  1410. y = np.array([y], dtype=t)
  1411. x[np.isnan(x)] = np.nan
  1412. y[np.isnan(y)] = np.nan
  1413. if not x.shape == y.shape:
  1414. raise ValueError("x and y do not have the same shape: %s - %s" %
  1415. (x.shape, y.shape))
  1416. def _diff(rx, ry, vdt):
  1417. diff = np.asarray(rx-ry, dtype=vdt)
  1418. return np.abs(diff)
  1419. rx = integer_repr(x)
  1420. ry = integer_repr(y)
  1421. return _diff(rx, ry, t)
  1422. def _integer_repr(x, vdt, comp):
  1423. # Reinterpret binary representation of the float as sign-magnitude:
  1424. # take into account two-complement representation
  1425. # See also
  1426. # https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
  1427. rx = x.view(vdt)
  1428. if not (rx.size == 1):
  1429. rx[rx < 0] = comp - rx[rx < 0]
  1430. else:
  1431. if rx < 0:
  1432. rx = comp - rx
  1433. return rx
  1434. def integer_repr(x):
  1435. """Return the signed-magnitude interpretation of the binary representation
  1436. of x."""
  1437. import numpy as np
  1438. if x.dtype == np.float16:
  1439. return _integer_repr(x, np.int16, np.int16(-2**15))
  1440. elif x.dtype == np.float32:
  1441. return _integer_repr(x, np.int32, np.int32(-2**31))
  1442. elif x.dtype == np.float64:
  1443. return _integer_repr(x, np.int64, np.int64(-2**63))
  1444. else:
  1445. raise ValueError(f'Unsupported dtype {x.dtype}')
  1446. @contextlib.contextmanager
  1447. def _assert_warns_context(warning_class, name=None):
  1448. __tracebackhide__ = True # Hide traceback for py.test
  1449. with suppress_warnings() as sup:
  1450. l = sup.record(warning_class)
  1451. yield
  1452. if not len(l) > 0:
  1453. name_str = f' when calling {name}' if name is not None else ''
  1454. raise AssertionError("No warning raised" + name_str)
  1455. def assert_warns(warning_class, *args, **kwargs):
  1456. """
  1457. Fail unless the given callable throws the specified warning.
  1458. A warning of class warning_class should be thrown by the callable when
  1459. invoked with arguments args and keyword arguments kwargs.
  1460. If a different type of warning is thrown, it will not be caught.
  1461. If called with all arguments other than the warning class omitted, may be
  1462. used as a context manager:
  1463. with assert_warns(SomeWarning):
  1464. do_something()
  1465. The ability to be used as a context manager is new in NumPy v1.11.0.
  1466. .. versionadded:: 1.4.0
  1467. Parameters
  1468. ----------
  1469. warning_class : class
  1470. The class defining the warning that `func` is expected to throw.
  1471. func : callable, optional
  1472. Callable to test
  1473. *args : Arguments
  1474. Arguments for `func`.
  1475. **kwargs : Kwargs
  1476. Keyword arguments for `func`.
  1477. Returns
  1478. -------
  1479. The value returned by `func`.
  1480. Examples
  1481. --------
  1482. >>> import warnings
  1483. >>> def deprecated_func(num):
  1484. ... warnings.warn("Please upgrade", DeprecationWarning)
  1485. ... return num*num
  1486. >>> with np.testing.assert_warns(DeprecationWarning):
  1487. ... assert deprecated_func(4) == 16
  1488. >>> # or passing a func
  1489. >>> ret = np.testing.assert_warns(DeprecationWarning, deprecated_func, 4)
  1490. >>> assert ret == 16
  1491. """
  1492. if not args:
  1493. return _assert_warns_context(warning_class)
  1494. func = args[0]
  1495. args = args[1:]
  1496. with _assert_warns_context(warning_class, name=func.__name__):
  1497. return func(*args, **kwargs)
  1498. @contextlib.contextmanager
  1499. def _assert_no_warnings_context(name=None):
  1500. __tracebackhide__ = True # Hide traceback for py.test
  1501. with warnings.catch_warnings(record=True) as l:
  1502. warnings.simplefilter('always')
  1503. yield
  1504. if len(l) > 0:
  1505. name_str = f' when calling {name}' if name is not None else ''
  1506. raise AssertionError(f'Got warnings{name_str}: {l}')
  1507. def assert_no_warnings(*args, **kwargs):
  1508. """
  1509. Fail if the given callable produces any warnings.
  1510. If called with all arguments omitted, may be used as a context manager:
  1511. with assert_no_warnings():
  1512. do_something()
  1513. The ability to be used as a context manager is new in NumPy v1.11.0.
  1514. .. versionadded:: 1.7.0
  1515. Parameters
  1516. ----------
  1517. func : callable
  1518. The callable to test.
  1519. \\*args : Arguments
  1520. Arguments passed to `func`.
  1521. \\*\\*kwargs : Kwargs
  1522. Keyword arguments passed to `func`.
  1523. Returns
  1524. -------
  1525. The value returned by `func`.
  1526. """
  1527. if not args:
  1528. return _assert_no_warnings_context()
  1529. func = args[0]
  1530. args = args[1:]
  1531. with _assert_no_warnings_context(name=func.__name__):
  1532. return func(*args, **kwargs)
  1533. def _gen_alignment_data(dtype=float32, type='binary', max_size=24):
  1534. """
  1535. generator producing data with different alignment and offsets
  1536. to test simd vectorization
  1537. Parameters
  1538. ----------
  1539. dtype : dtype
  1540. data type to produce
  1541. type : string
  1542. 'unary': create data for unary operations, creates one input
  1543. and output array
  1544. 'binary': create data for unary operations, creates two input
  1545. and output array
  1546. max_size : integer
  1547. maximum size of data to produce
  1548. Returns
  1549. -------
  1550. if type is 'unary' yields one output, one input array and a message
  1551. containing information on the data
  1552. if type is 'binary' yields one output array, two input array and a message
  1553. containing information on the data
  1554. """
  1555. ufmt = 'unary offset=(%d, %d), size=%d, dtype=%r, %s'
  1556. bfmt = 'binary offset=(%d, %d, %d), size=%d, dtype=%r, %s'
  1557. for o in range(3):
  1558. for s in range(o + 2, max(o + 3, max_size)):
  1559. if type == 'unary':
  1560. inp = lambda: arange(s, dtype=dtype)[o:]
  1561. out = empty((s,), dtype=dtype)[o:]
  1562. yield out, inp(), ufmt % (o, o, s, dtype, 'out of place')
  1563. d = inp()
  1564. yield d, d, ufmt % (o, o, s, dtype, 'in place')
  1565. yield out[1:], inp()[:-1], ufmt % \
  1566. (o + 1, o, s - 1, dtype, 'out of place')
  1567. yield out[:-1], inp()[1:], ufmt % \
  1568. (o, o + 1, s - 1, dtype, 'out of place')
  1569. yield inp()[:-1], inp()[1:], ufmt % \
  1570. (o, o + 1, s - 1, dtype, 'aliased')
  1571. yield inp()[1:], inp()[:-1], ufmt % \
  1572. (o + 1, o, s - 1, dtype, 'aliased')
  1573. if type == 'binary':
  1574. inp1 = lambda: arange(s, dtype=dtype)[o:]
  1575. inp2 = lambda: arange(s, dtype=dtype)[o:]
  1576. out = empty((s,), dtype=dtype)[o:]
  1577. yield out, inp1(), inp2(), bfmt % \
  1578. (o, o, o, s, dtype, 'out of place')
  1579. d = inp1()
  1580. yield d, d, inp2(), bfmt % \
  1581. (o, o, o, s, dtype, 'in place1')
  1582. d = inp2()
  1583. yield d, inp1(), d, bfmt % \
  1584. (o, o, o, s, dtype, 'in place2')
  1585. yield out[1:], inp1()[:-1], inp2()[:-1], bfmt % \
  1586. (o + 1, o, o, s - 1, dtype, 'out of place')
  1587. yield out[:-1], inp1()[1:], inp2()[:-1], bfmt % \
  1588. (o, o + 1, o, s - 1, dtype, 'out of place')
  1589. yield out[:-1], inp1()[:-1], inp2()[1:], bfmt % \
  1590. (o, o, o + 1, s - 1, dtype, 'out of place')
  1591. yield inp1()[1:], inp1()[:-1], inp2()[:-1], bfmt % \
  1592. (o + 1, o, o, s - 1, dtype, 'aliased')
  1593. yield inp1()[:-1], inp1()[1:], inp2()[:-1], bfmt % \
  1594. (o, o + 1, o, s - 1, dtype, 'aliased')
  1595. yield inp1()[:-1], inp1()[:-1], inp2()[1:], bfmt % \
  1596. (o, o, o + 1, s - 1, dtype, 'aliased')
  1597. class IgnoreException(Exception):
  1598. "Ignoring this exception due to disabled feature"
  1599. pass
  1600. @contextlib.contextmanager
  1601. def tempdir(*args, **kwargs):
  1602. """Context manager to provide a temporary test folder.
  1603. All arguments are passed as this to the underlying tempfile.mkdtemp
  1604. function.
  1605. """
  1606. tmpdir = mkdtemp(*args, **kwargs)
  1607. try:
  1608. yield tmpdir
  1609. finally:
  1610. shutil.rmtree(tmpdir)
  1611. @contextlib.contextmanager
  1612. def temppath(*args, **kwargs):
  1613. """Context manager for temporary files.
  1614. Context manager that returns the path to a closed temporary file. Its
  1615. parameters are the same as for tempfile.mkstemp and are passed directly
  1616. to that function. The underlying file is removed when the context is
  1617. exited, so it should be closed at that time.
  1618. Windows does not allow a temporary file to be opened if it is already
  1619. open, so the underlying file must be closed after opening before it
  1620. can be opened again.
  1621. """
  1622. fd, path = mkstemp(*args, **kwargs)
  1623. os.close(fd)
  1624. try:
  1625. yield path
  1626. finally:
  1627. os.remove(path)
  1628. class clear_and_catch_warnings(warnings.catch_warnings):
  1629. """ Context manager that resets warning registry for catching warnings
  1630. Warnings can be slippery, because, whenever a warning is triggered, Python
  1631. adds a ``__warningregistry__`` member to the *calling* module. This makes
  1632. it impossible to retrigger the warning in this module, whatever you put in
  1633. the warnings filters. This context manager accepts a sequence of `modules`
  1634. as a keyword argument to its constructor and:
  1635. * stores and removes any ``__warningregistry__`` entries in given `modules`
  1636. on entry;
  1637. * resets ``__warningregistry__`` to its previous state on exit.
  1638. This makes it possible to trigger any warning afresh inside the context
  1639. manager without disturbing the state of warnings outside.
  1640. For compatibility with Python 3.0, please consider all arguments to be
  1641. keyword-only.
  1642. Parameters
  1643. ----------
  1644. record : bool, optional
  1645. Specifies whether warnings should be captured by a custom
  1646. implementation of ``warnings.showwarning()`` and be appended to a list
  1647. returned by the context manager. Otherwise None is returned by the
  1648. context manager. The objects appended to the list are arguments whose
  1649. attributes mirror the arguments to ``showwarning()``.
  1650. modules : sequence, optional
  1651. Sequence of modules for which to reset warnings registry on entry and
  1652. restore on exit. To work correctly, all 'ignore' filters should
  1653. filter by one of these modules.
  1654. Examples
  1655. --------
  1656. >>> import warnings
  1657. >>> with np.testing.clear_and_catch_warnings(
  1658. ... modules=[np.core.fromnumeric]):
  1659. ... warnings.simplefilter('always')
  1660. ... warnings.filterwarnings('ignore', module='np.core.fromnumeric')
  1661. ... # do something that raises a warning but ignore those in
  1662. ... # np.core.fromnumeric
  1663. """
  1664. class_modules = ()
  1665. def __init__(self, record=False, modules=()):
  1666. self.modules = set(modules).union(self.class_modules)
  1667. self._warnreg_copies = {}
  1668. super().__init__(record=record)
  1669. def __enter__(self):
  1670. for mod in self.modules:
  1671. if hasattr(mod, '__warningregistry__'):
  1672. mod_reg = mod.__warningregistry__
  1673. self._warnreg_copies[mod] = mod_reg.copy()
  1674. mod_reg.clear()
  1675. return super().__enter__()
  1676. def __exit__(self, *exc_info):
  1677. super().__exit__(*exc_info)
  1678. for mod in self.modules:
  1679. if hasattr(mod, '__warningregistry__'):
  1680. mod.__warningregistry__.clear()
  1681. if mod in self._warnreg_copies:
  1682. mod.__warningregistry__.update(self._warnreg_copies[mod])
  1683. class suppress_warnings:
  1684. """
  1685. Context manager and decorator doing much the same as
  1686. ``warnings.catch_warnings``.
  1687. However, it also provides a filter mechanism to work around
  1688. https://bugs.python.org/issue4180.
  1689. This bug causes Python before 3.4 to not reliably show warnings again
  1690. after they have been ignored once (even within catch_warnings). It
  1691. means that no "ignore" filter can be used easily, since following
  1692. tests might need to see the warning. Additionally it allows easier
  1693. specificity for testing warnings and can be nested.
  1694. Parameters
  1695. ----------
  1696. forwarding_rule : str, optional
  1697. One of "always", "once", "module", or "location". Analogous to
  1698. the usual warnings module filter mode, it is useful to reduce
  1699. noise mostly on the outmost level. Unsuppressed and unrecorded
  1700. warnings will be forwarded based on this rule. Defaults to "always".
  1701. "location" is equivalent to the warnings "default", match by exact
  1702. location the warning warning originated from.
  1703. Notes
  1704. -----
  1705. Filters added inside the context manager will be discarded again
  1706. when leaving it. Upon entering all filters defined outside a
  1707. context will be applied automatically.
  1708. When a recording filter is added, matching warnings are stored in the
  1709. ``log`` attribute as well as in the list returned by ``record``.
  1710. If filters are added and the ``module`` keyword is given, the
  1711. warning registry of this module will additionally be cleared when
  1712. applying it, entering the context, or exiting it. This could cause
  1713. warnings to appear a second time after leaving the context if they
  1714. were configured to be printed once (default) and were already
  1715. printed before the context was entered.
  1716. Nesting this context manager will work as expected when the
  1717. forwarding rule is "always" (default). Unfiltered and unrecorded
  1718. warnings will be passed out and be matched by the outer level.
  1719. On the outmost level they will be printed (or caught by another
  1720. warnings context). The forwarding rule argument can modify this
  1721. behaviour.
  1722. Like ``catch_warnings`` this context manager is not threadsafe.
  1723. Examples
  1724. --------
  1725. With a context manager::
  1726. with np.testing.suppress_warnings() as sup:
  1727. sup.filter(DeprecationWarning, "Some text")
  1728. sup.filter(module=np.ma.core)
  1729. log = sup.record(FutureWarning, "Does this occur?")
  1730. command_giving_warnings()
  1731. # The FutureWarning was given once, the filtered warnings were
  1732. # ignored. All other warnings abide outside settings (may be
  1733. # printed/error)
  1734. assert_(len(log) == 1)
  1735. assert_(len(sup.log) == 1) # also stored in log attribute
  1736. Or as a decorator::
  1737. sup = np.testing.suppress_warnings()
  1738. sup.filter(module=np.ma.core) # module must match exactly
  1739. @sup
  1740. def some_function():
  1741. # do something which causes a warning in np.ma.core
  1742. pass
  1743. """
  1744. def __init__(self, forwarding_rule="always"):
  1745. self._entered = False
  1746. # Suppressions are either instance or defined inside one with block:
  1747. self._suppressions = []
  1748. if forwarding_rule not in {"always", "module", "once", "location"}:
  1749. raise ValueError("unsupported forwarding rule.")
  1750. self._forwarding_rule = forwarding_rule
  1751. def _clear_registries(self):
  1752. if hasattr(warnings, "_filters_mutated"):
  1753. # clearing the registry should not be necessary on new pythons,
  1754. # instead the filters should be mutated.
  1755. warnings._filters_mutated()
  1756. return
  1757. # Simply clear the registry, this should normally be harmless,
  1758. # note that on new pythons it would be invalidated anyway.
  1759. for module in self._tmp_modules:
  1760. if hasattr(module, "__warningregistry__"):
  1761. module.__warningregistry__.clear()
  1762. def _filter(self, category=Warning, message="", module=None, record=False):
  1763. if record:
  1764. record = [] # The log where to store warnings
  1765. else:
  1766. record = None
  1767. if self._entered:
  1768. if module is None:
  1769. warnings.filterwarnings(
  1770. "always", category=category, message=message)
  1771. else:
  1772. module_regex = module.__name__.replace('.', r'\.') + '$'
  1773. warnings.filterwarnings(
  1774. "always", category=category, message=message,
  1775. module=module_regex)
  1776. self._tmp_modules.add(module)
  1777. self._clear_registries()
  1778. self._tmp_suppressions.append(
  1779. (category, message, re.compile(message, re.I), module, record))
  1780. else:
  1781. self._suppressions.append(
  1782. (category, message, re.compile(message, re.I), module, record))
  1783. return record
  1784. def filter(self, category=Warning, message="", module=None):
  1785. """
  1786. Add a new suppressing filter or apply it if the state is entered.
  1787. Parameters
  1788. ----------
  1789. category : class, optional
  1790. Warning class to filter
  1791. message : string, optional
  1792. Regular expression matching the warning message.
  1793. module : module, optional
  1794. Module to filter for. Note that the module (and its file)
  1795. must match exactly and cannot be a submodule. This may make
  1796. it unreliable for external modules.
  1797. Notes
  1798. -----
  1799. When added within a context, filters are only added inside
  1800. the context and will be forgotten when the context is exited.
  1801. """
  1802. self._filter(category=category, message=message, module=module,
  1803. record=False)
  1804. def record(self, category=Warning, message="", module=None):
  1805. """
  1806. Append a new recording filter or apply it if the state is entered.
  1807. All warnings matching will be appended to the ``log`` attribute.
  1808. Parameters
  1809. ----------
  1810. category : class, optional
  1811. Warning class to filter
  1812. message : string, optional
  1813. Regular expression matching the warning message.
  1814. module : module, optional
  1815. Module to filter for. Note that the module (and its file)
  1816. must match exactly and cannot be a submodule. This may make
  1817. it unreliable for external modules.
  1818. Returns
  1819. -------
  1820. log : list
  1821. A list which will be filled with all matched warnings.
  1822. Notes
  1823. -----
  1824. When added within a context, filters are only added inside
  1825. the context and will be forgotten when the context is exited.
  1826. """
  1827. return self._filter(category=category, message=message, module=module,
  1828. record=True)
  1829. def __enter__(self):
  1830. if self._entered:
  1831. raise RuntimeError("cannot enter suppress_warnings twice.")
  1832. self._orig_show = warnings.showwarning
  1833. self._filters = warnings.filters
  1834. warnings.filters = self._filters[:]
  1835. self._entered = True
  1836. self._tmp_suppressions = []
  1837. self._tmp_modules = set()
  1838. self._forwarded = set()
  1839. self.log = [] # reset global log (no need to keep same list)
  1840. for cat, mess, _, mod, log in self._suppressions:
  1841. if log is not None:
  1842. del log[:] # clear the log
  1843. if mod is None:
  1844. warnings.filterwarnings(
  1845. "always", category=cat, message=mess)
  1846. else:
  1847. module_regex = mod.__name__.replace('.', r'\.') + '$'
  1848. warnings.filterwarnings(
  1849. "always", category=cat, message=mess,
  1850. module=module_regex)
  1851. self._tmp_modules.add(mod)
  1852. warnings.showwarning = self._showwarning
  1853. self._clear_registries()
  1854. return self
  1855. def __exit__(self, *exc_info):
  1856. warnings.showwarning = self._orig_show
  1857. warnings.filters = self._filters
  1858. self._clear_registries()
  1859. self._entered = False
  1860. del self._orig_show
  1861. del self._filters
  1862. def _showwarning(self, message, category, filename, lineno,
  1863. *args, use_warnmsg=None, **kwargs):
  1864. for cat, _, pattern, mod, rec in (
  1865. self._suppressions + self._tmp_suppressions)[::-1]:
  1866. if (issubclass(category, cat) and
  1867. pattern.match(message.args[0]) is not None):
  1868. if mod is None:
  1869. # Message and category match, either recorded or ignored
  1870. if rec is not None:
  1871. msg = WarningMessage(message, category, filename,
  1872. lineno, **kwargs)
  1873. self.log.append(msg)
  1874. rec.append(msg)
  1875. return
  1876. # Use startswith, because warnings strips the c or o from
  1877. # .pyc/.pyo files.
  1878. elif mod.__file__.startswith(filename):
  1879. # The message and module (filename) match
  1880. if rec is not None:
  1881. msg = WarningMessage(message, category, filename,
  1882. lineno, **kwargs)
  1883. self.log.append(msg)
  1884. rec.append(msg)
  1885. return
  1886. # There is no filter in place, so pass to the outside handler
  1887. # unless we should only pass it once
  1888. if self._forwarding_rule == "always":
  1889. if use_warnmsg is None:
  1890. self._orig_show(message, category, filename, lineno,
  1891. *args, **kwargs)
  1892. else:
  1893. self._orig_showmsg(use_warnmsg)
  1894. return
  1895. if self._forwarding_rule == "once":
  1896. signature = (message.args, category)
  1897. elif self._forwarding_rule == "module":
  1898. signature = (message.args, category, filename)
  1899. elif self._forwarding_rule == "location":
  1900. signature = (message.args, category, filename, lineno)
  1901. if signature in self._forwarded:
  1902. return
  1903. self._forwarded.add(signature)
  1904. if use_warnmsg is None:
  1905. self._orig_show(message, category, filename, lineno, *args,
  1906. **kwargs)
  1907. else:
  1908. self._orig_showmsg(use_warnmsg)
  1909. def __call__(self, func):
  1910. """
  1911. Function decorator to apply certain suppressions to a whole
  1912. function.
  1913. """
  1914. @wraps(func)
  1915. def new_func(*args, **kwargs):
  1916. with self:
  1917. return func(*args, **kwargs)
  1918. return new_func
  1919. @contextlib.contextmanager
  1920. def _assert_no_gc_cycles_context(name=None):
  1921. __tracebackhide__ = True # Hide traceback for py.test
  1922. # not meaningful to test if there is no refcounting
  1923. if not HAS_REFCOUNT:
  1924. yield
  1925. return
  1926. assert_(gc.isenabled())
  1927. gc.disable()
  1928. gc_debug = gc.get_debug()
  1929. try:
  1930. for i in range(100):
  1931. if gc.collect() == 0:
  1932. break
  1933. else:
  1934. raise RuntimeError(
  1935. "Unable to fully collect garbage - perhaps a __del__ method "
  1936. "is creating more reference cycles?")
  1937. gc.set_debug(gc.DEBUG_SAVEALL)
  1938. yield
  1939. # gc.collect returns the number of unreachable objects in cycles that
  1940. # were found -- we are checking that no cycles were created in the context
  1941. n_objects_in_cycles = gc.collect()
  1942. objects_in_cycles = gc.garbage[:]
  1943. finally:
  1944. del gc.garbage[:]
  1945. gc.set_debug(gc_debug)
  1946. gc.enable()
  1947. if n_objects_in_cycles:
  1948. name_str = f' when calling {name}' if name is not None else ''
  1949. raise AssertionError(
  1950. "Reference cycles were found{}: {} objects were collected, "
  1951. "of which {} are shown below:{}"
  1952. .format(
  1953. name_str,
  1954. n_objects_in_cycles,
  1955. len(objects_in_cycles),
  1956. ''.join(
  1957. "\n {} object with id={}:\n {}".format(
  1958. type(o).__name__,
  1959. id(o),
  1960. pprint.pformat(o).replace('\n', '\n ')
  1961. ) for o in objects_in_cycles
  1962. )
  1963. )
  1964. )
  1965. def assert_no_gc_cycles(*args, **kwargs):
  1966. """
  1967. Fail if the given callable produces any reference cycles.
  1968. If called with all arguments omitted, may be used as a context manager:
  1969. with assert_no_gc_cycles():
  1970. do_something()
  1971. .. versionadded:: 1.15.0
  1972. Parameters
  1973. ----------
  1974. func : callable
  1975. The callable to test.
  1976. \\*args : Arguments
  1977. Arguments passed to `func`.
  1978. \\*\\*kwargs : Kwargs
  1979. Keyword arguments passed to `func`.
  1980. Returns
  1981. -------
  1982. Nothing. The result is deliberately discarded to ensure that all cycles
  1983. are found.
  1984. """
  1985. if not args:
  1986. return _assert_no_gc_cycles_context()
  1987. func = args[0]
  1988. args = args[1:]
  1989. with _assert_no_gc_cycles_context(name=func.__name__):
  1990. func(*args, **kwargs)
  1991. def break_cycles():
  1992. """
  1993. Break reference cycles by calling gc.collect
  1994. Objects can call other objects' methods (for instance, another object's
  1995. __del__) inside their own __del__. On PyPy, the interpreter only runs
  1996. between calls to gc.collect, so multiple calls are needed to completely
  1997. release all cycles.
  1998. """
  1999. gc.collect()
  2000. if IS_PYPY:
  2001. # interpreter runs now, to call deleted objects' __del__ methods
  2002. gc.collect()
  2003. # two more, just to make sure
  2004. gc.collect()
  2005. gc.collect()
  2006. def requires_memory(free_bytes):
  2007. """Decorator to skip a test if not enough memory is available"""
  2008. import pytest
  2009. def decorator(func):
  2010. @wraps(func)
  2011. def wrapper(*a, **kw):
  2012. msg = check_free_memory(free_bytes)
  2013. if msg is not None:
  2014. pytest.skip(msg)
  2015. try:
  2016. return func(*a, **kw)
  2017. except MemoryError:
  2018. # Probably ran out of memory regardless: don't regard as failure
  2019. pytest.xfail("MemoryError raised")
  2020. return wrapper
  2021. return decorator
  2022. def check_free_memory(free_bytes):
  2023. """
  2024. Check whether `free_bytes` amount of memory is currently free.
  2025. Returns: None if enough memory available, otherwise error message
  2026. """
  2027. env_var = 'NPY_AVAILABLE_MEM'
  2028. env_value = os.environ.get(env_var)
  2029. if env_value is not None:
  2030. try:
  2031. mem_free = _parse_size(env_value)
  2032. except ValueError as exc:
  2033. raise ValueError(f'Invalid environment variable {env_var}: {exc}')
  2034. msg = (f'{free_bytes/1e9} GB memory required, but environment variable '
  2035. f'NPY_AVAILABLE_MEM={env_value} set')
  2036. else:
  2037. mem_free = _get_mem_available()
  2038. if mem_free is None:
  2039. msg = ("Could not determine available memory; set NPY_AVAILABLE_MEM "
  2040. "environment variable (e.g. NPY_AVAILABLE_MEM=16GB) to run "
  2041. "the test.")
  2042. mem_free = -1
  2043. else:
  2044. msg = f'{free_bytes/1e9} GB memory required, but {mem_free/1e9} GB available'
  2045. return msg if mem_free < free_bytes else None
  2046. def _parse_size(size_str):
  2047. """Convert memory size strings ('12 GB' etc.) to float"""
  2048. suffixes = {'': 1, 'b': 1,
  2049. 'k': 1000, 'm': 1000**2, 'g': 1000**3, 't': 1000**4,
  2050. 'kb': 1000, 'mb': 1000**2, 'gb': 1000**3, 'tb': 1000**4,
  2051. 'kib': 1024, 'mib': 1024**2, 'gib': 1024**3, 'tib': 1024**4}
  2052. size_re = re.compile(r'^\s*(\d+|\d+\.\d+)\s*({0})\s*$'.format(
  2053. '|'.join(suffixes.keys())), re.I)
  2054. m = size_re.match(size_str.lower())
  2055. if not m or m.group(2) not in suffixes:
  2056. raise ValueError(f'value {size_str!r} not a valid size')
  2057. return int(float(m.group(1)) * suffixes[m.group(2)])
  2058. def _get_mem_available():
  2059. """Return available memory in bytes, or None if unknown."""
  2060. try:
  2061. import psutil
  2062. return psutil.virtual_memory().available
  2063. except (ImportError, AttributeError):
  2064. pass
  2065. if sys.platform.startswith('linux'):
  2066. info = {}
  2067. with open('/proc/meminfo', 'r') as f:
  2068. for line in f:
  2069. p = line.split()
  2070. info[p[0].strip(':').lower()] = int(p[1]) * 1024
  2071. if 'memavailable' in info:
  2072. # Linux >= 3.14
  2073. return info['memavailable']
  2074. else:
  2075. return info['memfree'] + info['cached']
  2076. return None
  2077. def _no_tracing(func):
  2078. """
  2079. Decorator to temporarily turn off tracing for the duration of a test.
  2080. Needed in tests that check refcounting, otherwise the tracing itself
  2081. influences the refcounts
  2082. """
  2083. if not hasattr(sys, 'gettrace'):
  2084. return func
  2085. else:
  2086. @wraps(func)
  2087. def wrapper(*args, **kwargs):
  2088. original_trace = sys.gettrace()
  2089. try:
  2090. sys.settrace(None)
  2091. return func(*args, **kwargs)
  2092. finally:
  2093. sys.settrace(original_trace)
  2094. return wrapper