Path: blob/master/ invest-robot-contest_TinkoffBotTwitch-main/venv/lib/python3.8/site-packages/numpy/ma/testutils.py
7757 views
"""Miscellaneous functions for testing masked arrays and subclasses12:author: Pierre Gerard-Marchant3:contact: pierregm_at_uga_dot_edu4:version: $Id: testutils.py 3529 2007-11-13 08:01:14Z jarrod.millman $56"""7import operator89import numpy as np10from numpy import ndarray, float_11import numpy.core.umath as umath12import numpy.testing13from numpy.testing import (14assert_, assert_allclose, assert_array_almost_equal_nulp,15assert_raises, build_err_msg16)17from .core import mask_or, getmask, masked_array, nomask, masked, filled1819__all__masked = [20'almost', 'approx', 'assert_almost_equal', 'assert_array_almost_equal',21'assert_array_approx_equal', 'assert_array_compare',22'assert_array_equal', 'assert_array_less', 'assert_close',23'assert_equal', 'assert_equal_records', 'assert_mask_equal',24'assert_not_equal', 'fail_if_array_equal',25]2627# Include some normal test functions to avoid breaking other projects who28# have mistakenly included them from this file. SciPy is one. That is29# unfortunate, as some of these functions are not intended to work with30# masked arrays. But there was no way to tell before.31from unittest import TestCase32__some__from_testing = [33'TestCase', 'assert_', 'assert_allclose', 'assert_array_almost_equal_nulp',34'assert_raises'35]3637__all__ = __all__masked + __some__from_testing383940def approx(a, b, fill_value=True, rtol=1e-5, atol=1e-8):41"""42Returns true if all components of a and b are equal to given tolerances.4344If fill_value is True, masked values considered equal. Otherwise,45masked values are considered unequal. The relative error rtol should46be positive and << 1.0 The absolute error atol comes into play for47those elements of b that are very small or zero; it says how small a48must be also.4950"""51m = mask_or(getmask(a), getmask(b))52d1 = filled(a)53d2 = filled(b)54if d1.dtype.char == "O" or d2.dtype.char == "O":55return np.equal(d1, d2).ravel()56x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)57y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)58d = np.less_equal(umath.absolute(x - y), atol + rtol * umath.absolute(y))59return d.ravel()606162def almost(a, b, decimal=6, fill_value=True):63"""64Returns True if a and b are equal up to decimal places.6566If fill_value is True, masked values considered equal. Otherwise,67masked values are considered unequal.6869"""70m = mask_or(getmask(a), getmask(b))71d1 = filled(a)72d2 = filled(b)73if d1.dtype.char == "O" or d2.dtype.char == "O":74return np.equal(d1, d2).ravel()75x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)76y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)77d = np.around(np.abs(x - y), decimal) <= 10.0 ** (-decimal)78return d.ravel()798081def _assert_equal_on_sequences(actual, desired, err_msg=''):82"""83Asserts the equality of two non-array sequences.8485"""86assert_equal(len(actual), len(desired), err_msg)87for k in range(len(desired)):88assert_equal(actual[k], desired[k], f'item={k!r}\n{err_msg}')89return909192def assert_equal_records(a, b):93"""94Asserts that two records are equal.9596Pretty crude for now.9798"""99assert_equal(a.dtype, b.dtype)100for f in a.dtype.names:101(af, bf) = (operator.getitem(a, f), operator.getitem(b, f))102if not (af is masked) and not (bf is masked):103assert_equal(operator.getitem(a, f), operator.getitem(b, f))104return105106107def assert_equal(actual, desired, err_msg=''):108"""109Asserts that two items are equal.110111"""112# Case #1: dictionary .....113if isinstance(desired, dict):114if not isinstance(actual, dict):115raise AssertionError(repr(type(actual)))116assert_equal(len(actual), len(desired), err_msg)117for k, i in desired.items():118if k not in actual:119raise AssertionError(f"{k} not in {actual}")120assert_equal(actual[k], desired[k], f'key={k!r}\n{err_msg}')121return122# Case #2: lists .....123if isinstance(desired, (list, tuple)) and isinstance(actual, (list, tuple)):124return _assert_equal_on_sequences(actual, desired, err_msg='')125if not (isinstance(actual, ndarray) or isinstance(desired, ndarray)):126msg = build_err_msg([actual, desired], err_msg,)127if not desired == actual:128raise AssertionError(msg)129return130# Case #4. arrays or equivalent131if ((actual is masked) and not (desired is masked)) or \132((desired is masked) and not (actual is masked)):133msg = build_err_msg([actual, desired],134err_msg, header='', names=('x', 'y'))135raise ValueError(msg)136actual = np.asanyarray(actual)137desired = np.asanyarray(desired)138(actual_dtype, desired_dtype) = (actual.dtype, desired.dtype)139if actual_dtype.char == "S" and desired_dtype.char == "S":140return _assert_equal_on_sequences(actual.tolist(),141desired.tolist(),142err_msg='')143return assert_array_equal(actual, desired, err_msg)144145146def fail_if_equal(actual, desired, err_msg='',):147"""148Raises an assertion error if two items are equal.149150"""151if isinstance(desired, dict):152if not isinstance(actual, dict):153raise AssertionError(repr(type(actual)))154fail_if_equal(len(actual), len(desired), err_msg)155for k, i in desired.items():156if k not in actual:157raise AssertionError(repr(k))158fail_if_equal(actual[k], desired[k], f'key={k!r}\n{err_msg}')159return160if isinstance(desired, (list, tuple)) and isinstance(actual, (list, tuple)):161fail_if_equal(len(actual), len(desired), err_msg)162for k in range(len(desired)):163fail_if_equal(actual[k], desired[k], f'item={k!r}\n{err_msg}')164return165if isinstance(actual, np.ndarray) or isinstance(desired, np.ndarray):166return fail_if_array_equal(actual, desired, err_msg)167msg = build_err_msg([actual, desired], err_msg)168if not desired != actual:169raise AssertionError(msg)170171172assert_not_equal = fail_if_equal173174175def assert_almost_equal(actual, desired, decimal=7, err_msg='', verbose=True):176"""177Asserts that two items are almost equal.178179The test is equivalent to abs(desired-actual) < 0.5 * 10**(-decimal).180181"""182if isinstance(actual, np.ndarray) or isinstance(desired, np.ndarray):183return assert_array_almost_equal(actual, desired, decimal=decimal,184err_msg=err_msg, verbose=verbose)185msg = build_err_msg([actual, desired],186err_msg=err_msg, verbose=verbose)187if not round(abs(desired - actual), decimal) == 0:188raise AssertionError(msg)189190191assert_close = assert_almost_equal192193194def assert_array_compare(comparison, x, y, err_msg='', verbose=True, header='',195fill_value=True):196"""197Asserts that comparison between two masked arrays is satisfied.198199The comparison is elementwise.200201"""202# Allocate a common mask and refill203m = mask_or(getmask(x), getmask(y))204x = masked_array(x, copy=False, mask=m, keep_mask=False, subok=False)205y = masked_array(y, copy=False, mask=m, keep_mask=False, subok=False)206if ((x is masked) and not (y is masked)) or \207((y is masked) and not (x is masked)):208msg = build_err_msg([x, y], err_msg=err_msg, verbose=verbose,209header=header, names=('x', 'y'))210raise ValueError(msg)211# OK, now run the basic tests on filled versions212return np.testing.assert_array_compare(comparison,213x.filled(fill_value),214y.filled(fill_value),215err_msg=err_msg,216verbose=verbose, header=header)217218219def assert_array_equal(x, y, err_msg='', verbose=True):220"""221Checks the elementwise equality of two masked arrays.222223"""224assert_array_compare(operator.__eq__, x, y,225err_msg=err_msg, verbose=verbose,226header='Arrays are not equal')227228229def fail_if_array_equal(x, y, err_msg='', verbose=True):230"""231Raises an assertion error if two masked arrays are not equal elementwise.232233"""234def compare(x, y):235return (not np.alltrue(approx(x, y)))236assert_array_compare(compare, x, y, err_msg=err_msg, verbose=verbose,237header='Arrays are not equal')238239240def assert_array_approx_equal(x, y, decimal=6, err_msg='', verbose=True):241"""242Checks the equality of two masked arrays, up to given number odecimals.243244The equality is checked elementwise.245246"""247def compare(x, y):248"Returns the result of the loose comparison between x and y)."249return approx(x, y, rtol=10. ** -decimal)250assert_array_compare(compare, x, y, err_msg=err_msg, verbose=verbose,251header='Arrays are not almost equal')252253254def assert_array_almost_equal(x, y, decimal=6, err_msg='', verbose=True):255"""256Checks the equality of two masked arrays, up to given number odecimals.257258The equality is checked elementwise.259260"""261def compare(x, y):262"Returns the result of the loose comparison between x and y)."263return almost(x, y, decimal)264assert_array_compare(compare, x, y, err_msg=err_msg, verbose=verbose,265header='Arrays are not almost equal')266267268def assert_array_less(x, y, err_msg='', verbose=True):269"""270Checks that x is smaller than y elementwise.271272"""273assert_array_compare(operator.__lt__, x, y,274err_msg=err_msg, verbose=verbose,275header='Arrays are not less-ordered')276277278def assert_mask_equal(m1, m2, err_msg=''):279"""280Asserts the equality of two masks.281282"""283if m1 is nomask:284assert_(m2 is nomask)285if m2 is nomask:286assert_(m1 is nomask)287assert_array_equal(m1, m2, err_msg=err_msg)288289290