a
    p=icM                    @   s  d Z ddlZddlZddlZddlZddlZddlZddlZddlm	Z	m
Z
 ddlZddlZddlmZmZ ddlmZ ddlmZ ddlZddlZddlmZmZmZmZmZmZmZmZ ddlZddl m!Z! g d	Z"G d
d de#Z$e$Z%dZ&e' dkZ(e)edZ*e+eddduoe* Z,ej-j.j/Z0dd Z1dddZ2dd Z3dd Z4dd Z5ej6dkrtdddZ7ddd Z8n6ejdd! d"krd#e9  d$fd%d Z8nd&d  Z8ejdd! d"krd#e9  d$g fd'd(Z:ng fd)d(Z:dd.d/Z;dd0d1Z<d2d3 Z=dd5d6Z>dd7d8Z?dd:d;Z@dd<d=ZAdd>d?ZBdd@dAZCdBdC ZDdDdE ZEddFdGZFdHdI ZGddlHZHG dJdK dKeHjIZJeJdLZKdMdN ZLdOdP ZMddQdRZNddTdUZOdVdW ZPddYdZZQdd[d\ZRdd]d^ZSdd_d`ZTdadb ZUdcdd ZVejWddedfZXdgdh ZYejWddidjZZdkdl Z[edmdnfdodpZ\G dqdr dre#Z]ejWdsdt Z^ejWdudv Z_G dwdx dxej`ZaG dydz dzZbejWdd{d|Zcd}d~ Zddd Zedd Zfdd Zgdd Zhdd Zidd Zjdd Zkek Zldd ZmdS )z*
Utility function to facilitate testing.

    N)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_no_gc_cyclesbreak_cyclesHAS_LAPACK64	IS_PYSTONc                   @   s   e Zd ZdZdS )r,   z<Raise this exception to mark a test as a known failing test.N__name__
__module____qualname____doc__ r<   r<   m/home/droni/.local/share/virtualenvs/DPS-5Je3_V2c/lib/python3.9/site-packages/numpy/testing/_private/utils.pyr,   *   s   r,   PyPyZpyston_version_infogetrefcountc                  C   sR   d} d}zddl }W n ty*   d} Y n0 |j|k r:d} | sNd| }t||S )z# Import nose only when needed.
    T)   r   r   r   NFzANeed nose >= %d.%d.%d for tests - see https://nose.readthedocs.io)noseImportErrorZ__versioninfo__)Znose_is_goodZminimum_nose_versionrA   msgr<   r<   r=   import_nose8   s    

rD    c                 C   s6   d}| s2z
| }W n t y(   |}Y n0 t|dS )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)valrC   __tracebackhide__Zsmsgr<   r<   r=   r#   N   s    

r#   c                 C   s.   ddl m} || }t|ttr*td|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.corerJ   
isinstancetypeNotImplementedrF   )xrJ   str<   r<   r=   gisnanb   s
    rQ   c                 C   s\   ddl m}m} |dd. || }t|ttr:tdW d   n1 sN0    Y  |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 typeN)rK   rR   rS   rL   rM   rN   rF   )rO   rR   rS   rP   r<   r<   r=   	gisfinitet   s    &rW   c                 C   s\   ddl m}m} |dd. || }t|ttr:tdW d   n1 sN0    Y  |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   )isinfrS   rT   rU   z!isinf not supported for this typeN)rK   rX   rS   rL   rM   rN   rF   )rO   rX   rS   rP   r<   r<   r=   gisinf   s    &rY   ntc              	   C   s   dd l }|d u r|j}||| |d ||f}| }z^|||}	z6|| ||	|\}
}|W ||	 W || S ||	 0 W || n|| 0 d S )Nr   )	win32pdhPDH_FMT_LONGZMakeCounterPathZ	OpenQueryZ
AddCounterZCollectQueryDataZGetFormattedCounterValueZRemoveCounterZ
CloseQuery)objectcounterinstanceZinumformatmachiner\   pathZhqZhcrM   rH   r<   r<   r=   GetPerformanceAttributes   s&    



rd   pythonc                 C   s   dd l }tdd| ||jd S )Nr   ProcesszVirtual Bytes)r\   rd   r]   )processNamer`   r\   r<   r<   r=   r      s
    r      linuxz/proc/z/statc                 C   s`   zFt | d}| d}W d   n1 s00    Y  t|d W S  tyZ   Y dS 0 dS )zM
        Return virtual memory size in bytes of the running python.

        r N   )openreadlinesplitint	Exception)_proc_pid_statflr<   r<   r=   r      s    ,c                   C   s   t dS )zK
        Return memory usage of running python. [Not implemented]

        N)NotImplementedErrorr<   r<   r<   r=   r      s    c                 C   s   ddl }|s||   zFt| d}| d}W d   n1 sJ0    Y  t|d W S  ty   td|  |d    Y S 0 dS )
        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.

        r   Nrj   rk      d   )timeappendrm   rn   ro   rp   rq   )rr   
