B krdd@dAZ1ddCdZ2n2ej3ddDdEkrdFe4fdGdZ2ndHdZ2ej3ddDdEkr dFe4gfdIdZ5n gfdJdZ5ddOdZ6ddPd Z7dQdZ8ddSd Z9ddTd Z:ddVdWZ;ddXdZd[dZ?d\dZ@dd]dZAd^dZBd_dZCd`d ZDddadZEddcdZFdddeZGddgd$ZHddhdZIddid!ZJddjdkZKdldmZLdndoZMGdpdqdqeNZOGdrdsdseNZPejQddtduZRdvd"ZSejQddwdxZTdyd#ZUedzd{fd|d}ZVGd~d%d%e"ZWejQdd*ZXejQdd)ZYGdd&d&e jZZ[Gdd-d-eNZ\dS)z* Utility function to facilitate testing. )divisionabsolute_importprint_functionN)partialwraps)mkdtempmkstemp)SkipTest)float32emptyarange array_reprndarrayisnatarray) deprecate)StringIO assert_equalassert_almost_equalassert_approx_equalassert_array_equalassert_array_lessassert_string_equalassert_array_almost_equal assert_raises build_err_msgdecorate_methodsjiffiesmemusageprint_assert_equalraisesrandrundocs runstringverbosemeasureassert_assert_array_almost_equal_nulpassert_raises_regexassert_array_max_ulp assert_warnsassert_no_warningsassert_allcloseIgnoreExceptionclear_and_catch_warningsr KnownFailureExceptiontemppathtempdirIS_PYPY HAS_REFCOUNTsuppress_warningsc@seZdZdZdS)r0z= %d.%d.%d for tests - see http://nose.readthedocs.io)nose ImportErrorZ__versioninfo__)Z nose_is_goodZminimum_nose_versionr>msgr:r:r; import_nose5s   rAcCs8d}|s4y |}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) TypeErrorAssertionError)valr@__tracebackhide__Zsmsgr:r:r;r'Ks   cCs.ddlm}||}t|ttr*td|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.corerG isinstancetypeNotImplementedrC)xrGstr:r:r;gisnan_s rNc CsHddlm}m}|dd$||}t|ttr:tdWdQRX|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)isfiniteerrstateignore)invalidz$isfinite not supported for this typeN)rHrOrPrIrJrKrC)rLrOrPrMr:r:r; gisfiniteqs  rSc CsHddlm}m}|dd$||}t|ttr:tdWdQRX|S)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)isinfrPrQ)rRz!isinf not supported for this typeN)rHrTrPrIrJrKrC)rLrTrPrMr:r:r;gisinfs  rUzNnumpy.testing.rand is deprecated in numpy 1.11. Use numpy.random.rand instead.)messagecGsNddl}ddlm}m}|||}|j}x tt|D]}|||<q6W|S)zReturns an array of random numbers with the given shape. This only uses the standard library, so it is useful for testing purposes. rN)zerosfloat64)randomrHrWrXZflatrangelen)argsrYrWrXresultsfir:r:r;r"s ntc Csddl}|dkr|j}||||d||f}|}z<|||} z|||| |\} } | S|| XWd||XdS)Nr) win32pdh PDH_FMT_LONGZMakeCounterPathZ OpenQueryZ AddCounterZCollectQueryDataZGetFormattedCounterValueZ RemoveCounterZ CloseQuery) objectZcounterinstanceZinumformatmachinerbpathZhqZhcrJrEr:r:r;GetPerformanceAttributess   ripythoncCsddl}tdd|||jdS)NrZProcessz Virtual Bytes)rbrirc)Z processNamererbr:r:r;rsZlinuxz /proc/%s/statcCs<y,t|d}|d}|t|dSdSdS)zM Return virtual memory size in bytes of the running python. r N)openreadlinesplitcloseint)_proc_pid_statr^lr:r:r;rs  cCstdS)zK Return memory usage of running python. [Not implemented] N)NotImplementedErrorr:r:r:r;rscCsjddl}|s||y,t|d}|d}|t|dStd||dSdS)z 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. rNrlrm d)timeappendrorprqrrrs)rt _load_timeryr^rur:r:r;rs   cCs2ddl}|s||td||dS)z 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. rNrx)ryrzrs)r{ryr:r:r;rsItems are not equal:TZACTUALZDESIREDc Csd|g}|rN|ddkrDt|dt|krD|dd|g}n |||r xt|D]\}}t|tr~tt|d} nt} y | |} Wn4t k r} zd t |j | } Wdd} ~ XYnX| ddkrd| dd} | d 7} |d ||| fq^Wd|S) N raOrrm) precisionz[repr failed for <{}>: {}]rz...z %s: %s)findr[rz enumeraterIrrr repr ExceptionrfrJr6countjoin splitlines) Zarrayserr_msgheaderr%namesrr@r_aZr_funcrlexcr:r:r;rs& "   $c CsBd}t|trt|ts(ttt|tt|t|||xF|D]:\}}||krdtt|t||||d||f|qHWdSt|tt frt|tt frtt|t|||x2t t|D]"}t||||d||f|qWdSddl m }m }m} ddlm} m} m} t||s4t||rBt||||St||g||d} y| |pf| |}Wntk rd }YnX|r | |r| |}| |}n|}d}| |r| |}| |}n|}d}yt||t||Wntk r t| YnX||||kr&t| yt|rt| dS) aa 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. 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]) ... : Items are not equal: item=1 ACTUAL: 5 DESIRED: 6 Tz key=%r %sNz item=%r %sr)risscalarsignbit) iscomplexobjrealimag)r%F)rIdictrDrrJrr[itemslisttuplerZrHrrr numpy.librrrrr ValueErrorrSrNrCrvrrdtype)actualdesiredrr%rFkr_rrrrrrr@ usecomplexactualractualidesiredrdesirediZisdesnanZisactnanr:r:r;r"s#   ""             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: )pprintrwriterDgetvalue)Z test_stringrrrFrr@r:r:r;r s     c sd}ddlm}ddlm}m}m} y|p4|} Wntk rPd} YnXfdd} | r|r|} | } n} d} |r|}| }n}d}y t| |dt| |dWntk rt| YnXt |t t fst |t t fr t Sydt r6t stsJtrjtr^ts~t| nks~t| d SWnttfk rYnXtd d  krt| d S) ap 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) ... : Items are not equal: ACTUAL: 2.3333333333333002 DESIRED: 2.3333333399999998 >>> npt.assert_almost_equal(np.array([1.0,2.3333333333333]), ... np.array([1.0,2.33333334]), decimal=9) ... : Arrays are not almost equal (mismatch 50.0%) x: array([ 1. , 2.33333333]) y: array([ 1. , 2.33333334]) Tr)r)rrrFcsd}tg|dS)Nz*Arrays are not almost equal to %d decimals)r%r)r)r)rdecimalrrr%r:r;_build_err_msgs z+assert_almost_equal.._build_err_msg)rNg?g$@)rHrrrrrrrrDrIrrrrSrNrvrCabs)rrrrr%rFrrrrrrrrrrr:)rrrrr%r;rsNA       c Cs|d}ddl}tt||f\}}||kr*dS|jdd6d||||}|d|||}WdQRXy ||}Wntk rd}YnXy ||} Wntk rd} YnXt ||g|d ||d } y\t |rt |s0t |st |rt |rt |s,t | n||ks,t | dSWnt tfk rLYnX||| |d |d  krxt | dS) aU 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) ... : Items are not equal to 8 significant digits: ACTUAL: 1.234567e-021 DESIRED: 1.2345672000000001e-021 the evaluated condition that raises the exception is >>> abs(0.12345670e-20/1e-21 - 0.12345672e-20/1e-21) >= 10**-(8-1) True TrNrQ)rRg? gz-Items are not equal to %d significant digits:)rr%g$@r=)numpymapfloatrPrZpowerZfloorZlog10ZeroDivisionErrorrrSrNrDrCrv) rrZ significantrr%rFnpZscaleZ sc_desiredZ sc_actualr@r:r:r;rFs@9"       "c ! sXd} ddlm} m} m} m} m}| ddd| ddddd}dd }dfd d }yjd kpjd kpjjk}|stgdjjfdd}t||r|rd}}|r| | }}| |p| |}|r|||d d|rz| | }}| |p>| |}|rz|| k| kdd|| k| kdd|r|r||B||Bn6|r||n|rڈ||j dkrtdSn|rt|rt|rtj j j j krtt t }}| |s>| |rL|||dd| |s`| |rt|||}t |tr|}dg}n|}|}|}|sdd|dt|}tgd|fdd}|st|WnRtk rRddl}|} d| ftgdd}t|YnXdS)NTr)rrGrTanyinfF)copysubokcSs |jjdkS)Nz?bhilqpBHILQPefdgFDG)rchar)rLr:r:r;isnumbersz&assert_array_compare..isnumbercSs |jjdkS)NZMm)rr)rLr:r:r;istimesz$assert_array_compare..istimenanc sPyt||Wn<tk rJtgd|dd}t|YnXdS)zTHandling nan/inf: check that x and y have the nan/inf at the same locations.z x and y %s location mismatch:)rLy)r%rrrN)rrDr)Zx_idZy_idhasvalr@)rrrr%rLrr:r;chk_same_positions  z/assert_array_compare..chk_same_positionr:z (shapes %s, %s mismatch))rLr)r%rrr)rz+infz-infZNaTrxgY@r=z (mismatch %s%%)zerror during assertion: %s %s)r)rHrrGrTrrshaperrDsizerrJrrIboolZravelalltolistrr[r traceback format_exc)!Z comparisonrLrrr%rr equal_nan equal_infrFrrGrTrrrrrZcondr@Zhas_nanZhas_infZx_isnanZy_isnanZx_isinfZy_isinfZx_isnatZy_isnatrEZreducedmatchrZefmtr:)rrrr%rLrr;assert_array_compares                   rcCsd}ttj||||dddS)a, Raises an AssertionError if two array_like objects are not equal. Given two array_like objects, check that the shape is equal and all elements of these objects are equal. 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 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 inprecision with floats: >>> np.testing.assert_array_equal([1.0,np.pi,np.nan], ... [1, np.sqrt(np.pi)**2, np.nan]) ... : AssertionError: Arrays are not equal (mismatch 50.0%) x: array([ 1. , 3.14159265, NaN]) y: array([ 1. , 3.14159265, 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) TzArrays are not equal)rr%rN)roperator__eq__)rLrrr%rFr:r:r;rs? c snd}ddlm}mmmmddlmddlm fdd}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) ... : AssertionError: Arrays are not almost equal (mismatch 50.0%) 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) : ValueError: Arrays are not almost equal x: array([ 1. , 2.33333, NaN]) y: array([ 1. , 2.33333, 5. ]) Tr)aroundnumberfloat_ result_typer) issubdtype)rc sytt|st|rrt|}t|}||ks:dS|j|jkrRdkr^nn||kS||}||}Wnttfk rYnX|d}||ddd}t||}|js|}|dd kS)NFr=g?T)rrrg?g$@)rUrrrCrvrrZastype)rLrZxinfidZyinfidrz)rrrrnpanyrrr:r;compares$      z*assert_array_almost_equal..comparez*Arrays are not almost equal to %d decimals)rr%rrN) rHrrrrrZnumpy.core.numerictypesrZnumpy.core.fromnumericrr)rLrrrr%rFrrr:)rrrrrrrr;rYsH   c Cs d}ttj||||ddddS)aF 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]) ... : Arrays are not less-ordered (mismatch 50.0%) x: array([ 1., 1., NaN]) y: array([ 1., 2., NaN]) >>> np.testing.assert_array_less([1.0, 4.0], 3) ... : Arrays are not less-ordered (mismatch 50.0%) x: array([ 1., 4.]) y: array(3) >>> np.testing.assert_array_less([1.0, 2.0, 3.0], [4]) ... : Arrays are not less-ordered (shapes (3,), (1,) mismatch) x: array([ 1., 2., 3.]) y: array([4]) TzArrays are not less-orderedF)rr%rrN)rr__lt__)rLrrr%rFr:r:r;rs B cCst||dS)N)exec)Zastrrr:r:r;r$sc Csd}ddl}t|ts&ttt|t|ts@ttt|td|d|tjr\dSt | | d| d}g}x|rn| d}|drq|dr`|g}| d}|d r||| d}|d stt||||r,| d} | d r || n |d| td|d dd|d drTq||qtt|qW|szdSd d |} ||krt| dS)a Test if two strings are equal. If the given strings are equal, `assert_string_equal` does nothing. If they are not equal, an AssertionError is raised, and the diff between the strings is shown. Parameters ---------- actual : str The string to test for equality against the expected string. desired : str The expected string. Examples -------- >>> np.testing.assert_string_equal('abc', 'abc') >>> np.testing.assert_string_equal('abc', 'abcd') Traceback (most recent call last): File "", line 1, in ... AssertionError: Differences in strings: - abc+ abcd? + TrNz\Az\Zr=z z- z? z+ zDifferences in strings: %srB)difflibrIstrrDrrJrerMrZDifferrrpop startswithrzinsertextendrrstrip) rrrFrdiffZ diff_listZd1ruZd2Zd3r@r:r:r;rsL                 &  c sddlm}ddl}|dkr0td}|jd}tjtj |d}|||}| |}|j dd}g|rfdd } nd} x|D]} |j | | d qW|jdkr|rtd d dS) aT 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_moduleNr=__file__F)r%cs |S)N)rz)s)r@r:r;{zrundocs..)outzSome doctests failed: %sr)Z numpy.compatrdoctestsys _getframe f_globalsosrhsplitextbasenameZ DocTestFinderrZ DocTestRunnerrunZfailuresrDr) filenameZraise_on_errorrrr^namemZtestsZrunnerrZtestr:)r@r;r#Xs"      cOst}|jj||S)N)rAtoolsr!)r\kwargsr>r:r:r;r!scOsd}t}|jj||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)rArr)r\rrFr>r:r:r;rscOs:d}t}tjjdkr |jj}n|jj}|||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)rAr version_infomajorrr)Zassert_raises_regexp)Zexception_classZexpected_regexpr\rrFr>funcnamer:r:r;r)s   c s|dkrtdtj}n t|}|j}ddlmfdd|D}xd|D]\}yt|drj|j }n|j }Wnt k rwRYnX| |rR| dsRt||||qRWdS) 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_m)rr:r; sz$decorate_methods..compat_func_name_)rcompilersep__dict__inspectrvalueshasattrrr6AttributeErrorsearchrsetattr)clsZ decoratorZ testmatchZcls_attrmethodsZfunctionrr:)rr;rs      r=c Csftd}|j|j}}t|d|d}d}t}x ||krR|d7}t|||q4Wt|}d|S)aE 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 -------- >>> etime = np.testing.measure('for i in range(1000): np.sqrt(i**2)', ... times=times) >>> print("Time for a single execution : ", etime / times, "s") Time for a single execution : 0.005 s r=zTest name: %s rrg{Gz?)rrf_localsrrrr) Zcode_strtimesZlabelframeZlocsZglobscoder_elapsedr:r:r;r&s!   cCshtsdSddl}|ddd}|}d}t|}xtdD]}|||}q>Wtt||k~dS)zg Check that ufuncs don't mishandle refcount of object `1`. Used in a few regression tests. TrNi'rxr=)r4rr Zreshaperr<rZr')oprbcr_Zrcjdr:r:r;_assert_valid_refcount(s rHz>c s^d}ddlfdd}||}}df} t|||t||| ddS)aq Raises an AssertionError if two objects are not equal up to desired tolerance. The test is equivalent to ``allclose(actual, desired, rtol, atol)``. 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)) >>> assert_allclose(x, y, rtol=1e-5, atol=0) TrNcsjjj||dS)N)rtolatolr)ZcoreZnumericZisclose)rLr)rrrrr:r;rlsz assert_allclose..comparez'Not equal to tolerance rtol=%g, atol=%g)rr%rr)rZ asanyarrayrr) rrrrrrr%rFrrr:)rrrrr;r-<s- c Csd}ddl}||}||}|||||k||}|||||ks||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)) rrZspacingwhererrmax nulp_diffrD) rLrZnulprFrZaxZayrefr@Zmax_nulpr:r:r;r(vs1    cCs6d}ddl}t|||}|||ks2td||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)rrrrD)rr ZmaxulprrFrZretr:r:r;r*s$ csddl|r*j||d}j||d}n|}|}||}|s^|rftdj||d}j||d}|j|jkstd|j|jffdd}t|}t|}||||S)aFor 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 rN)rz'_nulp not implemented for complex arrayz+x and y do not have the same shape: %s - %scsj|||d}|S)N)r)rr)rxryvdtr)rr:r;_diffsznulp_diff.._diff)rrZ common_typerrvrr integer_repr)rLrrtrrrr:)rr;rs$     rcCsB||}|jdks.|||dk||dk<n|dkr>||}|S)Nr=r)Zviewr)rLrcomprr:r:r; _integer_reprs   rcCsZddl}|j|jkr(t||j|dS|j|jkrHt||j|dStd|jdS)zQReturn the signed-magnitude interpretation of the binary representation of x.rNilzUnsupported dtype %s)rrr rZint32rXZint64r)rLrr:r:r;r's   rc@s&eZdZdZdZdddZddZdS) WarningMessagez Holds the result of a single showwarning() call. Deprecated in 1.8.0 Notes ----- `WarningMessage` is copied from the Python 2.6 warnings module, so it can be used in NumPy with older Python versions. )rVcategoryrlinenofilelineNc Cs>t}x|jD]}t||||qW|r4|j|_nd|_dS)N)locals_WARNING_DETAILSrr6_category_name) selfrVr rr!r"r#Z local_valuesattrr:r:r;__init__Fs   zWarningMessage.__init__cCsd|j|j|j|j|jfS)NzD{message : %r, category : %r, filename : %r, lineno : %s, line : %r})rVr&rr!r#)r'r:r:r;__str__PszWarningMessage.__str__)NN)r6r7r8r9r%r)r*r:r:r:r;r5s   rc@s*eZdZdZd ddZddZdd ZdS) WarningManagera A context manager that copies and restores the warnings filter upon exiting the context. The 'record' argument 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()``. The 'module' argument is to specify an alternative module to the module named 'warnings' and imported under that name. This argument is only useful when testing the warnings module itself. Deprecated in 1.8.0 Notes ----- `WarningManager` is a copy of the ``catch_warnings`` context manager from the Python 2.6 warnings module, with slight modifications. It is copied so it can be used in NumPy with older Python versions. FNcCs,||_|dkrtjd|_n||_d|_dS)NwarningsF)_recordrmodules_module_entered)r'recordmoduler:r:r;r)os zWarningManager.__init__csh|jrtd|d|_|jj|_|jdd|j_|jj|_|jr`gfdd}||j_SdSdS)NzCannot enter %r twiceTcst||dS)N)rzr)r\r)logr:r; showwarningsz-WarningManager.__enter__..showwarning)r0 RuntimeErrorr/filters_filtersr4 _showwarningr-)r'r4r:)r3r; __enter__ws    zWarningManager.__enter__cCs*|jstd||j|j_|j|j_dS)Nz%Cannot exit %r without entering first)r0r5r7r/r6r8r4)r'r:r:r;__exit__s  zWarningManager.__exit__)FN)r6r7r8r9r)r9r:r:r:r:r;r+Vs r+c csVd}tB}||}dVt|dksH|dk r8d|nd}td|WdQRXdS)NTrz when calling %srBzNo warning raised)r5r1r[rD) warning_classrrFZsupruname_strr:r:r;_assert_warns_contexts  r=c OsD|s t|S|d}|dd}t||jd |||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`. rr=N)r)r=r6)r;r\rfuncr:r:r;r+s " c cs`d}tjddF}tddVt|dkrR|dk r>d|nd}td||fWdQRXdS)NT)r1alwaysrz when calling %srBzGot warnings%s: %s)r,catch_warnings simplefilterr[rD)rrFrur<r:r:r;_assert_no_warnings_contexts  rBc Os@|s tS|d}|dd}t|jd |||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`. rr=N)r)rBr6)r\rr>r:r:r;r,s  binaryc #sd}d}xtdD]xtdtd|D]|dkr|fdd}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|dkr6fdd}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 dffVq6WqWd 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, %srrZunarycstddS)N)r)r r:)rorr:r;rrz%_gen_alignment_data..)rNz out of placezin placer=raZaliasedrCcstddS)N)r)r r:)rrErr:r;r rcstddS)N)r)r r:)rrErr:r;r!rz in place1z in place2)rZrr ) rrJZmax_sizeZufmtZbfmtZinprrZinp1Zinp2r:)rrErr;_gen_alignment_datasT"    $$$&&&rFc@seZdZdZdS)r.z/Ignoring this exception due to disabled featureN)r6r7r8r9r:r:r:r;r.9sc os&t||}z |VWdt|XdS)zContext manager to provide a temporary test folder. All arguments are passed as this to the underlying tempfile.mkdtemp function. N)rshutilZrmtree)r\rZtmpdirr:r:r;r2=s  c os4t||\}}t|z |VWdt|XdS)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)rrrrremove)r\rfdrhr:r:r;r1Ls   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 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|_tt|j|ddS)N)r1)setunion class_modulesr._warnreg_copiessuperr/r))r'r1r.) __class__r:r;r)sz!clear_and_catch_warnings.__init__csDx4|jD]*}t|dr|j}||j|<|qWtt|S)N__warningregistry__) r.rrPrrMclearrNr/r9)r'modZmod_reg)rOr:r;r9s    z"clear_and_catch_warnings.__enter__csTtt|j|x>|jD]4}t|dr0|j||jkr|j|j|qWdS)NrP) rNr/r:r.rrPrQrMupdate)r'exc_inforR)rOr:r;r:s     z!clear_and_catch_warnings.__exit__)Fr:) r6r7r8r9rLr)r9r: __classcell__r:r:)rOr;r/bs ( c@steZdZdZdddZddZeddd fd d Zeddfd d ZeddfddZ ddZ ddZ ddZ ddZ dS)r5a Context manager and decorator doing much the same as ``warnings.catch_warnings``. However, it also provides a filter mechanism to work around http://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 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 = suppress_warnings() >>> sup.filter(module=np.ma.core) # module must match exact >>> @sup >>> def some_function(): ... # do something which causes a warning in np.ma.core ... pass r?cCs&d|_g|_|dkrtd||_dS)NF>r?locationoncer2zunsupported forwarding rule.)r0 _suppressionsr_forwarding_rule)r'Zforwarding_ruler:r:r;r)s zsuppress_warnings.__init__cCs>ttdrtdSx"|jD]}t|dr|jqWdS)N_filters_mutatedrP)rr,rZ _tmp_modulesrPrQ)r'r2r:r:r;_clear_registriess    z#suppress_warnings._clear_registriesrBNFcCs|r g}nd}|jr|dkr.tjd||dn8|jddd}tjd|||d|j|||j ||t |t j ||fn |j ||t |t j ||f|S)Nr?)r rV.z\.$)r rVr2)r0r,filterwarningsr6replacer[addr\_tmp_suppressionsrzrrIrX)r'r rVr2r1 module_regexr:r:r;_filters$ zsuppress_warnings._filtercCs|j|||dddS)a Add a new suppressing filter or apply it if the state is entered. Parameters ---------- category : class, optional Warning class to filter message : string, optional Regular expression matching the warning message. module : module, optional Module to filter for. Note that the module (and its file) must match exactly and cannot be a submodule. This may make it unreliable for external modules. Notes ----- When added within a context, filters are only added inside the context and will be forgotten when the context is exited. F)r rVr2r1N)re)r'r rVr2r:r:r;filters 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. T)r rVr2r1)re)r'r rVr2r:r:r;r10s zsuppress_warnings.recordcCs|jrtdtj|_tj|_|jddt_d|_g|_t|_ t|_ g|_ xt|j D]j\}}}}}|dk rx|dd=|dkrtj d||dqX|jddd}tj d|||d|j |qXW|jt_||S) Nz%cannot enter suppress_warnings twice.Tr?)r rVr]z\.r^)r rVr2)r0r5r,r4 _orig_showr6r7rbrJr[ _forwardedr3rXr_r6r`rar8r\)r'catZmessrrRr3rdr:r:r;r9Ns0 zsuppress_warnings.__enter__cGs*|jt_|jt_|d|_|`|`dS)NF)rgr,r4r7r6r\r0)r'rTr:r:r;r:ns zsuppress_warnings.__exit__cOs|dd}x|j|jdddD]\}} } } } t||r$| |jddk r$| dkr| dk rt||||f|} |j| | | dS| j |r$| dk rt||||f|} |j| | | dSq$W|j dkr|dkr|j ||||f||n | |dS|j dkr&|j|f}n4|j dkr@|j||f}n|j dkrZ|j|||f}||jkrjdS|j||dkr|j ||||f||n | |dS)N use_warnmsgrarr?rWr2rV)rrXrb issubclassrr\rr3rzrrrYrgZ _orig_showmsgrhra)r'rVr rr!r\rrjrirpatternrRZrecr@Z signaturer:r:r;r8vsL $                   zsuppress_warnings._showwarningcstfdd}|S)z_ Function decorator to apply certain suppressions to a whole function. c s ||SQRXdS)Nr:)r\r)r>r'r:r;new_funcsz,suppress_warnings.__call__..new_func)r)r'r>rmr:)r>r'r;__call__szsuppress_warnings.__call__)r?)r6r7r8r9r)r\Warningrerfr1r9r:r8rnr:r:r:r;r5sF   4)rB)NraNN)rjr)r|Tr}r~)rBT)rrBT)rrBT)rBTrBrTT)rBT)rrBT)rBT)NT)N)r=N)rrTrBT)r=)r=N)N)N)N)]r9Z __future__rrrrrrrr, functoolsrrrG contextlibZtempfilerrZ unittest.caser rHr r r r rrrZnumpy.lib.utilsrrior__all__rr0ZKnownFailureTestr%r.r3getattrr4rAr'rNrSrUr"rrirplatformgetpidrrrr rrrrrrr$rr#r!rr)rr&rr-r(r*rrrrdrr+contextmanagerr=r+rBr,rFr.r2r1r@r/r5r:r:r:r;s $              ) z b k D l IF . / 0 9 ? - 6!9 + $EA