o
    hu                    @   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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Zddl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m&Z&m'Z'm(Z( ddl)Zdd	l*m+Z+ dd
l,m-Z- ddl.m/Z/ g dZ0G dd de1Z2e2Z3dZ4e5ej6j7Z8zej9:dZ;W n ej9j<y   d Z=Z>Y nCw dZ=z'ej?dkre;j@jAjBZ>nddlCZCddlDZDeCjEe;Fdpddd dZ@e@jAjBZ>W n eGy   dZ>Y nw e>se;Hde8krdZ=eI dv ZJejKjLdkZMeNedZOePeddduoeO ZQejRjSjTZUdZVeWdp.dZXdeXv r6dZVeYeWdZZe[ejj\d kZ]dd!d"Z^ejLd#kr^		dd%d&Z_dd(d)Z`nejdd* d+krud,ea  d-fd.d)Z`nd/d) Z`ejdd* d+krd,ea  d-g fd0d1Zbng fd2d1Zb	3	 dd5d6Zcddd7d8d9Zdd:d; Zedd=d>Zf		dd?d@Zg		ddd4dBdCdDZhe+dEdFgdGdHgdIdJddd7dKdLZie+dEdFgdGdHgdIdJ		ddMdNZjddd7dOdPZkdQdR ZldSdT ZmddUdVZng fdWdXZoddlpZpG dYdZ dZepjqZrerd[Zsd\d] Ztd^d_ Zudd`daZvddcddZwdedf Zx		ddd7dhdiZyddjdkZzddldmZ{ddndoZ|dpdq Z}drds Z~ejddtduZdvdw ZejddxdyZdzd{ Zed|d}fd~dZG dd de1Zejdd Zejdd ZG dd dejZG dd dZejdddZdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Ze Zdd Z		b	dddZdddZdS )z*
Utility function to facilitate testing.

    N)partialwraps)mkdtempmkstemp)SkipTest)WarningMessage)intpfloat32emptyarange
array_reprndarrayisnatarray)isfiniteisnanisinf)_rename_parameter)pd_NA)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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IS_WASMsuppress_warningsassert_array_compareassert_no_gc_cyclesbreak_cyclesHAS_LAPACK64	IS_PYSTONIS_MUSLcheck_support_sveNOGIL_BUILDIS_EDITABLEIS_INSTALLED
NUMPY_ROOTrun_threadedIS_64BITc                   @      e Zd ZdZdS )r0   z<Raise this exception to mark a test as a known failing test.N__name__
__module____qualname____doc__ rJ   rJ   p/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/numpy/testing/_private/utils.pyr0   5       r0   numpyFT)      zdirect_url.jsonz{}c                 C   s   t jdi | S )NrJ   )typesSimpleNamespace)datarJ   rJ   rK   <lambda>M       rS   )object_hook)wasm32wasm64pypypyston_version_infogetrefcountHOST_GNU_TYPE muslPy_GIL_DISABLED   c                 C   s:   d}| sz| }W t| t y   |}Y t|w 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)valmsg__tracebackhide__smsgrJ   rJ   rK   r'   n   s   r'   ntc              	   C   s   dd l }|d u r|j}||| |d ||f}| }z(|||}	z|| ||	|\}
}|W ||	 W || S ||	 w || w )Nr   )	win32pdhPDH_FMT_LONGMakeCounterPath	OpenQuery
AddCounterCollectQueryDataGetFormattedCounterValueRemoveCounter
CloseQuery)objectcounterinstanceinumformatmachinerh   pathhqhctyperb   rJ   rJ   rK   GetPerformanceAttributes   s"   
r{   pythonc                 C   s   dd l }tdd| ||jd S )Nr   ProcesszVirtual Bytes)rh   r{   ri   )processNamers   rh   rJ   rJ   rK   r!      s
   r!      linuxz/proc/z/statc                 C   sZ   z"t | }| d}W d   n1 sw   Y  t|d W S  ty,   Y dS w )zM
        Return virtual memory size in bytes of the running python.

         N   )openreadlinesplitint	Exception)_proc_pid_statflrJ   rJ   rK   r!      s   
c                   C   s   t )zK
        Return memory usage of running python. [Not implemented]

        )NotImplementedErrorrJ   rJ   rJ   rK   r!      s   c                 C   s   ddl }|s||   z"t| }| d}W d   n1 s$w   Y  t|d W S  tyD   td|  |d    Y S w )
        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   Nr   rO   d   )timeappendr   r   r   r   r   )r   
_load_timer   r   r   rJ   rJ   rK   r       s   
r    c                 C   s2   ddl }| s| |   td|  | d   S )r   r   Nr   )r   r   r   )r   r   rJ   rJ   rK   r       s   Items are not equal:ACTUALDESIREDc                 C   s"  d| g}t |}|r+|ddkr&t|dt| k r&|d d | g}n|| |rt| D ]Z\}}t|trAtt|d}	nt	}	z|	|}
W n t
yg } zdt|j d| d	}
W Y d }~nd }~ww |
dd
kr~d|
 d d
 }
|
d7 }
|d||  d|
  q1d|S )N
rg   O   r   r   )	precisionz[repr failed for <z>: ]rN   z...: )strfindlenr   	enumerate
isinstancer   r   r   reprr   rz   rF   countjoin
splitlines)arrayserr_msgheaderr%   namesr   rc   iar_funcrexcrJ   rJ   rK   r      s,   
"

$
r   strictc             
   C   s|  d}t |trEt | tsttt| tt| t||| | D ]\}}|| vr1tt|t| | || d|d| | q#dS t |tt	frzt | tt	frztt| t||| t
