o 6a M@sdZddlZddlZddlZddlZddlZddlZddlZddlm Z m Z ddl Z ddl Z ddl mZmZddlmZddlmZddlZddlZddlmZmZmZmZmZmZmZmZddlZddl m!Z!gd Z"Gd d d e#Z$e$Z%dZ&e'd kZ(e)ed dduZ*ej+j,j-Z.ddZ/dddZ0ddZ1ddZ2ddZ3ej4dkr  dddZ5dddZ6nejdd d!krd"e7d#fd$dZ6nd%dZ6ejdd d!krd"e7d#gfd&d'Z8ngfd(d'Z8 ) ,dd-d.Z9dd/d0Z:d1d2Z;dd4d5Zdd;d<Z?dd=d>Z@dd?d@ZAdAdBZBdCdDZCddEdFZDdGdHZEddlFZFGdIdJdJeFjGZHeHdKZIdLdMZJdNdOZKddPdQZLddSdTZMdUdVZN * *ddXdYZOddZd[ZPdd\d]ZQdd^d_ZRd`daZSdbdcZTe jUddddeZVdfdgZWe jUddhdiZXdjdkZYedldmfdndoZZGdpdqdqe#Z[e jUdrdsZ\e jUdtduZ]Gdvdwdwej^Z_GdxdydyZ`e jUddzd{Zad|d}Zbd~dZcddZdddZeddZfddZgddZhdS)z* Utility function to facilitate testing. N)partialwraps)mkdtempmkstemp)SkipTest)WarningMessage)intpfloat32emptyarange array_reprndarrayisnatarray)StringIO)( assert_equalassert_almost_equalassert_approx_equalassert_array_equalassert_array_lessassert_string_equalassert_array_almost_equal assert_raises build_err_msgdecorate_methodsjiffiesmemusageprint_assert_equalraisesrundocs runstringverbosemeasureassert_assert_array_almost_equal_nulpassert_raises_regexassert_array_max_ulp assert_warnsassert_no_warningsassert_allcloseIgnoreExceptionclear_and_catch_warningsrKnownFailureExceptiontemppathtempdirIS_PYPY HAS_REFCOUNTsuppress_warningsassert_array_compare_assert_valid_refcount_gen_alignment_dataassert_no_gc_cycles break_cycles HAS_LAPACK64c@eZdZdZdS)r,zr>>/usr/lib/python3/dist-packages/numpy/testing/_private/utils.pyr,+r,PyPy getrefcountcCsRd}d}zddl}Wn tyd}Ynw|j|krd}|s'd|}t||S)z# Import nose only when needed. T)rrrNFzANeed nose >= %d.%d.%d for tests - see https://nose.readthedocs.io)nose ImportError__versioninfo__) nose_is_goodminimum_nose_versionrDmsgr>r>r? import_nose8s   rJcCs:d}|sz|}Wt|ty|}Yt|wdS)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)valrI__tracebackhide__smsgr>r>r?r#Ns  r#cCs.ddlm}||}t|ttrtd|S)alike isnan, but always raise an error if type not supported instead of returning a TypeError object. Notes ----- isnan and other ufunc sometimes return a NotImplementedType object instead of raising any exception. This function is a wrapper to make sure an exception is always raised. This should be removed once this problem is solved at the Ufunc level.r)isnanz!isnan not supported for this type) numpy.corerQ isinstancetypeNotImplementedrL)xrQstr>r>r?gisnanbs rXcC^ddlm}m}|dd||}t|ttrtdWd|S1s(wY|S)alike isfinite, but always raise an error if type not supported instead of returning a TypeError object. Notes ----- isfinite and other ufunc sometimes return a NotImplementedType object instead of raising any exception. This function is a wrapper to make sure an exception is always raised. This should be removed once this problem is solved at the Ufunc level.r)isfiniteerrstateignoreinvalidz$isfinite not supported for this typeN)rRrZr[rSrTrUrL)rVrZr[rWr>r>r? gisfinitet  r_cCrY)alike isinf, but always raise an error if type not supported instead of returning a TypeError object. Notes ----- isinf and other ufunc sometimes return a NotImplementedType object instead of raising any exception. This function is a wrapper to make sure an exception is always raised. This should be removed once this problem is solved at the Ufunc level.r)isinfr[r\r]z!isinf not supported for this typeN)rRrar[rSrTrUrL)rVrar[rWr>r>r?gisinfr`rbntc Csddl}|dur |j}||||d||f}|}z(|||} z|||| |\} } | W|| W||S|| w||w)Nr) win32pdh PDH_FMT_LONGMakeCounterPath OpenQuery AddCounterCollectQueryDataGetFormattedCounterValue RemoveCounter CloseQuery) objectcounterinstanceinumformatmachinerepathhqhcrTrNr>r>r?GetPerformanceAttributess"       rwpythoncCsddl}tdd|||jdS)NrProcessz Virtual Bytes)rerwrf) processNamerprer>r>r?rs rlinuxz/proc/z/statcCs\z#t|d}|d}Wdn1swYt|dWSty-YdSw)zM Return virtual memory size in bytes of the running python. r N)openreadlinesplitint Exception)_proc_pid_statflr>r>r?rs  cCst)zK Return memory usage of running python. [Not implemented] )NotImplementedErrorr>r>r>r?rscCsddl}|s ||z#t|d}|d}Wdn1s%wYt|dWStyEtd||dYSw) 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. rNr}r~ d)timeappendrrrrr)r _load_timerrrr>r>r?rs  rcCs2ddl}|s ||td||dS)rrNr)rrr)rrr>r>r?rsItems are not equal:TACTUALDESIREDc Csd|g}|r'|ddkr"t|dt|kr"|dd|g}n|||rt|D]Z\}}t|tr=tt|d} nt} z| |} Wnt yc} zdt |j d| d } WYd} ~ nd} ~ ww| dd krzd | dd } | d 7} |d||d | q-d |S) N rdOrr~) precisionz[repr failed for : ]z...: )findlenr enumeraterSr rr reprrrTr:countjoin splitlines) arrayserr_msgheaderr!namesrrIiar_funcr}excr>r>r?rs* "   $ rc Csxd}t|trEt|tsttt|tt|t||||D]\}}||vr1tt|t||||d|d||q#dSt|tt frzt|tt frztt|t|||t t|D]}t||||d|d||qddSddl m }m }m} ddlm} m} m} t||st||rt||||St||g||d } z | |p| |}Wn ttfyd }Ynw|r| |r| |}| |}n|}d}| |r| |}| |}n|}d}z t||t||Wn tyt| w||||kr t| z(t|}t|}t|jjt|jjk}|r0|r0|r,WdSt| Wn tttfy>YnwzFt|}t|}|rQ|rQWdSt|}t|}|jjd vsi|jjd vrmtd |dkr|dkr| || |kst| Wn tttfyYnwz ||kst| WdSttfy}z d |j dvrt| d}~ww)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)r isscalarsignbit iscomplexobjrealimagr!FMmz0cannot compare to a scalar with a different typezelementwise == comparison)!rSdictrMrrTrritemslisttuplerangerRr rr numpy.librrrrr ValueErrorrLrnpasarraydtyperrXcharDeprecationWarning FutureWarningargs)actualdesiredrr!rOkrr rrrrrrI usecomplexactualractualidesiredrdesirediisdesnatisactnat dtypes_matchisdesnanisactnan array_actual array_desireder>r>r?rs2              rcCs`d}ddl}||ks.t}|||d||||d|||t|dS)a Test if two objects are equal, and print an error message if test fails. The test is performed with ``actual == desired``. Parameters ---------- test_string : str The message supplied to AssertionError. actual : object The object to test for equality against `desired`. desired : object The expected result. Examples -------- >>> np.testing.print_assert_equal('Test XYZ of func xyz', [0, 1], [0, 1]) >>> np.testing.print_assert_equal('Test XYZ of func xyz', [0, 1], [0, 2]) Traceback (most recent call last): ... AssertionError: Test XYZ of func xyz failed ACTUAL: [0, 1] DESIRED: [0, 2] TrNz failed ACTUAL: z DESIRED: )pprintrwriterMgetvalue) test_stringrrrOrrIr>r>r?rs      rc sd}ddlm}ddlm}m}m} z |p|} Wn ty'd} Ynwfdd} | rs|rA|} | } n} d} |rR|}| }n}d}zt| |dt| |dWn tyrt| wt |t t fst |t t frt Sz.t rt ststrtrtst| Wd Skst| Wd SWn ttfyYnwtd d  krt| d S) 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) < 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)r rFcsd}tg|dS)N*Arrays are not almost equal to %d decimals)r!r)r)rrdecimalrrr!r>r?_build_err_msg-s z+assert_almost_equal.._build_err_msg)rN?$@)rRr rrrrrrrMrSrrrr_rXrrLabs)rrrrr!rOr rrrrrrrrrr>rr?rs\E         rc Csd}ddl}tt||f\}}||krdS|jdd d||||}|d|||}Wdn1s>wYz||}Wn tyTd}Ynwz||} Wn tyfd} Ynwt ||g|d ||d } z,t |r|t |st |st |rt |rt |st | WdS||kst | WdSWn t tfyYnw||| |d |d  krt | dS) aa Raises an AssertionError if two items are not equal up to significant digits. .. note:: It is recommended to use one of `assert_allclose`, `assert_array_almost_equal_nulp` or `assert_array_max_ulp` instead of this function for more consistent floating point comparisons. Given two numbers, check that they are approximately equal. Approximately equal is defined as the number of significant digits that agree. Parameters ---------- actual : scalar The object to check. desired : scalar The expected object. significant : int, optional Desired precision, default is 7. err_msg : str, optional The error message to be printed in case of failure. verbose : bool, optional If True, the conflicting values are appended to the error message. Raises ------ AssertionError If actual and desired are not equal up to specified precision. See Also -------- assert_allclose: Compare two array_like objects for equality with desired relative and/or absolute precision. assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal Examples -------- >>> np.testing.assert_approx_equal(0.12345677777777e-20, 0.1234567e-20) >>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345671e-20, ... significant=8) >>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345672e-20, ... significant=8) Traceback (most recent call last): ... AssertionError: Items are not equal to 8 significant digits: ACTUAL: 1.234567e-21 DESIRED: 1.2345672e-21 the evaluated condition that raises the exception is >>> abs(0.12345670e-20/1e-21 - 0.12345672e-20/1e-21) >= 10**-(8-1) True TrNr\r]g? gz-Items are not equal to %d significant digits:)rr!rrC)numpymapfloatr[rpowerfloorlog10ZeroDivisionErrorrr_rXrMrLr) rr significantrr!rOrscale sc_desired sc_actualrIr>r>r?rZsP:     rc % sd} ddlm} m} m} mmm} m}m}m }t |}t |}||}}dd}dd}| dffd d }z|j d kpM|j d kpM|j |j k}|skt ||gd |j d |j ddd}t|d}||r||r|r|||| dd}|r||||fddddO}||||fddddO}n||r||r|r|jj|jjkr|||tdd}|jdkr||||}}|jdkrWdSn|rWdS|||}t|tr|}| |g}n|}|}|dkr|j|jtd}|jdkr |jn|j}d||}d|||g}| ddd}ttgt||}||} t|d||krD|dt | n |d| | |dk}!||!r^| }"n |||!t||!}"t|d||kr}|d t |"n |d | |"Wdn 1swYWdn 1swYd!d!!|7t ||gdd}t|WdSt"yddl#}#|#$}$d"|$d#t ||gdd}t"|w)$NTr) r array2stringrQinfbool_r[allmaxobject_cS |jjdvS)Nz?bhilqpBHILQPefdgFDGrrrVr>r>r?isnumber z&assert_array_compare..isnumbercSr)Nrrrr>r>r?istimerz$assert_array_compare..istimenancsd}||}||}||kdkr(t||gd|dd}t|t|ts2|jdkr6|St|ts@|jdkrD|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:rVyr!rrrr)rrrMrSboolndim)rVrfunchasvalrOx_idy_idrI)rrrrr!r>r?func_assert_same_poss" z2assert_array_compare..func_assert_same_posr>z (shapes z, z mismatch)rrF)rrcs | kSNr>xyrr>r? z&assert_array_compare..z+infcs | kSrr>rrr>r?rrz-infNaTrrz&Mismatched elements: {} / {} ({:.3g}%)r\)r^dividerzMax absolute difference: zMax relative difference: rzerror during assertion: z )%rRrrrQrrr[rrrr asanyarrayshaperrMrrTrrsizerSrravelsumrrr contextlibsuppressrLrgetattrrstrrr traceback format_exc)% comparisonrVrrr!rr equal_nan equal_infrOrrrQr[rrroxoyrrrcondrIflaggedrNreduced n_mismatch n_elementspercent_mismatchremarkserror max_abs_errornonzero max_rel_errorrefmtr>)rrrrrr!r?r2s,   %                (r2cCsd}ttj||||dddS)al 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. Parameters ---------- x : array_like The actual object to check. y : 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. 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 `x` and `y` 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 -------- 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: 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) TzArrays are not equal)rr!rN)r2operator__eq__rVrrr!rOr>r>r?rWsN  rc shd}ddlmmmm}ddlmddlmfdd}t |||||dd d S) a Raises an AssertionError if two objects are not equal up to desired precision. .. note:: It is recommended to use one of `assert_allclose`, `assert_array_almost_equal_nulp` or `assert_array_max_ulp` instead of this function for more consistent floating point comparisons. The test verifies identical shapes and that the elements of ``actual`` and ``desired`` satisfy. ``abs(desired-actual) < 1.5 * 10**(-decimal)`` That is a looser test than originally documented, but agrees with what the actual implementation did up to rounding vagaries. An exception is raised at shape mismatch or conflicting values. In contrast to the standard usage in numpy, NaNs are compared like numbers, no assertion is raised if both objects have NaNs in the same positions. Parameters ---------- 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_typer) issubdtype)anyc sz<t|s t|r;t|}t|}||ksWdS|j|jkr*dkr1nn||kWS||}||}Wn ttfyGYnw|d}t||}t||}|jsd| }|dd kS)NFrCg?rr) rbrr rLrrrrrastype)rVrxinfidyinfidrzrr(r*npanyr'r)r>r?compares(         z*assert_array_almost_equal..comparer)rr!rrN) rRr'r(r)rnumpy.core.numerictypesr*numpy.core.fromnumericr+r2)rVrrrr!rOrr2r>r0r?rsM    rc Cs d}ttj||||ddddS)ag 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 actual and desired objects are not equal. 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!rrN)r2r$__lt__r&r>r>r?rs L  rcCst||dSr)exec)astrrr>r>r?r nsr c Cstd}ddl}t|tsttt|t|ts ttt|||kr&dSt|| d| d}g}|r| d}| drEq8| dr|g}| d}| dra| || d}| dsltt|| ||r| d} | dr| | n| d| |dd|ddkrq8||q8tt||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: rK)difflibrSrrMrrTrDifferr2rpop startswithrinsertextendrrstrip) rrrOr9diff diff_listd1rd2d3rIr>r>r?rrsR                  rc sddlm}ddl}|durtd}|jd}tjtj |d}|||}| |}|j dd}g|rAfdd } nd} |D] } |j | | d qE|jdkr_|ratd d dSdS) 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_locationNrC__file__Frcs |Sr)r)srIr>r?rrzrundocs..)outzSome doctests failed: %sr)numpy.distutils.misc_utilrEdoctestsys _getframe f_globalsosrtsplitextbasename DocTestFinderr DocTestRunnerrunfailuresrMr) filenameraise_on_errorrErKrnamemtestsrunnerrItestr>rHr?rs$     rcGst}|jj|S)aDecorator to check for raised exceptions. The decorated test function must raise one of the passed exceptions to pass. If you want to test many assertions about exceptions in a single test, you may want to use `assert_raises` instead. .. warning:: This decorator is nose specific, do not use it if you are using a different test framework. Parameters ---------- args : exceptions The test passes if any of the passed exceptions is raised. Raises ------ AssertionError Examples -------- Usage:: @raises(TypeError, ValueError) def test_raises_type_error(): raise TypeError("This test passes") @raises(Exception) def test_that_fails_by_passing(): pass )rJtoolsr)rrDr>r>r?rs" rc@seZdZddZdS)_DummycCsdSrr>)selfr>r>r?nopsz _Dummy.nopN)r:r;r<r`r>r>r>r?r^s r^r`cOsd}tj|i|S)a assert_raises(exception_class, callable, *args, **kwargs) assert_raises(exception_class) Fail unless an exception of class exception_class is thrown by callable when invoked with arguments args and keyword arguments kwargs. If a different type of exception is thrown, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception. Alternatively, `assert_raises` can be used as a context manager: >>> from numpy.testing import assert_raises >>> with assert_raises(ZeroDivisionError): ... 1 / 0 is equivalent to >>> def div(x, y): ... return x / y >>> assert_raises(ZeroDivisionError, div, 1, 0) T)_d assertRaises)rkwargsrOr>r>r?rsrcOsd}tj||g|Ri|S)aY 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`. Name of this function adheres to Python 3.2+ reference, but should work in all versions down to 2.6. Notes ----- .. versionadded:: 1.9.0 T)raassertRaisesRegex)exception_classexpected_regexprrcrOr>r>r?r%5sr%c s|dur tdtj}nt|}|j}ddlmfdd|D}|D],}zt|dr4|j }n|j }Wn t yAYq(w| |rT| dsTt||||q(dS) a  Apply a decorator to all methods in a class matching a regular expression. The given decorator is applied to all public methods of `cls` that are matched by the regular expression `testmatch` (``testmatch.search(methodname)``). Methods that are private, i.e. start with an underscore, are ignored. Parameters ---------- cls : class Class whose methods to decorate. decorator : function Decorator to apply to methods testmatch : compiled regexp or str, optional The regular expression. Default value is None, in which case the nose default (``re.compile(r'(?:^|[\b_\.%s-])[Tt]est' % os.sep)``) is used. If `testmatch` is a string, it is compiled to a regular expression first. Nz(?:^|[\\b_\\.%s-])[Tt]estr isfunctioncsg|]}|r|qSr>r>).0_mrgr>r? msz$decorate_methods..compat_func_name_)recompilerOsep__dict__inspectrhvalueshasattrrlr:AttributeErrorsearchr<setattr)cls decorator testmatchcls_attrmethodsfunctionfuncnamer>rgr?rMs&    rrCc Csltd}|j|j}}t|d|dd}d}t}||kr-|d7}t|||||kst|}d|S)aG Return elapsed time for executing code in the namespace of the caller. The supplied code string is compiled with the Python builtin ``compile``. The precision of the timing is 10 milli-seconds. If the code will execute fast on this timescale, it can be executed many times to get reasonable timing accuracy. Parameters ---------- code_str : str The code to be timed. times : int, optional The number of times the code is executed. Default is 1. The code is only compiled once. label : str, optional A label to identify `code_str` with. This is passed into ``compile`` as the second argument (for run-time error messages). Returns ------- elapsed : float Total elapsed time in seconds for executing `code_str` `times` times. Examples -------- >>> times = 10 >>> etime = np.testing.measure('for i in range(1000): np.sqrt(i**2)', times=times) >>> print("Time for a single execution : ", etime / times, "s") # doctest: +SKIP Time for a single execution : 0.005 s rCz Test name: r~r6rg{Gz?)rLrMf_localsrNrorr6) code_strtimeslabelframelocsglobscoderelapsedr>r>r?r"|s !  r"c CstsdSddl}ddl}|ddd}|}d}|z"t|}tdD]}|||}q't t||kW| ~dS| w)zg Check that ufuncs don't mishandle refcount of object `1`. Used in a few regression tests. TrNi'rrC) r0gcrr reshapedisablerLrBrr#enable) oprrbcrrcjdr>r>r?r3s     r3Hz>c sfd}ddlfdd}||}}dddd} t|||t||| d dS) a Raises an AssertionError if two objects are not equal up to desired tolerance. 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 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) TrNcsjjj||dS)N)rtolatolr)corenumericiscloserrrrrr>r?r2sz assert_allclose..comparezNot equal to tolerance rtol=gz, atol=)rr!rr)rrr2r) rrrrrrr!rOr2rr>rr?r)s- r)c Csd}ddl}||}||}|||||k||}|||||ksN||s4||r>> 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_diffrM) rVrnulprOraxayrefrImax_nulpr>r>r?r$s1   r$cCs@d}ddl}t|||}|||kstd|||f|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))rrrrMr)rrmaxulprrOrretr>r>r?r&=s*  r&csddl|rj||d}j||d}n |}|}||}|s/|r3tdj|g|d}j|g|d}j||<j||<|j|jksct d|j|jffdd}t |}t |}||||S)anFor each item in x and y, return the number of representable floating points between them. Parameters ---------- x : array_like first input array y : array_like second input array dtype : dtype, optional Data-type to convert `x` and `y` to if given. Default is None. Returns ------- nulp : array_like number of representable floating point numbers between each item in x and y. Notes ----- For computing the ULP difference, this API does not differentiate between various representations of NAN (ULP difference between 0x7fc00000 and 0xffc00000 is zero). Examples -------- # By definition, epsilon is the smallest number such as 1 + eps != 1, so # there should be exactly one ULP between 1 and 1 + eps >>> nulp_diff(1, 1 + np.finfo(x.dtype).eps) 1.0 rNrz'_nulp not implemented for complex arrayz+x and y do not have the same shape: %s - %scsj|||d}|SNr)rr)rxryvdtr@rr>r?_diffs znulp_diff.._diff) rr common_typerrrrrQr r integer_repr)rVrrtrrrr>rr?rqs*        rcCsD||}|jdks|||dk||dk<|S|dkr ||}|S)NrCr)viewr )rVrcomprr>r>r? _integer_reprs  rcCsxddl}|j|jkrt||j|dS|j|jkr$t||j|dS|j|jkr4t||j|dSt d|j)zQReturn the signed-magnitude interpretation of the binary representation of x.rNiilzUnsupported dtype ) rrfloat16rint16r int32float64int64r)rVrr>r>r?rs   rccspd}t(}||}dVt|dks&|durd|nd}td|WddS1s1wYdS)NTr when calling rKzNo warning raised)r1recordrrM) warning_classrXrOsuprname_strr>r>r?_assert_warns_contexts   "rcOs`|st|S|d}|dd}t||jd||i|WdS1s)wYdS)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 rrCNrX)rr:)rrrcrr>r>r?r's-  $r'ccs~d}tjdd,}tddVt|dkr-|dur!d|nd}td|d|WddS1s8wYdS) NTralwaysrrrKz Got warningsr)warningscatch_warnings simplefilterrrM)rXrOrrr>r>r?_assert_no_warnings_contexts  "rcOs\|stS|d}|dd}t|jd||i|WdS1s'wYdS)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`. rrCNr)rr:rrcrr>r>r?r(s  $r(binaryc #sd}d}tdD]щtdtd|D]|dkrfdd}tfdd }|||d ffV|}|||d ffV|d d |d d |d d d ffV|d d |d d |d d d ffV|d d |d d |d d dffV|d d |d d |d d dffV|dkrڇfdd}fdd} tfdd }||| |d ffV|}||| |dffV| }||||dffV|d d |d d | d d |d d d ffV|d d |d d | d d |d d d ffV|d d |d d | d d |d d d ffV|d d |d d | d d |d d dffV|d d |d d | d d |d d dffV|d d |d d | d d |d d dffVqq d S)a generator producing data with different alignment and offsets to test simd vectorization Parameters ---------- dtype : dtype data type to produce type : string 'unary': create data for unary operations, creates one input and output array 'binary': create data for unary operations, creates two input and output array max_size : integer maximum size of data to produce Returns ------- if type is 'unary' yields one output, one input array and a message containing information on the data if type is 'binary' yields one output array, two input array and a message containing information on the data z,unary offset=(%d, %d), size=%d, dtype=%r, %sz1binary offset=(%d, %d, %d), size=%d, dtype=%r, %srr8unaryctddSrr r>rorGr>r?r[z%_gen_alignment_data..rNz out of placezin placerCrdaliasedrcrrrr>rr>r?rircrrrr>rr>r?rjrz in place1z in place2)rrr ) rrTmax_sizeufmtbfmtinprIrinp1inp2r>rr?r4=sv    $$$&&&r4c@r8)r*z/Ignoring this exception due to disabled featureNr9r>r>r>r?r*r@r*c os4t|i|}z |VWt|dSt|w)zContext manager to provide a temporary test folder. All arguments are passed as this to the underlying tempfile.mkdtemp function. N)rshutilrmtree)rrctmpdirr>r>r?r.s r.c osBt|i|\}}t|z |VWt|dSt|w)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)rrOcloseremove)rrcfdrtr>r>r?r-s  r-cs>eZdZdZdZd fdd ZfddZfdd ZZS) r+a< Context manager that resets warning registry for catching warnings Warnings can be slippery, because, whenever a warning is triggered, Python adds a ``__warningregistry__`` member to the *calling* module. This makes it impossible to retrigger the warning in this module, whatever you put in the warnings filters. This context manager accepts a sequence of `modules` as a keyword argument to its constructor and: * stores and removes any ``__warningregistry__`` entries in given `modules` on entry; * resets ``__warningregistry__`` to its previous state on exit. This makes it possible to trigger any warning afresh inside the context manager without disturbing the state of warnings outside. For compatibility with Python 3.0, please consider all arguments to be keyword-only. Parameters ---------- record : bool, optional Specifies whether warnings should be captured by a custom implementation of ``warnings.showwarning()`` and be appended to a list returned by the context manager. Otherwise None is returned by the context manager. The objects appended to the list are arguments whose attributes mirror the arguments to ``showwarning()``. modules : sequence, optional Sequence of modules for which to reset warnings registry on entry and restore on exit. To work correctly, all 'ignore' filters should filter by one of these modules. Examples -------- >>> import warnings >>> with np.testing.clear_and_catch_warnings( ... modules=[np.core.fromnumeric]): ... warnings.simplefilter('always') ... warnings.filterwarnings('ignore', module='np.core.fromnumeric') ... # do something that raises a warning but ignore those in ... # np.core.fromnumeric r>Fcs*t||j|_i|_tj|ddS)Nr)setunion class_modulesmodules_warnreg_copiessuper__init__)r_rr __class__r>r?rsz!clear_and_catch_warnings.__init__cs<|jD]}t|dr|j}||j|<|qtSN__warningregistry__)rrtrcopyrclearr __enter__)r_modmod_regrr>r?rs   z"clear_and_catch_warnings.__enter__csLtj||jD]}t|dr|j||jvr#|j|j|q dSr)r__exit__rrtrrrupdate)r_exc_inforrr>r?rs     z!clear_and_catch_warnings.__exit__)Fr>) r:r;r<r=rrrr __classcell__r>r>rr?r+s ) r+c@szeZdZdZdddZddZeddd fd d Zeddfd d ZeddfddZ ddZ ddZ ddddZ ddZ dS)r1a 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 rcCs&d|_g|_|dvrtd||_dS)NF>oncermodulelocationzunsupported forwarding rule.)_entered _suppressionsr_forwarding_rule)r_forwarding_ruler>r>r?r8s  zsuppress_warnings.__init__cCs:ttdr tdS|jD] }t|dr|jqdS)N_filters_mutatedr)rtrr _tmp_modulesrr)r_rr>r>r?_clear_registriesBs    z#suppress_warnings._clear_registriesrKNFcCs|rg}nd}|jrE|durtjd||dn|jddd}tjd|||d|j|||j ||t |t j ||f|S|j ||t |t j ||f|S)Nrcategorymessage.\.$rrr)rrfilterwarningsr:replaceraddr_tmp_suppressionsrrnroIr)r_rrrr module_regexr>r>r?_filterNs. zsuppress_warnings._filtercCs|j|||dddS)a Add a new suppressing filter or apply it if the state is entered. Parameters ---------- category : class, optional Warning class to filter message : string, optional Regular expression matching the warning message. module : module, optional Module to filter for. Note that the module (and its file) must match exactly and cannot be a submodule. This may make it unreliable for external modules. Notes ----- When added within a context, filters are only added inside the context and will be forgotten when the context is exited. FrrrrNrr_rrrr>r>r?filtergs  zsuppress_warnings.filtercCs|j|||ddS)ai Append a new recording filter or apply it if the state is entered. All warnings matching will be appended to the ``log`` attribute. Parameters ---------- category : class, optional Warning class to filter message : string, optional Regular expression matching the warning message. module : module, optional Module to filter for. Note that the module (and its file) must match exactly and cannot be a submodule. This may make it unreliable for external modules. Returns ------- log : list A list which will be filled with all matched warnings. Notes ----- When added within a context, filters are only added inside the context and will be forgotten when the context is exited. Trrrr>r>r?r~s zsuppress_warnings.recordcCs|jrtdtj|_tj|_|jddt_d|_g|_t|_ t|_ g|_ |j D]5\}}}}}|dur;|dd=|durHtj d||dq+|jddd}tj d|||d|j |q+|jt_||S) Nz%cannot enter suppress_warnings twice.Trrrrrr)r RuntimeErrorr showwarning _orig_showfilters_filtersrrr _forwardedlogrrr:rr _showwarningr)r_catmessrmrrrr>r>r?rs4 zsuppress_warnings.__enter__cGs*|jt_|jt_|d|_|`|`dS)NF)r rr r r rr)r_rr>r>r?rs zsuppress_warnings.__exit__) use_warnmsgcOs|j|jdddD]Z\}} } } } t||re| |jddure| durB| dur?t||||fi|} |j| | | dS| j |re| durbt||||fi|} |j| | | dSq |j dkr|dur|j ||||g|Ri|dS| |dS|j dkr|j|f}n|j dkr|j||f}n |j dkr|j|||f}||j vrdS|j ||dur|j ||||g|Ri|dS| |dS)Nrdrrrrr)rr issubclassmatchrrrrrFr<rr  _orig_showmsgrr)r_rrrVlinenorrrcrrmpatternrrecrI signaturer>r>r?rsb               zsuppress_warnings._showwarningcstfdd}|S)z_ Function decorator to apply certain suppressions to a whole function. cs6|i|WdS1swYdSrr>)rrcrr_r>r?new_funcs $z,suppress_warnings.__call__..new_funcr)r_rrr>rr?__call__szsuppress_warnings.__call__)r)r:r;r<r=rrWarningrrrrrrrr>r>r>r?r1s I    3r1c csd}ts dVdStttt}z8tdD] }tdkr'nqtdt tj dVt}tj dd}Wtj dd=t |t ntj dd=t |t w|r|durld|nd}t d||t|ddd |DdS) NTrrz]Unable to fully collect garbage - perhaps a __del__ method is creating more reference cycles?rrKzXReference cycles were found{}: {} objects were collected, of which {} are shown below:{}c ss6|]}dt|jt|t|ddVqdS)z {} object with id={}: {}rz N)rrrTr:idrpformatr)rirr>r>r? - s z/_assert_no_gc_cycles_context..)r0r#r isenabledr get_debugrcollectr  set_debug DEBUG_SAVEALLgarbagerrMrrrr)rXrOgc_debugrn_objects_in_cyclesobjects_in_cyclesrr>r>r?_assert_no_gc_cycles_context sP          r,cOs^|stS|d}|dd}t|jd||i|WddS1s(wYdS)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. rrCNr)r,r:rr>r>r?r58 s "r5cCs,ttrtttdSdS)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)rr%r/r>r>r>r?r6Z s   r6csddlfdd}|S)z:Decorator to skip a test if not enough memory is availablerNcstfdd}|S)NcsJt}|dur |z|i|WSty$dYdSw)NzMemoryError raised)check_free_memoryskip MemoryErrorxfail)rkwrI) free_bytesrpytestr>r?wrapperq s  z3requires_memory..decorator..wrapperrrr4r2r3rr?ryp s z"requires_memory..decorator)r3)r2ryr>r6r?requires_memoryl sr8c Csd}tj|}|dur4zt|}Wnty(}z td|d|d}~ww|dd|d}nt}|dur@d}d }n |dd |dd }||krR|SdS) 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.rdz GB memory required, but z GB available)rOenvironget _parse_sizer_get_mem_available)r2env_var env_valuemem_freerrIr>r>r?r- s$    r-cCsdddddddddddddd d }td d |tj}||}|r0|d |vr8t d|dt t |d||d S)z3Convert memory size strings ('12 GB' etc.) to floatrCii@Biʚ;lJ)ii@l)rKrrrYrrkbmbgbtbkibmibgibtibz^\s*(\d+|\d+\.\d+)\s*({0})\s*$|r8zvalue z not a valid size) rnrorrrkeysrrlowergrouprrr)size_strsuffixessize_rerYr>r>r?r< s  r<c Csz ddl}|jWSttfyYnwtjdr]i}tdd"}|D]}| }t |dd||d d <q&Wdn1sHwYd |vrU|d S|d |d SdS) z5Return available memory in bytes, or None if unknown.rNr|z /proc/meminfor}rCrA: memavailablememfreecached) psutilvirtual_memory availablerErurLplatformr<rrrstriprL)rUinforlinepr>r>r?r= s$   $r=cs&ttdsStfdd}|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 gettracec s:t}ztd|i|Wt|St|wr)rLr]settrace)rrcoriginal_tracer7r>r?r4 s  z_no_tracing..wrapper)rtrLrr5r>r7r? _no_tracing s r`)rK)NrdNN)rxr)rTrr)rKT)rrKT)rKTrKrTT)rrKT)NTr)rCN)rrTrKT)rC)ir=rOrLrXrnrr$r functoolsrrrr tempfilerr unittest.caserrrrrrRrr r r r r rrnumpy.linalg.lapack_liteior__all__rr,KnownFailureTestr!python_implementationr/rr0linalg lapack_lite_ilp64r7rJr#rXr_rbrXrwrgetpidrrrrrrr2rrrr rrrunittestTestCaser^rarr%rr"r3r)r$r&rrrcontextmanagerrr'rr(r4r*r.r-rr+r1r,r5r6r8r-r<r=r`r>r>r>r?s  (         ! ) ~c   S qS G.(  /. : ? 4?  6  $E  B 3"