scico.numpy.testing¶
Test support functions.
Functions
|
Assert that works in release mode. |
|
Raises an AssertionError if two objects are not equal up to desired tolerance. |
|
Raises an AssertionError if two items are not equal up to desired precision. |
|
Raises an AssertionError if two items are not equal up to significant digits. |
|
Raises an AssertionError if two objects are not equal up to desired precision. |
|
Compare two arrays relatively to their spacing. |
|
None |
|
Raises an AssertionError if two array_like objects are not equal. |
|
Raises an AssertionError if two array_like objects are not ordered by less than. |
|
Check that all items of arrays differ in at most N Units in the Last Place. |
|
Raises an AssertionError if two objects are not equal. |
|
Fail if the given callable produces any reference cycles. |
|
Fail if the given callable produces any warnings. |
Fail unless an exception of class exception_class is thrown by callable when invoked with arguments args and keyword arguments kwargs. |
|
Fail unless an exception of class exception_class and with message that matches expected_regexp is thrown by callable when invoked with arguments args and keyword arguments kwargs. |
|
|
Test if two strings are equal. |
|
Fail unless the given callable throws the specified warning. |
Break reference cycles by calling gc.collect. |
|
|
None |
|
gh-22982 |
|
Apply a decorator to all methods in a class matching a regular expression. |
|
Return number of jiffies elapsed. |
|
Return elapsed time for executing code in the namespace of the caller. |
|
Return virtual memory size in bytes of the running python. |
|
Test if two objects are equal, and print an error message if test fails. |
|
Runs a function many times in parallel |
|
Run doctests found in the given file. |
|
None |
|
Context manager to provide a temporary test folder. |
|
Context manager for temporary files. |
- scico.numpy.testing.assert_(val, msg='')¶
Assert that works in release mode. Accepts callable msg to allow deferring evaluation until failure.
The Python built-in
assertdoes not work when executing code in optimized mode (the-Oflag) - no byte-code is generated for it.For documentation on usage, refer to the Python documentation.
- scico.numpy.testing.assert_allclose(actual, desired, rtol=1e-07, atol=0, equal_nan=True, err_msg='', verbose=True, *, strict=False)¶
Raises an AssertionError if two objects are not equal up to desired tolerance.
Given two array_like objects, check that their shapes and all elements are equal (but see the Notes for the special handling of a scalar). An exception is raised if the shapes mismatch or any values conflict. In contrast to the standard usage in numpy, NaNs are compared like numbers, no assertion is raised if both objects have NaNs in the same positions.
The test is equivalent to
allclose(actual, desired, rtol, atol), except that it is stricter: it doesn’t broadcast its operands, and has tighter default tolerance values. It compares the difference between actual and desired toatol + rtol * abs(desired).- Parameters:
actual (array_like) – Array obtained.
desired (array_like) – Array desired.
rtol (float, optional) – Relative tolerance.
atol (float, optional) – Absolute tolerance.
equal_nan (bool, optional.) – If True, NaNs will compare equal.
err_msg (str, optional) – The error message to be printed in case of failure.
verbose (bool, optional) – If True, the conflicting values are appended to the error message.
strict (bool, optional) –
If True, raise an
AssertionErrorwhen either the shape or the data type of the arguments does not match. The special handling of scalars mentioned in the Notes section is disabled.Added in version 2.0.0.
- Raises:
AssertionError – If actual and desired are not equal up to specified precision.
Notes
When one of actual and desired is a scalar and the other is array_like, the function performs the comparison as if the scalar were broadcasted to the shape of the array. Note that empty arrays are therefore considered equal to scalars. This behaviour can be disabled by setting
strict==True.Examples
>>> x = [1e-5, 1e-3, 1e-1] >>> y = np.arccos(np.cos(x)) >>> np.testing.assert_allclose(x, y, rtol=1e-5, atol=0)
As mentioned in the Notes section, assert_allclose has special handling for scalars. Here, the test checks that the value of numpy.sin is nearly zero at integer multiples of π.
>>> x = np.arange(3) * np.pi >>> np.testing.assert_allclose(np.sin(x), 0, atol=1e-15)
Use strict to raise an
AssertionErrorwhen comparing an array with one or more dimensions against a scalar.>>> np.testing.assert_allclose(np.sin(x), 0, atol=1e-15, strict=True) Traceback (most recent call last): ... AssertionError: Not equal to tolerance rtol=1e-07, atol=1e-15 (shapes (3,), () mismatch) ACTUAL: array([ 0.000000e+00, 1.224647e-16, -2.449294e-16]) DESIRED: array(0)
The strict parameter also ensures that the array data types match:
>>> y = np.zeros(3, dtype=np.float32) >>> np.testing.assert_allclose(np.sin(x), y, atol=1e-15, strict=True) Traceback (most recent call last): ... AssertionError: Not equal to tolerance rtol=1e-07, atol=1e-15 (dtypes float64, float32 mismatch) ACTUAL: array([ 0.000000e+00, 1.224647e-16, -2.449294e-16]) DESIRED: array([0., 0., 0.], dtype=float32)
- scico.numpy.testing.assert_almost_equal(actual, desired, decimal=7, err_msg='', verbose=True)¶
Raises an AssertionError if two items are not equal up to desired precision.
Note
It is recommended to use one of assert_allclose, assert_array_almost_equal_nulp or assert_array_max_ulp instead of this function for more consistent floating point comparisons.
The test verifies that the elements of actual and desired satisfy:
abs(desired-actual) < float64(1.5 * 10**(-decimal))
That is a looser test than originally documented, but agrees with what the actual implementation in assert_array_almost_equal did up to rounding vagaries. An exception is raised at conflicting values. For ndarrays this delegates to assert_array_almost_equal
- Parameters:
actual (array_like) – The object to check.
desired (array_like) – The expected object.
decimal (int, optional) – Desired precision, default is 7.
err_msg (str, optional) – The error message to be printed in case of failure.
verbose (bool, optional) – If True, the conflicting values are appended to the error message.
- Raises:
AssertionError – If actual and desired are not equal up to specified precision.
See also
assert_allcloseCompare two array_like objects for equality with desired relative and/or absolute precision.
assert_array_almost_equal_nulp,assert_array_max_ulp,assert_equalExamples
>>> from numpy.testing import assert_almost_equal >>> assert_almost_equal(2.3333333333333, 2.33333334) >>> assert_almost_equal(2.3333333333333, 2.33333334, decimal=10) Traceback (most recent call last): ... AssertionError: Arrays are not almost equal to 10 decimals ACTUAL: 2.3333333333333 DESIRED: 2.33333334
>>> assert_almost_equal(np.array([1.0,2.3333333333333]), ... np.array([1.0,2.33333334]), decimal=9) Traceback (most recent call last): ... AssertionError: Arrays are not almost equal to 9 decimals Mismatched elements: 1 / 2 (50%) Mismatch at index: [1]: 2.3333333333333 (ACTUAL), 2.33333334 (DESIRED) Max absolute difference among violations: 6.66669964e-09 Max relative difference among violations: 2.85715698e-09 ACTUAL: array([1. , 2.333333333]) DESIRED: array([1. , 2.33333334])
- scico.numpy.testing.assert_approx_equal(actual, desired, significant=7, err_msg='', verbose=True)¶
Raises an AssertionError if two items are not equal up to significant digits.
Note
It is recommended to use one of assert_allclose, assert_array_almost_equal_nulp or assert_array_max_ulp instead of this function for more consistent floating point comparisons.
Given two numbers, check that they are approximately equal. Approximately equal is defined as the number of significant digits that agree.
- Parameters:
actual (scalar) – The object to check.
desired (scalar) – The expected object.
significant (int, optional) – Desired precision, default is 7.
err_msg (str, optional) – The error message to be printed in case of failure.
verbose (bool, optional) – If True, the conflicting values are appended to the error message.
- Raises:
AssertionError – If actual and desired are not equal up to specified precision.
See also
assert_allcloseCompare two array_like objects for equality with desired relative and/or absolute precision.
assert_array_almost_equal_nulp,assert_array_max_ulp,assert_equalExamples
>>> np.testing.assert_approx_equal(0.12345677777777e-20, 0.1234567e-20) >>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345671e-20, ... significant=8) >>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345672e-20, ... significant=8) Traceback (most recent call last): ... AssertionError: Items are not equal to 8 significant digits: ACTUAL: 1.234567e-21 DESIRED: 1.2345672e-21
the evaluated condition that raises the exception is
>>> abs(0.12345670e-20/1e-21 - 0.12345672e-20/1e-21) >= 10**-(8-1) True
- scico.numpy.testing.assert_array_almost_equal(actual, desired, decimal=6, err_msg='', verbose=True)¶
Raises an AssertionError if two objects are not equal up to desired precision.
Note
It is recommended to use one of assert_allclose, assert_array_almost_equal_nulp or assert_array_max_ulp instead of this function for more consistent floating point comparisons.
The test verifies identical shapes and that the elements of
actualanddesiredsatisfy:abs(desired-actual) < 1.5 * 10**(-decimal)
That is a looser test than originally documented, but agrees with what the actual implementation did up to rounding vagaries. An exception is raised at shape mismatch or conflicting values. In contrast to the standard usage in numpy, NaNs are compared like numbers, no assertion is raised if both objects have NaNs in the same positions.
- Parameters:
actual (array_like) – The actual object to check.
desired (array_like) – The desired, expected object.
decimal (int, optional) – Desired precision, default is 6.
err_msg (str, optional) – The error message to be printed in case of failure.
verbose (bool, optional) – If True, the conflicting values are appended to the error message.
- Raises:
AssertionError – If actual and desired are not equal up to specified precision.
See also
assert_allcloseCompare two array_like objects for equality with desired relative and/or absolute precision.
assert_array_almost_equal_nulp,assert_array_max_ulp,assert_equalExamples
the first assert does not raise an exception
>>> np.testing.assert_array_almost_equal([1.0,2.333,np.nan], ... [1.0,2.333,np.nan])
>>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan], ... [1.0,2.33339,np.nan], decimal=5) Traceback (most recent call last): ... AssertionError: Arrays are not almost equal to 5 decimals Mismatched elements: 1 / 3 (33.3%) Mismatch at index: [1]: 2.33333 (ACTUAL), 2.33339 (DESIRED) Max absolute difference among violations: 6.e-05 Max relative difference among violations: 2.57136612e-05 ACTUAL: array([1. , 2.33333, nan]) DESIRED: array([1. , 2.33339, nan])
>>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan], ... [1.0,2.33333, 5], decimal=5) Traceback (most recent call last): ... AssertionError: Arrays are not almost equal to 5 decimals nan location mismatch: ACTUAL: array([1. , 2.33333, nan]) DESIRED: array([1. , 2.33333, 5. ])
- scico.numpy.testing.assert_array_almost_equal_nulp(x, y, nulp=1)¶
Compare two arrays relatively to their spacing.
This is a relatively robust method to compare two arrays whose amplitude is variable.
- Parameters:
x (array_like) – Input arrays.
y (array_like) – Input arrays.
nulp (int, optional) – The maximum number of unit in the last place for tolerance (see Notes). Default is 1.
- Returns:
None
- Raises:
AssertionError – If the spacing between x and y for one or more elements is larger than nulp.
See also
assert_array_max_ulpCheck that all items of arrays differ in at most N Units in the Last Place.
spacingReturn the distance between x and the nearest adjacent number.
Notes
An assertion is raised if the following condition is not met:
abs(x - y) <= nulp * spacing(maximum(abs(x), abs(y)))
Examples
>>> x = np.array([1., 1e-10, 1e-20]) >>> eps = np.finfo(x.dtype).eps >>> np.testing.assert_array_almost_equal_nulp(x, x*eps/2 + x)
>>> np.testing.assert_array_almost_equal_nulp(x, x*eps + x) Traceback (most recent call last): ... AssertionError: Arrays are not equal to 1 ULP (max is 2)
- scico.numpy.testing.assert_array_compare(comparison, x, y, err_msg='', verbose=True, header='', precision=6, equal_nan=True, equal_inf=True, *, strict=False, names=('ACTUAL', 'DESIRED'))¶
None
- scico.numpy.testing.assert_array_equal(actual, desired, err_msg='', verbose=True, *, strict=False)¶
Raises an AssertionError if two array_like objects are not equal.
Given two array_like objects, check that the shape is equal and all elements of these objects are equal (but see the Notes for the special handling of a scalar). An exception is raised at shape mismatch or conflicting values. In contrast to the standard usage in numpy, NaNs are compared like numbers, no assertion is raised if both objects have NaNs in the same positions.
The usual caution for verifying equality with floating point numbers is advised.
Note
When either actual or desired is already an instance of numpy.ndarray and desired is not a
dict, the behavior ofassert_equal(actual, desired)is identical to the behavior of this function. Otherwise, this function performs np.asanyarray on the inputs before comparison, whereas assert_equal defines special comparison rules for common Python types. For example, only assert_equal can be used to compare nested Python lists. In new code, consider using only assert_equal, explicitly converting either actual or desired to arrays if the behavior of assert_array_equal is desired.- Parameters:
actual (array_like) – The actual object to check.
desired (array_like) – The desired, expected object.
err_msg (str, optional) – The error message to be printed in case of failure.
verbose (bool, optional) – If True, the conflicting values are appended to the error message.
strict (bool, optional) –
If True, raise an AssertionError when either the shape or the data type of the array_like objects does not match. The special handling for scalars mentioned in the Notes section is disabled.
Added in version 1.24.0.
- Raises:
AssertionError – If actual and desired objects are not equal.
See also
assert_allcloseCompare two array_like objects for equality with desired relative and/or absolute precision.
assert_array_almost_equal_nulp,assert_array_max_ulp,assert_equalNotes
When one of actual and desired is a scalar and the other is array_like, the function checks that each element of the array_like is equal to the scalar. Note that empty arrays are therefore considered equal to scalars. This behaviour can be disabled by setting
strict==True.Examples
The first assert does not raise an exception:
>>> np.testing.assert_array_equal([1.0,2.33333,np.nan], ... [np.exp(0),2.33333, np.nan])
Assert fails with numerical imprecision with floats:
>>> np.testing.assert_array_equal([1.0,np.pi,np.nan], ... [1, np.sqrt(np.pi)**2, np.nan]) Traceback (most recent call last): ... AssertionError: Arrays are not equal Mismatched elements: 1 / 3 (33.3%) Mismatch at index: [1]: 3.141592653589793 (ACTUAL), 3.1415926535897927 (DESIRED) Max absolute difference among violations: 4.4408921e-16 Max relative difference among violations: 1.41357986e-16 ACTUAL: array([1. , 3.141593, nan]) DESIRED: array([1. , 3.141593, nan])
Use assert_allclose or one of the nulp (number of floating point values) functions for these cases instead:
>>> np.testing.assert_allclose([1.0,np.pi,np.nan], ... [1, np.sqrt(np.pi)**2, np.nan], ... rtol=1e-10, atol=0)
As mentioned in the Notes section, assert_array_equal has special handling for scalars. Here the test checks that each value in x is 3:
>>> x = np.full((2, 5), fill_value=3) >>> np.testing.assert_array_equal(x, 3)
Use strict to raise an AssertionError when comparing a scalar with an array:
>>> np.testing.assert_array_equal(x, 3, strict=True) Traceback (most recent call last): ... AssertionError: Arrays are not equal (shapes (2, 5), () mismatch) ACTUAL: array([[3, 3, 3, 3, 3], [3, 3, 3, 3, 3]]) DESIRED: array(3)
The strict parameter also ensures that the array data types match:
>>> x = np.array([2, 2, 2]) >>> y = np.array([2., 2., 2.], dtype=np.float32) >>> np.testing.assert_array_equal(x, y, strict=True) Traceback (most recent call last): ... AssertionError: Arrays are not equal (dtypes int64, float32 mismatch) ACTUAL: array([2, 2, 2]) DESIRED: array([2., 2., 2.], dtype=float32)
- scico.numpy.testing.assert_array_less(x, y, err_msg='', verbose=True, *, strict=False)¶
Raises an AssertionError if two array_like objects are not ordered by less than.
Given two array_like objects x and y, check that the shape is equal and all elements of x are strictly less than the corresponding elements of y (but see the Notes for the special handling of a scalar). An exception is raised at shape mismatch or values that are not correctly ordered. In contrast to the standard usage in NumPy, no assertion is raised if both objects have NaNs in the same positions.
- Parameters:
x (array_like) – The smaller object to check.
y (array_like) – The larger object to compare.
err_msg (string) – The error message to be printed in case of failure.
verbose (bool) – If True, the conflicting values are appended to the error message.
strict (bool, optional) –
If True, raise an AssertionError when either the shape or the data type of the array_like objects does not match. The special handling for scalars mentioned in the Notes section is disabled.
Added in version 2.0.0.
- Raises:
AssertionError – If x is not strictly smaller than y, element-wise.
See also
assert_array_equaltests objects for equality
assert_array_almost_equaltest objects for equality up to precision
Notes
When one of x and y is a scalar and the other is array_like, the function performs the comparison as though the scalar were broadcasted to the shape of the array. This behaviour can be disabled with the strict parameter.
Examples
The following assertion passes because each finite element of x is strictly less than the corresponding element of y, and the NaNs are in corresponding locations.
>>> x = [1.0, 1.0, np.nan] >>> y = [1.1, 2.0, np.nan] >>> np.testing.assert_array_less(x, y)
The following assertion fails because the zeroth element of x is no longer strictly less than the zeroth element of y.
>>> y[0] = 1 >>> np.testing.assert_array_less(x, y) Traceback (most recent call last): ... AssertionError: Arrays are not strictly ordered `x < y` Mismatched elements: 1 / 3 (33.3%) Mismatch at index: [0]: 1.0 (x), 1.0 (y) Max absolute difference among violations: 0. Max relative difference among violations: 0. x: array([ 1., 1., nan]) y: array([ 1., 2., nan])
Here, y is a scalar, so each element of x is compared to y, and the assertion passes.
>>> x = [1.0, 4.0] >>> y = 5.0 >>> np.testing.assert_array_less(x, y)
However, with
strict=True, the assertion will fail because the shapes do not match.>>> np.testing.assert_array_less(x, y, strict=True) Traceback (most recent call last): ... AssertionError: Arrays are not strictly ordered `x < y` (shapes (2,), () mismatch) x: array([1., 4.]) y: array(5.)
With
strict=True, the assertion also fails if the dtypes of the two arrays do not match.>>> y = [5, 5] >>> np.testing.assert_array_less(x, y, strict=True) Traceback (most recent call last): ... AssertionError: Arrays are not strictly ordered `x < y` (dtypes float64, int64 mismatch) x: array([1., 4.]) y: array([5, 5])
- scico.numpy.testing.assert_array_max_ulp(a, b, maxulp=1, dtype=None)¶
Check that all items of arrays differ in at most N Units in the Last Place.
- Parameters:
a (array_like) – Input arrays to be compared.
b (array_like) – Input arrays to be compared.
maxulp (int, optional) – The maximum number of units in the last place that elements of a and b can differ. Default is 1.
dtype (dtype, optional) – Data-type to convert a and b to if given. Default is None.
- Returns:
ret (ndarray) – Array containing number of representable floating point numbers between items in a and b.
- Raises:
AssertionError – If one or more elements differ by more than maxulp.
Notes
For computing the ULP difference, this API does not differentiate between various representations of NAN (ULP difference between 0x7fc00000 and 0xffc00000 is zero).
See also
assert_array_almost_equal_nulpCompare two arrays relatively to their spacing.
Examples
>>> a = np.linspace(0., 1., 100) >>> res = np.testing.assert_array_max_ulp(a, np.arcsin(np.sin(a)))
- scico.numpy.testing.assert_equal(actual, desired, err_msg='', verbose=True, *, strict=False)¶
Raises an AssertionError if two objects are not equal.
Given two objects (scalars, lists, tuples, dictionaries or numpy arrays), check that all elements of these objects are equal. An exception is raised at the first conflicting values.
This function handles NaN comparisons as if NaN was a “normal” number. That is, AssertionError is not raised if both objects have NaNs in the same positions. This is in contrast to the IEEE standard on NaNs, which says that NaN compared to anything must return False.
- Parameters:
actual (array_like) – The object to check.
desired (array_like) – The expected object.
err_msg (str, optional) – The error message to be printed in case of failure.
verbose (bool, optional) – If True, the conflicting values are appended to the error message.
strict (bool, optional) –
If True and either of the actual and desired arguments is an array, raise an
AssertionErrorwhen either the shape or the data type of the arguments does not match. If neither argument is an array, this parameter has no effect.Added in version 2.0.0.
- Raises:
AssertionError – If actual and desired are not equal.
Notes
When one of actual and desired is a scalar and the other is array_like, the function checks that each element of the array_like is equal to the scalar. Note that empty arrays are therefore considered equal to scalars. This behaviour can be disabled by setting
strict==True.Examples
>>> np.testing.assert_equal([4, 5], [4, 6]) Traceback (most recent call last): ... AssertionError: Items are not equal: item=1 ACTUAL: 5 DESIRED: 6
The following comparison does not raise an exception. There are NaNs in the inputs, but they are in the same positions.
>>> np.testing.assert_equal(np.array([1.0, 2.0, np.nan]), [1, 2, np.nan])
As mentioned in the Notes section, assert_equal has special handling for scalars when one of the arguments is an array. Here, the test checks that each value in x is 3:
>>> x = np.full((2, 5), fill_value=3) >>> np.testing.assert_equal(x, 3)
Use strict to raise an AssertionError when comparing a scalar with an array of a different shape:
>>> np.testing.assert_equal(x, 3, strict=True) Traceback (most recent call last): ... AssertionError: Arrays are not equal (shapes (2, 5), () mismatch) ACTUAL: array([[3, 3, 3, 3, 3], [3, 3, 3, 3, 3]]) DESIRED: array(3)
The strict parameter also ensures that the array data types match:
>>> x = np.array([2, 2, 2]) >>> y = np.array([2., 2., 2.], dtype=np.float32) >>> np.testing.assert_equal(x, y, strict=True) Traceback (most recent call last): ... AssertionError: Arrays are not equal (dtypes int64, float32 mismatch) ACTUAL: array([2, 2, 2]) DESIRED: array([2., 2., 2.], dtype=float32)
- scico.numpy.testing.assert_no_gc_cycles(*args, **kwargs)¶
Fail if the given callable produces any reference cycles.
If called with all arguments omitted, may be used as a context manager:
with assert_no_gc_cycles(): do_something()
- Parameters:
func (callable) – The callable to test.
*args (Arguments) – Arguments passed to func.
**kwargs (Kwargs) – Keyword arguments passed to func.
- Returns:
Nothing. The result is deliberately discarded to ensure that all cycles
are found.
- scico.numpy.testing.assert_no_warnings(*args, **kwargs)¶
Fail if the given callable produces any warnings.
If called with all arguments omitted, may be used as a context manager:
with assert_no_warnings(): do_something()
The ability to be used as a context manager is new in NumPy v1.11.0.
- Parameters:
func (callable) – The callable to test.
*args (Arguments) – Arguments passed to func.
**kwargs (Kwargs) – Keyword arguments passed to func.
- Returns:
The value returned by func.
- scico.numpy.testing.assert_raises(exception_class, callable, *args, **kwargs)¶
- scico.numpy.testing.assert_raises(exception_class) None
Fail unless an exception of class exception_class is thrown by callable when invoked with arguments args and keyword arguments kwargs. If a different type of exception is thrown, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception.
Alternatively, assert_raises can be used as a context manager:
>>> from numpy.testing import assert_raises >>> with assert_raises(ZeroDivisionError): ... 1 / 0
is equivalent to
>>> def div(x, y): ... return x / y >>> assert_raises(ZeroDivisionError, div, 1, 0)
- scico.numpy.testing.assert_raises_regex(exception_class, expected_regexp, callable, *args, **kwargs)¶
- scico.numpy.testing.assert_raises_regex(exception_class, expected_regexp) None
Fail unless an exception of class exception_class and with message that matches expected_regexp is thrown by callable when invoked with arguments args and keyword arguments kwargs.
Alternatively, can be used as a context manager like assert_raises.
- scico.numpy.testing.assert_string_equal(actual, desired)¶
Test if two strings are equal.
If the given strings are equal, assert_string_equal does nothing. If they are not equal, an AssertionError is raised, and the diff between the strings is shown.
- Parameters:
Examples
>>> np.testing.assert_string_equal('abc', 'abc') >>> np.testing.assert_string_equal('abc', 'abcd') Traceback (most recent call last): File "<stdin>", line 1, in <module> ... AssertionError: Differences in strings: - abc+ abcd? +
- scico.numpy.testing.assert_warns(warning_class, *args, **kwargs)¶
Fail unless the given callable throws the specified warning.
A warning of class warning_class should be thrown by the callable when invoked with arguments args and keyword arguments kwargs. If a different type of warning is thrown, it will not be caught.
If called with all arguments other than the warning class omitted, may be used as a context manager:
with assert_warns(SomeWarning): do_something()
The ability to be used as a context manager is new in NumPy v1.11.0.
Deprecated since version 2.4: This is deprecated. Use warnings.catch_warnings or
pytest.warnsinstead.- Parameters:
warning_class (class) – The class defining the warning that func is expected to throw.
func (callable, optional) – Callable to test
*args (Arguments) – Arguments for func.
**kwargs (Kwargs) – Keyword arguments for func.
- Returns:
The value returned by func.
Examples
>>> import warnings >>> def deprecated_func(num): ... warnings.warn("Please upgrade", DeprecationWarning) ... return num*num >>> with np.testing.assert_warns(DeprecationWarning): ... assert deprecated_func(4) == 16 >>> # or passing a func >>> ret = np.testing.assert_warns(DeprecationWarning, deprecated_func, 4) >>> assert ret == 16
- scico.numpy.testing.break_cycles()¶
Break reference cycles by calling gc.collect.
Objects can call other objects’ methods (for instance, another object’s __del__) inside their own __del__. On PyPy, the interpreter only runs between calls to gc.collect, so multiple calls are needed to completely release all cycles.
- scico.numpy.testing.build_err_msg(arrays, err_msg, header='Items are not equal:', verbose=True, names=('ACTUAL', 'DESIRED'), precision=8)¶
None
- scico.numpy.testing.check_support_sve(__cache=[])¶
gh-22982
- scico.numpy.testing.decorate_methods(cls, decorator, testmatch=None)¶
Apply a decorator to all methods in a class matching a regular expression.
The given decorator is applied to all public methods of cls that are matched by the regular expression testmatch (
testmatch.search(methodname)). Methods that are private, i.e. start with an underscore, are ignored.- Parameters:
cls (class) – Class whose methods to decorate.
decorator (function) – Decorator to apply to methods
testmatch (compiled regexp or str, optional) – The regular expression. Default value is None, in which case the nose default (
re.compile(r'(?:^|[\b_\.%s-])[Tt]est' % os.sep)) is used. If testmatch is a string, it is compiled to a regular expression first.
- scico.numpy.testing.jiffies(_proc_pid_stat=None, _load_time=None)¶
Return number of jiffies elapsed.
Return number of jiffies (1/100ths of a second) that this process has been scheduled in user mode. See man 5 proc.
- scico.numpy.testing.measure(code_str, times=1, label=None)¶
Return elapsed time for executing code in the namespace of the caller.
The supplied code string is compiled with the Python builtin
compile. The precision of the timing is 10 milli-seconds. If the code will execute fast on this timescale, it can be executed many times to get reasonable timing accuracy.- Parameters:
- Returns:
elapsed (float) – Total elapsed time in seconds for executing code_str times times.
Examples
>>> times = 10 >>> etime = np.testing.measure('for i in range(1000): np.sqrt(i**2)', times=times) >>> print("Time for a single execution : ", etime / times, "s") Time for a single execution : 0.005 s
- scico.numpy.testing.memusage(_proc_pid_stat=None)¶
Return virtual memory size in bytes of the running python.
- scico.numpy.testing.print_assert_equal(test_string, actual, desired)¶
Test if two objects are equal, and print an error message if test fails.
The test is performed with
actual == desired.- Parameters:
Examples
>>> np.testing.print_assert_equal('Test XYZ of func xyz', [0, 1], [0, 1]) >>> np.testing.print_assert_equal('Test XYZ of func xyz', [0, 1], [0, 2]) Traceback (most recent call last): ... AssertionError: Test XYZ of func xyz failed ACTUAL: [0, 1] DESIRED: [0, 2]
- scico.numpy.testing.run_threaded(func, max_workers=8, pass_count=False, pass_barrier=False, outer_iterations=1, prepare_args=None)¶
Runs a function many times in parallel
- scico.numpy.testing.rundocs(filename=None, raise_on_error=True)¶
Run doctests found in the given file.
By default rundocs raises an AssertionError on failure.
- Parameters:
Notes
The doctests can be run by the user/developer by adding the
doctestsargument to thetest()call. For example, to run all tests (including doctests) fornumpy.lib:>>> np.lib.test(doctests=True)
- scico.numpy.testing.runstring(astr, dict)¶
None
- scico.numpy.testing.tempdir(*args, **kwargs)¶
Context manager to provide a temporary test folder.
All arguments are passed as this to the underlying tempfile.mkdtemp function.
- scico.numpy.testing.temppath(*args, **kwargs)¶
Context manager for temporary files.
Context manager that returns the path to a closed temporary file. Its parameters are the same as for tempfile.mkstemp and are passed directly to that function. The underlying file is removed when the context is exited, so it should be closed at that time.
Windows does not allow a temporary file to be opened if it is already open, so the underlying file must be closed after opening before it can be opened again.