U ã€C^“Hã(@sdZddlmZmZmZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl m Z mZddlZddlZddlmZmZddlmZddl mZddlZddlmZmZmZmZmZmZmZm Z ddl!Z"ej#dd krìdd l$m%Z%n dd l%m%Z%d d d ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2g(Z&Gd3d'„d'e'ƒZ(e(Z)dZ*e +¡d4kZ,e-ed5dƒdk Z.e/e"j0d6ƒZ1d7d8„Z2dŽd:d„Z3d;d<„Z4d=d>„Z5d?d@„Z6ej7dAk�rØd�dCdD„Z8d�dFd„Z9n2ejddG…dHk�rdIe :¡fdJd„Z9ndKd„Z9ejddG…dHk�r6dIe :¡gfdLd„Z;n gfdMd„Z;d‘dRd„Zd“dVd „Z?d”dWd „Z@d•dYd-„ZAd–dZd„ZBd—d[d„ZCd˜d\d„ZDd]d„ZEd^d„ZFd™d_d„ZGd`d„ZHddlIZIGdadb„dbeIjJƒZKeKdcƒZLddd„ZMded„ZNdšdfd„ZOd›dhd„ZPdid.„ZQdœdkd#„ZRd�dld„ZSdždmd „ZTdŸdndo„ZUdpdq„ZVdrds„ZWejXd dtdu„ƒZYdvd!„ZZejXd¡dwdx„ƒZ[dyd"„Z\edzd{fd|d/„Z]Gd}d$„d$e'ƒZ^ejXd~d)„ƒZ_ejXdd(„ƒZ`Gd€d%„d%e jaƒZbGd�d,„d,ecƒZdejXd¢d‚dƒ„ƒZed„d0„Zfd…d1„Zgd†d‡„Zhdˆd‰„ZidŠd‹„ZjdŒd�„ZkdS)£z* Utility function to facilitate testing. é)ÚdivisionÚabsolute_importÚprint_functionN)ÚpartialÚwraps)ÚmkdtempÚmkstemp)ÚSkipTest)ÚWarningMessage)ÚintpÚfloat32ÚemptyÚarangeÚ array_reprÚndarrayÚisnatÚarrayé)ÚStringIOÚ assert_equalÚassert_almost_equalÚassert_approx_equalÚassert_array_equalÚassert_array_lessÚassert_string_equalÚassert_array_almost_equalÚ assert_raisesÚ build_err_msgÚdecorate_methodsÚjiffiesÚmemusageÚprint_assert_equalÚraisesÚrundocsÚ runstringÚverboseÚmeasureÚassert_Úassert_array_almost_equal_nulpÚassert_raises_regexÚassert_array_max_ulpÚ assert_warnsÚassert_no_warningsÚassert_allcloseÚIgnoreExceptionÚclear_and_catch_warningsr ÚKnownFailureExceptionÚtemppathÚtempdirÚIS_PYPYÚ HAS_REFCOUNTÚsuppress_warningsÚassert_array_compareÚ_assert_valid_refcountÚ_gen_alignment_dataÚassert_no_gc_cyclesÚ break_cyclesÚ HAS_LAPACK64c@seZdZdZdS)r0z= %d.%d.%d for tests - see https://nose.readthedocs.io)ÚnoseÚ ImportErrorZ__versioninfo__)Z nose_is_goodZminimum_nose_versionrFÚmsgrArArBÚ import_nose<s   þrIÚcCs8d}|s4z |ƒ}Wntk r*|}YnXt|ƒ‚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)Ú TypeErrorÚAssertionError)ÚvalrHÚ__tracebackhide__ZsmsgrArArBr'Rs   cCs.ddlm}||ƒ}t|ttƒƒr*tdƒ‚|S)a�like 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.corerOÚ isinstanceÚtypeÚNotImplementedrK)ÚxrOÚstrArArBÚgisnanfs rVc CsHddlm}m}|dd��$||ƒ}t|ttƒƒr:tdƒ‚W5QRX|S)a‡like 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)ÚisfiniteÚerrstateÚignore©Úinvalidz$isfinite not supported for this type)rPrWrXrQrRrSrK)rTrWrXrUrArArBÚ gisfinitexs  r\c CsHddlm}m}|dd��$||ƒ}t|ttƒƒr:tdƒ‚W5QRX|S)a�like 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)ÚisinfrXrYrZz!isinf not supported for this type)rPr]rXrQrRrSrK)rTr]rXrUrArArBÚgisinf‹s  r^Úntéÿÿÿÿc CsŠddl}|dkr|j}| |||d||f¡}| ¡}zD| ||¡} z&| |¡| | |¡\} } | W¢W¢S| | ¡XW5| |¡XdS)Nr) Úwin32pdhÚ PDH_FMT_LONGZMakeCounterPathZ OpenQueryZ CloseQueryZ AddCounterZ RemoveCounterZCollectQueryDataZGetFormattedCounterValue) ÚobjectÚcounterÚinstanceZinumÚformatÚmachineraÚpathZhqZhcrRrMrArArBÚGetPerformanceAttributes s    riÚpythoncCsddl}tdd|||jdƒS)NrÚProcessz Virtual Bytes)rarirb)Ú processNamererarArArBr ºsþéÚlinuxz /proc/%s/statcCsJz.t|dƒ}| ¡ d¡}| ¡t|dƒWStk rDYdSXdS)zM Return virtual memory size in bytes of the running python. Úrú éN)ÚopenÚreadlineÚsplitÚcloseÚintÚ Exception)Ú_proc_pid_statÚfÚlrArArBr Âs cCst‚dS)zK Return memory usage of running python. [Not implemented] N)ÚNotImplementedErrorrArArArBr ÏscCszddl}|s| | ¡¡z.t|dƒ}| ¡ d¡}| ¡t|dƒWStk rttd| ¡|dƒYSXdS)ú¸ 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. rNrorpé éd)ÚtimeÚappendrrrsrtrurvrw)rxÚ _load_timerryrzrArArBrØs  cCs2ddl}|s| | ¡¡td| ¡|dƒS)r|rNr~)rr€rv)r�rrArArBrïsúItems are not equal:T©ZACTUALZDESIREDéc Csd|g}|rN| d¡dkrDt|ƒdt|ƒkrD|dd|g}n | |¡|�rt|ƒD]¨\}}t|tƒr|tt|d�} nt} z | |ƒ} Wn4t k rÀ} zd  t |ƒj | ¡} W5d} ~ XYnX|   d¡dkrîd |  ¡dd…¡} | d 7} | d ||| f¡q\d |¡S) NÚ r`éOrrp)Ú precisionz[repr failed for <{}>: {}]rz...z %s: %s)ÚfindÚlenr€Ú enumeraterQrrrÚreprrwrfrRr=ÚcountÚjoinÚ splitlines) ZarraysÚerr_msgÚheaderr%Únamesr‡rHÚiÚaZr_funcroÚexcrArArBrýs& "   $c Cs’d}t|tƒr†t|tƒs(ttt|ƒƒƒ‚tt|ƒt|ƒ||ƒ| ¡D]:\}}||krbtt|ƒƒ‚t||||d||f|ƒqFdSt|tt fƒrìt|tt fƒrìtt|ƒt|ƒ||ƒt t|ƒƒD]"}t||||d||f|ƒqÄdSddl m }m }m} ddlm} m} m} t||ƒ�s,t||ƒ�r:t||||ƒSt||g||d�} z| |ƒ�p^| |ƒ}Wnttfk �r€d }YnX|�r| |ƒ�r¤| |ƒ}| |ƒ}n|}d}| |ƒ�rÈ| |ƒ}| |ƒ}n|}d}zt||ƒt||ƒWntk �rt| ƒ‚YnX||ƒ||ƒk�r"t| ƒ‚zLt|ƒ}t|ƒ}t|ƒjjt|ƒjjk}|�rl|�rl|�rdWdSt| ƒ‚Wntttfk �rŠYnXzˆt|ƒ}t|ƒ}|�r°|�r°WdSt|ƒ}t|ƒ}|jjd k�sÜ|jjd k�rätd ƒ‚|dk�r|dk�r| |ƒ| |ƒk�st| ƒ‚Wntttfk �r0YnXz||k�sFt| ƒ‚WnDttfk �rŒ}z d |jdk�rzt| ƒ‚n‚W5d}~XYnXdS) 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, no assertion is 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]) Tz key=%r %sNz item=%r %sr)rÚisscalarÚsignbit©Ú iscomplexobjÚrealÚimag©r%FÚMmz0cannot compare to a scalar with a different typezelementwise == comparison) rQÚdictrLr‹rRrr‰ÚitemsÚlistÚtupleÚrangerPrr•r–Ú numpy.libr˜r™ršrrÚ ValueErrorrKrrÚdtyper{rVÚcharÚDeprecationWarningÚ FutureWarningÚargs)ÚactualÚdesiredr�r%rNÚkr’rr•r–r˜r™ršrHÚ usecomplexÚactualrÚactualiÚdesiredrÚdesirediZisdesnatZisactnatZ dtypes_matchZisdesnanZisactnanZ array_actualZ array_desiredÚerArArBrs–2               ÿ    cCs`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: )ÚpprintrÚwriterLÚgetvalue)Z test_stringr©rªrNr²rHrArArBr!¶s     éc sÌd}ddlm}ddlm}m}m} z|ˆƒp4|ˆƒ} Wntk rPd} YnX‡‡‡‡‡fdd„} | rî|ˆƒr„|ˆƒ} | ˆƒ} nˆ} d} |ˆƒr¦|ˆƒ}| ˆƒ}nˆ}d}z t| |ˆd�t| |ˆd�Wntk rìt| ƒƒ‚YnXt ˆ|t t fƒ�st ˆ|t t fƒ�r t ˆˆˆˆƒSzft ˆƒ�r6t ˆƒ�s„tˆƒ�sJtˆƒ�rjtˆƒ�r^tˆƒ�s~t| ƒƒ‚nˆˆk�s~t| ƒƒ‚Wd SWnttfk �r YnXtˆˆƒd d ˆ k�rÈt| ƒƒ‚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 -------- >>> import numpy.testing as npt >>> npt.assert_almost_equal(2.3333333333333, 2.33333334) >>> npt.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 >>> npt.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 Mismatch: 50% Max absolute difference: 6.66669964e-09 Max relative difference: 2.85715698e-09 x: array([1. , 2.333333333]) y: array([1. , 2.33333334]) Tr)rr—Fcsdˆ}tˆˆgˆˆ|d�S)Nú*Arrays are not almost equal to %d decimals)r%r�)r)r�©r©Údecimalrªr�r%rArBÚ_build_err_msg/s ÿz+assert_almost_equal.._build_err_msg)r¸Nçø?ç$@)rPrr¢r˜r™ršr£rrLrQr rŸrr\rVr{rKÚabs)r©rªr¸r�r%rNrr˜r™ršr¬r¹r­r®r¯r°rAr·rBrßsPD    ÿ    c Cs~d}ddl}tt||fƒ\}}||kr*dS|jdd��6d| |¡| |¡}| d| | |¡¡¡}W5QRXz ||}Wntk r–d}YnXz ||} Wntk r¼d} YnXt ||g|d ||d �} z^t |ƒrêt |ƒ�s2t |ƒsüt |ƒ�rt |ƒ�rt |ƒ�s,t | ƒ‚n||k�s,t | ƒ‚WdSWnt tfk �rNYnX| || ¡| d |d  ¡k�rzt | ƒ‚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 TrNrYrZgà?é gz-Items are not equal to %d significant digits:)r�r%r»rE)ÚnumpyÚmapÚfloatrXr¼ÚpowerÚfloorÚlog10ÚZeroDivisionErrorrr\rVrLrKr{) r©rªZ significantr�r%rNÚnpZscaleZ sc_desiredZ sc_actualrHrArArBr\sD:"    ý   "éc % sÆd} ddlm} m} m} m‰m‰m} m}m}m }| |ddd�}| |ddd�}||}}dd„}dd „}| d f‡‡‡‡‡fd d „ }�zì|j d kp¢|j d kp¢|j |j k}|sØt ||gˆd|j |j fˆˆdˆd�}t |ƒ‚ˆdƒ}||ƒ�rJ||ƒ�rJ|�r |||| d d�}|�r†||||‡fdd„dd�O}||||‡fdd„dd�O}n<||ƒ�r†||ƒ�r†|�r†|j j|j jk�r†|||tdd�}|jdk�r¼||||}}|jdk�rÈWdSn |�rÈWdS|||ƒ}t|tƒ�rî|}| |gƒ}n| ¡}| ¡}|dk�rl|j|jtd�}|jdk�r,|jn|j}d||}d |||¡g}| ddd��Út t¡�Ät||ƒ}||ƒ} t|d|ƒ|k�r¢| dt| ƒ¡n| d| | ƒ¡ˆ|dkƒ}!||!ƒ�rÖ| ˆƒ}"n|||!t||!ƒƒ}"t|d|ƒ|k�r| dt|"ƒ¡n| d| |"ƒ¡W5QRXW5QRXˆd d  |¡7‰t ||gˆˆˆdˆd�}t |ƒ‚WnRt k �rÀddl!}#|# "¡}$d!|$ˆf‰t ||gˆˆˆdˆd�}t |ƒ‚YnXdS)"NTr) rÚ array2stringrOÚinfÚbool_rXÚallÚmaxÚobject_F)ÚcopyÚsubokcSs |jjdkS)Nz?bhilqpBHILQPefdgFDG©r¤r¥©rTrArArBÚisnumberËsz&assert_array_compare..isnumbercSs |jjdkS)NrœrÏrÐrArArBÚistimeÎsz$assert_array_compare..istimeÚnancsŒ||ƒ}||ƒ}ˆ||kƒ ¡dkrLt||gˆd|ˆˆdˆd�}t|ƒ‚t|tƒs`|jdkrhˆ|ƒSt|tƒs||jdkr„ˆ|ƒS|SdS)z‹Handling 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:©rTÚy©r%r�r‘r‡rN)rÊrrLrQÚboolÚndim)rTrÕÚfuncÚhasvalZx_idZy_idrH)rÉr�r�r‡r%rArBÚfunc_assert_same_posÑs$ ÿýz2assert_array_compare..func_assert_same_posrAz (shapes %s, %s mismatch)rÔrÖ)rÙrÚcs |ˆ kS©NrA©Zxy©rÈrArBÚóz&assert_array_compare..z+infcs |ˆ kSrÜrArÝrÞrArBrß ràz-infZNaT©r¤r~z&Mismatched elements: {} / {} ({:.3g}%)rY)r[Údivider¤zMax absolute difference: zMax relative difference: r…zerror during assertion: %s %s)#rPrrÇrOrÈrÉrXrÊrËrÌÚshaperrLr¤rRrrØÚsizerQr×ZravelÚsumr rfÚ contextlibÚsuppressrKr¼Úgetattrr€Ústrr�r£Ú tracebackÚ format_exc)%Z comparisonrTrÕr�r%r�r‡Ú equal_nanÚ equal_infrNrrÇrOrXrÊrËrÌZoxZoyrÑrÒrÛZcondrHZflaggedrMZreducedZ n_mismatchZ n_elementsZpercent_mismatchZremarksÚerrorZ max_abs_errorZnonzeroZ max_rel_errorrêZefmtrA)rÉr�r�rÈr‡r%rBr6¿sÈ, # ÿÿû þ þ        ÿÿ  ÿÿ   ÿÿ þ  ÿcCsd}ttj||||dd�dS)aI 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 Mismatch: 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)r�r%r�N)r6ÚoperatorÚ__eq__©rTrÕr�r%rNrArArBrYs M ÿc sjd}ddlm‰m‰m‰m‰ddlm‰ddlm‰‡‡‡‡‡‡‡fdd„}t |||||dˆˆd �d S) aM 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 Mismatch: 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)ÚnumberÚfloat_Ú result_typer)Ú issubdtype)Úanyc sàzxˆt|ƒƒsˆt|ƒƒrvt|ƒ}t|ƒ}||k ¡s.comparer¶)r�r%r�r‡N) rPròrórôrZnumpy.core.numerictypesrõZnumpy.core.fromnumericrör6)rTrÕr¸r�r%rNrùrArørBr«sK   þc Cs d}ttj||||ddd�dS)a 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 Mismatch: 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 Mismatch: 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)r�r%r�ríN)r6rïÚ__lt__rñrArArBrs I ýcCst||ƒdSrÜ)Úexec)Zastrr�rArArBr$jsc Cs‚d}ddl}t|tƒs&ttt|ƒƒƒ‚t|tƒs@ttt|ƒƒƒ‚||krLdSt| ¡ |  d¡|  d¡¡ƒ}g}|�rP|  d¡}|  d¡rŒqp|  d¡�rB|g}|  d¡}|  d¡rÆ|  |¡|  d¡}|  d¡sÜtt|ƒƒ‚|  |¡|�r|  d¡} |   d¡�r|  | ¡n |  d| ¡|dd…|dd…k�r6qp| |¡qptt|ƒƒ‚qp|�sZdSd d  |¡ ¡} ||k�r~t| ƒ‚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: %srJ)ÚdifflibrQrérLr‹rRrŸZDifferrùrŽÚpopÚ startswithr€ÚinsertÚextendr�Úrstrip) r©rªrNrýÚdiffZ diff_listZd1rzZd2Zd3rHrArArBrnsL                   c sÂddlm}ddl}|dkr0t d¡}|jd}tj tj  |¡¡d}|||ƒ}|  ¡  |¡}|j dd�}g‰|r‚‡fdd „} nd} |D]} |j | | d �qŠ|jdkr¾|r¾td d  ˆ¡ƒ‚dS) 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)Únpy_load_moduleNrEÚ__file__Fr›cs ˆ |¡SrÜ)r€)Ús©rHrArBrß×ràzrundocs..)ÚoutzSome doctests failed: %sr…)Z numpy.compatrÚdoctestÚsysÚ _getframeÚ f_globalsÚosrhÚsplitextÚbasenameZ DocTestFinderrˆZ DocTestRunnerÚrunZfailuresrLr�) ÚfilenameZraise_on_errorrr ryÚnameÚmÚtestsÚrunnerrÚtestrArrBr#´s"     cGstƒ}|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 )rIZtoolsr")r¨rFrArArBr"âs"c@seZdZdd„ZdS)Ú_DummycCsdSrÜrA)ÚselfrArArBÚnopsz _Dummy.nopN)r=r>r?rrArArArBr srrcOsd}tj||ŽS)aá assert_raises(exception_class, callable, *args, **kwargs) assert_raises(exception_class) Fail unless an exception of class exception_class is thrown by callable when invoked with arguments args and keyword arguments kwargs. If a different type of exception is thrown, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception. Alternatively, `assert_raises` can be used as a context manager: >>> from numpy.testing import assert_raises >>> with assert_raises(ZeroDivisionError): ... 1 / 0 is equivalent to >>> def div(x, y): ... return x / y >>> assert_raises(ZeroDivisionError, div, 1, 0) T)Ú_dZ assertRaises)r¨ÚkwargsrNrArArBrscOs0d}tjjdkrtj}ntj}|||f|ž|Ž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 Tr)r Ú version_infoÚmajorrÚassertRaisesRegexZassertRaisesRegexp)Zexception_classZexpected_regexpr¨rrNÚfuncnamerArArBr)0s  c s´|dkrt dtj¡}n t |¡}|j}ddlm‰‡fdd„| ¡Dƒ}|D]^}zt|dƒrh|j }n|j }Wnt k rˆYqPYnX|  |¡rP|  d¡sPt||||ƒƒqPdS) a  Apply a decorator to all methods in a class matching a regular expression. The given decorator is applied to all public methods of `cls` that are matched by the regular expression `testmatch` (``testmatch.search(methodname)``). Methods that are private, i.e. start with an underscore, are ignored. Parameters ---------- cls : class Class whose methods to decorate. decorator : function Decorator to apply to methods testmatch : compiled regexp or str, optional The regular expression. Default value is None, in which case the nose default (``re.compile(r'(?:^|[\b_\.%s-])[Tt]est' % os.sep)``) is used. If `testmatch` is a string, it is compiled to a regular expression first. Nz(?:^|[\\b_\\.%s-])[Tt]estr©Ú isfunctioncsg|]}ˆ|ƒr|‘qSrArA)Ú.0Ú_mr rArBÚ osz$decorate_methods..Úcompat_func_nameÚ_)ÚreÚcompiler ÚsepÚ__dict__Úinspectr!ÚvaluesÚhasattrr%r=ÚAttributeErrorÚsearchrÿÚsetattr)ÚclsÚ decoratorZ testmatchZcls_attrÚmethodsÚfunctionrrAr rBrOs      rEc Csbt d¡}|j|j}}t|d|dƒ}d}tƒ}||krP|d7}t|||ƒq2tƒ|}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 rEzTest name: %s rûrg{®Gáz„?)r r Úf_localsr r(rrû) Zcode_strÚtimesÚlabelÚframeZlocsZglobsÚcoder’ÚelapsedrArArBr&~s! þ c Cs„tsdSddl}ddl}| d¡ dd¡}|}d}| ¡z8t |¡}t dƒD]}|||ƒ}qNt t |¡|kƒW5| ¡X~dS)zg Check that ufuncs don't mishandle refcount of object `1`. Used in a few regression tests. TrNi'r~rEé) r4r¾ÚgcrZreshapeÚdisableÚenabler rDr¡r') ÚoprÅr<ÚbÚcr’ÚrcÚjÚdrArArBr7®s    çH¯¼šò×z>c s^d}ddl‰‡‡‡‡fdd„}ˆ |¡ˆ |¡}}dˆˆf} 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) TrNcsˆjjj||ˆˆˆd�S)N)ÚrtolÚatolrì)ÚcoreÚnumericÚiscloserÔ©rGrìrÅrFrArBrùösÿz assert_allclose..comparez'Not equal to tolerance rtol=%g, atol=%g)r�r%r�rì)r¾Z asanyarrayr6ré) r©rªrFrGrìr�r%rNrùr�rArKrBr-Æs- ÿc Csšd}ddl}| |¡}| |¡}|| | ||k||¡¡}| | ||¡|k¡s–| |¡sh| |¡rrd|}n| t||ƒ¡} d|| f}t|ƒ‚dS)aÛ Compare two arrays relatively to their spacing. This is a relatively robust method to compare two arrays whose amplitude is variable. Parameters ---------- x, y : array_like Input arrays. nulp : int, optional The maximum number of unit in the last place for tolerance (see Notes). Default is 1. Returns ------- None Raises ------ AssertionError If the spacing between `x` and `y` for one or more elements is larger than `nulp`. See Also -------- assert_array_max_ulp : Check that all items of arrays differ in at most N Units in the Last Place. spacing : Return the distance between x and the nearest adjacent number. Notes ----- An assertion is raised if the following condition is not met:: abs(x - y) <= nulps * spacing(maximum(abs(x), abs(y))) Examples -------- >>> x = np.array([1., 1e-10, 1e-20]) >>> eps = np.finfo(x.dtype).eps >>> np.testing.assert_array_almost_equal_nulp(x, x*eps/2 + x) >>> np.testing.assert_array_almost_equal_nulp(x, x*eps + x) Traceback (most recent call last): ... AssertionError: 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)) r¾r¼ÚspacingÚwhererÊr˜rËÚ nulp_diffrL) rTrÕZnulprNrÅZaxZayÚrefrHZmax_nulprArArBr(s1    cCs6d}ddl}t|||ƒ}| ||k¡s2td|ƒ‚|S)a£ 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`. 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))) TrNz(Arrays are not almost equal up to %g ULP)r¾rNrÊrL)r“r@Zmaxulpr¤rNrÅÚretrArArBr*?s$ ÿcsÊddl‰|r*ˆj||d�}ˆj||d�}nˆ |¡}ˆ |¡}ˆ ||¡}ˆ |¡s^ˆ |¡rftdƒ‚ˆj||d�}ˆj||d�}|j|jks¢td|j|jfƒ‚‡fdd„}t|ƒ}t|ƒ}||||ƒS)a¨For 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. Examples -------- # By definition, epsilon is the smallest number such as 1 + eps != 1, so # there should be exactly one ULP between 1 and 1 + eps >>> nulp_diff(1, 1 + np.finfo(x.dtype).eps) 1.0 rNráz'_nulp not implemented for complex arrayz+x and y do not have the same shape: %s - %scsˆj|||d�}ˆ |¡S©Nrá)rr¼)ÚrxÚryÚvdtr©rÅrArBÚ_diff™sznulp_diff.._diff)r¾rZ common_typer˜r{rãr£Ú integer_repr)rTrÕr¤ÚtrVrRrSrArUrBrNls&     ÿ rNcCsB| |¡}|jdks.|||dk||dk<n|dkr>||}|S)NrEr)Úviewrä)rTrTÚcomprRrArArBÚ _integer_repr¢s   r[cCszddl}|j|jkr(t||j| d¡ƒS|j|jkrHt||j| d¡ƒS|j|jkrht||j| d¡ƒSt d|jƒ‚dS)zQReturn the signed-magnitude interpretation of the binary representation of x.rNi€ÿÿi€lûÿÿÿzUnsupported dtype %s) r¾r¤Zfloat16r[Zint16r Zint32Zfloat64Zint64r£)rTrÅrArArBrW±s   rWc csVd}tƒ�B}| |¡}dVt|ƒdksH|dk r8d|nd}td|ƒ‚W5QRXdS)NTrú when calling %srJzNo warning raised)r5Úrecordr‰rL)Ú warning_classrrNÚsuprzÚname_strrArArBÚ_assert_warns_context¿s  rac OsP|s t|ƒS|d}|dd…}t||jd��|||ŽW5QR£SQRXdS)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 The callable to test. \*args : Arguments Arguments passed to `func`. \*\*kwargs : Kwargs Keyword arguments passed to `func`. Returns ------- The value returned by `func`. rrEN©r)rar=)r^r¨rrÙrArArBr+Ês " c cs`d}tjdd��F}t d¡dVt|ƒdkrR|dk r>d|nd}td||fƒ‚W5QRXdS)NT©r]Úalwaysrr\rJzGot warnings%s: %s)ÚwarningsÚcatch_warningsÚ simplefilterr‰rL)rrNrzr`rArArBÚ_assert_no_warnings_contextõs  rhc OsL|s tƒS|d}|dd…}t|jd��|||ŽW5QR£SQRXdS)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`. rrENrb)rhr=©r¨rrÙrArArBr,s  Úbinaryéc #sºd}d}tdƒD�]¢‰tˆdtˆd|ƒƒD�]‚‰|dk�rt‡‡‡fdd„}tˆfˆd�ˆd …}||ƒ|ˆˆˆˆ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„} tˆfˆd�ˆd …}||ƒ| ƒ|ˆˆˆˆˆd ffV|ƒ}||| ƒ|ˆˆˆˆˆdffV| ƒ}||ƒ||ˆˆˆˆˆdffV|d d …|ƒd d …| ƒd d …|ˆd ˆˆˆd ˆd ffV|d d …|ƒd d …| ƒd d …|ˆˆd ˆˆd ˆd ffV|d d …|ƒd d …| ƒd d …|ˆˆˆd ˆd ˆd ffV|ƒd d …|ƒd d …| ƒd d …|ˆd ˆˆˆd ˆdffV|ƒd d …|ƒd d …| ƒd d …|ˆˆd ˆˆd ˆdffV|ƒd d …|ƒd d …| ƒd d …|ˆˆˆd ˆd ˆdffVq.qd S)aÓ generator producing data with different alignment and offsets to test simd vectorization Parameters ---------- dtype : dtype data type to produce type : string 'unary': create data for unary operations, creates one input and output array 'binary': create data for unary operations, creates two input and output array max_size : integer maximum size of data to produce Returns ------- if type is 'unary' yields one output, one input array and a message containing information on the data if type is 'binary' yields one output array, two input array and a message containing information on the data z,unary offset=(%d, %d), size=%d, dtype=%r, %sz1binary offset=(%d, %d, %d), size=%d, dtype=%r, %srrüZunarycstˆˆd�ˆd…SrQ©rrA©r¤ÚorrArBrßBràz%_gen_alignment_data..ráNz out of placezin placerEr`Úaliasedrjcstˆˆd�ˆd…SrQrlrArmrArBrßPràcstˆˆd�ˆd…SrQrlrArmrArBrßQràz in place1z in place2)r¡rËr ) r¤rRÚmax_sizeZufmtZbfmtÚinprrDZinp1Zinp2rArmrBr8$sn ÿÿÿÿ ÿ ÿ ÿ$ÿ$ÿ$ÿ&ÿ&ÿ&ÿc@seZdZdZdS)r.z/Ignoring this exception due to disabled featureNr<rArArArBr.isc os&t||Ž}z |VW5t |¡XdS)z�Context manager to provide a temporary test folder. All arguments are passed as this to the underlying tempfile.mkdtemp function. N)rÚshutilÚrmtree)r¨rZtmpdirrArArBr2ns  c os4t||Ž\}}t |¡z |VW5t |¡XdS)açContext 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)rr ruÚremove)r¨rÚfdrhrArArBr1}s   cs>eZdZdZdZd ‡fdd„ Z‡fdd„Z‡fdd „Z‡ZS) 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 rAFcs.t|ƒ |j¡|_i|_tt|ƒj|d�dS)Nrc)ÚsetÚunionÚ class_modulesÚmodulesÚ_warnreg_copiesÚsuperr/Ú__init__)rr]ry©Ú __class__rArBr|¿sz!clear_and_catch_warnings.__init__cs@|jD]*}t|dƒr|j}| ¡|j|<| ¡qtt|ƒ ¡S©NÚ__warningregistry__) ryr-r€rÍrzÚclearr{r/Ú __enter__)rÚmodZmod_regr}rArBr‚Äs    z"clear_and_catch_warnings.__enter__csPtt|ƒj|Ž|jD]4}t|dƒr.|j ¡||jkr|j |j|¡qdSr) r{r/Ú__exit__ryr-r€r�rzÚupdate)rÚexc_inforƒr}rArBr„Ìs     z!clear_and_catch_warnings.__exit__)FrA) r=r>r?r@rxr|r‚r„Ú __classcell__rArAr}rBr/“s ) c@steZdZdZddd„Zdd„Zeddd fd d „Zeddfd d „Zeddfdd„Z dd„Z dd„Z dd„Z dd„Z 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 rdcCs&d|_g|_|dkrtdƒ‚||_dS)NF>ÚlocationrdÚonceÚmodulezunsupported forwarding rule.)Ú_enteredÚ _suppressionsr£Ú_forwarding_rule)rZforwarding_rulerArArBr|s zsuppress_warnings.__init__cCs:ttdƒrt ¡dS|jD]}t|dƒr|j ¡qdS)NÚ_filters_mutatedr€)r-rerŽÚ _tmp_modulesr€r�)rrŠrArArBÚ_clear_registries)s    z#suppress_warnings._clear_registriesrJNFcCs¬|r g}nd}|jrˆ|dkr.tjd||d�n8|j dd¡d}tjd|||d�|j |¡| ¡|j  ||t   |t j ¡||f¡n |j   ||t   |t j ¡||f¡|S)Nrd©ÚcategoryÚmessageÚ.ú\.ú$©r’r“rŠ)r‹reÚfilterwarningsr=Úreplacer�Úaddr�Ú_tmp_suppressionsr€r'r(ÚIrŒ)rr’r“rŠr]Ú module_regexrArArBÚ_filter5s4ÿþ ÿÿzsuppress_warnings._filtercCs|j|||dd�dS)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. F©r’r“rŠr]N©rž©rr’r“rŠrArArBÚfilterNs ÿzsuppress_warnings.filtercCs|j|||dd�S)ai Append a new recording filter or apply it if the state is entered. All warnings matching will be appended to the ``log`` attribute. Parameters ---------- category : class, optional Warning class to filter message : string, optional Regular expression matching the warning message. module : module, optional Module to filter for. Note that the module (and its file) must match exactly and cannot be a submodule. This may make it unreliable for external modules. Returns ------- log : list A list which will be filled with all matched warnings. Notes ----- When added within a context, filters are only added inside the context and will be forgotten when the context is exited. TrŸr r¡rArArBr]es ÿzsuppress_warnings.recordcCsÖ|jrtdƒ‚tj|_tj|_|jdd…t_d|_g|_tƒ|_ tƒ|_ g|_ |j D]j\}}}}}|dk rv|dd…=|dkr�tj d||d�qV|j dd¡d}tj d|||d�|j  |¡qV|jt_| ¡|S) Nz%cannot enter suppress_warnings twice.Trdr‘r”r•r–r—)r‹Ú RuntimeErrorreÚ showwarningÚ _orig_showÚfiltersÚ_filtersr›rvr�Ú _forwardedÚlogrŒr˜r=r™ršÚ _showwarningr�)rÚcatZmessr&rƒr©r�rArArBr‚ƒs< ÿþzsuppress_warnings.__enter__cGs*|jt_|jt_| ¡d|_|`|`dS)NF)r¥rer¤r§r¦r�r‹)rr†rArArBr„£s zsuppress_warnings.__exit__cOs¨| dd¡}|j|jddd…D]¬\}} } } } t||ƒr"|  |jd¡dk r"| dkrŒ| dk r†t||||f|Ž} |j | ¡|  | ¡dS| j   |¡r"| dk rÈt||||f|Ž} |j | ¡|  | ¡dSq"|j dk�r|dk�r|j ||||f|ž|Žn |  |¡dS|j dk�r&|j|f}n4|j dk�r@|j||f}n|j dk�rZ|j|||f}||jk�rjdS|j |¡|dk�rš|j ||||f|ž|Žn |  |¡dS)NÚ use_warnmsgr`rrdr‰rŠrˆ)rþrŒr›Ú issubclassÚmatchr¨r r©r€rrÿr�r¥Z _orig_showmsgr¨rš)rr“r’rÚlinenor¨rr¬r«r&ÚpatternrƒZrecrHÚ signaturerArArBrª«sb ÿ ÿÿÿ   ÿÿ    ÿÿ        ÿzsuppress_warnings._showwarningcstˆƒ‡‡fdd„ƒ}|S)z_ Function decorator to apply certain suppressions to a whole function. c s&ˆ�ˆ||ŽW5QR£SQRXdSrÜrA)r¨r©rÙrrArBÚnew_funcäsz,suppress_warnings.__call__..new_func©r)rrÙr³rAr²rBÚ__call__ßszsuppress_warnings.__call__)rd)r=r>r?r@r|r�ÚWarningržr¢r]r‚r„rªrµrArArArBr5ÕsI   4c csæd}tsdVdStt ¡ƒt ¡t ¡}zRt dƒD]}t  ¡dkr8qVq8t dƒ‚t tj ¡dVt  ¡}tjdd…}W5tjdd…=t |¡t ¡X|râ|dk r¶d|nd}t d ||t|ƒd dd „|Dƒ¡¡ƒ‚dS) NTr~rz]Unable to fully collect garbage - perhaps a __del__ method is creating more reference cycles?r\rJzXReference cycles were found{}: {} objects were collected, of which {} are shown below:{}c ss4|],}d t|ƒjt|ƒt |¡ dd¡¡VqdS)z {} object with id={}: {}r…z N)rfrRr=Úidr²Úpformatr™)r"rnrArArBÚ  s üýz/_assert_no_gc_cycles_context..)r4r'r<Ú isenabledr=Z get_debugÚgarbageZ set_debugr>r¡Úcollectr£Z DEBUG_SAVEALLrLrfr‰r�)rrNZgc_debugr’Zn_objects_in_cyclesZobjects_in_cyclesr`rArArBÚ_assert_no_gc_cycles_contextìsB   ÿ     ûúÿr½c OsD|s tƒS|d}|dd…}t|jd��|||ŽW5QRXdS)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. rrENrb)r½r=rirArArBr9 s  cCs t ¡trt ¡t ¡dS)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)r<r¼r3rArArArBr:B s csddl‰‡‡fdd„}|S)z:Decorator to skip a test if not enough memory is availablerNcstˆƒ‡‡‡fdd„ƒ}|S)NcsJtˆƒ}|dk rˆ |¡z ˆ||ŽWStk rDˆ d¡YnXdS)NzMemoryError raised)Úcheck_free_memoryÚskipÚ MemoryErrorZxfail)r“ÚkwrH)Ú free_bytesrÙÚpytestrArBÚwrapperX s  z3requires_memory..decorator..wrapperr´)rÙrÄ©rÂrÃ)rÙrBr2W s z"requires_memory..decorator)rÃ)rÂr2rArÅrBÚrequires_memoryS srÆc Cs¦d}tj |¡}|dk rjz t|ƒ}Wn2tk rV}ztd ||¡ƒ‚W5d}~XYnXd |d|¡}n,tƒ}|dkr‚d}d}nd |d|d¡}||kr¢|SdS) zŽ Check whether `free_bytes` amount of memory is currently free. Returns: None if enough memory available, otherwise error message ZNPY_AVAILABLE_MEMNz%Invalid environment variable {}: {!s}zJ{0} GB memory required, but environment variable NPY_AVAILABLE_MEM={1} setgeÍÍAzCould not determine available memory; set NPY_AVAILABLE_MEM environment variable (e.g. NPY_AVAILABLE_MEM=16GB) to run the test.r`z,{0} GB memory required, but {1} GB available)r ÚenvironÚgetÚ _parse_sizer£rfÚ_get_mem_available)rÂÚenv_varZ env_valueZmem_freer”rHrArArBr¾i s.  ÿþÿr¾cCsŽdddddddddddddd d œ}t d  d  | ¡¡¡tj¡}| | ¡¡}|r`| d ¡|krnt d |¡ƒ‚t t | d¡ƒ|| d ¡ƒS)z3Convert memory size strings ('12 GB' etc.) to floatrEièi@BiÊš;lJ)£éii@l)rJr@r«rÚgrXÚkbÚmbÚgbÚtbZkibZmibZgibZtibz^\s*(\d+|\d+\.\d+)\s*({0})\s*$ú|rüzvalue {!r} not a valid size) r'r(rfr�Úkeysrœr®ÚlowerÚgroupr£rvrÀ)Zsize_strÚsuffixesZsize_rerrArArBrɉ s.ý ÿÿrÉc Cs¬zddl}| ¡jWSttfk r,YnXtj d¡r¨i}tddƒ�:}|D].}|  ¡}t |dƒd||d  d¡  ¡<qNW5QRXd |kr˜|d S|d |d SdS) z5Return available memory in bytes, or None if unknown.rNrnz /proc/meminfororErÌú:Z memavailableZmemfreeÚcached) ÚpsutilZvirtual_memoryÚ availablerGr.r ÚplatformrÿrrrtrvÚstriprÔ)rÙÚinforyÚlineÚprArArBrÊ™ s   .rÊ)rJ)Nr`NN)rjr)r‚Trƒr„)rJT)rµrJT)rµrJT)rJTrJrÆTT)rJT)rÆrJT)rJT)NT)N)rEN)rErTrJT)rE)rEN)N)N)N)N)lr@Ú __future__rrrr r rÛr'r<rïreÚ functoolsrrrrræÚtempfilerrZ unittest.caser r r²rPr r r rrrrrZnumpy.__config__r¾rÚiorÚ__all__rwr0ZKnownFailureTestr%Úpython_implementationr3rèr4r-Z __config__r;rIr'rVr\r^rrir Úgetpidrrrr!rrr6rrrr$rr#r"ZunittestZTestCaserrrr)rr&r7r-r(r*rNr[rWÚcontextmanagerrar+rhr,r8r.r2r1rfr/rcr5r½r9r:rÆr¾rÉrÊrArArArBÚs0  ( ô    ÿ    ÿ  ÿ  ) } cþ  R o PF .( / 0ÿ : ? - 6 + $E  B 3"