t|D ]}t| | || d|d| | qddS ddlm}m}	m}
 ddlm}m}m} t | |st ||rt| ||||d	S t| |g||d
}z
|| p||}W n ttfy   d}Y nw |r|| r|| }|| }n| }d}||r||}||}n|}d}zt|| t|| W n ty   t|w |	||	| krt|z(t|}t| }t|jjt| jjk}|r2|r2|r.W dS t|W n tttfy@   Y nw zFt|}t| }|rS|rSW dS t| }t|}|jjdv sk|jjdv rotd|dkr| dkr|
||
| kst|W n tttfy   Y nw z|| kst|W dS  ttfy } zd|j d v rt| d}~ww )ah  
    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.

    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.
    strict : bool, optional
        If True and either of the `actual` and `desired` arguments is an array,
        raise an ``AssertionError`` when either the shape or the data type of
        the arguments does not match. If neither argument is an array, this
        parameter has no effect.

        .. versionadded:: 2.0.0

    Raises
    ------
    AssertionError
        If actual and desired are not equal.

    See Also
    --------
    assert_allclose
    assert_array_almost_equal_nulp,
    assert_array_max_ulp,

    Notes
    -----
    By default, when one of `actual` and `desired` is a scalar and the other is
    an array, the function checks that each element of the array is equal to
    the scalar. This behaviour can be disabled by setting ``strict==True``.

    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])

    As mentioned in the Notes section, `assert_equal` has special
    handling for scalars when one of the arguments is an array.
    Here, the test checks that each value in `x` is 3:

    >>> x = np.full((2, 5), fill_value=3)
    >>> np.testing.assert_equal(x, 3)

    Use `strict` to raise an AssertionError when comparing a scalar with an
    array of a different shape:

    >>> np.testing.assert_equal(x, 3, strict=True)
    Traceback (most recent call last):
        ...
    AssertionError:
    Arrays are not equal
    <BLANKLINE>
    (shapes (2, 5), () mismatch)
     ACTUAL: array([[3, 3, 3, 3, 3],
           [3, 3, 3, 3, 3]])
     DESIRED: array(3)

    The `strict` parameter also ensures that the array data types match:

    >>> x = np.array([2, 2, 2])
    >>> y = np.array([2., 2., 2.], dtype=np.float32)
    >>> np.testing.assert_equal(x, y, strict=True)
    Traceback (most recent call last):
        ...
    AssertionError:
    Arrays are not equal
    <BLANKLINE>
    (dtypes int64, float32 mismatch)
     ACTUAL: array([2, 2, 2])
     DESIRED: array([2., 2., 2.], dtype=float32)
    Tzkey=r   Nzitem=r   )r   isscalarsignbitiscomplexobjrealimagr   r%   FMmz0cannot compare to a scalar with a different typezelementwise == comparison)!r   dictra   r   rz   r   r   itemslisttuplerangenumpy._corer   r   r   rM   r   r   r   r   r   