_load_timery   rs   rt   r<   r<   r=   r      s    ,r   c                 C   s2   ddl }| s| |   td|  | d   S )rv   r   Nrx   )ry   rz   rp   )r{   ry   r<   r<   r=   r      s    Items are not equal:TZACTUALZDESIRED   c                 C   s  d| g}|rN| ddkrDt|dt| k rD|d d | g}n
|| |rt| D ]\}}t|tr|tt|d}	nt}	z|	|}
W n< t	y } z$dt
|j d| d	}
W Y d }~n
d }~0 0 |
dd
krd|
 d d
 }
|
d7 }
|d||  d|
  q\d|S )N
r[   O   r   rk   )	precisionz[repr failed for <z>: ]   z...: )findlenrz   	enumeraterL   r   r   r   reprrq   rM   r8   countjoin
splitlines)Zarrayserr_msgheaderr!   namesr   rC   iaZr_funcrj   excr<   r<   r=   r      s&    
"

.r   c              
   C   s  d}t |trt | ts(ttt| tt| t||| | D ]>\}}|| vrbtt|t| | || d|d| | qFdS t |tt	frt | tt	frtt| t||| t
t|D ]&}t| | || d|d| | qdS ddlm}m}m}	 ddlm}
m}m} t | |s4t ||rBt| |||S t| |g||d	}z|
| pf|
|}W n ttfy   d
}Y n0 |r|
| r|| }|| }n| }d}|
|r||}||}n|}d}zt|| t|| W n ty
   t|Y n0 |||| kr&t|zPt|}t| }t|jjt| jjk}|rt|rt|rlW dS t|W n tttfy   Y n0 zt|}t| }|r|rW dS t| }t|}|jjdv s|jjdv rtd|dkr| dkr|	||	| kst|W n tttfy8   Y n0 z|| ksNt|W nF ttfy } z(d|j d v rt|n W Y d}~n
d}~0 0 dS )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])

    Tzkey=r   Nzitem=r   )r   isscalarsignbitiscomplexobjrealimagr!   FMmz0cannot compare to a scalar with a different typezelementwise == comparison)!rL   dictrG   r   rM   r   r   itemslisttuplerangerK   r   r   r   	numpy.libr   r   r   r   r   
ValueErrorrF   r   npasarraydtyperu   rQ   charDeprecationWarningFutureWarningargs)actualdesiredr   r!   rI   kr   r   r   r   r   r   r   rC   
usecomplexactualractualidesiredrdesirediZisdesnatZisactnatZdtypes_matchZisdesnanZisactnanZarray_actualZarray_desireder<   r<   r=   r     s    2












r   c                 C   s`   d}ddl }||ks\t }||  |d | || |d | || t| dS )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]

    Tr   Nz failed
ACTUAL: 
z
DESIRED: 
)pprintr   writerG   getvalue)test_stringr   r   rI   r   rC   r<   r<   r=   r     s    


r      c              	      s  d}ddl m} ddlm}m}m}	 z| p4|}
W n tyN   d}
Y n0  fdd}|
r| r| }|	 }n }d}|r|}|	}n}d}z t||d t||d W n ty   t| Y n0 t	 |t
tfst	|t
tfrt S zftr2t stsFt rftrZt szt| n kszt| W d	S W n ttfy   Y n0 t  d
d   krt| 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
    <BLANKLINE>
    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   r   Fc                     s   d } t  g| dS )N*Arrays are not almost equal to %d decimals)r!   r   )r   )r   r   decimalr   r   r!   r<   r=   _build_err_msg-  s    z+assert_almost_equal.<locals>._build_err_msg)r   N      ?      $@)rK   r   r   r   r   r   r   r   rG   rL   r   r   r   rW   rQ   ru   rF   abs)r   r   r   r   r!   rI   r   r   r   r   r   r   r   r   r   r   r<   r   r=   r     sP    E





r   c              	   C   s  d}ddl }tt| |f\} }|| kr*dS |jdd@ d||||   }|d|||}W d   n1 s|0    Y  z|| }W n ty   d}Y n0 z| | }	W n ty   d}	Y n0 t	| |g|d	| |d
}
z`t
|rt
| sDt|st| r,t|r"t| s>t|
n|| ks>t|
W dS W n ttfy^   Y n0 |||	 |d|d  krt|
dS )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

    Tr   NrT   rU   g      ?
   g        z-Items are not equal to %d significant digits:)r   r!   r   r@   )numpymapfloatrS   r   powerfloorlog10ZeroDivisionErrorr   rW   rQ   rG   rF   ru   )r   r   Zsignificantr   r!   rI   r   scaleZ
