K i ubdZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlZddlmZmZddlmZddlmZmZddlmZddlmZddlZddlZddlm Z m!Z!m"Z"dd l#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+gd Z,Gd d e-Z.e.Z/dZ0e jbejdjfZ4 ejjjmd Z7dZ8 ejrdk\r!e7jtjvjxZ=nFddl>Z>ddl?Z?e>je7jdxsddZ:e:jvjxZ=e=se7jd e4k7rdZ8 e jdvZFejjdk(ZIeJedZKeLeddduxreK ZMejjjdZQejjjZUdZVejdxsdZXdeXvrdZVeYejdZZejejRjdk(Z]d`dZ^ejdk(r dad Z_dbd!Z`nejdd"d#k(rdcd$Z`nd%Z`ejdd"d#k(rddd&Zangfd'Za ded)Zbdfdd*d+Zcd,Zddgd-Ze dgd.Zf dhdd(d/d0Zgdfdd*d1Zh did2Zidfdd*d3Zjd4Zkd5Zldjd6Zmgfd7ZnddloZoGd8d9eojZqeqd:Zrd;Zsd<Ztdcd=Zudkd>Zvd?Zw dldd*d@ZxdmdAZydkdBZzdcdCZ{dDZ|dEZ}ejdcdFZdGZejdcdHZdIZe(dJdKfdLZGdMdNe-ZejdOZejdPZGdQdRejZGdSdTZejdcdUZdVZdWZdXZdYZdZZd[Zd\Zd]ZeZd^Z dnd_Zy#eB$rdZ=YwxYw#ejjj$rdxZ8Z=YwxYw)oz* Utility function to facilitate testing. N)partialwraps)StringIO)mkdtempmkstemp)SkipTest)WarningMessage)isfiniteisinfisnan)arangearray array_repremptyfloat32intpisnatndarray)0 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_PYSTONIS_MUSLcheck_support_sve NOGIL_BUILD IS_EDITABLE IS_INSTALLED NUMPY_ROOT run_threadedIS_64BITBLAS_SUPPORTS_FPEceZdZdZy)r/zrTJs)>)>)F)FrK) object_hookF)wasm32wasm64pypypyston_version_info getrefcount HOST_GNU_TYPEmuslPy_GIL_DISABLEDchd}|s |}t|y#t$r|}Yt|wxYw)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__smsgs rLr&r&msL  5DT""  DT"" s  11ntcddl}| |j}|j|||d||f}|j} |j ||} |j ||j | |\} } | |j| |j|S#|j| wxYw#|j|wxYw)Nr) win32pdh PDH_FMT_LONGMakeCounterPath OpenQuery AddCounterCollectQueryDataGetFormattedCounterValue RemoveCounter CloseQuery) objectcounterinstanceinumformatmachineripathhqhctypercs rLGetPerformanceAttributesr|s  >**F''&(D)-w)89    ! $$$R.B +))"-$==b&I c&&r*    #&&r*    #s#B.'B5B.B++B..Cc>ddl}tdd|||jdS)NrProcessz Virtual Bytes)rir|rj) processNamertris rLr r s(' ?(3X(0(=(=tE ErKlinuxc|xsdtjd} t|5}|jj d}dddt dS#1swYxYw#t $rYywxYw)zM Return virtual memory size in bytes of the running python. /proc//stat N)osgetpidopenreadlinesplitint Exception)_proc_pid_statfls rLr r sx (FVBIIK=+F n% ,JJL&&s+ ,qu:  , ,   s( A+ A A+A($A++ A76A7ct)zK Return memory usage of running python. [Not implemented] )NotImplementedErrorrJrKrLr r s "!rKc|xsdtjd}|xsg}ddl}|s|j|j t |5}|j j d}dddtdS#1swYxYw#t$r%td|j|dz zcYSwxYw) 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. rrrNrrOd) rrtimeappendrrrrr)r _load_timerrrs rLrrs(FVBIIK=+F%2    diik * <n% ,JJL&&s+ ,qu:  , , <sdiikJqM9:; ; : ]rNz...: )strfindlenr enumerate isinstancerrrreprrr{rFcountjoin splitlines) arrayserr_msgheaderr$namesrrdiar_funcrexcs rLrrs: &=/C'lG <<  #G rCK7G(Gq6C<')*C JJw f% ,DAq!W% yA E1Iwwt}q IIallnRa01U  JJ58*Bqc* + , 99S>  E(a)9)9(:#cU!D EsD  D;D66D;strictc d}t|trt|tsttt |t t |t ||||jD]7\}}||vrtt|t ||||d|d||9yt|ttfrjt|ttfrTt t |t |||tt |D]}t ||||d|d||yddl m }m } m} ddlm} m} m} t|| s t|| rt'||||| St)||g|| } | |xs| |}|rS| |r| |}||}n|}d}| |r| |}||}n|}d} t ||t ||| || |k7r t| t/|}t/|}t1j2|j4jt1j2|j4jk(}|r|r|ryt| t9|}t9|}|r|ryt1j2|}t1j2|}|j4j:d vs|j4j:d vr t7d |dk(r!|dk(r| || |k(s t| ||k(s t|y#t*t,f$rd }YwxYw#t$r t|wxYw#t,t*t6f$rYwxYw#t,t*t6f$rYrwxYw#t<t>f$r"}d|j@dvr t|d}~wwxYw)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=rNzitem=rimag iscomplexobjreal)isscalarrsignbitrr$FMmz0cannot compare to a scalar with a different typezelementwise == comparison)!rdictrbrr{rritemslisttuplerangerMrrr numpy._corerrrrr ValueErrorrarnpasarraydtyperr charDeprecationWarning FutureWarningargs)actualdesiredrr$rrekrrrrrrrrd usecomplexactualractualidesiredrdesirediisdesnatisactnat dtypes_matchisdesnanisactnan array_actual array_desiredes rLrrsF'4 &$' d6l!34 4S[#g,AMMO "DAq$T!W-- GAJ$qe2gY0G  " " 'D%=)j$.OS[#g,As7|$ "A GAJ%uBwi0H  " " ..66&'"j'&B!&'7G)/1 1 )7G DC !&)B\'-B   6lG6lGGG  G}HG}HHH & ( + ( + HV,,S!! >= 7+1166 6*00556 $S))  >=  zz&)  7+    # #t +##((D0 &'>? ? a>> 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: )pprintrwriterbgetvalue) test_stringrrrerrds rLr!r!sw8 g j + '( fc" -  gs#S\\^,, rKchd}ddlm}m}m}ddlm}  |xs|} fd} | rW|r|} |} n} d} |r|}|}n}d} t| |t| |t| ttfst| ttfrtS tr tsSts tr'tr tst| yk(st| y t#z t%j&d d  zzk\rt| y#t $rd} YSwxYw#t$rt| wxYw#tt f$rY|wxYw) 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]) Trr)rFc0dz}tg|S)N*Arrays are not almost equal to %d decimals)r$r)r)rrdecimalrrr$s rL_build_err_msgz+assert_almost_equal.._build_err_msgKs(>Hfg.$*, ,rK)rN?$@)rMrrrrrrrrbrrrrr r rraabsrfloat64)rrrrr$rerrrrrrrrrrs````` rLrrsJ..# !&)B\'-B ,,   6lG6lGGG  G}HG}HHH 3 7 C 7 C&7E401'GUD#9:('7KK  !hv&6W~vg5=()9:: &$^%566  '7 7V  31A+A BB^-..CW  0 3 !12 2 3"  +   s6E01F AFF0 E?>E?FF10F1c ,d}ddl}tt||f\}}||k(ry|jd5d|j||j|zz}|j d|j |j|}ddd |z } |z } t||g|d |z| } t|r t|sIt|s t|r"t|r t|s t| y||k(s t| y |j|| z |j d |d z k\r t| y#1swYxYw#t$rd}YwxYw#t$rd} YwxYw#ttf$rYxwxYw) 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)rMmapfloaterrstaterpowerfloorlog10ZeroDivisionErrorrr r rbrar) rr significantrr$rerscale sc_desired sc_actualrds rLrrwsvEFG#45VW& X &8vrvvg78XRXXhbhhuo678u_ UN   7>L C  !hv&6W~vg5=(-- &$S))  '7rvvj9$%#q7I)JJS!!K988    " * +   sIAEE E0:A FFE E-,E-0 E>=E>FF)rrc    2d} ddlm} m} m}m2m}m}m}tj|}tj|}||}}d}d}d}|df fd } | r5|j|jk(xr|j|jk(}n;|jd k(xs|jd k(xs|j|jk(}|su|j|jk7rd |jd |jd }nd |jd |jd }t||g|z }t|tjd}||r?||r7|r ||||d}|r&||||2fddz}||||2fddz}n||rH||r@|r|jj|jjk(r|||t d}n||r||r|j}|r||jk(rt#|drwt%|j&t(xrtj |j&}d} t|j&|s|r |||||jj&}|j,dkDr||||}}|j.dk(ry|ry|||}tj0|} t%|tr|}t3|g}!n |j5}!|!j}|dk7rT|!j.|!j7t8z }"|j,dk7r |j.n |!j.}#d|"z|#z }$d|"d|#d|$ddg}%|d 5t;j<t*5t?||z }&tj@|jtjBr&t?||z }'tjD|&|'|&!|&| }(||(})tG|&d"||k(r|%jId#tK|)zn|%jId#| |)ztj|dk7}*tjL| |*}+| |+r t32},n>|&|+}-tjN||&j}.|.|+}/||-t?|/z },tG|&d"||k(r|%jId$tK|,zn|%jId$| |,zddddddtKd%d%jQ|%zz t||g }t|y#t*$rd}YwxYw#1swYdxYw#1swYhxYw#tR$r;ddl*}0|0jW}1d&|1d't||g }tS|wxYw)(NTr)all array2stringrinfr maxobject_c2|jjdvS)Nz?bhilqpBHILQPefdgFDGrrxs rLisnumberz&assert_array_compare..isnumbersww||555rKc2|jjdvS)Nrrrs rListimez$assert_array_compare..istimesww||t##rKc4|jjdk(S)NTrrs rL isvstringz'assert_array_compare..isvstringsww||s""rKnancd}||}||}tj||k(jdk7r$t||gd|zz }t |t |ts|j dk(rtj|St |ts|j dk(rtj|S|S)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$rrrr)rboolrrrbrndim) ryfunchasvalrex_idy_idrdrrrrr$s rLfunc_assert_same_posz2assert_array_compare..func_assert_same_poss!AwAw 7744< $ $ &$ .A3$+F# %C !% % dD !TYY!^774= d #tyyA~774= KrKrJz (shapes z, z mismatch)z (dtypes rF)rrc|k(SNrJxyrs rLrTz&assert_array_compare../ sd rKz+infc| k(SrrJrs rLrTz&assert_array_compare..2rrKz-infNaT na_objectrrrzMismatched elements: z / z (z.3gz%)r)routrz*Max absolute difference among violations: z*Max relative difference among violations: rzerror during assertion: z ),rrrrrr rrr asanyarrayshaperrrbrr{rhasattrrrrrarsize logical_notrravelsumr contextlibsuppressr issubdtypeunsignedintegerminimumgetattrrr logical_and broadcast_torr traceback format_exc)3 comparisonrrrr$rr equal_nan equal_infrrrerrrr rroxoyrr r rcondreasonrdflaggeddtis_nan bool_errorsrcinvalidsreduced n_mismatch n_elementspercent_mismatchremarkserrorerror2 reduced_error max_abs_errornonzerononzero_and_invalid max_rel_errornonzero_invalid_error broadcasted_ynonzero_invalid_yr2efmtrs3 ```` ` @rLr6r6sQQQ aA aAB6$#).e%%NI 77agg%>#& c4 DSElGiikG;;=D 4<  $ (??J)0): J"Z/*< .zl#j\J+C045Gh') ;((3';AJE}}QWWb.@.@A!$QU 5&e<$)(OM$' $6Mugw77BH!-012 H*=9:;!gga1foG*,..7*K'//0(-c 056I0J-(*5;;(G ,9:M,N)(+,A.12C.D-E)F ugw77BH!-012 H*=9:;K';) ;T'lG tdii00 0GR'(/&+*35C!% %o =!$"#K$N';';) ;) ;b ##%.tfDAQFGWV"'9>osrH V4+V AV4V4C V4V(8FV9V(AV4 VV4VV4V% !V((V1-V44AW8c Hd}ttj||||d|y)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$rres rLrrs(v&'7!(1G &(rKc v d}ddlm m ddlmddlm fd}t|||||dzy ) 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)any)r,c t|st|r]t|}t|}||k(jsy|j|jcxk(rdk(rnn||k(S||}||} |d}t j ||}t||z }|j s|jt j}|dd zzkS#ttf$rY|wxYw)NFrg?rr) r rr&rarrr#rrastyper) rrxinfidyinfidrzrr,npanyrTrUs rLcomparez*assert_array_almost_equal..comparevs U1X%a/qq&(--/ 66QVV(q(6MvgJvgJ Ar" MM!U # AJ!''6*$A3))))./   sA C-&C-6 C--C?>C?r)rr$rrN)rrTrUnumpy._core.fromnumericrVnumpy._core.numerictypesr,r6) rrrrr$rer]r,r\rTrUs ` @@@@rLrr#s?\/43**4&'7!(AGK rKc Ld}ttj||||dd|d y)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`F)rr)rr$rr6rrN)r6rQ__lt__)rrrr$rres rLrrs.T!Q!( I#( &) +rKct||yr)exec)astrrs rLr#r# s trKc,d}ddl}t|tstt t |t|tstt t |||k(ryt |jj|jd|jd}g}|r-|jd}|jdr&|jdr|g}|jd}|jdr"|j||jd}|jdstt ||j||rF|jd} | jdr|j| n|jd| |dd|ddk(r |j|tt ||syd d j|j!} ||k7r t| y) 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: r\)difflibrrrbrr{rDifferr]rpop startswithrinsertextendrrstrip) rrrergdiff diff_listd1rd2d3rds rLrr s6 fc "T$v,/00 gs #T$w-011&  (():):4)@""4(* +DI  XXa[ ==   == A!B}}T" XXa[==&$T"X.. HHRLXXa[==&HHRLKK2&!"vAB   Q  T"X&&  %bggi&8&?&?&A%B CC S!!rKcddl}ddlm}|$tjd}|j d}t jjt jj|d}|||}|jj|}|jd}g} |r | j} nd} |D]} |j| | |jdkDr |rt!d d j#| zyy) 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 rN)exec_mod_from_locationr__file__Frr!zSome doctests failed: %sr)doctestnumpy.distutils.misc_utilrtsys _getframe f_globalsrrxsplitextbasename DocTestFinderr DocTestRunnerrrunfailuresrbr) filenameraise_on_errorrvrtrnamemtestsrunnerrdr"tests rLr"r"Ts,@ MM! ;;z* 77  BGG,,X6 7 :DtX.A  ! ! # ( ( +E  " "5 " 1F Cjj" 4S !"~8499S>IJJ .rKc|r|dSddl}d} |j|dd}d|jv}|j ||dS#t|jf$rd}Y/wxYw)z gh-22982 rNlscpuT)capture_outputtextsveF) subprocessrstdoutOSErrorSubprocessErrorr)__cachercmdoutputresults rLr<r<sy qz CDtD&--' NN6 1: Z// 0s"AA! A!ceZdZdZy)_DummycyrrJ)selfs rLnopz _Dummy.nops rKN)rFrGrHrrJrKrLrrs rKrrc0d}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)_d assertRaises)rkwargsres rLrrs2 ??D +F ++rKc:d}tj||g|i|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`. T)rassertRaisesRegex)exception_classexpected_regexprrres rLr(r(s'   R4 R6 RRrKc|'tjdtjz}ntj|}|j}ddlm}|jDcgc] }||s |}}|D]_} t|dr |j}n |j}|j|s;|jdrMt||||aycc}w#t$rYswxYw)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) isfunctioncompat_func_name_)recompilersep__dict__inspectrvaluesr%rrFAttributeErrorsearchrjsetattr) cls decorator testmatchcls_attrr_mmethodsfunctionfuncnames rLrrs.JJ;bffDE JJy) ||H#$OO-@bBr@G@ 8 x!34#44#,,   H %h.A.A#.F C9X#6 7 8A   s# C1C=%C!! C-,C-ctjd}|j|j}}t |d|dd}d}t }||kr|dz }t |||||krt |z }d|zS)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: rrcrg{Gz?)rxryf_localsrzrrrc) code_strtimeslabelframelocsglobscoderelapseds rLr%r%sB MM! E..%//%D 8{5'3V rKc~tsyddl}ddl}|jdj dd}|}d}|j  t j|}tdD] }|||} tt j||k\|jy#|jwxYw)zg Check that ufuncs don't mishandle refcount of object `1`. Used in a few regression tests. TrNi'rr) r3gcrMr reshapedisablerxrZrr&enable) oprrbcrrcjds rL_assert_valid_refcountr-s   )$$S#.A A ABJJL __Q r A1aA "b()  s AB))B<c  d}ddl  fd}  j| j|}}dddd} t| ||t||| |y) 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)``. 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) TrNcXjjj||S)N)rtolatolr5)_corenumericisclose)rrrr5rrs rLr]z assert_allclose..compares0xx''14d1:(< >> 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 r)) rMrspacingwhererrr nulp_diffrb) rrnulpreraxayrefrdmax_nulps rLr'r'sb B B HBHHR"Wb"56 6C 266&"&&Q-3& ' 2??1 !3,TF$7CS!!rvvi1o.H,TF-|1MCS!! (rKcd}ddl}t|||}|j||ks td||j|fz|S)ai Check that all items of arrays differ in at most N Units in the Last Place. Parameters ---------- a, 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_nulp : Compare 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))) TrNzCArrays are not almost equal up to %g ULP (max difference is %g ULP))rMrrrbr)rrmaxulprrerrets rLr)r)s^T Aq% C 266#- >$fbffSk234 4 JrKcddl|r)j||}j||}n$j|}j|}j||}j|sj|r t dj |g|}j |g|}j |j|<j |j|<|j|jk(s%td|jd|jfd}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 rNr z'_nulp not implemented for complex arrayz#Arrays do not have the same shape: z - cVj||z |}j|SNr )rr)rxryvdtrnrs rL_diffznulp_diff.._diff\s)rzz"r'-rvvd|rK) rMr common_typerrrr r r$r integer_repr)rrrtrrrrs @rLrr's6@ BJJq & BJJq & BJJqM BJJqMq!Arq_R__Q/!"KLL!AA!AAVVAhbhhqkNVVAhbhhqkN 77agg >qwwis177)TUU aB aB R rKc|j|}|jdk(s|||dkz ||dk<|S|dkr||z }|S)Nrr)viewr&)rrcomprs rL _integer_reprresT B GGqLBrAvJ&26  I a BY IrKcddl}|j|jk(r't||j|jdS|j|j k(r't||j |j dS|j|jk(r't||j|jdStd|j)zQReturn the signed-magnitude interpretation of the binary representation of x.rNiilzUnsupported dtype ) rMrfloat16rint16rint32rint64r)rrs rLrrssww"**Q("((6*:;; BJJ Q("((6*:;; BJJ Q("((6*:;;-aggY788rKc#Kd}t5}|j|}dt|dkDs|d|nd}td|z dddy#1swYyxYww)NTr when calling r\zNo warning raised)r5recordrrb) warning_classrresuprname_strs rL_assert_warns_contextrsq  A JJ} % 1vz262Bv.H !4x!?@ @AAAs A ;A A AA c|s |s t|St|dkrd|vr tdtd|d}|dd}t||j5||i|cdddS#1swYyxYw)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. 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)rr RuntimeErrorrF)rrrrs rLr*r*sV $]33 TQ f + EFF 7D 8D }4== A%T$V$%%%s A++A4c#Kd}tjd5}tjddt|dkDr|d|nd}t d|d| dddy#1swYyxYww) NTralwaysrrr\z Got warningsr)warningscatch_warnings simplefilterrrb)rrerrs rL_assert_no_warnings_contextrs   -Ah' q6A:262Bv.H <zA3!?@ @ AAAsA3AA' A3'A0,A3c|s tS|d}|dd}t|j5||i|cdddS#1swYyxYw)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. 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`. rrNr)rrFrrrs rLr+r+sR2 *,, 7D 8D $$-- 8%T$V$%%%s ?Abinaryc #0 Kd}d}tdD]| t dzt dz|D]Y |dk(r̈ fd}t f d}||| d fzf|}||| d fzf|d d|dd | d z d z d fzf|dd |d d| d z d z d fzf|dd |d d| d z d z d fzf|d d|dd | d z d z d fzf|dk(sۈ fd} fd} t f d}||| | d fzf|}||| | dfzf| }|||| dfzf|d d|dd | dd | d z d z d fzf|dd |d d| dd | d z d z d fzf|dd |dd | d d| d z d z d fzf|d d|dd | dd | d z d z d fzf|dd |d d| dd | d z d z d fzf|dd |dd | d d| d z d z d fzf\yw)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, %srNrfunaryc$tdSrr rossrLrTz%_gen_alignment_data..sfQe4QR8rKr Nz out of placezin placerraliasedr c$tdSrrrsrLrTz%_gen_alignment_data.. vau5ab9rKc$tdSrrrsrLrTz%_gen_alignment_data..!rrKz in place1z in place2)rrr) rr{max_sizeufmtbfmtinpr"rinp1inp2rrs ` @@rL_gen_alignment_datars2 :D >D 1X';q1uc!a%23& ;Aw8QD.qr235$!Q5.)I"IIIEDAq!UJ#????!"gsuSbz4UAq1ue^<,===#2hab 4Aq1ue^<,===eCRj#%)TAq1ueY7.888eABisTUAq1ueY7.888x99QD.qr2464641a7,888FDFD1a 4%555FD1a 4%555!"gtvcr{DF3BKUAq!a%?:@@@#2hqr DF3BKAq!a%?:@@@#2hs TVABZ1q5!a%?:@@@fQRj$&"+tvcr{DUAq!a% :=;;;fSbk46!":tvcr{DAq!a% :=;;;fSbk46#2;qr D1q5!a% :=;;;K& ;';s D JFJceZdZdZy)r-z/Ignoring this exception due to disabled featureNrErJrKrLr-r-9s5rKr-c/Kt|i|} |tj|y#tj|wxYww)zContext manager to provide a temporary test folder. All arguments are passed as this to the underlying tempfile.mkdtemp function. N)rshutilrmtree)rrtmpdirs rLr1r1>s9d %f %F  f fs A)AAAc/Kt|i|\}}tj| |tj|y#tj|wxYww)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)rrfdrxs rLr0r0MsF''HBHHRL  $ $s$AAAAAc<eZdZdZdZdfd ZfdZfdZxZS)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, 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 rJct|j|j|_i|_t ||y)Nr)setunion class_modulesmodules_warnreg_copiessuper__init__)rrr, __class__s rLr/z!clear_and_catch_warnings.__init__s77|))$*<*<= ! 'rKc|jD]H}t|ds|j}|j|j|<|j Jt |SN__warningregistry__)r,r%r3copyr-clearr. __enter__)rmodmod_regr0s rLr6z"clear_and_catch_warnings.__enter__s[<< Cs1211,3LLN$$S)   w ""rKct|||jD]_}t|dr|jj ||j vs8|jj|j |ayr2)r.__exit__r,r%r3r5r-update)rexc_infor7r0s rLr:z!clear_and_catch_warnings.__exit__so (#<< JCs12''--/d***''..t/C/CC/HI  JrK)FrJ) rFrGrHrIr+r/r6r: __classcell__)r0s@rLr.r.cs&(RM( #JJrKr.cheZdZdZddZdZedddfdZeddfdZeddfd Z d Z d Z dd d Z dZ y)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 cLd|_g|_|dvr td||_y)NF>oncermodulelocationzunsupported forwarding rule.)_entered _suppressionsr_forwarding_rule)rforwarding_rules rLr/zsuppress_warnings.__init__s0   "J J;< < /rKcttdrtjy|jD])}t|ds|jj +y)N_filters_mutatedr3)r%rrH _tmp_modulesr3r5)rrAs rL_clear_registriesz#suppress_warnings._clear_registriessR 8/ 0  % % ' '' 3Fv45**002 3rKr\NFc4|rg}nd}|jr|tjd||nc|jj dddz}tjd||||j j ||j|jj||tj|tj||f|S|jj||tj|tj||f|S)Nrcategorymessage.\.$rMrNrA)rCrfilterwarningsrFreplacerIaddrJ_tmp_suppressionsrrrIrD)rrMrNrAr module_regexs rL_filterzsuppress_warnings._filter s FF ==~''xB &66sEBSH ''x')!!%%f-&&(  " " ) )7BJJw$=vvN P      % %7BJJw$=vvN P rKc.|j|||dy)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. FrMrNrArNrYrrMrNrAs rLfilterzsuppress_warnings.filter s( h!  #rKc,|j|||dS)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. Tr[r\r]s rLrzsuppress_warnings.record5 s#6||Xwv#') )rKc|jr tdtj|_tj |_|j ddt_d|_g|_t|_ t|_ g|_ |jD]}\}}}}}||dd=|tjd||+|jjdddz}tjd||||jj!||j"t_|j%|S) Nz%cannot enter suppress_warnings twice.TrrLrOrPrQrR)rCrr showwarning _orig_showfilters_filtersrVr)rI _forwardedlogrDrSrFrTrU _showwarningrJ)rcatmessrr7rfrXs rLr6zsuppress_warnings.__enter__S s ==FG G".. (( ==+ !#E%&*&8&8 + "Cq#sF{''sD: #||33C?#E ''sD')!!%%c* + $00   rKc|jt_|jt_|j d|_|`|`y)NF)rbrrardrcrJrC)rr<s rLr:zsuppress_warnings.__exit__s s7#==   O MrK) use_warnmsgc|j|jzdddD]\}} } } } t||s| j|jd5| ?| ;t ||||fi|} |j j| | j| y| jj|s| ;t ||||fi|} |j j| | j| y|jdk(r.||j||||g|i|y|j|y|jdk(r|j|f}n>|jdk(r|j||f}n|jdk(r|j|||f}|jvry|jj|||j||||g|i|y|j|y)Nrrrr@rArB)rDrV issubclassrrr rfrrurjrErb _orig_showmsgrerU)rrNrMrlinenorkrrrhrpatternr7recrd signatures rLrgzsuppress_warnings._showwarning{ s""T%;%;;TrT*C  %CGS#8S)MM',,q/2>;,Wh-3?7=?, 3\\,,X6,Wh-3?7=?, 3+ 2  H ,"8V1!%1)/1 "";/   F * x0I  " "h . x:I  " "j 0 x6BI  '  I&   DOOGXx &$ &$ &   { +rKc2tfd}|S)z_ Function decorator to apply certain suppressions to a whole function. cD5|i|cdddS#1swYyxYwrrJ)rrrrs rLnew_funcz,suppress_warnings.__call__..new_func s( -T,V, - - -sr)rrrus`` rL__call__zsuppress_warnings.__call__ s" t -  -rK)r)rFrGrHrIr/rJWarningrYr^rr6r:rgrwrJrKrLr5r5sZHR0 3 '42&r$#.&r$)<@)-1,f rKr5c #>Kd}tsdyttjtjtj } t dD]}tjdk(sn tdtjtjdtj}tjdd}tjdd=tj|tj|rE|d|nd}tdj||t|dj!d|Dy#tjdd=tj|tjwxYww) NTrrz]Unable to fully collect garbage - perhaps a __del__ method is creating more reference cycles?rr\zXReference cycles were found{}: {} objects were collected, of which {} are shown below:{}c 3K|]V}djt|jt|t j |j ddXyw)z {} object with id={}: {}rz N)rvr{rFidrpformatrT).0rs rL z/_assert_no_gc_cycles_context.. sR  8>>Q((1q)11$AsAA)r3r&r isenabledr get_debugrcollectr set_debug DEBUG_SAVEALLgarbagerrbrvrr)rregc_debugrn_objects_in_cyclesobjects_in_cyclesrs rL_assert_no_gc_cycles_contextr sM   BLLNJJL||~Hs 6Azz|q  656 6 R%%& !jjlJJqM JJqM X .2.>^D6*B - V#%& 1     JJqM X s&AF%EFFc|s tS|d}|dd}t|j5||i|dddy#1swYyxYw)a 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. rrNr)rrFr s rLr7r7 sR0 +-- 7D 8D %4== 9 dfs ?ActjtrQtjtjtjtjyy)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)rrr2rJrKrLr8r8 s9JJL    rKcddlfd}|S)z:Decorator to skip a test if not enough memory is availablerNc4tfd}|S)Nct}|j| |i|S#t$rjdYywxYw)NzMemoryError raised)check_free_memoryskip MemoryErrorxfail)rkwrd free_bytesrpytests rLwrapperz3requires_memory..decorator..wrapper' sM#J/C C  3Q~"~% 3 12 3s)AArv)rrrrs` rLrz"requires_memory..decorator& s t 3  3rK)r)rrrs` @rLrequires_memoryr" s  rKcd}tjj|}| t|}|dz d|d}n#t }|d}d }n|dz }|dz }|d |d }||kr|SdS#t$r}t d|d|d}~wwxYw) z Check whether `free_bytes` amount of memory is currently free. Returns: None if enough memory available, otherwise error message NPY_AVAILABLE_MEMNzInvalid environment variable rgeAz@ 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.rz GB memory required, but z GB available)renvironget _parse_sizer_get_mem_available)renv_var env_valuemem_freerrd free_bytes_gb mem_free_gbs rLrr8 s "G w'I O"9-Hs"#$$$-;d4&'  CH&,M"S.K"O#<[MWCZ'31T1% O?@@ uQWWQZ 8AGGAJ#77 88rKc ddl}|jjS#ttf$rYnwxYwt j jdri}td5}|D]F}|j}t|ddz||djdj<H dddn #1swYnxYwd|vr|dS|d |d zSy) z5Return available memory in bytes, or None if unknown.rNrz /proc/meminforr: memavailablememfreecached) psutilvirtual_memory available ImportErrorrrxplatformrjrrrstripr)rinforlineps rLrrh s $$&000  (    ||w' / " Aa AJJL03AaD D0@QqTZZ_**,- A A A A T !' ' ?T(^3 3 s 22!A B77CcRttdsStfd}|S)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 gettracectj} tjd|i|tj|S#tj|wxYwr)rxrsettrace)rroriginal_tracers rLrz_no_tracing..wrapper sE \\^N - T"T,V, ^, ^,s A A )r%rxr)rrs` rL _no_tracingr s1 3 # t -  -rKcz tjdjdd}|S#t$rd}Y|SwxYw)NCS_GNU_LIBC_VERSIONrr0.0)rconfstrrsplitr)vers rL_get_glibc_versionr sHjj./66s;A> J  Js '+ ::c*tdk7xr t|kS)Nr) _glibcverrs rLrTrT syE1Ci!mrKc t|D]}tjj|5}|g}n|}|r&t j |} |j | |rt|D cgc] } || g| } } nt|D cgc]} |g| } } g} | D] } | j |j| " t |kr|r j | D]}|j dddycc} wcc} w#t$r&}ddl }|jd|d|dYd}~xd}~wwxYw#t |kr|r jwwwxYw#1swYnxYw)z&Runs a function many times in parallel) max_workersNrz Spawning z threads failed with error z@ (likely due to resource limits on the system running the tests))r concurrentfuturesThreadPoolExecutor threadingBarrierrsubmitrrrrabortr)rr pass_count pass_barrierouter_iterations prepare_argsrtperbarrierrall_argsrargrrrs rLrArA s# $  33 3L ##~#++K8 G$6;K6HIT1,t,II383EFaTMDMFF $#5CNN:3::s#345w<+-,MMO   3  JF   9 i }5%%&E*8899 9 w<+-,MMO3?-/  sfAE03D E0 DE0!'DE  8E0 E0 E E<E EE  $E--E00E: )r\)NrNN)pythonrr)NN)zItems are not equal:Trr_)r\T)r\T)r\Tr\TT)rr\T)NT)rN)gHz>rTr\T)r)r_FFrN)rIconcurrent.futuresrr*rimportlib.metadata importlibrQrpathlibrrrr rx sysconfigrr functoolsrriortempfilerr unittest.caserr rMrnumpy.linalg._umath_linalgr r r rr rrrrrrr__all__rr/KnownFailureTestr$Pathruparentr@metadata distributionnp_distr? version_infoorigindir_infoeditabler>jsonrQloads read_textr locate_filePackageNotFoundErrorrwr4implementationrr2r%r:r/r3r_multiarray_umath_blas_supports_fperClinalg _umath_linalg_ilp64r9r;get_config_var_vrr=ritemsizerBr&r|r rrrr!rrr6rrrr#rr"r<unittestTestCaserrrr(rr%rr,r'r)rrrcontextmanagerrr*rr+rr-r1r0rr.r5rr7r8rrrrrrr_glibc_older_thanrArJrKrLr s   $%"#!((WWW $ I )  W\\"++ & - -   --g6GL    w &!..11::K  TZZ!!"34<FF!//22K 7..w7:E (    4 4   ! !V + C. / sM40<NY HH..AA$G||))00  Yo.4" R<G+9++,=>? 288BGG  % % *#(77d?;??C$8E  \\"1  "<<w<. 8+AGH:OeOd&-Rz/zAC $`"FMO@DE#(0EEP~(#~(BCE&*p fp+p+fD"N,K^!, X    E],: S +8\+\4CG(,j(8=j(Z<"~1h;|  9 AA8%v AA%D&HrB;J i     *?Jx66?JDSSl 0 0 fB$,2>9"0(  D2767"iR  !..'!&&L;'s%P A6O??P  P  P.-P.