a :jgj@sdZddlZddlZddlZddlZddlZddlZddlZddlm Z m Z ddl Z ddl Z ddl mZmZddlmZddlmZddlZddlZddlZddlmZmZmZmZmZmZmZmZddlm Z m!Z!m"Z"ddl#Zdd l$m%Z%dd l&m'Z'gd Z(Gd d d e)Z*e*Z+dZ,e-dvZ.ej/j0dkZ1e2edZ3e4eddduoPe3 Z5ej6j7j8Z9ddZ:dZ;eej0dkrdddZ?dd d!Z@n6ejdd"d#krd$eAd%fd&d!Z@nd'd!Z@ejdd"d#krd$eAd%gfd(d)ZBn gfd*d)ZBdd.d/ZCddd0d1d2ZDd3d4ZEeFdd6d7ZGeFdd8d9ZHeFddd,d;dd?gd@dAgdBdCddd0dDdEZJeFe%d>d?gd@dAgdBdCddFdGZKddd0dHdIZLdJdKZMdLdMZNddNdOZOdPdQZPePZQddlRZRGdRdSdSeRjSZTeTdTZUdUdVZVdWdXZWddYdZZXdd\d]ZYd^d_ZZddd0dadbZ[ddcddZ\ddedfZ]ddgdhZ^didjZ_dkdlZ`e jaddmdnZbdodpZce jaddqdrZddsdtZeedudvfdwdxZfGdydzdze)Zge jad{d|Zhe jad}d~ZiGdddejjZkGdddZle jadddZmddZnddZoddZpddZqddZrddZsddZtddZueuZvddZwdS)z* Utility function to facilitate testing. N)partialwraps)mkdtempmkstemp)SkipTest)WarningMessage)intpfloat32emptyarange array_reprndarrayisnatarray)isfiniteisnanisinf)_rename_parameter)StringIO)* assert_equalassert_almost_equalassert_approx_equalassert_array_equalassert_array_lessassert_string_equalassert_array_almost_equal assert_raises build_err_msgdecorate_methodsjiffiesmemusageprint_assert_equalrundocs runstringverbosemeasureassert_assert_array_almost_equal_nulpassert_raises_regexassert_array_max_ulp assert_warnsassert_no_warningsassert_allcloseIgnoreExceptionclear_and_catch_warningsrKnownFailureExceptiontemppathtempdirIS_PYPY HAS_REFCOUNTIS_WASMsuppress_warningsassert_array_compareassert_no_gc_cycles break_cycles HAS_LAPACK64 IS_PYSTON_OLD_PROMOTIONIS_MUSL _SUPPORTS_SVEc@seZdZdZdS)r/z<rIF HOST_GNU_TYPEmuslTcCs6d}|s2z |}Wnty(|}Yn0t|dS)aI Assert that works in release mode. Accepts callable msg to allow deferring evaluation until failure. The Python built-in ``assert`` does not work when executing code in optimized mode (the ``-O`` flag) - no byte-code is generated for it. For documentation on usage, refer to the Python documentation. TN) TypeErrorAssertionError)valmsg__tracebackhide__ZsmsgrCrCrDr&Hs    r&ntc Csddl}|dur|j}||||d||f}|}z^|||} z6|||| |\} } | W|| W||S|| 0W||n ||0dS)Nr) win32pdh PDH_FMT_LONGZMakeCounterPathZ OpenQueryZ AddCounterZCollectQueryDataZGetFormattedCounterValueZ RemoveCounterZ CloseQuery) objectcounterinstanceZinumformatmachinerUpathZhqZhctyperPrCrCrDGetPerformanceAttributes^s&      r^pythoncCsddl}tdd|||jdS)NrProcessz Virtual Bytes)rUr^rV) processNamerYrUrCrCrDr ys r linuxz/proc/z/statcCs^zDt|}|d}Wdn1s.0Yt|dWStyXYdS0dS)zM Return virtual memory size in bytes of the running python.  N)openreadlinesplitint Exception)_proc_pid_statflrCrCrDr s  , cCstdS)zK Return memory usage of running python. [Not implemented] N)NotImplementedErrorrCrCrCrDr scCsddl}|s||zDt|}|d}Wdn1sH0Yt|dWStytd||dYS0dS) 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. rNrd d)timeappendrfrgrhrirj)rk _load_timerrrlrmrCrCrDrs , rcCs2ddl}|s||td||dS)rorNrq)rrrsri)rtrrrCrCrDrsItems are not equal:ZACTUALZDESIREDc Cs$d|g}t|}|rV|ddkrLt|dt|krL|dd|g}n |||rt|D]\}}t|trtt|d} nt } z | |} Wn<t y} z$dt |j d| d } WYd} ~ n d} ~ 00| dd krd| dd } | d 7} |d||d | qdd|S) N rTOrrd) precisionz[repr failed for : ]z...: )strfindlenrs enumerate isinstancer rr reprrjr]r?countjoin splitlines) Zarrayserr_msgheaderr$namesrzrQiaZr_funcrexcrCrCrDrs( "   .rstrictc Csd}t|trt|ts(ttt|tt|t||||D]>\}}||vrbtt|t||||d|d||qFdSt|tt frt|tt frtt|t|||t t|D]&}t||||d|d||qdSddl m }m } m} ddlm} m} m} t||s4t||rFt|||||d St||g||d }z| |pj| |}Wnttfyd }Yn0|r| |r| |}| |}n|}d}| |r| |}| |}n|}d}zt||t||Wntyt|Yn0| || |kr*t|zPt|}t|}t|jjt|jjk}|rx|rx|rpWdSt|WntttfyYn0zt|}t|}|r|rWdSt|}t|}|jjd vs|jjd vrtd |dkr |dkr | || |ks t|Wntttfy<Yn0z||ksRt|WnFttfy}z(d|j dvrt|nWYd}~n d}~00dS)ah 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 ``AssertionError`` when either the shape or the data type of the arguments does not match. If neither argument is an array, this parameter has no effect. .. versionadded:: 2.0.0 Raises ------ AssertionError If actual and desired are not equal. See Also -------- assert_allclose assert_array_almost_equal_nulp, assert_array_max_ulp, Notes ----- By default, when one of `actual` and `desired` is a scalar and the other is an array, the function checks that each element of the array is equal to the scalar. 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) Tzkey=rxNzitem=r)r isscalarsignbit iscomplexobjrealimagrr$FMmz0cannot compare to a scalar with a different typezelementwise == comparison)!rdictrOrr]rritemslisttuplerange numpy._corer rrnumpyrrrrr ValueErrorrNrrHasarraydtypernrcharDeprecationWarning FutureWarningargs)actualdesiredrr$rrRkrr rrrrrrQ usecomplexactualractualidesiredrdesirediZisdesnatZisactnatZ dtypes_matchZisdesnanZisactnanZ array_actualZ array_desirederCrCrDrsc                      rcCs`d}ddl}||ks\t}|||d||||d|||t|dS)a Test if two objects are equal, and print an error message if test fails. The test is performed with ``actual == desired``. Parameters ---------- test_string : str The message supplied to AssertionError. actual : object The object to test for equality against `desired`. desired : object The expected result. 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] TrNz failed ACTUAL: z DESIRED: )pprintrwriterOgetvalue)Z test_stringrrrRrrQrCrCrDr!s     r!c sd}ddlm}ddlm}m}m} z|p4|} WntyNd} Yn0fdd} | r|r|} | } n} d} |r|}| }n}d}z t| |dt| |dWntyt| Yn0t |t t fst |t t frt Szft r2t stsFtrftrZtszt| nkszt| Wd SWnttfyYn0ttd d  krt| d S) aN 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_allclose: Compare two array_like objects for equality with desired relative and/or absolute precision. assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal Examples -------- >>> 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%) 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]) Tr)r rFcsd}tg|dS)N*Arrays are not almost equal to %d decimals)r$r)r)rrdecimalrrr$rCrD_build_err_msg#s z+assert_almost_equal.._build_err_msg)rN?$@)rr rrrrrrrOrrrrrrrnrNabsrHfloat64)rrrrr$rRr rrrrrrrrrrCrrDrsPF          "rc Csd}ddl}tt||f\}}||kr*dS|jdd@d||||}|d|||}Wdn1s|0Yz ||}Wntyd}Yn0z ||} Wntyd} Yn0t ||g|d ||d } z`t |rt |sDt |st |r,t |r"t |s>t | n||ks>t | WdSWnt tfy^Yn0||| |d |d  krt | dS) aa 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_allclose: Compare two array_like objects for equality with desired relative and/or absolute precision. assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal Examples -------- >>> 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 TrNignore)invalidg? gz-Items are not equal to %d significant digits:)rr$r)rmapfloaterrstaterpowerfloorlog10ZeroDivisionErrorrrrrOrNrn) rrZ significantrr$rRrHscaleZ sc_desiredZ sc_actualrQrCrCrDrPsB<6         "r)rrc 2 sJd} ddlm} m} mm}m}m}m}t |}t |}||}}dd}dd}dd }| d ffd d }zv| r|j |j ko|j |j k}n |j d kp|j d kp|j |j k}|s|j |j krd|j d|j d}nd|j d|j d}t ||g|d}t |td}||r||r|rR|||| d d}|rn||||fddddO}||||fddddO}n||r||r|rn|j j|j jkrn|||tdd}n||rn||rn|j }|rn||j krnt|drnt|jto t|j}d}zt|jWntyLd}Yn0|sZ|rn|||| |j jd}|jdkr||||}}|jdkrWdSn |rWdS|||}t|} t|tr|}t|g}!n|}!|!}|dkr|!j|!jtd}"|jdkr|jn|!j}#d|"|#}$d|"|#|$g}%|d d!Vtt(t ||}&t!|j tj"rt ||}'tj#|&|'|&d"|&| }(||(})t$|&d#||kr|%%d$t&|)n|%%d$| |)t|dk}*t'| |*}+||+rt},n.|&|+}-t(||&j }.|.|+}/||-t |/},t$|&d#||krb|%%d%t&|,n|%%d%| |,Wdn1s0YWdn1s0Yt&d&d&)|%7t ||gd}t |WnTt*yDddl+}0|0,}1d'|1d(t ||gd}t*|Yn0dS))NTr) array2stringrinfrallmaxobject_cSs |jjdvS)Nz?bhilqpBHILQPefdgFDGrrxrCrCrDisnumbersz&assert_array_compare..isnumbercSs |jjdvS)NrrrrCrCrDistimesz$assert_array_compare..istimecSs |jjdkS)NTrrrCrCrD isvstringsz'assert_array_compare..isvstringnancsd}||}||}t||kdkrRt||gd|d}t|t|tsf|jdkrpt|St|ts|jdkrt|S|SdS)zHandling nan/inf. Combine results of running func on x and y, checking that they are True at the same locations. Tz %s location mismatch:r$rrrzrN)rHboolrrrOrndim)ryfunchasvalrRZx_idZy_idrQ)rrrrzr$rCrDfunc_assert_same_poss&   z2assert_array_compare..func_assert_same_posrCz (shapes z, z mismatch)z (dtypes rF)rrcs | kSNrCZxyrrCrDrI rJz&assert_array_compare..z+infcs | kSrrCrrrCrDrIrJz-infZNaT na_objectrrrqz&Mismatched elements: {} / {} ({:.3g}%)r)routrz*Max absolute difference among violations: z*Max relative difference among violations: rxzerror during assertion: z )-rrrrrrrrrH asanyarrayshaperrrOrr]rhasattrrrrrNrsizeZ logical_notrZravelsumrrZ contextlibsuppressr issubdtypeZunsignedintegerminimumgetattrrsr~ logical_andZ broadcast_torr traceback format_exc)2Z comparisonrrrr$rrz equal_nan equal_infrrrRrrrrrroxZoyrrrrZcondreasonrQZflaggeddtis_nanZ bool_errorsrPZinvalidsZreducedZ n_mismatchZ n_elementsZpercent_mismatchZremarkserrorZerror2Z reduced_errorZ max_abs_errorZnonzeroZnonzero_and_invalidZ max_rel_errorZnonzero_invalid_errorZ broadcasted_yZnonzero_invalid_yrZefmtrC)rrrrrzr$rDr6s $   '                       D  r6rrrrz2.0.0) dep_versionc Cs d}ttj||||d|ddS)a 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 of ``assert_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. .. versionadded:: 1.24.0 Raises ------ AssertionError If actual and desired objects are not equal. See Also -------- assert_allclose: Compare two array_like objects for equality with desired relative and/or absolute precision. assert_array_almost_equal_nulp, assert_array_max_ulp, assert_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 object is equal to the scalar. This behaviour can be disabled with the `strict` parameter. 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%) 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) TzArrays are not equal)rr$rrN)r6operator__eq__)rrrr$rrRrCrCrDrs | rc s^d}ddlmmddlmddlmfdd}t|||||dd d S) a 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 ``actual`` and ``desired`` satisfy:: 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_allclose: Compare two array_like objects for equality with desired relative and/or absolute precision. assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal Examples -------- 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%) 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. ]) Tr)number result_type)r)anyc szxt|st|rvt|}t|}||ks.comparer)rr$rrzN)rrrZnumpy._core.numerictypesrZnumpy._core.fromnumericrr6)rrrrr$rRrrCrrDrsP   rc Cs$d}ttj||||dd|dd dS)aJ 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. .. versionadded:: 2.0.0 Raises ------ AssertionError If x is not strictly smaller than y, element-wise. See Also -------- assert_array_equal: tests objects for equality assert_array_almost_equal: test 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%) 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]) Tz'Arrays are not strictly ordered `x < y`Frr)rr$rrrrN)r6r__lt__)rrrr$rrRrCrCrDrwsj rcCst||dSr)exec)ZastrrrCrCrDr#sr#c Csd}ddl}t|ts&ttt|t|ts@ttt|||krLdSt|| d| d}g}|rP| d}| drqp| drB|g}| d}| dr| || d}| dstt|| ||r| d} | dr| | n | d| |dd|ddkr6qp||qptt|qp|sZdSd d |} ||krt| dS) a 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 ---------- actual : str The string to test for equality against the expected string. desired : str The expected string. Examples -------- >>> np.testing.assert_string_equal('abc', 'abc') >>> np.testing.assert_string_equal('abc', 'abcd') Traceback (most recent call last): File "", line 1, in ... AssertionError: Differences in strings: - abc+ abcd? + TrNz z- z? z+ zDifferences in strings: rL)difflibrr~rOrr]rZDifferrrpop startswithrsinsertextendrrstrip) rrrRrdiffZ diff_listZd1rmZd2Zd3rQrCrCrDrsP                  rc sddlm}ddl}|dur0td}|jd}tjtj |d}|||}| |}|j dd}g|rfdd } nd} |D]} |j | | d q|jdkr|rtd d dS) aX Run doctests found in the given file. By default `rundocs` raises an AssertionError on failure. Parameters ---------- filename : str The path to the file for which the doctests are run. raise_on_error : bool Whether to raise an AssertionError when a doctest fails. Default is True. Notes ----- The doctests can be run by the user/developer by adding the ``doctests`` argument to the ``test()`` call. For example, to run all tests (including doctests) for ``numpy.lib``: >>> np.lib.test(doctests=True) # doctest: +SKIP r)exec_mod_from_locationNr__file__Frcs |Sr)rs)srQrCrDrIXrJzrundocs..rzSome doctests failed: %srx)Znumpy.distutils.misc_utilr doctestsys _getframe f_globalsosr\splitextbasenameZ DocTestFinderrZ DocTestRunnerrunZfailuresrOr) filenameZraise_on_errorr rrlnamemZtestsrunnerrtestrCrrDr"5s"     r"cCsBddl}d}z|j|ddd}d|jvWSty<YdS0dS)z gh-22982 rNZlscpuT)capture_outputtextZsveF) subprocessrstdoutOSError)rcmdoutputrCrCrDcheck_support_svecs  r#c@seZdZddZdS)_DummycCsdSrrC)selfrCrCrDnopzsz _Dummy.nopN)r?r@rAr&rCrCrCrDr$ysr$r&cOsd}tj|i|S)a assert_raises(exception_class, callable, *args, **kwargs) assert_raises(exception_class) 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) T)_dZ assertRaises)rkwargsrRrCrCrDrsrcOsd}tj||g|Ri|S)a assert_raises_regex(exception_class, expected_regexp, callable, *args, **kwargs) assert_raises_regex(exception_class, expected_regexp) 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`. Notes ----- .. versionadded:: 1.9.0 T)r'assertRaisesRegex)Zexception_classZexpected_regexprr(rRrCrCrDr(sr(c s|durtdtj}n t|}|j}ddlmfdd|D}|D]\}zt|drh|j }n|j }Wnt yYqPYn0| |rP| dsPt||||qPdS) a  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. Nz(?:^|[\\b_\\.%s-])[Tt]estr isfunctioncsg|]}|r|qSrCrC).0_mr*rCrD rJz$decorate_methods..compat_func_name_)recompilersep__dict__inspectr+valuesrr/r?AttributeErrorsearchrsetattr)cls decoratorZ testmatchZcls_attrmethodsfunctionfuncnamerCr*rDrs       rrc Csftd}|j|j}}t|d|dd}d}t}||krT|d7}t|||q6t|}d|S)aG 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 ---------- code_str : str The code to be timed. times : int, optional The number of times the code is executed. Default is 1. The code is only compiled once. label : str, optional A label to identify `code_str` with. This is passed into ``compile`` as the second argument (for run-time error messages). 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") # doctest: +SKIP Time for a single execution : 0.005 s rz Test name: rdrrg{Gz?)rrf_localsrr2rr) Zcode_strtimeslabelframeZlocsZglobscoderelapsedrCrCrDr%s!  r%c CstsdSddl}ddl}|ddd}|}d}|z@t|}tdD]}|||}qNt t||kW| n | 0~dS)zg Check that ufuncs don't mishandle refcount of object `1`. Used in a few regression tests. TrNi'rqr) r3gcrr ZreshapedisablerrFrr&enable) oprFrHbcrrcjdrCrCrD_assert_valid_refcounts   rOHz>c shd}ddlfdd} ||}}dddd} t| ||t||| |d dS) u 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)`` (note that ``allclose`` has different default values). It compares the difference between `actual` and `desired` to ``atol + rtol * abs(desired)``. .. versionadded:: 1.5.0 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 ``AssertionError`` when 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. .. versionadded:: 2.0.0 Raises ------ AssertionError If actual and desired are not equal up to specified precision. See Also -------- assert_array_almost_equal_nulp, assert_array_max_ulp 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. This behaviour can be disabled with the `strict` parameter. 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 ``AssertionError`` when 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) TrNcsjjj||dS)N)rtolatolr)Z_corenumericiscloserrRrrHrQrCrDrsz assert_allclose..comparezNot equal to tolerance rtol=gz, atol=)rr$rrr)rrr6r~) rrrQrRrrr$rrRrrrCrUrDr,*sar,c Csd}ddl}||}||}|||||k||}|||||ks||sh||rvd|d}n$|t||} d|d| dd}t|dS) a Compare two arrays relatively to their spacing. This is a relatively robust method to compare two arrays whose amplitude is variable. Parameters ---------- x, 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_ulp : Check that all items of arrays differ in at most N Units in the Last Place. spacing : Return 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) TrNzArrays are not equal to z ULPz ULP (max is rV)) rrspacingwhererrr nulp_diffrO) rrZnulprRrHaxZayrefrQZmax_nulprCrCrDr's1  r'cCs@d}ddl}t|||}|||ks>> a = np.linspace(0., 1., 100) >>> res = np.testing.assert_array_max_ulp(a, np.arcsin(np.sin(a))) TrNzCArrays are not almost equal up to %g ULP (max difference is %g ULP))rrZrrOr)rrJZmaxulprrRrHretrCrCrDr)s*  r)csddl|r*j||d}j||d}n|}|}||}|s^|rftdj|g|d}j|g|d}j||<j||<|j|jkst d|j|jffdd}t |}t |}||||S)anFor each item in x and y, return the number of representable floating points between them. Parameters ---------- x : array_like first input array y : array_like second input array dtype : dtype, optional Data-type to convert `x` and `y` to if given. Default is None. Returns ------- nulp : array_like number of representable floating point numbers between each item in x and y. Notes ----- For computing the ULP difference, this API does not differentiate between various representations of NAN (ULP difference between 0x7fc00000 and 0xffc00000 is zero). Examples -------- # By definition, epsilon is the smallest number such as 1 + eps != 1, so # there should be exactly one ULP between 1 and 1 + eps >>> nulp_diff(1, 1 + np.finfo(x.dtype).eps) 1.0 rNrz'_nulp not implemented for complex arrayz*Arrays do not have the same shape: %s - %scsj|||d}|SNr)rr)rxryvdtr rHrCrD_diffBsznulp_diff.._diff) rrZ common_typerrnrrrrr integer_repr)rrrtrcr_r`rCrbrDrZ s*       rZcCsB||}|jdks.|||dk||dk<n|dkr>||}|S)Nrr)viewr)rracompr_rCrCrD _integer_reprKs   rhcCs|ddl}|j|jkr(t||j|dS|j|jkrHt||j|dS|j|jkrht||j|dSt d|jdS)zQReturn the signed-magnitude interpretation of the binary representation of x.rNiilzUnsupported dtype ) rrZfloat16rhZint16r Zint32rZint64r)rrHrCrCrDrdZs   rdccsld}tN}||}dVt|dksJ|dur:d|nd}td|Wdn1s^0YdS)NTr when calling rLzNo warning raised)r5recordrrO) warning_classrrRsuprmname_strrCrCrD_assert_warns_contexths  rncOs|s|st|St|dkr4d|vr,tdtd|d}|dd}t||jd||i|WdS1sz0YdS)a, 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. .. versionadded:: 1.4.0 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 rmatchzAassert_warns does not use 'match' kwarg, use pytest.warns insteadz(assert_warns(...) needs at least one argrNr)rnr RuntimeErrorr?)rkrr(rrCrCrDr*ss-  r*ccszd}tjddV}tddVt|dkrX|dur@d|nd}td|d|Wdn1sl0YdS) NTrjalwaysrrirLz Got warningsr})warningscatch_warnings simplefilterrrO)rrRrmrmrCrCrD_assert_no_warnings_contexts  rwcOs\|s tS|d}|dd}t|jd||i|WdS1sN0YdS)a; 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. .. versionadded:: 1.7.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`. rrNrp)rwr?rr(rrCrCrDr+s  r+binaryc #sd}d}tdD]tdtd|D]|dkrtfdd}tfdd }|||d ffV|}|||d ffV|d d |d d |d d d ffV|d d |d d |d d d ffV|d d |d d |d d dffV|d d |d d |d d dffV|dkr.fdd}fdd} tfdd }||| |d ffV|}||| |dffV| }||||dffV|d d |d d | d d |d d d ffV|d d |d d | d d |d d d ffV|d d |d d | d d |d d d ffV|d d |d d | d d |d d dffV|d d |d d | d d |d d dffV|d d |d d | d d |d d dffVq.qd S)a generator producing data with different alignment and offsets to test simd vectorization Parameters ---------- dtype : dtype data type to produce type : string 'unary': create data for unary operations, creates one input and output array 'binary': create data for unary operations, creates two input and output array max_size : integer maximum size of data to produce Returns ------- if type is 'unary' yields one output, one input array and a message containing information on the data if type is 'binary' yields one output array, two input array and a message containing information on the data z,unary offset=(%d, %d), size=%d, dtype=%r, %sz1binary offset=(%d, %d, %d), size=%d, dtype=%r, %sr|rZunarycstddSr^r rCror rCrDrIrJz%_gen_alignment_data..rNz out of placezin placerrTaliasedrycstddSr^r{rCr|rCrDrI rJcstddSr^r{rCr|rCrDrI rJz in place1z in place2)rrr ) rr]max_sizeZufmtZbfmtinprrNZinp1Zinp2rCr|rD_gen_alignment_datasn    $$$&&&rc@seZdZdZdS)r-z/Ignoring this exception due to disabled featureNr>rCrCrCrDr-$sr-c os4t|i|}z|VWt|n t|0dS)zContext manager to provide a temporary test folder. All arguments are passed as this to the underlying tempfile.mkdtemp function. N)rshutilrmtree)rr(ZtmpdirrCrCrDr1)sr1c osBt|i|\}}t|z|VWt|n t|0dS)aContext 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. N)rrcloseremove)rr(fdr\rCrCrDr08s  r0cs>eZdZdZdZd fdd ZfddZfdd ZZS) r.a? Context manager that resets warning registry for catching warnings Warnings can be slippery, because, whenever a warning is triggered, Python adds a ``__warningregistry__`` member to the *calling* module. This makes it impossible to retrigger the warning in this module, whatever you put in the warnings filters. This context manager accepts a sequence of `modules` as a keyword argument to its constructor and: * stores and removes any ``__warningregistry__`` entries in given `modules` on entry; * resets ``__warningregistry__`` to its previous state on exit. This makes it possible to trigger any warning afresh inside the context manager without disturbing the state of warnings outside. For compatibility with Python 3.0, please consider all arguments to be keyword-only. Parameters ---------- record : bool, optional Specifies whether warnings should be captured by a custom implementation of ``warnings.showwarning()`` and be appended to a list returned by the context manager. Otherwise None is returned by the context manager. The objects appended to the list are arguments whose attributes mirror the arguments to ``showwarning()``. modules : sequence, optional Sequence of modules for which to reset warnings registry on entry and restore on exit. To work correctly, all 'ignore' filters should filter by one of these modules. Examples -------- >>> import warnings >>> with np.testing.clear_and_catch_warnings( ... modules=[np._core.fromnumeric]): ... warnings.simplefilter('always') ... warnings.filterwarnings('ignore', module='np._core.fromnumeric') ... # do something that raises a warning but ignore those in ... # np._core.fromnumeric rCFcs*t||j|_i|_tj|ddS)Nrr)setunion class_modulesmodules_warnreg_copiessuper__init__)r%rjr __class__rCrDrzsz!clear_and_catch_warnings.__init__cs<|jD]*}t|dr|j}||j|<|qtSN__warningregistry__)rrrcopyrclearr __enter__)r%modZmod_regrrCrDrs    z"clear_and_catch_warnings.__enter__csLtj||jD]4}t|dr*|j||jvr|j|j|qdSr)r__exit__rrrrrupdate)r%exc_inforrrCrDrs      z!clear_and_catch_warnings.__exit__)FrC) r?r@rArBrrrr __classcell__rCrCrrDr.Ns ) r.c@szeZdZdZdddZddZeddd fd d Zeddfd d ZeddfddZ ddZ ddZ ddddZ ddZ dS)r5a Context manager and decorator doing much the same as ``warnings.catch_warnings``. However, it also provides a filter mechanism to work around https://bugs.python.org/issue4180. This bug causes Python before 3.4 to not reliably show warnings again after they have been ignored once (even within catch_warnings). It means that no "ignore" filter can be used easily, since following tests might need to see the warning. Additionally it allows easier specificity for testing warnings and can be nested. Parameters ---------- forwarding_rule : str, optional One of "always", "once", "module", or "location". Analogous to the usual warnings module filter mode, it is useful to reduce noise mostly on the outmost level. Unsuppressed and unrecorded warnings will be forwarded based on this rule. Defaults to "always". "location" is equivalent to the warnings "default", match by exact location the warning warning originated from. Notes ----- Filters added inside the context manager will be discarded again when leaving it. Upon entering all filters defined outside a context will be applied automatically. When a recording filter is added, matching warnings are stored in the ``log`` attribute as well as in the list returned by ``record``. If filters are added and the ``module`` keyword is given, the warning registry of this module will additionally be cleared when applying it, entering the context, or exiting it. This could cause warnings to appear a second time after leaving the context if they were configured to be printed once (default) and were already printed before the context was entered. Nesting this context manager will work as expected when the forwarding rule is "always" (default). Unfiltered and unrecorded warnings will be passed out and be matched by the outer level. On the outmost level they will be printed (or caught by another warnings context). The forwarding rule argument can modify this behaviour. Like ``catch_warnings`` this context manager is not threadsafe. Examples -------- With a context manager:: with np.testing.suppress_warnings() as sup: sup.filter(DeprecationWarning, "Some text") sup.filter(module=np.ma.core) log = sup.record(FutureWarning, "Does this occur?") command_giving_warnings() # The FutureWarning was given once, the filtered warnings were # ignored. All other warnings abide outside settings (may be # printed/error) assert_(len(log) == 1) assert_(len(sup.log) == 1) # also stored in log attribute Or as a decorator:: sup = np.testing.suppress_warnings() sup.filter(module=np.ma.core) # module must match exactly @sup def some_function(): # do something which causes a warning in np.ma.core pass rscCs&d|_g|_|dvrtd||_dS)NF>rslocationmoduleoncezunsupported forwarding rule.)_entered _suppressionsr_forwarding_rule)r%Zforwarding_rulerCrCrDrs zsuppress_warnings.__init__cCs:ttdrtdS|jD]}t|dr|jqdS)N_filters_mutatedr)rrtr _tmp_modulesrr)r%rrCrCrD_clear_registriess    z#suppress_warnings._clear_registriesrLNFcCs|r g}nd}|jr|dur.tjd||dn8|jddd}tjd|||d|j|||j ||t |t j ||fn |j ||t |t j ||f|S)Nrscategorymessage.\.$rrr)rrtfilterwarningsr?replaceraddr_tmp_suppressionsrsr1r2Ir)r%rrrrj module_regexrCrCrD_filters, zsuppress_warnings._filtercCs|j|||dddS)a Add a new suppressing filter or apply it if the state is entered. Parameters ---------- category : class, optional Warning class to filter message : string, optional Regular expression matching the warning message. module : module, optional Module to filter for. Note that the module (and its file) must match exactly and cannot be a submodule. This may make it unreliable for external modules. Notes ----- When added within a context, filters are only added inside the context and will be forgotten when the context is exited. FrrrrjNrr%rrrrCrCrDfilter s zsuppress_warnings.filtercCs|j|||ddS)ai Append a new recording filter or apply it if the state is entered. All warnings matching will be appended to the ``log`` attribute. Parameters ---------- category : class, optional Warning class to filter message : string, optional Regular expression matching the warning message. module : module, optional Module to filter for. Note that the module (and its file) must match exactly and cannot be a submodule. This may make it unreliable for external modules. Returns ------- log : list A list which will be filled with all matched warnings. Notes ----- When added within a context, filters are only added inside the context and will be forgotten when the context is exited. TrrrrCrCrDrj s zsuppress_warnings.recordcCs|jrtdtj|_tj|_|jddt_d|_g|_t|_ t|_ g|_ |j D]j\}}}}}|durv|dd=|durtj d||dqV|jddd}tj d|||d|j |qV|jt_||S) Nz%cannot enter suppress_warnings twice.Trsrrrrr)rrqrt showwarning _orig_showfilters_filtersrrr _forwardedlogrrr?rr _showwarningr)r%catZmessr0rrrrCrCrDr> s4 zsuppress_warnings.__enter__cGs*|jt_|jt_|d|_|`|`dS)NF)rrtrrrrr)r%rrCrCrDr^ s zsuppress_warnings.__exit__) use_warnmsgcOs|j|jdddD]\}} } } } t||r| |jddur| dur| dur~t||||fi|} |j| | | dS| j |r| durt||||fi|} |j| | | dSq|j dkr|dur|j ||||g|Ri|n | |dS|j dkr(|j|f}n4|j dkrB|j||f}n|j dkr\|j|||f}||j vrldS|j ||dur|j ||||g|Ri|n | |dS)NrTrrsrrr)rr issubclassrorrrrsr rrrZ _orig_showmsgrr)r%rrrlinenorrr(rr0patternrZrecrQ signaturerCrCrDrf s`                zsuppress_warnings._showwarningcstfdd}|S)z_ Function decorator to apply certain suppressions to a whole function. cs6|i|WdS1s(0YdSrrC)rr(rr%rCrDnew_func sz,suppress_warnings.__call__..new_funcr)r%rrrCrrD__call__ szsuppress_warnings.__call__)rs)r?r@rArBrrWarningrrrjrrrrrCrCrCrDr5sI     3r5c csd}tsdVdStttt}zptdD]}tdkr8qVq8tdt tj dVt}tj dd}Wtj dd=t |t n tj dd=t |t 0|r|durd|nd}t d||t|ddd |DdS) NTrqrz]Unable to fully collect garbage - perhaps a __del__ method is creating more reference cycles?rirLzXReference cycles were found{}: {} objects were collected, of which {} are shown below:{}c ss4|],}dt|jt|t|ddVqdS)z {} object with id={}: {}rxz N)rZr]r?idrpformatr)r,r}rCrCrD s z/_assert_no_gc_cycles_context..)r3r&rF isenabledrGZ get_debugrcollectrqZ set_debugZ DEBUG_SAVEALLgarbagerHrOrZrr)rrRZgc_debugrZn_objects_in_cyclesZobjects_in_cyclesrmrCrCrD_assert_no_gc_cycles_context sH          rcOs\|s tS|d}|dd}t|jd||i|Wdn1sN0YdS)a4 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() .. versionadded:: 1.15.0 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. rrNrp)rr?rxrCrCrDr7 s  r7cCs0ttr,ttttdS)a1 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. N)rFrr2rCrCrCrDr8 s r8csddlfdd}|S)z:Decorator to skip a test if not enough memory is availablerNcstfdd}|S)NcsLt}|dur|z|i|WStyFdYn0dS)NzMemoryError raised)check_free_memoryskip MemoryErrorZxfail)rkwrQ) free_bytesrpytestrCrDwrapper s  z3requires_memory..decorator..wrapperrrrrrrrDr; s z"requires_memory..decorator)r)rr;rCrrDrequires_memory src Csd}tj|}|durtz t|}Wn8ty\}z td|d|WYd}~n d}~00|dd|d}n0t}|durd}d }n|dd |dd }||kr|SdS) z Check whether `free_bytes` amount of memory is currently free. Returns: None if enough memory available, otherwise error message ZNPY_AVAILABLE_MEMNzInvalid environment variable r}geAz@ GB memory required, but environment variable NPY_AVAILABLE_MEM=z setzCould not determine available memory; set NPY_AVAILABLE_MEM environment variable (e.g. NPY_AVAILABLE_MEM=16GB) to run the test.rTz GB memory required, but z GB available)renvironget _parse_sizer_get_mem_available)renv_varZ env_valueZmem_freerrQrCrCrDr% s   *  rcCsdddddddddddddd d }td d |tj}||}|r`|d |vrpt d|dt t |d||d S)z3Convert memory size strings ('12 GB' etc.) to floatrii@Biʚ;lJ)ii@l)rLrJrrrVrekbmbgbtbZkibZmibZgibZtibz^\s*(\d+|\d+\.\d+)\s*({0})\s*$|rzvalue z not a valid size) r1r2rZrkeysrrolowergrouprrir)size_strsuffixesZsize_rerrCrCrDrB s rc Cszddl}|jWSttfy*Yn0tjdri}tdD}|D].}| }t |dd||d d <qJWdn1s0Yd|vr|dS|d |d SdS) z5Return available memory in bytes, or None if unknown.rNrcz /proc/meminforr:Z memavailableZmemfreecached) psutilZvirtual_memory available ImportErrorr7rplatformrrfrhristripr)rinforllineprCrCrDrR s   Brcs*ttdsStfdd}|SdS)z Decorator to temporarily turn off tracing for the duration of a test. Needed in tests that check refcounting, otherwise the tracing itself influences the refcounts gettracec s>t}z$td|i|Wt|St|0dSr)rrsettrace)rr(Zoriginal_tracerrCrDrs s  z_no_tracing..wrapperN)rrrrrCrrD _no_tracingj s  rcCs4ztddd}Wnty.d}Yn0|S)NCS_GNU_LIBC_VERSIONrdr0.0)rconfstrrsplitrj)verrCrCrD_get_glibc_version~ s   rcCstdkot|kS)Nr) _glibcverrrCrCrDrI rJ)rL)NrTNN)r_r)ruTrvrw)rLT)rrLT)rrLT)rLTrLrTT)rLT)rrLT)rLT)NT)N)rN)rPrTrLT)r)rN)N)N)N)N)xrBrrrr1rFrrt functoolsrrrrtempfilerrZ unittest.caserrr sysconfigrrHrrr r r r r rrrrrZnumpy.linalg._umath_linalgZ numpy._utilsrior__all__rjr/ZKnownFailureTestr$r[r4implementationrr2rr:rr3ZlinalgZ _umath_linalgZ_ilp64r9r;r<get_config_var_vr&r^r getpidrrrr!Z_no_nep50_warningrrr6rrrr#rr"r#r=ZunittestZTestCaser$r'rr(rr%rOr,r'r)rZrhrdcontextmanagerrnr*rwr+rr-r1r0rur.r5rr7r8rrrrrrrZ_glibc_older_thanrCrCrCrDs  (              S) ~ dKssG . / . o ? 4 ? = $E  B 3#