sc_desiredZ	sc_actualrC   r<   r<   r=   r   Z  sB    :6




"r      c	           %         s  d}	ddl m}
m}m}mm m}m}m}m	} t
|}t
|}|| }}dd }dd }|df fd	d
	}z|jdkp|jdkp|j|jk}|st||gd|j d|j d dd}t| d}||rH||rH|r||||dd}|r||||fddddO }||||fddddO }n<||r||r|r|jj|jjkr|||tdd}|jdkr||  ||   }}|jdkrW d S n|rW d S | ||}t|tr|}|
|g}n| }| }|dkr|j|jtd }|jdkr*|jn|j}d| | }d|||g}|dd tt t|| }||} t|d||kr|dt |   n|d||    |dk}!||! r|
}"n|||! t||!  }"t|d||kr|d t |"  n|d ||"  W d    n1 s80    Y  W d    n1 sX0    Y  d!d!!| 7 t||gdd}t|W nT t"y   dd l#}#|#$ }$d"|$ d# t||gdd}t"|Y n0 d S )$NTr   )	r   array2stringrJ   infbool_rS   allmaxobject_c                 S   s   | j jdv S )Nz?bhilqpBHILQPefdgFDGr   r   rO   r<   r<   r=   isnumber  s    z&assert_array_compare.<locals>.isnumberc                 S   s   | j jdv S )Nr   r   r   r<   r<   r=   istime  s    z$assert_array_compare.<locals>.istimenanc                    s   d}|| }||} ||k  dkrPt| |gd|  dd}t|t|tsd|jdkrl |S t|ts|jdkr |S |S d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:rO   yr!   r   r   r   r   N)r   r   rG   rL   boolndim)rO   r   funchasvalrI   Zx_idZy_idrC   )r   r   r   r   r!   r<   r=   func_assert_same_pos  s"    z2assert_array_compare.<locals>.func_assert_same_posr<   z	
(shapes z, z
 mismatch)r   r   F)r   r   c                    s
   |  
 kS Nr<   Zxyr   r<   r=   <lambda>      z&assert_array_compare.<locals>.<lambda>z+infc                    s
   |   kS r   r<   r   r   r<   r=   r     r   z-infZNaTr   rx   z&Mismatched elements: {} / {} ({:.3g}%)rT   )r   r   zMax absolute difference: zMax relative difference: r   zerror during assertion:

z

)%rK   r   r   rJ   r   r   rS   r   r   r   r   
asanyarrayshaper   rG   r   rM   r   r   sizerL   r   Zravelsumr   ra   
contextlibsuppressrF   r   getattrrz   strr   r   	traceback
format_exc)%Z
comparisonrO   r   r   r!   r   r   	equal_nan	equal_infrI   r   r   rJ   rS   r   r   r   oxZoyr   r   r   ZcondrC   ZflaggedrH   ZreducedZ
n_mismatchZ
n_elementsZpercent_mismatchZremarkserrorZmax_abs_errorZnonzeroZmax_rel_errorr   Zefmtr<   )r   r   r   r   r   r!   r=   r2     s    ,


% 





F
r2   c                 C   s   d}t tj| |||dd dS )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
    <BLANKLINE>
    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)

    TzArrays are not equal)r   r!   r   N)r2   operator__eq__rO   r   r   r!   rI   r<   r<   r=   r   W  s    Nr   c              	      sh   d}ddl mmmm} ddlm ddlm  fdd}t	|| |||d   d	 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
    <BLANKLINE>
    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
    <BLANKLINE>
    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<W dS | j|j  krTdkrbn n
| |kW S | |  } ||  }W n ttfy   Y n0 |d}t||}t| | }|js|	}|dd    k S )NFr@   g      ?r   r   )
rY   r   r   rF   ru   r   r   r   r   Zastype)rO   r   ZxinfidZyinfidr   zr   r   r   Znpanyr   r   r<   r=   compare  s$    