ValueErrorr`   r   npasarraydtyper   r   charDeprecationWarningFutureWarningargs)actualdesiredr   r%   r   rd   kr   r   r   r   r   r   r   rc   
usecomplexactualractualidesiredrdesirediisdesnatisactnatdtypes_matchisdesnanisactnanarray_actualarray_desirederJ   rJ   rK   r      s   c








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   writera   getvalue)test_stringr   r   rd   r   rc   rJ   rJ   rK   r"     s   


r"      c              	      s  d}ddl m} ddlm}m}m}	 z
| p|}
W n ty'   d}
Y nw  fdd}|
rs| rA| }|	 }n }d}|rR|}|	}n}d}zt||d t||d W n tyr   t| w t	 |t
tfst	|t
tfrt S z.trt stst rtrt st| W d	S  kst| W d	S W n ttfy   Y nw t  td
d   krt| d	S )aN	  
    Raises an AssertionError if two items are not equal up to desired
    precision.

    .. note:: It is recommended to use one of `assert_allclose`,
              `assert_array_almost_equal_nulp` or `assert_array_max_ulp`
              instead of this function for more consistent floating point
              comparisons.

    The test verifies that the elements of `actual` and `desired` satisfy::

        abs(desired-actual) < float64(1.5 * 10**(-decimal))

    That is a looser test than originally documented, but agrees with what the
    actual implementation in `assert_array_almost_equal` did up to rounding
    vagaries. An exception is raised at conflicting values. For ndarrays this
    delegates to assert_array_almost_equal

    Parameters
    ----------
    actual : array_like
        The object to check.
    desired : array_like
        The expected object.
    decimal : int, optional
        Desired precision, default is 7.
    err_msg : str, optional
        The error message to be printed in case of failure.
    verbose : bool, optional
        If True, the conflicting values are appended to the error message.

    Raises
    ------
    AssertionError
      If actual and desired are not equal up to specified precision.

    See Also
    --------
    assert_allclose: Compare two array_like objects for equality with desired
                     relative and/or absolute precision.
    assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal

    Examples
    --------
    >>> from numpy.testing import assert_almost_equal
    >>> assert_almost_equal(2.3333333333333, 2.33333334)
    >>> assert_almost_equal(2.3333333333333, 2.33333334, decimal=10)
    Traceback (most recent call last):
        ...
    AssertionError:
    Arrays are not almost equal to 10 decimals
     ACTUAL: 2.3333333333333
     DESIRED: 2.33333334

    >>> assert_almost_equal(np.array([1.0,2.3333333333333]),
    ...                     np.array([1.0,2.33333334]), decimal=9)
    Traceback (most recent call last):
        ...
    AssertionError:
    Arrays are not almost equal to 9 decimals
    <BLANKLINE>
    Mismatched elements: 1 / 2 (50%)
    Max absolute difference among violations: 6.66669964e-09
    Max relative difference among violations: 2.85715698e-09
     ACTUAL: array([1.         , 2.333333333])
     DESIRED: 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%   rJ   rK   _build_err_msgI  s   z+assert_almost_equal.<locals>._build_err_msg)r   N      ?      $@)r   r   rM   r   r   r   r   r   ra   r   r   r   r   r   r   r   r`   absr   float64)r   r   r   r   r%   rd   r   r   r   r   r   r   r   r   r   r   rJ   r   rK   r     s\   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>w   Y  z|| }W n tyT   d}Y nw z| | }	W n tyf   d}	Y nw t	| |g|d	| |d
}
z,t
|r|t
| st|st| rt|rt| st|
W dS || kst|
W dS W n ttfy   Y nw |||	 |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   Nignore)invalidg      ?
   g        z-Items are not equal to %d significant digits:)r   r%   r      )rM   mapfloaterrstater   powerfloorlog10ZeroDivisionErrorr   r   r   ra   r`   r   )r   r   significantr   r%   rd   r   scale
sc_desired	sc_actualrc   rJ   rJ   rK   r   v  sP   ; r      )r   r   c	          2         s.  d}ddl m}m}mm}m}m}m} t	|}t	|}||}}dd }dd }dd	 }|d
f fdd	}z1|	rM|j
|j
koK|j|jk}n|j
dkp\|j
dkp\|j
|j
k}|s|j
|j
krqd|j
 d|j
 d}nd|j d|j d}t||g | d}t|td}||r||r|r||||d
d}|r||||fddddO }||||fddddO }nj||r||r|r|jj|jjkr|||tdd}nO||r.||r.|j}|r.||jkr.t|dr.t|jtot|j}d}zt|j W n ty   d}Y nw |s$|r.|||||jjd}|jdkrI||  ||  }}|jdkrHW d S n|rOW d S | ||}t|} t|trg|}t|g}!n| }!|! }|dkrl|!j|!jtd }"|jdkr|jn|!j}#d|" |# }$d|"|#|$g}%|d d! tt t || }&t!|jtj"rt || }'tj#|&|'|&d" |&|  }(||(})t$|&d#||kr|%%d$t&|)  n	|%%d$||)  t|dk}*t'| |*}+||+ rt},n|&|+ }-t(||&j
}.|.|+ }/||-t |/ },t$|&d#||kr&|%%d%t&|,  n	|%%d%||,  W d    n	1 s:w   Y  W d    n	1 sJw   Y  t&   d&d&)|% 7  t||g d}t|W d S  t*y   dd l+}0|0, }1d'|1 d( t||g d}t*|w ))NTr   )array2stringr   infr   allmaxobject_c                 S      | j jdv S )Nz?bhilqpBHILQPefdgFDGr   r   xrJ   rJ   rK   isnumber     z&assert_array_compare.<locals>.isnumberc                 S   r   )Nr   r   r   rJ   rJ   rK   istime  r   z$assert_array_compare.<locals>.istimec                 S   s   | j jdkS )NTr   r   rJ   rJ   rK   	isvstring  r   z'assert_array_compare.<locals>.isvstringnanc                    s   d}|| }||}t ||k dkr)t| |g d|  d}t|t|ts3|jdkr8t |S t|tsB|jdkrGt |S |S )zHandling nan/inf.

        Combine results of running func on x and y, checking that they are True
        at the same locations.

        Tz
%s location mismatch:r%   r   r   r   r   )r   boolr   r   ra   r   ndim)r   yfunchasvalrd   x_idy_idrc   )r   r   r   r   r%   rJ   rK   func_assert_same_pos  s&   

z2assert_array_compare.<locals>.func_assert_same_posrJ   z	
(shapes z, z
 mismatch)z	
(dtypes r   F)r  r  c                    s
   |  
 kS NrJ   xyr   rJ   rK   rS   0     
 z&assert_array_compare.<locals>.<lambda>z+infc                    s
   |   kS r	  rJ   r
  r  rJ   rK   rS   3  r  z-infNaT	na_objectr   r   r   z&Mismatched elements: {} / {} ({:.3g}%)r   )r   outr   z*Max absolute difference among violations: z*Max relative difference among violations: r   zerror during assertion:

z

)-r   r   r   r   r   r   r   r   r   
asanyarrayshaper   r   ra   r  rz   r   hasattrr   r  r   r`   r  sizelogical_notr   ravelsumr   ru   
contextlibsuppressr   
issubdtypeunsignedintegerminimumgetattrr   r   logical_andbroadcast_tor   r   	traceback
format_exc)2
comparisonr   r  r   r%   r   r   	equal_nan	equal_infr   r   rd   r   r   r   r   r   r   oxoyr   r   r   r  condreasonrc   flaggeddtis_nanbool_errorsrb   invalidsreduced
n_mismatch
n_elementspercent_mismatchremarkserrorerror2reduced_errormax_abs_errornonzerononzero_and_invalidmax_rel_errornonzero_invalid_errorbroadcasted_ynonzero_invalid_yr"  efmtrJ   )r   r   r   r   r   r%   rK   r7     s   $


' 







