idLdZddlZddlZddlZddlZddlZddlZddlZddlm Z m Z ddl Z ddl Z ddl mZmZddlmZddlmZddlZddlZddlZddlmZmZmZmZmZmZmZmZddlm Z m!Z!m"Z"ddl#Zdd l$m%Z%gd Z&Gd d e'Z(e(Z)dZ*ej+d vZ,ej-j.dkZ/e0edZ1e2eddduoe1 Z3ej4j5j6Z7dZ8dZ9ej:dpdZ;de;vrdZ9dadZn-ejdddkrdej?d fd!Z>nd"Z>ejdddkrdej?d gfd#Z@ngfd$Z@ ddd(ZAded)ZBd*ZCejDdfd,ZEejD dfd-ZFejD dgdd/d0ZGdedd/d1ZHejDdhd2ZIded3ZJd4ZKd5ZLdid6ZMd7ZNeNZOddlPZPGd8d9ePjQZReRd:ZSd;ZTd<ZUdjd=ZVdkd?ZWd@ZX dldBZYdmdCZZdkdDZ[djdEZ\dFZ]dGZ^e j_djdHZ`dIZae j_djdJZbdKZcedLdMfdNZdGdOdPe'Zee j_dQZfe j_dRZgGdSdTejhZiGdUdVZje j_djdWZkdXZldYZmdZZnd[Zod\Zpd]Zqd^Zrd_ZsesZtd`ZudS)nz* Utility function to facilitate testing. N)partialwraps)mkdtempmkstemp)SkipTest)WarningMessage)intpfloat32emptyarange array_reprndarrayisnatarray)isfiniteisnanisinf)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_SVEceZdZdZdS)r/zrP;s022h>rEF HOST_GNU_TYPEmuslTchd}|s- |}n#t$r|}YnwxYwt|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__smsgs rFr&r&Gs` # 355DD   DDD T""" ##s   ntcddl}||j}||||d||f}|} |||} |||| |\} } | || ||S#|| wxYw#||wxYw)Nr) win32pdh PDH_FMT_LONGMakeCounterPath OpenQuery AddCounterCollectQueryDataGetFormattedCounterValue RemoveCounter CloseQuery) objectcounterinstanceinumformatmachiner^pathhqhctyperWs rFGetPerformanceAttributesrq]s  >*F'''68T*.*9::    ! ! $$$R..B +))"---$==b&II c&&r***    # # # #&&r****    # # # #s#C /B/C /CC C pythonc<ddl}tdd|||jdS)NrProcessz Virtual Bytes)r^rqr_) processNamerir^s rFr r xs1' ?(3X(0(=tEE ErElinuxz/proc/z/statc t|5}|d}dddn #1swxYwYt|dS#t$rYdSwxYw)zM Return virtual memory size in bytes of the running python.  N)openreadlinesplitint Exception)_proc_pid_statfls rFr r s  n%% ,JJLL&&s++ , , , , , , , , , , , , , , ,qu::     FF s3A%(A A%A  A% A  A%% A32A3ct)zK Return memory usage of running python. [Not implemented] )NotImplementedErrorrDrErFr r s "!rEcddl}|s'|| t|5}|d}dddn #1swxYwYt |dS#t $r0t d||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. rNry d)timeappendr{r|r}r~r)r _load_timerrrs rFrrs   +   diikk * * * 8n%% ,JJLL&&s++ , , , , , , , , , , , , , , ,qu::  8 8 8sDIIKK 1 5677 7 7 7 8s4B(A2& B2A66B9A6:B7C  C cddl}|s'||td||dz zS)rrNr)rrr~)rrs rFrrsU   +   diikk * * *3 JqM12333rEItems are not equal:ACTUALDESIREDcd|zg}|ra|ddkr3t|dt|z kr|ddz|zg}n|||rt|D]\}}t |t rt t|} nt} | |} n2#t$r%} dt|j d| d } Yd} ~ nd} ~ wwxYw| dd kr4d | dd } | d z } |d||d | d |S) N r\Orry) precisionz[repr failed for : ]z...: )findlenr enumerate isinstancerrr reprrrpr@countjoin splitlines) arrayserr_msgheaderr$namesrrXiar_funcrexcs rFrrs &=/C <<   # #G r#f++~(E(Eq6C<')*CC JJw   ,f%% , ,DAq!W%%  yAAA EF1II E E EDa)9DDcDDD Ewwt}}q  IIallnnRaR011U  JJ*58**q** + + + + 99S>>s4 C C/ C**C/c d}t|trt|ts)ttt |t t |t ||||D]I\}}||vrtt|t ||||d|d||JdSt|ttfrt|ttfrqt t |t |||tt |D]&}t ||||d|d||'dSddl m }m }m} ddlm} m} m} t||st||rt'||||St)||g|| } | |p | |}n#t*t,f$rd }YnwxYw|r| |r| |}| |}n|}d}| |r| |}| |}n|}d} t ||t ||n#t$rt| wxYw||||krt|  t/|}t/|}t1j|jjt1j|jjk}|r|r|rdSt| n#t,t*t6f$rYnwxYw t9|}t9|}|r|rdSt1j|}t1j|}|jjd vs|jjd vrt7d |dkr-|dkr'| || |kst| n#t,t*t6f$rYnwxYw ||kst| dS#t<t>f$r$}d |j dvrt| d}~wwxYw)a 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. 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 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. Raises ------ AssertionError If actual and desired are not equal. 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]) Tzkey=rNzitem=r)risscalarsignbit iscomplexobjrealimagr$FMmz0cannot compare to a scalar with a different typezelementwise == comparison)!rdictrVrrprritemslisttuplerange numpy.corerrr numpy.librrrrr ValueErrorrUrrNasarraydtyperrcharDeprecationWarning FutureWarningargs)actualdesiredrr$rYkrrrrrrrrX usecomplexactualractualidesiredrdesirediisdesnatisactnat dtypes_matchisdesnanisactnan array_actual array_desiredes rFrrsYd'4  &$'' 5 d6ll!3!344 4S[[#g,,AAAMMOO " "DAq$T!WW--- GAJ0Gq0G0Gg0G0G  " " " "'D%=))j$.O.OS[[#g,,AAAs7||$$ " "A GAJ0H0H0Hw0H0H  " " " "55555555552222222222&'""Ej'&B&BE!&'7GDDD )7G D D DC !\&))B\\'-B-B  " & <   d6llGd6llGGGG <  tG}}HtG}}HHHH & ( + + + ( + + + + & & & %% % &xHHV,,,,S!!! >>== 7++16 6**056  * * *$S))) z#6 7      >>==    Fz&))  7++   #t + +#(D00 &'>?? ? a<d}ddl}||kst}|||d|j|||d|j||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: )pprintrwriterVgetvalue) test_stringrrrYrrXs rFr!r!ts8MMM g  jj + '((( fc""" -    gs###S\\^^,,,  rEcDd}ddlm}ddlm}m}m}  |p |} n#t $rd} YnwxYwfd} | r|r|} | } n} d} |r|}| }n}d} t| |t| |n%#t$rt| wxYwt|ttfst|ttfrtS trtsststr6trtst| nkst| dSn#tt f$rYnwxYwt#z t%jd d  zzkrt| dS) a$ 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: 6.66669964e-09 Max relative difference: 2.85715698e-09 x: array([1. , 2.333333333]) y: array([1. , 2.33333334]) Tr)rrFc8dz}tg|S)N*Arrays are not almost equal to %d decimals)r$r)r)rrdecimalrrr$s rF_build_err_msgz+assert_almost_equal.._build_err_msgs2>Hfg.$*,,, ,rE)rN?$@)rrrrrrrrrVrrrrrrrrUabsrNfloat64)rrrrr$rYrrrrrrrrrrs````` rFrrsL""""""2222222222 !\&))B\\'-B-B  ,,,,,,,,, 3 <   d6llGd6llGGGG <  tG}}HtG}}HHHH 3 7 C C C C 7 C C C C C 3 3 3 !1!122 2 3&7E4011L'GUD#9::L('7KKK  !! hv&6&6 W~~ ;v ;g;5==;()9)9:::;&((()9)9::: F   +      7V  31A+A B BBB^^--...CBs+0 ??$B??"C!1BGGGc d}ddl}tt||f\}}||krdS|jd5d|j||j|zz}|jd|j|j|}dddn #1swxYwY ||z }n#t$rd}YnwxYw ||z } n#t$rd} YnwxYwt||g|d |z| } t|rt|sct|st|r.t|rt|st| n||kst| dSn#ttf$rYnwxYw|j|| z |jd |d z 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)numpymapfloaterrstaterpowerfloorlog10ZeroDivisionErrorrrrrVrUr) rr significantrr$rYrNscale sc_desired sc_actualrXs rFrrsxEFG#455VW& X & & &88VRVG__vrvf~~56XRXhbhuoo6677888888888888888U]  5L    7>L   C  !! hv&6&6 W~~ .v .g.5==.(---.&(((--- F  * +      rvj9$%%#Q7G)H)HHHS!!!IHsIABBB$B** B98B9=C CC.A?E00FF)strictc   '(d} ddlm} m} m(m'm} m}m}m}tj |}tj |}||}}d}d}| df'fd } | r!|j |j ko|j |j k}n&|j dkp|j dkp|j |j k}|s`|j |j krd |j d |j d }nd |j d |j d }t||g|zd }t|'d}||rI||r>|r|||| d}|r*||||(fddz}||||(fddz}nF||r;||r0|r.|j j|j jkr|||t d}|jdkr ||||}}|jdkrdSn|rdS|||}t'|t(r|}t+|g}n(|}|}|dkrf|j|t0z }|jdkr|jn|j}d|z|z }d|||g}| d5t5jt85t;||z } tj|j tjr)t;||z }!tj | |!| || }"tC| d||kr&|"dtG|"zn!|"d| |"z'|dk}#||#rt+(}$n'|| |#t;||#z }$tC| d||kr&|"dtG|$zn!|"d| |$zdddn #1swxYwYdddn #1swxYwYdd$|zz t||gd }t|dS#tJ$rGddl&}%|%'}&d |&d!t||gd }tK|wxYw)"NTr) array2stringrinfbool_rallmaxobject_c|jjdvS)Nz?bhilqpBHILQPefdgFDGrrxs rFisnumberz&assert_array_compare..isnumbersw|555rEc|jjdvS)Nrrrs rFistimez$assert_array_compare..istimesw|t##rEnancd}||}||}||kdkr,t||g d|zz d }t|t|ts |jdkr |St|ts |jdkr |S|S)zHandling nan/inf. Combine results of running func on x and y, checking that they are True at the same locations. Tz x and y %s location mismatch:ryr$rrrr)rrrVrboolndim) rrfunchasvalrYx_idy_idrXrrrrr$s rFfunc_assert_same_posz2assert_array_compare..func_assert_same_poss!tAwwtAww 5   " " $ $ , ,A '*K#)++!+4;F&0IGGGC!%% % dD ! ! TY!^^5;;  d # # tyA~~5;; KrErDz (shapes z, z mismatch)z (dtypes rrF)rr c| kSNrDxyrs rFrPz&assert_array_compare.. sd rEz+infc| kSrrDrs rFrPz&assert_array_compare..rrEz-infNaTrrz&Mismatched elements: {} / {} ({:.3g}%)r)routrzMax absolute difference: zMax relative difference: rzerror during assertion: z )(rrrrrrrrrrN asanyarrayshaperrrVrprrsizerrrravelsumr rk contextlibsuppressrUr issubdtypeunsignedintegerminimumgetattrrstrrr traceback format_exc)) comparisonrrrr$rr equal_nan equal_infrrYrrrrrroxoyrrr condreasonrXflaggedrWreduced n_mismatch n_elementspercent_mismatchremarkserrorerror2 max_abs_errornonzero max_rel_errorr#efmtrrs) ```` @@rFr6r6sf//////////////////// aA aAB666$$$).e##########Jk  J7ag%>?Gh''' F F(33FFAJJE}QWb.@AA=!$QU 5&e<<<<$'CJJMugw777BB'B),]););(<==== 'B)5m)D)D(EFFF $eAFmmGsG8}}N(-c (+E'NS7__,L(M(M ugw777BB'B),]););(<==== 'B)5m)D)D(EFFF3FFFFFFFFFFFFFFF F F F F F F F F F F F F F F F< tdii000 0GR'(/&0IGGGC!%% %U >> 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: 4.4408921e-16 Max relative difference: 1.41357986e-16 x: array([1. , 3.141593, nan]) y: 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) x: array([[3, 3, 3, 3, 3], [3, 3, 3, 3, 3]]) y: 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) x: array([2, 2, 2]) y: array([2., 2., 2.], dtype=float32) TzArrays are not equal)rr$rrN)r6operator__eq__)rrrr$rrYs rFrr(s?^!Q!(1G &((((((rEc  d}ddlm mm ddlmddlm  fd}t|||||dzd 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 ---------- x : array_like The actual object to check. y : 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: 6.e-05 Max relative difference: 2.57136612e-05 x: array([1. , 2.33333, nan]) y: 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 x and y nan location mismatch: x: array([1. , 2.33333, nan]) y: array([1. , 2.33333, 5. ]) Tr)numberfloat_ result_type)r)anyc6  t|s t|rjt|}t|}||ksdS|j|jcxkrdkr nn||kS||}||}n#ttf$rYnwxYw |d}t j||}t||z }|j s| }|dd zzkS)NFrg?rr) rrrrUrrNrrrastype) rrxinfidyinfidrzrr=rnpanyr<r>s rFcomparez*assert_array_almost_equal..comparesD uU1XX %%a// qq&(--//! 56QV((((q(((((6MvgJvgJ./    D   Ar"" M!U # # AJJz!'6** !  A3))))sA&B+B BB21B2r)rr$rrN) rr<r=r>numpy.core.numerictypesrnumpy.core.fromnumericr?r6) rrrrr$rYrFr=rrEr<r>s ` @@@@@rFrrs\6666666666222222333333**********4!QAGK      rEc Jd}ttj||||dddS)ai Raises an AssertionError if two array_like objects are not ordered by less than. Given two array_like objects, check that the shape is equal and all elements of the first object are strictly smaller than those of the second object. An exception is raised at shape mismatch or incorrectly ordered values. Shape mismatch does not raise if an object has zero dimension. In contrast to the standard usage in numpy, NaNs are compared, 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. 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 Examples -------- >>> np.testing.assert_array_less([1.0, 1.0, np.nan], [1.1, 2.0, np.nan]) >>> np.testing.assert_array_less([1.0, 1.0, np.nan], [1, 2.0, np.nan]) Traceback (most recent call last): ... AssertionError: Arrays are not less-ordered Mismatched elements: 1 / 3 (33.3%) Max absolute difference: 1. Max relative difference: 0.5 x: array([ 1., 1., nan]) y: array([ 1., 2., nan]) >>> np.testing.assert_array_less([1.0, 4.0], 3) Traceback (most recent call last): ... AssertionError: Arrays are not less-ordered Mismatched elements: 1 / 2 (50%) Max absolute difference: 2. Max relative difference: 0.66666667 x: array([1., 4.]) y: array(3) >>> np.testing.assert_array_less([1.0, 2.0, 3.0], [4]) Traceback (most recent call last): ... AssertionError: Arrays are not less-ordered (shapes (3,), (1,) mismatch) x: array([1., 2., 3.]) y: array([4]) TzArrays are not less-orderedF)rr$rr'N)r6r9__lt__)rrrr$rYs rFrrs?P!Q!( =#(******rEc&t||dSr)exec)astrrs rFr#r#^strEcbd}ddl}t|ts)tt t |t|ts)tt t |||krdSt || d| d}g}|r| d}| dr.| dr$|g}| d}| dr*| || d}| dstt || ||rV| d} | dr| | n| d| |dd|ddkrQ||htt ||sdSd 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: rR)difflibrr"rVrrprDifferrFrpop startswithrinsertextendrrstrip) rrrYrPdiff diff_listd1rd2d3rXs rFrrbs}6NNN fc " "1T$v,,//000 gs # #2T$w--00111&   (():):4)@)@""4((** + +DI ' XXa[[ ==     ==   A!B}}T"" ! XXa[[==&& /$T"XX... HHRLLL 'XXa[[==&&'HHRLLLLKK2&&&!""vABB   Q    T"XX&&&  Cbggi&8&8&?&?&A&A C CC S!!!rEc0 ddlm}ddl}|!tjd}|jd}t jt j |d}|||}| |}| d}g |r fd} nd} |D]} | | | |jdkr'|r'td d  zdSdS) aV 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__Frc.|Sr)r)srXs rFrPzrundocs..s 1 rErzSome doctests failed: %sr)numpy.distutils.misc_utilr]doctestsys _getframe f_globalsosrmsplitextbasename DocTestFinderr DocTestRunnerrunfailuresrVr) filenameraise_on_errorr]rbrnamemtestsrunnerrtestrXs @rFr"r"s;,A@@@@@NNN M!  ;z* 7  BG,,X66 7 7 :DtX..A  ! ! # # ( ( + +E  " "5 " 1 1F C%%%%"" 4S !!!! ~8499S>>IJJJrEctddl}d} ||dd}d|jvS#t$rYdSwxYw)z gh-22982 rNlscpuT)capture_outputtextsveF) subprocessrkstdoutOSError)rycmdoutputs rFcheck_support_sver~s`  CDtDD %% uus ) 77ceZdZdZdS)_DummycdSrrD)selfs rFnopz _Dummy.nops rEN)r@rArBrrDrErFrrs#     rErrc(d}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)rkwargsrYs rFrrs2 ?D +F + ++rEc2d}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)rassertRaisesRegex)exception_classexpected_regexprrrYs rFr(r(s-"  R4 R R R6 R RRrEc|"tjdtjz}ntj|}|j}ddlmfd|D}|D]w} t|dr|j }n|j }n#t$rY/wxYw| |r/| dst||||xdS)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) isfunctionc*g|]}| |SrDrD).0_mrs rF z$decorate_methods..Gs&@@@bB@r@@@rEcompat_func_name_)recompilerfsep__dict__inspectrvalueshasattrrr@AttributeErrorsearchrSsetattr)cls decorator testmatchcls_attrmethodsfunctionfuncnamers @rFrr's.J;bfDEE Jy)) |H#"""""@@@@HOO--@@@G 8 8 x!344 -#4#,    H    H % % 8h.A.A#.F.F 8 C99X#6#6 7 7 7 Fs,B  BBrctjd}|j|j}}t |d|dd}d}t }||kr|dz }t |||||kt |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: ryrLrg{Gz?)rcrdf_localsrerrrL) code_strtimeslabelframelocsglobscoderelapseds rFr%r%VsB M!  E.%/%D 835333V < c  d}ddl  fd} j| j|}}dddd} t|||t||| dS) a 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. 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 checks that each element of the array_like object is equal to the scalar. 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) TrNcLjj||S)N)rtolatolr&)corenumericisclose)rrrr&rNrs rFrFz assert_allclose..compares/w&&q!$T1:'<< >> 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: X and Y are not equal to 1 ULP (max is 2) TrNzX and Y are not equal to %d ULPz+X and Y are not equal to %d ULP (max is %g)) rrspacingwhererrr nulp_diffrV) rrnulprYrNaxayrefrXmax_nulps rFr'r'sb B B HBHR"Wb"5566 6C 26&"&1++$ % %" 2?1   S!3!3 S3d:CCrvi1oo..H?4BRRCS!!! ""rEcd}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))rrrrVr)rrmaxulprrYrNrets rFr)r)#suT Aq% C 26#- 4>$fbfSkk2344 4 JrEcddl|r%j||}j||}n j|}j|}j||}j|sj|rt dj|g|}j|g|}j|j|<j|j|<|j|jkstd|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 rNrz'_nulp not implemented for complex arrayz$x and y do not have the same shape: z - cNj||z |}j|SNr)rr)rxryvdtrWrNs rF_diffznulp_diff.._diffs-rz"R%s+++rvd||rE) rr common_typerrrrrrr integer_repr)rrrtrrrrNs @rFrrWs@  BJq & & & BJq & & & BJqMM BJqMMq!ArqM_R_Q//M!"KLLL!AA!AAVAhbhqkkNVAhbhqkkN 7ag  j'''177,-- - aB aB 5R  rEc||}|jdks|||dkz ||dk<n |dkr||z }|S)Nrr)viewr)rrcomprs rF _integer_reprrsQ B GqLLBrAvJ&26 66B IrEcpddl}|j|jkr$t||j|jdS|j|jkr$t||j|jdS|j|jkr$t||j|jdStd|j)zQReturn the signed-magnitude interpretation of the binary representation of x.rNiilzUnsupported dtype ) rrfloat16rint16r int32rint64r)rrNs rFrrsw"*Q("(6*:*:;;; BJ  Q("(6*:*:;;; BJ  Q("(6*:*:;;;7ag77888rEc#Kd}t5}||}dVt|dks|d|nd}td|z ddddS#1swxYwYdS)NTr when calling rRzNo warning raised)r5recordrrV) warning_classrorYsuprname_strs rF_assert_warns_contextrs   A JJ} % % 1vvzz262B....H !4x!?@@ @AAAAAAAAAAAAAAAAAAsAA))A-0A-c|st|S|d}|dd}t||j5||i|cdddS#1swxYwYdS)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 rrNro)rr@)rrrrs rFr*r*sZ 4$]333 7D 8D }4= A A A%%tT$V$$%%%%%%%%%%%%%%%%%%sAAAc#Kd}tjd5}tjddVt|dkr|d|nd}t d|d| ddddS#1swxYwYdS) NTralwaysrrrRz Got warningsr)warningscatch_warnings simplefilterrrV)rorYrrs rF_assert_no_warnings_contextrs   - - -Ah'''  q66A::262B....H !?!?!?A!?!?@@ @ AAAAAAAAAAAAAAAAAAsA A22A69A6c|stS|d}|dd}t|j5||i|cdddS#1swxYwYdS)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`. rrNr)rr@rrrs rFr+r+s6 -*,,, 7D 8D $$- 8 8 8%%tT$V$$%%%%%%%%%%%%%%%%%%sA  AAbinaryc # Kd}d}tdD]p t dzt dz|D]G |dkr fd}t f d}||| d fzfV|}||| d fzfV|d d|dd | d z d z d fzfV|dd |d d| d z d z d fzfV|dd |d d| d z d z d fzfV|d d|dd | d z d z d fzfV|dkr! fd} fd} t f d}||| | d fzfV|}||| | dfzfV| }|||| dfzfV|d d|dd | dd | d z d z d fzfV|dd |d d| dd | d z d z d fzfV|dd |dd | d d| d z d z d fzfV|d d|dd | dd | d z d z d fzfV|dd |d d| dd | d z d z d fzfV|dd |dd | d d| d z d z d fzfVIrdS)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, %srrOunaryc6tdSrr ror`srFrPz%_gen_alignment_data..AsfQe444QRR8rErNz out of placezin placerr\aliasedrc6tdSrrrsrFrPz%_gen_alignment_data..Ovau555abb9rEc6tdSrrrsrFrPz%_gen_alignment_data..PrrEz in place1z in place2)rrr ) rrpmax_sizeufmtbfmtinprrinp1inp2rr`s ` @@rF_gen_alignment_datar#s2 :D >D 1XX';';q1uc!a%2233& ;& ;Aw888888QD...qrr23355$!Q5.)I"IIIIICEEDAq!UJ#??????!""gssuuSbSz4UAq1ue^<,=====#2#habb 4Aq1ue^<,=====ceeCRCj##%%)TAq1ueY7.88888ceeABBissTUAq1ueY7.88888x999999999999QD...qrr244664466D1a7-88888DFFDDFFD1a 4%55555DFFD1a 4%55555!""gttvvcrc{DDFF3B3KUAq!a%?:@@@@@#2#hqrr DDFF3B3KAq!a%?:@@@@@#2#hss TTVVABBZ1q5!a%?:@@@@@dffQRRj$$&&"+ttvvcrc{DUAq!a% :=;;;;;dffSbSk4466!"":ttvvcrc{DAq!a% :=;;;;;dffSbSk4466#2#;qrr D1q5!a% :=;;;;;K& ;';';rEceZdZdZdS)r-z/Ignoring this exception due to disabled featureNr?rDrErFr-r-hs55DrEr-c/Kt|i|} |Vtj|dS#tj|wxYw)zContext manager to provide a temporary test folder. All arguments are passed as this to the underlying tempfile.mkdtemp function. N)rshutilrmtree)rrtmpdirs rFr1r1msTd %f % %F  f fs *Ac/Kt|i|\}}tj| |Vtj|dS#tj|wxYw)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)rrfcloseremove)rrfdrms rFr0r0|s\'''HBHRLLL  $ $s AAc<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 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 rDFct||j|_i|_t |dS)Nr)setunion class_modulesmodules_warnreg_copiessuper__init__)rrr __class__s rFrz!clear_and_catch_warnings.__init__sJ7||))$*<== ! '''''rEc|jD]I}t|dr7|j}||j|<|Jt SN__warningregistry__)rrrcopyrclearr __enter__)rmodmod_regrs rFr!z"clear_and_catch_warnings.__enter__sh<  Cs122 1,3LLNN$S) ww  """rEctj||jD]Y}t|dr|j||jvr%|j|j|ZdSr)r__exit__rrrr rupdate)rexc_infor"rs rFr%z!clear_and_catch_warnings.__exit__s(##< J JCs122 0'--///d***'..t/CC/HIII  J JrE)FrD) r@rArBrCrrr!r% __classcell__)rs@rFr.r.s((RM(((((( #####JJJJJJJJJrEr.cjeZdZdZddZdZedddfdZeddfd Zeddfd Z d Z d Z dd dZ dZ 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 rcVd|_g|_|dvrtd||_dS)NF>oncermodulelocationzunsupported forwarding rule.)_entered _suppressionsr_forwarding_rule)rforwarding_rules rFrzsuppress_warnings.__init__s<   "J J J;<< < /rEcttdrtjdS|jD]+}t|dr|j,dS)N_filters_mutatedr)rrr3 _tmp_modulesrr )rr,s rF_clear_registriesz#suppress_warnings._clear_registries(sr 8/ 0 0   % ' ' ' F' 3 3Fv455 3*00222 3 3rErRNFc|rg}nd}|jr|tjd||nd|jdddz}tjd||||j|||j ||tj |tj ||fn<|j ||tj |tj ||f|S)Nrcategorymessage.\.$r8r9r,)r.rfilterwarningsr@replacer4addr5_tmp_suppressionsrrrIr/)rr8r9r,r module_regexs rF_filterzsuppress_warnings._filter4sA  FFF = P~'xBBBBB &66sEBBSH 'x'))))!%%f---&&(((  " ) )7BJw$=$=vvN P P P P   % %7BJw$=$=vvN P P P rEc8||||ddS)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. Fr8r9r,rNrDrr8r9r,s rFfilterzsuppress_warnings.filterMs2( h!  # # # # #rEc4||||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. TrFrGrHs rFrzsuppress_warnings.recordds(6||Xwv#')) )rEcj|jrtdtj|_tj|_|jddt_d|_g|_t|_ t|_ g|_ |j D]y\}}}}}||dd=|tj d||)|jdddz}tj d||||j |z|jt_||S) Nz%cannot enter suppress_warnings twice.Trr7r:r;r<r=)r. RuntimeErrorr showwarning _orig_showfilters_filtersrArr4 _forwardedlogr/r>r@r?r@ _showwarningr5)rcatmessrr"rRrCs rFr!zsuppress_warnings.__enter__sH = HFGG G". ( =+ !#EE%%&*&8 + + "Cq#sF{'sD::::: #|33C??#E 'sD'))))!%%c****#0     rEc|jt_|jt_|d|_|`|`dS)NF)rNrrMrPrOr5r.)rr's rFr%zsuppress_warnings.__exit__s=#=     O MMMrE) use_warnmsgc|j|jzdddD]\}} } } } t||r| |jd| D| ?t ||||fi|} |j| | | dS| j |rD| ?t ||||fi|} |j| | | dS|j dkr.||j ||||g|Ri|n| |dS|j dkr |j|f}n,|j dkr |j||f}n|j dkr |j|||f}||j vrdS|j |||j ||||g|Ri|dS| |dS)Nr\rrr+r,r-)r/rA issubclassmatchrrrRrr^rSr0rN _orig_showmsgrQr@)rr9r8rmlinenorWrrrTrpatternr"recrX signatures rFrSzsuppress_warnings._showwarningsz"T%;;TTrT*C   %CGS#8S)) MM',q/22>;,Wh-3??7=??,,, 3FF\,,X66,Wh-3??7=??,,, 3FF  H , ,"8V1!%111)/1111"";/// F  F * * x0II  "h . . x:II  "j 0 0 x6BI  ' ' F I&&&   DOGXx &$ & & &$ & & & & &   { + + + + +rEc@tfd}|S)z_ Function decorator to apply certain suppressions to a whole function. cL5|i|cdddS#1swxYwYdSrrD)rrrrs rFnew_funcz,suppress_warnings.__call__..new_funcs - -tT,V,, - - - - - - - - - - - - - - - - - -s r)rrrbs`` rF__call__zsuppress_warnings.__call__s; t - - - - -  -rE)r)r@rArBrCrr5WarningrDrIrr!r%rSrdrDrErFr5r5sHHR0000 3 3 3 '42&r$####.&r$))))<@)-1,1,1,1,1,f     rEr5c #TKd}tsdVdSttjtjtj} t dD]}tjdkrntdtj tj dVtj}tj dd}tj dd=tj |tj n;#tj dd=tj |tj wxYw|rX|d|nd}td||t|dd|DdS) NTrrz]Unable to fully collect garbage - perhaps a __del__ method is creating more reference cycles?rrRzXReference cycles were found{}: {} objects were collected, of which {} are shown below:{}c 3K|]`}dt|jt|t j|ddVadS)z {} object with id={}: {}rz N)rkrpr@idrpformatr?)rrs rF z/_assert_no_gc_cycles_context.. sz  8>>Q(1q))11$AArE)r3r&r isenabledr get_debugrcollectrL set_debug DEBUG_SAVEALLgarbagerrVrkrr)rorYgc_debugrn_objects_in_cyclesobjects_in_cyclesrs rF_assert_no_gc_cycles_contextrts   BLNNJLLL|~~Hs 6 6Az||q  !566 6 R%&&& !jllJqqqM JqqqM X  JqqqM X  .2.>*D***B - V#%&& 1        s BD8E c|stS|d}|dd}t|j5||i|ddddS#1swxYwYdS)a3 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. rrNr)rtr@rs rFr7r7 s4 .+--- 7D 8D %4= 9 9 9 dfs AAActjtrNtjtjtjtjdSdS)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)rrmr2rDrErFr8r8A sQJLLL    rEcddlfd}|S)z:Decorator to skip a test if not enough memory is availablerNcBtfd}|S)Nct}|| |i|S#t$rdYdSwxYw)NzMemoryError raised)check_free_memoryskip MemoryErrorxfail)rkwrX free_bytesrpytests rFwrapperz3requires_memory..decorator..wrapperX su#J//C C    3tQ~"~~% 3 3 3 1222222 3s1AArc)rrrrs` rFrz"requires_memory..decoratorW s> t 3 3 3 3 3 3  3rE)r)rrrs` @rFrequires_memoryrS s3MMM       rEc*d}tj|}|D t|}n'#t$r}t d|d|d}~wwxYw|dz d|d}n#t }|d}d }n|dz d |dz d }||kr|ndS) 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.r\z GB memory required, but z GB available)rfenvironget _parse_sizer_get_mem_available)renv_var env_valuemem_freerrXs rFrzrzi s "G w''I O"9--HH O O OMWMMMMNN N OS.44$-444&''  CHH^YYhslYYYCZ''33T1s5 AAAcdddddddddddddd d }tjd d |tj}||}|r|d |vrtd|dtt|d||d zS)z3Convert memory size strings ('12 GB' etc.) to floatrii@Biʚ;lJ)ii@l)rRrrrprrkbmbgbtbkibmibgibtibz^\s*(\d+|\d+\.\d+)\s*({0})\s*$|rOzvalue z not a valid size) rrrkrkeysrBrZlowergrouprr~r)size_strsuffixessize_rerps rFrr sAgG'GGGMMH j:AA !!##$&D**G  hnn&&''A A (**?(???@@@ uQWWQZZ  8AGGAJJ#77 8 88rEc ddl}|jS#ttf$rYnwxYwt jdri}td5}|D]\}| }t|ddz||d d <] dddn #1swxYwYd|vr|dS|d |d zSdS) z5Return available memory in bytes, or None if unknown.rNrwz /proc/meminforr: memavailablememfreecached) psutilvirtual_memory available ImportErrorrrcplatformrSr{r}r~stripr)rinforlineps rFrr sc  $$&&00  (      |w'' 4 / " " Aa A AJJLL03AaD D0@QqTZZ__**,,-- A A A A A A A A A A A A A A A A T ! !' ' ?T(^3 3 4s33&A CCCcjttdsStfd}|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)rcrsettrace)rroriginal_tracers rFrz_no_tracing..wrapper s^ \^^N - T"""tT,V,, ^,,,, ^,,,,s AA)rrcr)rrs` rF _no_tracingr sL 3 # #  t - - - -  -rEc tjddd}n#t$rd}YnwxYw|S)NCS_GNU_LIBC_VERSIONryr0.0)rfconfstrrsplitr)vers rF_get_glibc_versionr sWj.//66s;;A>  Js -0 ??c.tdko t|kS)Nr) _glibcverrs rFrPrP syE1Ci!mrE)rR)Nr\NN)rrr)rTrr)rRT)rrRT)rRTrRrTT)rrRT)NTr)rN)rrTrRT)r)vrCrfrcrrrr9r functoolsrrr rtempfilerr unittest.caserrr sysconfigrrNrr r r r r rrrrrrnumpy.linalg.lapack_liteior__all__rr/KnownFailureTestr$rlr4implementationror2rr:r!r3linalg lapack_lite_ilp64r9r;r<get_config_var_vr&rqr getpidrrrr!_no_nep50_warningrrr6rrrr#rr"r~r=unittestTestCaserrrr(rr%rr,r'r)rrrcontextmanagerrr*rr+rr-r1r0rr.r5rtr7r8rrzrrrrr_glibc_older_thanrDrErFrs  $$$$$$$$ %%%%%%%%""""""###### FFFFFFFFFFFFFFFFFFFF((((((((((       I   )  (    4 4  !V + GC. / / wsM400<NY |'. >>  Yo..4" R<<G####(7d??;??C$$$$6EEEEE  \"1"  ; ; ; ;     """<w:  :::r88888* 4 4 4 4+AGH8]]]]@&-&-&-R{/{/{/{/|@B $a"a"a"a"HLN@Dc#(cccccLr(r(r(r(r(r(jn n n n bL*L*L*L*^D"D"D"N+K+K+K+K\   "!##      X     VE]],,,:SSS*, , , , ^++++\   4CG(,CNCNCNCNL<"<"<"<"~1111h<<<<~    9 9 9 AAAA3%3%3%l AAAA!%!%!%H&HrB;B;B;B;J     i        *?J?J?J?J?Jx6?J?J?JDSSSSSSSSl 0 0 0 0 f   F$,222: 9 9 9 0(   DDrE