z*assert_array_almost_equal.<locals>.comparer   )r   r!   r   r   N)
rK   r   r   r   r   Znumpy.core.numerictypesr   Znumpy.core.fromnumericr   r2   )rO   r   r   r   r!   rI   r   r   r<   r   r=   r     s    Mr   c              	   C   s    d}t tj| |||ddd dS )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
    <BLANKLINE>
    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
    <BLANKLINE>
    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
    <BLANKLINE>
    (shapes (3,), (1,) mismatch)
     x: array([1., 2., 3.])
     y: array([4])

    TzArrays are not less-orderedF)r   r!   r   r   N)r2   r   __lt__r   r<   r<   r=   r     s    Lr   c                 C   s   t | | d S r   )exec)Zastrr   r<   r<   r=   r    n  s    r    c                 C   s  d}ddl }t| ts&ttt| t|ts@ttt||| krLdS t| | 	d|	d}g }|rP|
d}|drqp|drB|g}|
d}|dr|| |
d}|dstt||| |r|
d}	|	dr||	 n|d|	 |dd |dd kr6qp|| qptt|qp|sZdS d	d
|  }
| |krt|
dS )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 "<stdin>", line 1, in <module>
    ...
    AssertionError: Differences in strings:
    - abc+ abcd?    +

    Tr   Nz  z- z? z+    zDifferences in strings:
rE   )difflibrL   r   rG   r   rM   r   Differr   r   pop
startswithrz   insertextendr   rstrip)r   r   rI   r   diffZ	diff_listd1rt   d2Zd3rC   r<   r<   r=   r   r  sP    












r   c                    s   ddl m} ddl}| du r0td}|jd } tjtj	| d }||| }|
 |}|jdd}g  |r fdd	}	nd}	|D ]}
|j|
|	d
 q|jdkr|rtdd  dS )aV  
    Run doctests found in the given file.

    By default `rundocs` raises an AssertionError on failure.

    Parameters
    ----------
    filename : str
        The path to the file for which the doctests are run.
    raise_on_error : bool
        Whether to raise an AssertionError when a doctest fails. Default is
        True.

    Notes
    -----
    The doctests can be run by the user/developer by adding the ``doctests``
    argument to the ``test()`` call. For example, to run all tests (including
    doctests) for `numpy.lib`:

    >>> np.lib.test(doctests=True)  # doctest: +SKIP
    r   )exec_mod_from_locationNr@   __file__Fr   c                    s
     | S r   )rz   )srC   r<   r=   r     r   zrundocs.<locals>.<lambda>)outzSome doctests failed:
%sr   )Znumpy.distutils.misc_utilr  doctestsys	_getframe	f_globalsosrc   splitextbasenameZDocTestFinderr   ZDocTestRunnerrunZfailuresrG   r   )filenameZraise_on_errorr  r  rs   namemtestsrunnerr
  testr<   r	  r=   r     s"    


r   c                  G   s   t  }|jj|  S )a  Decorator 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

    )rD   Ztoolsr   )r   rA   r<   r<   r=   r     s    "r   c                   @   s   e Zd Zdd ZdS )_Dummyc                 C   s   d S r   r<   )selfr<   r<   r=   nop  s    z
_Dummy.nopN)r8   r9   r:   r  r<   r<   r<   r=   r    s   r  r  c                  O   s   d}t j| 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)r   kwargsrI   r<   r<   r=   r     s    r   c                 O   s   d}t j| |g|R i |S )a  
    assert_raises_regex(exception_class, expected_regexp, callable, *args,
                        **kwargs)
    assert_raises_regex(exception_class, expected_regexp)

    Fail unless an exception of class exception_class and with message that
    matches expected_regexp is thrown by callable when invoked with arguments
    args and keyword arguments kwargs.

    Alternatively, can be used as a context manager like `assert_raises`.

    Notes
    -----
    .. versionadded:: 1.9.0

    T)r  assertRaisesRegex)Zexception_classZexpected_regexpr   r  rI   r<   r<   r=   r%   5  s    r%   c              	      s   |du rt dtj }n
t |}| j}ddlm   fdd| D }|D ]\}zt|drh|j	}n|j
}W n ty   Y qPY n0 ||rP|dsPt| ||| qPdS )	a  
    Apply a decorator to all methods in a class matching a regular expression.

    The given decorator is applied to all public methods of `cls` that are
    matched by the regular expression `testmatch`
    (``testmatch.search(methodname)``). Methods that are private, i.e. start
    with an underscore, are ignored.

    Parameters
    ----------
    cls : class
        Class whose methods to decorate.
    decorator : function
        Decorator to apply to methods
    testmatch : compiled regexp or str, optional
        The regular expression. Default value is None, in which case the
        nose default (``re.compile(r'(?:^|[\b_\.%s-])[Tt]est' % os.sep)``)
        is used.
        If `testmatch` is a string, it is compiled to a regular expression
        first.

    Nz(?:^|[\\b_\\.%s-])[Tt]estr   