*
9r7   r   r  r   r   z2.0.0)dep_versionc             	   C   s    d}t tj| |||d|d dS )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 (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.

    .. note:: When either `actual` or `desired` is already an instance of
        `numpy.ndarray` and `desired` is not a ``dict``, the behavior of
        ``assert_equal(actual, desired)`` is identical to the behavior of this
        function. Otherwise, this function performs `np.asanyarray` on the
        inputs before comparison, whereas `assert_equal` defines special
        comparison rules for common Python types. For example, only
        `assert_equal` can be used to compare nested Python lists. In new code,
        consider using only `assert_equal`, explicitly converting either
        `actual` or `desired` to arrays if the behavior of `assert_array_equal`
        is desired.

    Parameters
    ----------
    actual : array_like
        The actual object to check.
    desired : 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.
    strict : bool, optional
        If True, raise an AssertionError when either the shape or the data
        type of the array_like objects does not match. The special
        handling for scalars mentioned in the Notes section is disabled.

        .. versionadded:: 1.24.0

    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 `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 behaviour can be disabled with the `strict` parameter.

    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 among violations: 4.4408921e-16
    Max relative difference among violations: 1.41357986e-16
     ACTUAL: array([1.      , 3.141593,      nan])
     DESIRED: array([1.      , 3.141593,      nan])

    Use `assert_allclose` or one of the nulp (number of floating point values)
    functions for these cases instead:

    >>> np.testing.assert_allclose([1.0,np.pi,np.nan],
    ...                            [1, np.sqrt(np.pi)**2, np.nan],
    ...                            rtol=1e-10, atol=0)

    As mentioned in the Notes section, `assert_array_equal` has special
    handling for scalars. Here the test checks that each value in `x` is 3:

    >>> x = np.full((2, 5), fill_value=3)
    >>> np.testing.assert_array_equal(x, 3)

    Use `strict` to raise an AssertionError when comparing a scalar with an
    array:

    >>> np.testing.assert_array_equal(x, 3, strict=True)
    Traceback (most recent call last):
        ...
    AssertionError:
    Arrays are not equal
    <BLANKLINE>
    (shapes (2, 5), () mismatch)
     ACTUAL: array([[3, 3, 3, 3, 3],
           [3, 3, 3, 3, 3]])
     DESIRED: array(3)

    The `strict` parameter also ensures that the array data types match:

    >>> x = np.array([2, 2, 2])
    >>> y = np.array([2., 2., 2.], dtype=np.float32)
    >>> np.testing.assert_array_equal(x, y, strict=True)
    Traceback (most recent call last):
        ...
    AssertionError:
    Arrays are not equal
    <BLANKLINE>
    (dtypes int64, float32 mismatch)
     ACTUAL: array([2, 2, 2])
     DESIRED: array([2., 2., 2.], dtype=float32)
    TzArrays are not equal)r   r%   r   r   N)r7   operator__eq__)r   r   r   r%   r   rd   rJ   rJ   rK   r     s
   |
r   c              	      s^   d}ddl 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
    ----------
    actual : array_like
        The actual object to check.
    desired : 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 among violations: 6.e-05
    Max relative difference among violations: 2.57136612e-05
     ACTUAL: array([1.     , 2.33333,     nan])
     DESIRED: 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>
    nan location mismatch:
     ACTUAL: array([1.     , 2.33333,     nan])
     DESIRED: array([1.     , 2.33333, 5.     ])

    Tr   )numberresult_type)r  )anyc              	      s   z<t | st |r;t | }t |}||k sW dS | j|j  kr*dkr1n n| |kW S | |  } ||  }W n ttfyG   Y nw |d}t||}t| | }|jse|	tj
}|dd    k S )NFr   g      ?r   r   )r   r   r  r`   r   r   r  r   r   astyper   )r   r  xinfidyinfidr   zr   r  npanyrC  rD  rJ   rK   comparez  s(   



z*assert_array_almost_equal.<locals>.comparer   )r   r%   r   r   N)r   rC  rD  numpy._core.numerictypesr  numpy._core.fromnumericrE  r7   )r   r   r   r   r%   rd   rL  rJ   rJ  rK   r   &  s   O

r   c                C   s$   d}t tj| |||dd|dd	 dS )aJ  
    Raises an AssertionError if two array_like objects are not ordered by less
    than.

    Given two array_like objects `x` and `y`, check that the shape is equal and
    all elements of `x` are strictly less than the corresponding elements of
    `y` (but see the Notes for the special handling of a scalar). An exception
    is raised at shape mismatch or values that are not correctly ordered. In
    contrast to the  standard usage in NumPy, 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.
    strict : bool, optional
        If True, raise an AssertionError when either the shape or the data
        type of the array_like objects does not match. The special
        handling for scalars mentioned in the Notes section is disabled.

        .. versionadded:: 2.0.0

    Raises
    ------
    AssertionError
      If x is not strictly smaller than y, element-wise.

    See Also
    --------
    assert_array_equal: tests objects for equality
    assert_array_almost_equal: test objects for equality up to precision

    Notes
    -----
    When one of `x` and `y` is a scalar and the other is array_like, the
    function performs the comparison as though the scalar were broadcasted
    to the shape of the array. This behaviour can be disabled with the `strict`
    parameter.

    Examples
    --------
    The following assertion passes because each finite element of `x` is
    strictly less than the corresponding element of `y`, and the NaNs are in
    corresponding locations.

    >>> x = [1.0, 1.0, np.nan]
    >>> y = [1.1, 2.0, np.nan]
    >>> np.testing.assert_array_less(x, y)

    The following assertion fails because the zeroth element of `x` is no
    longer strictly less than the zeroth element of `y`.

    >>> y[0] = 1
    >>> np.testing.assert_array_less(x, y)
    Traceback (most recent call last):
        ...
    AssertionError:
    Arrays are not strictly ordered `x < y`
    <BLANKLINE>
    Mismatched elements: 1 / 3 (33.3%)
    Max absolute difference among violations: 0.
    Max relative difference among violations: 0.
     x: array([ 1.,  1., nan])
     y: array([ 1.,  2., nan])

    Here, `y` is a scalar, so each element of `x` is compared to `y`, and
    the assertion passes.

    >>> x = [1.0, 4.0]
    >>> y = 5.0
    >>> np.testing.assert_array_less(x, y)

    However, with ``strict=True``, the assertion will fail because the shapes
    do not match.

    >>> np.testing.assert_array_less(x, y, strict=True)
    Traceback (most recent call last):
        ...
    AssertionError:
    Arrays are not strictly ordered `x < y`
    <BLANKLINE>
    (shapes (2,), () mismatch)
     x: array([1., 4.])
     y: array(5.)

    With ``strict=True``, the assertion also fails if the dtypes of the two
    arrays do not match.

    >>> y = [5, 5]
    >>> np.testing.assert_array_less(x, y, strict=True)
    Traceback (most recent call last):
        ...
    AssertionError:
    Arrays are not strictly ordered `x < y`
    <BLANKLINE>
    (dtypes float64, int64 mismatch)
     x: array([1., 4.])
     y: array([5, 5])
    Tz'Arrays are not strictly ordered `x < y`Fr   r  )r   r%   r   r&  r   r   N)r7   rA  __lt__)r   r  r   r%   r   rd   rJ   rJ   rK   r     s   j