isfunctionc                    s   g | ]} |r|qS r<   r<   ).0_mr   r<   r=   
<listcomp>j  r   z$decorate_methods.<locals>.<listcomp>compat_func_name_)recompiler  sep__dict__inspectr!  valueshasattrr%  r8   AttributeErrorsearchr   setattr)cls	decoratorZ	testmatchZcls_attrmethodsfunctionfuncnamer<   r   r=   r   J  s     



r   r@   c           	      C   sf   t d}|j|j }}t| d| dd}d}t }||k rT|d7 }t||| q6t | }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

    r@   zTest name: rk   r   r   g{Gz?)r  r  f_localsr  r(  r   r   )	Zcode_strtimeslabelframelocsglobscoder   elapsedr<   r<   r=   r"   y  s    !

r"   c           	      C   s   t sdS ddl}ddl}|ddd}|}d}|  z@t|}tdD ]}| ||}qNt	t||k W |
  n
|
  0 ~dS )zg
    Check that ufuncs don't mishandle refcount of object `1`.
    Used in a few regression tests.
    Tr   Ni'  rx   r@      )r0   gcr   r   Zreshapedisabler  r?   r   r#   enable)	opr?  r   bcr   rcjdr<   r<   r=   _assert_valid_refcount  s    
rH  Hz>c           
   	      sf   d}ddl  fdd}| | } }ddd d}	t|| |t|||	d	 dS )
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)

    Tr   Nc                    s   j jj| | dS )N)rtolatolr   )corenumericiscloser   rK  r   r   rJ  r<   r=   r     s    z assert_allclose.<locals>.comparezNot equal to tolerance rtol=gz, atol=)r   r!   r   r   )r   r   r2   r   )
r   r   rJ  rK  r   r   r!   rI   r   r   r<   rO  r=   r)     s    -r)   c           
      C   s   d}ddl }|| }||}|||||k|| }||| | |ks|| sh||rrd| }n|t| |}	d||	f }t|dS )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)

    Tr   NzX 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_diffrG   )
rO   r   ZnulprI   r   axZayrefrC   Zmax_nulpr<   r<   r=   r$     s    1


r$   c                 C   s@   d}ddl }t| ||}|||ks<td|||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)))

    Tr   NzCArrays are not almost equal up to %g ULP (max difference is %g ULP))r   rS  r   rG   r   )r   rC  Zmaxulpr   rI   r   retr<   r<   r=   r&   :  s    *r&   c                    s   ddl  |r* j| |d}  j||d}n | }  |} | |} | s^ |rftd j| g|d}  j|g|d} j|  | <  j| |< | j|jkst	d| j|jf  fdd}t
| }t
|}||||S )an  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.

    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
    r   Nr   z'_nulp not implemented for complex arrayz+x and y do not have the same shape: %s - %sc                    s    j | | |d} |S Nr   )r   r   )rxryvdtr  r   r<   r=   _diff  s    znulp_diff.<locals>._diff)r   r   Zcommon_typer   ru   r   r   rJ   r   r   integer_repr)rO   r   r   tr\  rX  rY  r<   r[  r=   rS  n  s*     


rS  c                 C   sB   |  |}|jdks.|||dk   ||dk < n|dk r>|| }|S )Nr@   r   )viewr   )rO   rZ  comprX  r<   r<   r=   _integer_repr  s    

ra  c                 C   s|   ddl }| j|jkr(t| |j|dS | j|jkrHt| |j|dS | j|jkrht| |j|dS t	d| j dS )zQReturn the signed-magnitude interpretation of the binary representation
    of x.r   Ni i   l         zUnsupported dtype )
r   r   float16ra  int16r	   int32float64int64r   )rO   r   r<   r<   r=   r]    s    r]  c                 c   sl   d}t  N}|| }d V  t|dksJ|d ur:d| nd}td| W d    n1 s^0    Y  d S )NTr    when calling rE   zNo warning raised)r1   recordr   rG   )warning_classr  rI   suprt   name_strr<   r<   r=   _assert_warns_context  s    
rl  c                 O   s`   |st | S |d }|dd }t | |jd ||i |W  d   S 1 sR0    Y  dS )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
    r   r@   Nr  )rl  r8   )ri  r   r  r   r<   r<   r=   r'     s    -r'   c                 c   sz   d}t jddV}t d d V  t|dkrX| d ur@d|  nd}td| d| W d    n1 sl0    Y  d S )	NTrh  alwaysr   rg  rE   zGot warningsr   )warningscatch_warningssimplefilterr   rG   )r  rI   rt   rk  r<   r<   r=   _assert_no_warnings_context  s    
rs  c                  O   s\   | s
t  S | d }| dd } t |jd || i |W  d   S 1 sN0    Y  dS )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`.

    r   r@   Nrm  )rs  r8   r   r  r   r<   r<   r=   r(     s    r(   binary   c           
      #   s  d}d}t dD ]t d td |D ]|dkrt fdd}tf dd	 }|| | d
f fV  | }||| df fV  |dd	 | d	d |d d  d
f fV  |d	d | dd	 |d d  d
f fV  | d	d | dd	 |d d  df fV  | dd	 | d	d |d d  df fV  |dkr. fdd} fdd}	tf dd	 }|| |	 | d
f fV  | }|||	 | df fV  |	 }|| || df fV  |dd	 | d	d |	 d	d |d d  d
f fV  |d	d | dd	 |	 d	d |d d  d
f fV  |d	d | d	d |	 dd	 |d d  d
f fV  | dd	 | d	d |	 d	d |d d  df fV  | d	d | dd	 |	 d	d |d d  df fV  | d	d | d	d |	 dd	 |d d  df fV  q.q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, %sr   r   Zunaryc                      s   t  dd  S rW  r   r<   r   or  r<   r=   r   X  r   z%_gen_alignment_data.<locals>.<lambda>r   Nzout of placezin placer@   r[   aliasedru  c                      s   t  dd  S rW  rw  r<   rx  r<   r=   r   f  r   c                      s   t  dd  S rW  rw  r<   rx  r<   r=   r   g  r   z	in place1z	in place2)r   r   r
   )
r   rM   max_sizeZufmtZbfmtinpr
  rG  Zinp1Zinp2r<   rx  r=   _gen_alignment_data:  sn    


$$$&&&r}  c                   @   s   e Zd ZdZdS )r*   z/Ignoring this exception due to disabled featureNr7   r<   r<   r<   r=   r*     s   r*   c               	   o   s4   t | i |}z|V  W t| nt| 0 dS )zContext manager to provide a temporary test folder.

    All arguments are passed as this to the underlying tempfile.mkdtemp
    function.

    N)r   shutilrmtree)r   r  Ztmpdirr<   r<   r=   r.     s    r.   c               	   o   sB   t | i |\}}t| z|V  W t| nt| 0 dS )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)r   r  closeremove)r   r  fdrc   r<   r<   r=   r-     s
    
r-   c                       s>   e Zd ZdZdZd
 fdd	Z fddZ fdd	Z  ZS )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<   Fc                    s*   t || j| _i | _t j|d d S )Nrn  )setunionclass_modulesmodules_warnreg_copiessuper__init__)r  rh  r  	__class__r<   r=   r    s    z!clear_and_catch_warnings.__init__c                    s<   | j D ]*}t|dr|j}| | j|< |  qt  S N__warningregistry__)r  r-  r  copyr  clearr  	__enter__)r  modZmod_regr  r<   r=   r    s    


z"clear_and_catch_warnings.__enter__c                    sL   t  j|  | jD ]4}t|dr*|j  || jv r|j| j|  qd S r  )r  __exit__r  r-  r  r  r  update)r  exc_infor  r  r<   r=   r    s    



z!clear_and_catch_warnings.__exit__)Fr<   )	r8   r9   r:   r;   r  r  r  r  __classcell__r<   r<   r  r=   r+     s
   )r+   c                   @   sz   e Zd ZdZdddZdd Zeddd	fd
dZeddfddZeddfddZ	dd Z
dd ZddddZdd ZdS )r1   a  
    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
    ro  c                 C   s&   d| _ g | _|dvrtd|| _d S )NF>   locationro  moduleoncezunsupported forwarding rule.)_entered_suppressionsr   _forwarding_rule)r  Zforwarding_ruler<   r<   r=   r  5  s
    zsuppress_warnings.__init__c                 C   s:   t tdrt  d S | jD ]}t |dr|j  qd S )N_filters_mutatedr  )r-  rp  r  _tmp_modulesr  r  )r  r  r<   r<   r=   _clear_registries?  s    