r   c                 C   s   t | | d S r	  )exec)astrr   rJ   rJ   rK   r$     s   r$   c                 C   st  d}ddl }t| tsttt| t|ts ttt||| kr&dS t| | 	d|	d}g }|r|
d}|drEq8|dr|g}|
d}|dra|| |
d}|dsltt||| |r|
d}	|	dr||	 n|d|	 |dd |dd krq8|| q8tt||sd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:
r\   )difflibr   r   ra   r   rz   r   DifferrL  r   pop
startswithr   insertextendr   rstrip)r   r   rd   rT  diff	diff_listd1r   d2d3rc   rJ   rJ   rK   r     sR   













r   c                    s   ddl m} ddl}| du rtd}|jd } tjtj	| d }||| }|
 |}|jdd}g  |rA fdd	}	nd}	|D ]	}
|j|
|	d
 qE|jdkr_|ratdd  dS dS )aX  
    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	  )r   )src   rJ   rK   rS   {  r  zrundocs.<locals>.<lambda>r  zSome doctests failed:
%sr   )numpy.distutils.misc_utilr`  doctestsys	_getframe	f_globalsosrw   splitextbasenameDocTestFinderr   DocTestRunnerrunfailuresra   r   )filenameraise_on_errorr`  re  r   namemtestsrunnerr  testrJ   rc  rK   r#   X  s$   


r#   c              	   C   sf   | r| d S ddl }d}z|j|ddd}d|jv }W n t|jfy)   d}Y nw | | | d S )z
    gh-22982
    r   NlscpuT)capture_outputtextsveF)