z#suppress_warnings._clear_registriesrE   NFc                 C   s   |r
g }nd }| j r|d u r.tjd||d n8|jddd }tjd|||d | j| |   | j	||t
|t
j||f n | j	||t
|t
j||f |S )Nro  categorymessage.\.$r  r  r  )r  rp  filterwarningsr8   replacer  addr  _tmp_suppressionsrz   r'  r(  Ir  )r  r  r  r  rh  module_regexr<   r<   r=   _filterK  s,    zsuppress_warnings._filterc                 C   s   | j |||dd dS )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  rh  Nr  r  r  r  r  r<   r<   r=   filterd  s    
zsuppress_warnings.filterc                 C   s   | j |||dd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  r<   r<   r=   rh  {  s    
zsuppress_warnings.recordc                 C   s   | j rtdtj| _tj| _| jd d  t_d| _ g | _t | _	t | _
g | _| jD ]j\}}}}}|d urv|d d = |d u rtjd||d qV|jddd }tjd|||d | j	| qV| jt_|   | S )	Nz%cannot enter suppress_warnings twice.Tro  r  r  r  r  r  )r  RuntimeErrorrp  showwarning
_orig_showfilters_filtersr  r  r  
_forwardedlogr  r  r8   r  r  _showwarningr  )r  catZmessr&  r  r  r  r<   r<   r=   r    s4    
zsuppress_warnings.__enter__c                 G   s*   | j t_| jt_|   d| _| ` | `d S )NF)r  rp  r  r  r  r  r  )r  r  r<   r<   r=   r    s    zsuppress_warnings.__exit__)use_warnmsgc                O   s  | j | j d d d D ]\}}	}
}}t||r|
|jd d ur|d u r|d ur~t||||fi |}| j| ||  d S |j	|r|d urt||||fi |}| j| ||  d S q| j
dkr|d u r| j||||g|R i | n
| | d S | j
dkr(|j|f}n4| j
dkrB|j||f}n| j
dkr\|j|||f}|| jv rld S | j| |d u r| j||||g|R i | n
| | d S )Nr[   r   ro  r  r  r  )r  r  
issubclassmatchr   r   r  rz   r  r   r  r  Z_orig_showmsgr  r  )r  r  r  r  linenor  r   r  r  r&  patternr  ZrecrC   	signaturer<   r<   r=   r    s`    





zsuppress_warnings._showwarningc                    s   t   fdd}|S )z_
        Function decorator to apply certain suppressions to a whole
        function.
        c                     s6     | i |W  d    S 1 s(0    Y  d S r   r<   )r   r  r   r  r<   r=   new_func  s    z,suppress_warnings.__call__.<locals>.new_funcr   )r  r   r  r<   r  r=   __call__  s    zsuppress_warnings.__call__)ro  )r8   r9   r:   r;   r  r  Warningr  r  rh  r  r  r  r  r<   r<   r<   r=   r1     s   I

 	3r1   c              
   c   s  d}t sd V  d S tt  t  t }zptdD ]}t dkr8 qVq8tdt	tj
 d V  t }tjd d  }W tjd d = t	| t  n tjd d = t	| t  0 |r| d urd|  nd}td||t|ddd	 |D d S )
NTrx   r   z]Unable to fully collect garbage - perhaps a __del__ method is creating more reference cycles?rg  rE   zXReference cycles were found{}: {} objects were collected, of which {} are shown below:{}c              	   s   s4   | ],}d  t|jt|t|ddV  qdS )z
  {} object with id={}:
    {}r   z
    N)ra   rM   r8   idr   pformatr  )r"  ry  r<   r<   r=   	<genexpr>*	  s   z/_assert_no_gc_cycles_context.<locals>.<genexpr>)r0   r#   r?  	isenabledr@  	get_debugr   collectr  	set_debugZDEBUG_SAVEALLgarbagerA  rG   ra   r   r   )r  rI   Zgc_debugr   Zn_objects_in_cyclesZobjects_in_cyclesrk  r<   r<   r=   _assert_no_gc_cycles_context	  sH    




r  c                  O   s\   | s
t  S | d }| dd } t |jd || i | W d   n1 sN0    Y  dS )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.

    r   r@   Nrm  )r  r8   rt  r<   r<   r=   r3   5	  s    r3   c                   C   s0   t   tr,t   t   t   t   dS )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  r/   r<   r<   r<   r=   r4   W	  s    	r4   c                    s   ddl  fdd}|S )z:Decorator to skip a test if not enough memory is availabler   Nc                    s   t   fdd}|S )Nc                     sL   t  }|d ur| z| i |W S  tyF   d Y n0 d S )NzMemoryError raised)check_free_memoryskipMemoryErrorZxfail)r   kwrC   )
free_bytesr   pytestr<   r=   wrappern	  s    
z3requires_memory.<locals>.decorator.<locals>.wrapperr  r   r  r  r  r   r=   r2  m	  s    z"requires_memory.<locals>.decorator)r  )r  r2  r<   r  r=   requires_memoryi	  s    r  c              
   C   s   d}t j|}|durtzt|}W n8 ty\ } z td| d| W Y d}~n
d}~0 0 | d  d| d}n0t }|du rd}d	}n| d  d
|d  d}|| k r|S dS )z
    Check whether `free_bytes` amount of memory is currently free.
    Returns: None if enough memory available, otherwise error message
    ZNPY_AVAILABLE_MEMNzInvalid environment variable r   g    eAz@ GB memory required, but environment variable NPY_AVAILABLE_MEM=z setzCould not determine available memory; set NPY_AVAILABLE_MEM environment variable (e.g. NPY_AVAILABLE_MEM=16GB) to run the test.r[   z GB memory required, but z GB available)r  environget_parse_sizer   _get_mem_available)r  env_varZ	env_valueZmem_freer   rC   r<   r<   r=   r  	  s     *

r  c                 C   s   dddddddddddddd	d
}t dd| t j}||  }|r`|d|vrpt	d| dt
t|d||d  S )z3Convert memory size strings ('12 GB' etc.) to floatr@   i  i@B i ʚ;l    J)   i   i   @l        )rE   rC  r   r  rP  r^  kbmbgbtbZkibZmibZgibZtibz^\s*(\d+|\d+\.\d+)\s*({0})\s*$|r   zvalue z not a valid size)r'  r(  ra   r   keysr  r  lowergroupr   rp   r   )Zsize_strsuffixesZsize_rer  r<   r<   r=   r  	  s    r  c               	   C   s   zddl } |  jW S  ttfy*   Y n0 tjdri }tddD}|D ].}|	 }t
|d d ||d d < qLW d   n1 s0    Y  d	|v r|d	 S |d
 |d  S dS )z5Return available memory in bytes, or None if unknown.r   Nri   z/proc/meminforj   r@   r  :ZmemavailableZmemfreecached)psutilZvirtual_memory	availablerB   r.  r  platformr   rm   ro   rp   stripr  )r  infors   linepr<   r<   r=   r  	  s    Br  c                    s*   t tds S t  fdd}|S d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  }z$t d   | i |W t | S t | 0 d S r   )r  r  settrace)r   r  Zoriginal_tracer  r<   r=   r  	  s    

z_no_tracing.<locals>.wrapperN)r-  r  r   r  r<   r  r=   _no_tracing	  s
    
r  c               
   C   sF   zt ddd } W n( ty@ } zd} W Y d }~n
d }~0 0 | S )NCS_GNU_LIBC_VERSIONrk   r@   0.0)r  confstrrsplitrq   )verinstr<   r<   r=   _get_glibc_version	  s
    r  c                 C   s   t dkot | k S )Nr  )	_glibcverr   r<   r<   r=   r   	  r   r   )rE   )Nr[   NN)re   r   )r|   Tr}   r~   )rE   T)r   rE   T)r   rE   T)rE   TrE   r   TT)rE   T)r   rE   T)rE   T)NT)N)r@   N)rI  r   TrE   T)r@   )r@   N)N)N)N)N)nr;   r  r  r  r'  r?  r   rp  	functoolsr   r   r~  r   tempfiler   r   Zunittest.caser   r   r   r   r   rK   r   r	   r
   r   r   r   r   r   Znumpy.linalg.lapack_liteior   __all__rq   r,   ZKnownFailureTestr!   python_implementationr/   r-  r6   r   r0   ZlinalgZlapack_liteZ_ilp64r5   rD   r#   rQ   rW   rY   r  rd   r   getpidr   r   r   r   r   r   r2   r   r   r   r    r   r   r   ZunittestZTestCaser  r  r   r%   r   r"   rH  r)   r$   r&   rS  ra  r]  contextmanagerrl  r'   rs  r(   r}  r*   r.   r-   rq  r+   r1   r  r3   r4   r  r  r  r  r  r  r  Z_glibc_older_thanr<   r<   r<   r=   <module>   s   (


  
  

 !)
~
c  
 
S
q
SG
.(
/
.  
:
?
4
?
6
$E

B  3"	