subprocessrn  stdoutOSErrorSubprocessErrorr   )__cacher{  cmdoutputresultrJ   rJ   rK   r=     s   
r=   c                   @   s   e Zd Zdd ZdS )_Dummyc                 C   s   d S r	  rJ   )selfrJ   rJ   rK   nop  s   z
_Dummy.nopN)rF   rG   rH   r  rJ   rJ   rJ   rK   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   kwargsrd   rJ   rJ   rK   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`.
    T)r  assertRaisesRegex)exception_classexpected_regexpr   r  rd   rJ   rJ   rK   r)     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r4|j	}n|j
}W n	 tyA   Y q(w ||rT|dsTt| ||| q(d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 rJ   rJ   ).0_mr  rJ   rK   
<listcomp>      z$decorate_methods.<locals>.<listcomp>compat_func_name_)recompileri  sep__dict__inspectr  valuesr  r  rF   AttributeErrorsearchrW  setattr)cls	decorator	testmatchcls_attrmethodsfunctionfuncnamerJ   r  rK   r     s&   

r   r   c           	      C   sl   t d}|j|j}}t| d| dd}d}t }||k r-|d7 }t||| ||k st | }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: r   rQ  r   g{Gz?)rf  rg  f_localsrh  r  r    rQ  )	code_strtimeslabelframelocsglobscoder   elapsedrJ   rJ   rK   r&     s   
!
r&   c           	      C   s   t sdS ddl}ddl}|ddd}|}d}|  z"t|}tdD ]}| ||}q't	t||k W |
  ~dS |
  w )zg
    Check that ufuncs don't mishandle refcount of object `1`.
    Used in a few regression tests.
    Tr   Ni'  r   r      )r4   gcrM   r   reshapedisablerf  rZ   r   r'   enable)	opr  r   bcr   rcjdrJ   rJ   rK   _assert_valid_refcount1  s    

r  Hz>c             
      sh   d}ddl  fdd}	| |} }ddd d}
t|	| |t|||
|d	 dS )
u  
    Raises an AssertionError if two objects are not equal up to desired
    tolerance.

    Given two array_like objects, check that their shapes and all elements
    are equal (but see the Notes for the special handling of a scalar). An
    exception is raised if the shapes mismatch or any values conflict. In
    contrast to the standard usage in numpy, NaNs are compared like numbers,
    no assertion is raised if both objects have NaNs in the same positions.

    The test is equivalent to ``allclose(actual, desired, rtol, atol)`` (note
    that ``allclose`` has different default values). It compares the difference
    between `actual` and `desired` to ``atol + rtol * abs(desired)``.

    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.
    strict : bool, optional
        If True, raise an ``AssertionError`` when either the shape or the data
        type of the arguments does not match. The special handling of scalars
        mentioned in the Notes section is disabled.

        .. versionadded:: 2.0.0

    Raises
    ------
    AssertionError
        If actual and desired are not equal up to specified precision.

    See Also
    --------
    assert_array_almost_equal_nulp, assert_array_max_ulp

    Notes
    -----
    When one of `actual` and `desired` is a scalar and the other is
    array_like, the function performs the comparison as if the scalar were
    broadcasted to the shape of the array.
    This behaviour can be disabled with the `strict` parameter.

    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)

    As mentioned in the Notes section, `assert_allclose` has special
    handling for scalars. Here, the test checks that the value of `numpy.sin`
    is nearly zero at integer multiples of π.

    >>> x = np.arange(3) * np.pi
    >>> np.testing.assert_allclose(np.sin(x), 0, atol=1e-15)

    Use `strict` to raise an ``AssertionError`` when comparing an array
    with one or more dimensions against a scalar.

    >>> np.testing.assert_allclose(np.sin(x), 0, atol=1e-15, strict=True)
    Traceback (most recent call last):
        ...
    AssertionError:
    Not equal to tolerance rtol=1e-07, atol=1e-15
    <BLANKLINE>
    (shapes (3,), () mismatch)
     ACTUAL: array([ 0.000000e+00,  1.224647e-16, -2.449294e-16])
     DESIRED: array(0)

    The `strict` parameter also ensures that the array data types match:

    >>> y = np.zeros(3, dtype=np.float32)
    >>> np.testing.assert_allclose(np.sin(x), y, atol=1e-15, strict=True)
    Traceback (most recent call last):
        ...
    AssertionError:
    Not equal to tolerance rtol=1e-07, atol=1e-15
    <BLANKLINE>
    (dtypes float64, float32 mismatch)
     ACTUAL: array([ 0.000000e+00,  1.224647e-16, -2.449294e-16])
     DESIRED: array([0., 0., 0.], dtype=float32)

    Tr   Nc                    s   j jj| | dS )N)rtolatolr%  )_corenumericiscloserO  r  r%  r   r  rJ   rK   rL    s   z assert_allclose.<locals>.comparezNot equal to tolerance rtol=gz, atol=)r   r%   r   r%  r   )rM   r  r7   r   )r   r   r  r  r%  r   r%   r   rd   rL  r   rJ   r  rK   r-   K  s   _
r-   c           
      C   s   d}ddl }|| }||}|||||k|| }||| | |ksT|| s4||r>d| d}t||t| |}	d| d|	dd}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) <= nulp * 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: Arrays are not equal to 1 ULP (max is 2)

    Tr   NzArrays are not equal to z ULPz ULP (max is r  ))	rM   r   spacingwherer   r   r   	nulp_diffra   )
r   r  nulprd   r   axayrefrc   max_nulprJ   rJ   rK   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))rM   r  r   ra   r   )r   r  maxulpr   rd   r   retrJ   rJ   rK   r*     s   *r*   c                    s   ddl  |r j| |d}  j||d}n
 | }  |} | |} | s/ |r3td j| g|d}  j|g|d} j|  | <  j| |< | j|jksct	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*Arrays do not have the same shape: %s - %sc                    s    j | | |d} |S Nr  )r   r   )rxryvdtr[  r   rJ   rK   _diffa  s   
znulp_diff.<locals>._diff)rM   r   common_typer   r   r   r   r   r  r   integer_repr)r   r  r   tr  r  r  rJ   r  rK   r  +  s*    


r  c                 C   sD   |  |}|jdks|||dk   ||dk < |S |dk r || }|S )Nr   r   )viewr  )r   r  compr  rJ   rJ   rK   _integer_reprj  s   

r  c                 C   sx   ddl }| j|jkrt| |j|dS | j|jkr$t| |j|dS | j|jkr4t| |j|dS t	d| j )zQReturn the signed-magnitude interpretation of the binary representation
    of x.r   Ni i   l         zUnsupported dtype )
rM   r   float16r  int16r	   int32r   int64r   )r   r   rJ   rJ   rK   r  y  s   r  c                 c   sp    d}t  (}|| }d V  t|dks&|d urd| nd}td| W d    d S 1 s1w   Y  d S )NTr    when calling r\   zNo warning raised)r6   recordr   ra   )warning_classrr  rd   supr   name_strrJ   rJ   rK   _assert_warns_context  s   
"r  c                 O   s   |s|st | S t|dk rd|v rtdtd|d }|dd }t | |jd ||i |W  d   S 1 s=w   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.

    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   matchzAassert_warns does not use 'match' kwarg, use pytest.warns insteadz(assert_warns(...) needs at least one argr   Nrr  )r  r   RuntimeErrorrF   )r  r   r  r  rJ   rJ   rK   r+     s   +$r+   c                 c   s~    d}t jdd,}t d d V  t|dkr-| d ur!d|  nd}td| d| W d    d S 1 s8w   Y  d S )	NTr  alwaysr   r  r\   zGot warningsr   )warningscatch_warningssimplefilterr   ra   )rr  rd   r   r  rJ   rJ   rK   _assert_no_warnings_context  s   
"r  c                  O   s\   | st  S | d }| dd } t |jd || i |W  d   S 1 s'w   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.

    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   Nr  )r  rF   r   r  r  rJ   rJ   rK   r,     s   $r,   binary   c           
      #   s   d}d}t dD ]щt d td |D ]|dkr 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, %srN   rS  unaryc                         t  dd  S r  r   rJ   r   orb  rJ   rK   rS         z%_gen_alignment_data.<locals>.<lambda>r  Nzout of placezin placer   rg   aliasedr  c                      r  r  r  rJ   r  rJ   rK   rS   &  r  c                      r  r  r  rJ   r  rJ   rK   rS   '  r  z	in place1z	in place2)r   r   r
   )
r   rz   max_sizeufmtbfmtinpr  r  inp1inp2rJ   r  rK   _gen_alignment_data  sv   


$$$&&&r  c                   @   rD   )r.   z/Ignoring this exception due to disabled featureNrE   rJ   rJ   rJ   rK   r.   ?  rL   r.   c               	   o   s4    t | i |}z|V  W t| dS t| w )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  tmpdirrJ   rJ   rK   r2   D  s
   r2   c               	   o   sB    t | i |\}}t| z|V  W t| dS t| w )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   ri  closeremove)r   r  fdrw   rJ   rJ   rK   r1   S  s   
r1   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
    rJ   Fc                    s*   t || j| _i | _t j|d d S )Nr  )setunionclass_modulesmodules_warnreg_copiessuper__init__)r  r  r  	__class__rJ   rK   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  modmod_regr	  rJ   rK   r    s   


z"clear_and_catch_warnings.__enter__c                    sL   t  j|  | jD ]}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	  rJ   rK   r    s   



z!clear_and_catch_warnings.__exit__)FrJ   )	rF   rG   rH   rI   r  r  r  r  __classcell__rJ   rJ   r	  rK   r/   i  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 )r6   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
    r  c                 C   s&   d| _ g | _|dvrtd|| _d S )NF>   oncer  modulelocationzunsupported forwarding rule.)_entered_suppressionsr   _forwarding_rule)r  forwarding_rulerJ   rJ   rK   r    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  r  r  _tmp_modulesr  r  )r  r  rJ   rJ   rK   _clear_registries  s   



z#suppress_warnings._clear_registriesr\   NFc                 C   s   |rg }nd }| j rE|d u rtjd||d n|jddd }tjd|||d | j| |   | j	||t
|t
j||f |S | j	||t
|t
j||f |S )Nr  categorymessage.\.$r!  r"  r  )r  r  filterwarningsrF   replacer  addr  _tmp_suppressionsr   r  r  Ir  )r  r!  r"  r  r  module_regexrJ   rJ   rK   _filter	  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  r  Nr-  r  r!  r"  r  rJ   rJ   rK   filter$	  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/  r0  rJ   rJ   rK   r  ;	  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 ]5\}}}}}|d ur;|d d = |d u rHtjd||d q+|jddd }tjd|||d | j	| q+| jt_|   | S )	Nz%cannot enter suppress_warnings twice.Tr  r   r#  r$  r%  r&  )r  r  r  showwarning
_orig_showfilters_filtersr*  r  r  
_forwardedlogr  r'  rF   r(  r)  _showwarningr  )r  catmessr  r  r7  r,  rJ   rJ   rK   r  Y	  s4   
zsuppress_warnings.__enter__c                 G   s*   | j t_| jt_|   d| _| ` | `d S )NF)r3  r  r2  r5  r4  r  r  )r  r  rJ   rJ   rK   r  y	  s   zsuppress_warnings.__exit__)use_warnmsgc                O   s  | j | j d d d D ]Z\}}	}
}}t||re|
|jd d ure|d u rB|d ur?t||||fi |}| j| ||  d S |j	|re|d urbt||||fi |}| j| ||  d S q| j
dkr|d u r| j||||g|R i | d S | | d S | j
dkr|j|f}n| j
dkr|j||f}n| j
dkr|j|||f}|| jv rd S | j| |d u r| j||||g|R i | d S | | d S )Nrg   r   r  r  r  r  )r  r*  
issubclassr  r   r   r7  r   ra  rW  r  r3  _orig_showmsgr6  r)  )r  r"  r!  rp  linenor;  r   r  r9  r  patternr  recrc   	signaturerJ   rJ   rK   r8  	  sb   









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w   Y  d S r	  rJ   )r   r  r  r  rJ   rK   new_func	  s   $z,suppress_warnings.__call__.<locals>.new_funcr   )r  r  rC  rJ   rB  rK   __call__	  s   zsuppress_warnings.__call__)r  )rF   rG   rH   rI   r  r  Warningr-  r1  r  r  r  r8  rE  rJ   rJ   rJ   rK   r6     s    
I
 	3r6   c              
   c   s   d}t s
d V  d S tt  t  t }z8tdD ]
}t dkr' nqt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  w |r| d urld|  nd}td||t|ddd	 |D d S )
NTr   r   z]Unable to fully collect garbage - perhaps a __del__ method is creating more reference cycles?r  r\   zXReference cycles were found{}: {} objects were collected, of which {} are shown below:{}c              	   s   s6    | ]}d  t|jt|t|ddV  qdS )z
  {} object with id={}:
    {}r   z
    N)ru   rz   rF   idr   pformatr(  )r  r  rJ   rJ   rK   	<genexpr>	  s    
z/_assert_no_gc_cycles_context.<locals>.<genexpr>)r4   r'   r  	isenabledr  	get_debugr   collectr  	set_debugDEBUG_SAVEALLgarbager  ra   ru   r   r   )rr  rd   gc_debugr   n_objects_in_cyclesobjects_in_cyclesr  rJ   rJ   rK   _assert_no_gc_cycles_context	  sP   




rS  c                  O   s^   | st  S | d }| dd } t |jd || i | W d   dS 1 s(w   Y  dS )a  
    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()

    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   Nr  )rS  rF   r  rJ   rJ   rK   r8   	  s   "r8   c                   C   s4   t   trt   t   t   t   dS 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  rL  r3   rJ   rJ   rJ   rK   r9   
  s   	r9   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                     sJ   t  }|d ur| z| i |W S  ty$   d Y d S w )NzMemoryError raised)check_free_memoryskipMemoryErrorxfail)r   kwrc   )
free_bytesr  pytestrJ   rK   wrapper-
  s   
z3requires_memory.<locals>.decorator.<locals>.wrapperrD  r  r[  rY  rZ  r  rK   r  ,
  s   z"requires_memory.<locals>.decorator)rZ  )rY  r  rJ   r]  rK   requires_memory(
  s   r_  c              
   C   s   d}t j|}|dur4zt|}W n ty( } z
td| d| d}~ww | d  d| d}nt }|du r@d}d	}n| d }|d }| d
| d}|| k rV|S dS )z
    Check whether `free_bytes` amount of memory is currently free.
    Returns: None if enough memory available, otherwise error message
    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.rg   z GB memory required, but z GB available)ri  environget_parse_sizer   _get_mem_available)rY  env_var	env_valuemem_freer   rc   free_bytes_gbmem_free_gbrJ   rJ   rK   rT  >
  s(   

rT  c                 C   s   dddddddddddddd	d
}t dd| t j}||  }|r0|d|vr8t	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        )r\   r  r   rs  r  r  kbmbgbtbkibmibgibtibz^\s*(\d+|\d+\.\d+)\s*({0})\s*$|rS  zvalue z not a valid size)r  r  ru   r   keysr+  r  lowergroupr   r   r   )size_strsuffixessize_rers  rJ   rJ   rK   rc  ]
  s    rc  c               	   C   s   z
ddl } |  jW S  ttfy   Y nw tjdr\i }td"}|D ]}|	 }t
|d d ||d d < q%W d   n1 sGw   Y  d|v rT|d S |d	 |d
  S dS )z5Return available memory in bytes, or None if unknown.r   Nr   z/proc/meminfor   rj  :memavailablememfreecached)psutilvirtual_memory	availableImportErrorr  rf  platformrW  r   r   r   stripru  )r~  infor   lineprJ   rJ   rK   rd  m
  s$   
$rd  c                    s&   t tds S t  fd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 | w r	  )rf  r  settrace)r   r  original_tracer^  rJ   rK   r[  
  s
   
z_no_tracing.<locals>.wrapper)r  rf  r   r\  rJ   r^  rK   _no_tracing
  s
   
r  c                  C   s4   zt ddd } W | S  ty   d} Y | S w )NCS_GNU_LIBC_VERSIONr   r   0.0)ri  confstrrsplitr   )verrJ   rJ   rK   _get_glibc_version
  s   r  c                 C   s   t dkot | k S )Nr  )	_glibcverr   rJ   rJ   rK   rS   
  rT   c              
      s  t |D ]}tjj|do}|du rg  n|  |r$t|} | |r3 fddt |D }	n fddt |D }	zg }
|	D ]
}|
|j|  qDW t|
|k r\|r\|	  nt|
|k rj|rk|	  w w w |
D ]}|
  qnW d   n1 sw   Y  qdS )z&Runs a function many times in parallel)max_workersNc                    s   g | ]	}|g R qS rJ   rJ   r  r   r   r  rJ   rK   r  
  s    z run_threaded.<locals>.<listcomp>c                    s   g | ]}g R qS rJ   rJ   r  r  rJ   rK   r  
  r  )r   
concurrentfuturesThreadPoolExecutor	threadingBarrierr   submitr   abortr  )r  r  
pass_countpass_barrierouter_iterationsprepare_argsr  tpebarrierall_argsr  argr   rJ   r  rK   rB   
  s:   



rB   c                 C   s.   | t u s| dkrtjj| |dS tjj|dS )Nunsetr  coerce)r  )r   r   dtypesStringDTyper  rJ   rJ   rK   get_stringdtype_dtype
  s   r  )r\   )Nrg   NN)r|   r   )r   Tr   r_   )r\   T)r   r\   T)r\   Tr\   r   TT)r   r\   T)NTr	  )r   N)r  r   Tr\   T)r   )r_   FFr   N)T)rI   ri  rf  pathlibr  r  r  rA  r  	functoolsr   r   r  r  tempfiler   r   unittest.caser   r   r   	sysconfigconcurrent.futuresr  r  importlib.metadata	importlibrM   r   r   r   r	   r
   r   r   r   r   r   r   r   r   numpy.linalg._umath_linalgnumpy._utilsr   numpy._core.tests._natyper   ior   __all__r   r0   KnownFailureTestr%   Pathra  parentrA   metadatadistributionnp_distPackageNotFoundErrorr@   r?   version_infoorigindir_infoeditablejsonrP   loads	read_textr  locate_filerv   r5   implementationrr  r3   r  r;   r  r4   linalg_umath_linalg_ilp64r:   r<   get_config_var_vr  r>   r   itemsizerC   r'   r{   r!   getpidr    r   r   r"   r   r   r7   r   r   r   r$   r   r#   r=   unittestTestCaser  r  r   r)   r   r&   r  r-   r(   r*   r  r  r  contextmanagerr  r+   r  r,   r  r.   r2   r1   r  r/   r6   rS  r8   r9   r_  rT  rc  rd  r  r  r  _glibc_older_thanrB   r  rJ   rJ   rJ   rK   <module>   s:   (
	





 S
)~
d K ss
G.

/.
m
?
4?
;
"E

B  3!	
