
    ɯwgU*                       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	Z	ddl
Z
ddlmZ ddlmZ ddlmZmZ ddl
mZ ddlmZ ddlmZmZmZmZmZmZ g dZdZ ej>                         d	v Z e	jB                  jD                  d
k(  Z# e$e	d      Z% e&e	dd      duxr e% Z'dBdZ(d Z)d Z*d Z+	 	 	 	 dCdZ,dDdZ-d Z.dEdZ/dEdZ0	 	 	 	 	 	 dFdddZ1dDdddZ2dGdZ3dDdZ4d Z5ddl6Z6 G d de6jn                        Z8 e8d      Z9d  Z:dHd!Z;d" Z<	 	 	 	 	 	 dId#Z=dJd$Z>dKd%Z?dHd&Z@d' ZAd( ZBej                  dHd)       ZDd* ZEej                  dHd+       ZFd, ZGed-d.fd/ZH G d0 d1eI      ZJej                  d2        ZKej                  d3        ZL G d4 d5e
j                        ZN G d6 d7      ZOej                  dHd8       ZPd9 ZQd: ZRd; ZSd< ZTd= ZUd> ZVd? ZWd@ ZX eX       ZYdA ZZy)Lz*
Utility function to facilitate testing.

    Nwraps)StringIO)mkdtempmkstemp)WarningMessage)arangeasarrayemptyfloat32intpndarray)assert_equalassert_almost_equalassert_approx_equalassert_array_equalassert_array_lessassert_string_equalassert_assert_array_almost_equalbuild_err_msgdecorate_methodsprint_assert_equalverboser   assert_array_almost_equal_nulpassert_raises_regexassert_array_max_ulpassert_warnsassert_no_warningsassert_allcloseIgnoreExceptionclear_and_catch_warningstemppathtempdirIS_PYPYHAS_REFCOUNTIS_WASMsuppress_warningsassert_array_compareassert_no_gc_cyclesbreak_cycles	IS_PYSTON)wasm32wasm64pypypyston_version_infogetrefcountc                 h    d}| s	  |       }t        |      y# t         $ r |}Y t        |      w xY w)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__smsgs       _/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/torch/_numpy/testing/utils.pyr   r   E   sL     	5D T""   	DT""	s    11c                 ,    t        j                  |       S N)npisnanxs    r9   gisnanr@   Y       88A;    c                 ,    t        j                  |       S r;   )r<   isfiniter>   s    r9   	gisfiniterE   ]   s    ;;q>rB   c                 ,    t        j                  |       S r;   )r<   isinfr>   s    r9   gisinfrH   a   rA   rB   c                 d   d|z   g}|rL|j                  d      dk(  r't        |      dt        |      z
  k  r|d   dz   |z   g}n|j                  |       |rt        |       D ]  \  }}t	        |t
              rt
        j                  }	nt        }		  |	|      }
|
j                  d      d	kD  r'dj                  |
j                         d d	       }
|
d
z  }
|j                  d||    d|
         dj                  |      S # t        $ r&}dt        |      j                   d| d}
Y d }~d }~ww xY w)N
O   r    z[repr failed for <z>: ]   z...: )findlenappend	enumerate
isinstancer   __repr__repr	Exceptiontype__name__countjoin
splitlines)arrayserr_msgheaderr   names	precisionr6   iar_funcrexcs               r9   r   r   e   s4    &=/C<<#GrCK7G(Gq6C<')*CJJwf% 	,DAq!W% !))E1I wwt}q IIallnRa01U
JJ58*Bqc*+	,  99S>  E(a)9)9(:#cU!DEs   D  	D/	D**D/c           	          d}t        | du |du g      }|dk(  rt        d|  d|       |dk(  ryt        | t        j                        st        |t        j                        r| |k(  }|st        d|  d|       yt        |t
              rt        | t
              r| |k(  sJ yt        |t              rt        | t              st        t        t        |                   t        t        |       t        |      ||       |j                         D ]4  }|| vrt        t        |            t        | |   ||   d|d| |       6 yt        |t        t        f      rjt        | t        t        f      rTt        t        |       t        |      ||       t        t        |            D ]  }t        | |   ||   d	|d| |        yd
dlm}m}	m}
m}m}m} t        | |      st        ||      rt-        | |||      S t/        | |g||      }	  |	|       xs  |	|      }|rS |	|       r ||       } ||       }n| }d
} |	|      r ||      } ||      }n|}d
}	 t        ||       t        ||        |
|       |
|       k7  rt        |      	 t5        |      }t5        |       }|r|ryt        j6                  |       }t        j6                  |      }|d
k(  r!| d
k(  r ||       ||       k(  st        |      	 || k(  st        |      y# t0        t2        f$ r d}Y w xY w# t        $ r t        |      w xY w# t2        t0        t8        f$ r Y Xw xY w# t:        t<        f$ r"}d|j>                  d
   v rt        |       d}~ww xY w)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])

    TN   zNot equal: z !=    zkey=rJ   zitem=r   )imagiscomplexobjisscalarr   realsignbit)r   Fzelementwise == comparison) sumr4   rU   r<   DTypestrdictrW   rY   r   rR   keyslisttuplerangetorch._numpyrk   rl   rm   r   rn   ro   r   r   
ValueErrorr3   r@   r
   NotImplementedErrorDeprecationWarningFutureWarningargs)actualdesiredr_   r   r7   	num_nonesresultkrk   rl   rm   r   rn   ro   r6   
usecomplexactualractualidesiredrdesirediisdesnanisactnanarray_actualarray_desiredes                            r9   r   r      s   d Vt^W_56IA~{6($wi@AA	a &"((#z'288'D7" ;vhd7)!DEE'3Jvs$;   '4 &$' d6l!344S[#g,A 	RA$T!W--GAJ$qe2gY0GQ	R 	'D%=)j$.OS[#g,As7|$ 	SAGAJ%uBwi0H'R	SQQ&'"j'&B!&'7GDD
)7G
DC
!&)B\'-B
 6lG6lGGG G}HG}HHH	&(+(+
 HV,,S!!'?&> zz&)

7+a<FaK7#wv6$S))

6! %% "] 	" 
&  	& %%	&, z#67  . &!&&)3 %%sO   L  L* M 0AM M L'&L'*L?MMN+NNc                    d}ddl }||k(  s|t               }|j                  |        |j                  d        |j                   ||       |j                  d        |j                   ||       t        |j	                               y)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])  # doctest: +SKIP
    >>> np.testing.print_assert_equal('Test XYZ of func xyz', [0, 1], [0, 2])  # doctest: +SKIP
    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   writer4   getvalue)test_stringr~   r   r7   r   r6   s         r9   r   r      sw    8 gj		+		'(fc"		- gs#S\\^,, rB   c                 `    d}ddl m}m}m}m}	 	  |       xs  |      }
 fd}|
rW |       r |	       } |       }n }d} |      r |	      } |      }n}d}	 t        ||       t        ||       t         |t        t        f      st        |t        t        f      rt               S 	 t              rt               sSt              st               r't              rt               st         |             y k(  st         |             y	 t!         z
        t#        j$                  dd	 z  z        k\  rt         |             y# t
        $ r d}
Y Sw xY w# t        $ r t         |             w xY w# t        t        f$ r Y |w xY w)
aV	  
    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 torch._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.666699636781459e-09
    Max relative difference: 2.8571569790287484e-09
     x: torch.ndarray([1.0000, 2.3333], dtype=float64)
     y: torch.ndarray([1.0000, 2.3333], dtype=float64)

    Tr   )rk   rl   r   rn   Fc                  0    dz  } t        g|       S )N*Arrays are not almost equal to %d decimals)r   r`   )r   )r`   r~   decimalr   r_   r   s    r9   _build_err_msgz+assert_almost_equal.<locals>._build_err_msg  s$    =Gfg.QWXXrB   )r   N      ?      $@)rx   rk   rl   r   rn   ry   r   r4   rU   rv   ru   r   rE   r@   rz   r3   absr<   float64)r~   r   r   r_   r   r7   rk   rl   r   rn   r   r   r   r   r   r   s   `````           r9   r   r   I  s   J >>
!&)B\'-B
Y Y 6lG6lGGG G}HG}HHH	37C7C &7E401Z'5$'6 )'7KK '"y'8g&.wF6N()9::  &(()9:: (9 7V

37(1C+C DD^-.. EY  
.  	3 !122	3&  + s6   E, -E> AF F ,E;:E;>FF-,F-c                    d}ddl }t        t        | |f      \  } }|| k(  ryd |j                  |       |j                  |       z   z  } |j                  d |j
                   |j                  |                  }	 ||z  }	 | |z  }	t        | |g|d|z  |      }
	 t        |      rt        |       sIt        |      st        |       r"t        |      rt        |       st        |
      y|| k(  st        |
      y	  |j                  ||	z
         |j                  d	|d
z
         k\  rt        |
      y# t        $ r d}Y w xY w# t        $ r d}	Y w xY w# t        t        f$ r Y lw xY w)a  
    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)  # doctest: +SKIP
    >>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345671e-20,  # doctest: +SKIP
    ...                                significant=8)
    >>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345672e-20,  # doctest: +SKIP
    ...                                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   Ng      ?
   g        z-Items are not equal to %d significant digits:)r`   r   r   ri   )numpymapfloatr   powerfloorlog10ZeroDivisionErrorr   rE   r@   r4   r3   rz   )r~   r   significantr_   r   r7   r<   scale
sc_desired	sc_actualr6   s              r9   r   r     s   t EFG#45VW& 6266'?VRVVF^34EBHHR("((5/23Eu_
UN	 	>L	C '"y'8g&.wF6N(--  &((-- (9 rvvj9$%$+/8J)KKS!! L5  
  	( *+ s=   >D7 E AE ,E 7EEEEE+*E+F)strictc	          	        %& d}
ddl m}m}m}m%m&m}m}  ||      } ||      }d }||}}|df%fd	}	 |	r5|j                  |j                  k(  xr |j                  |j                  k(  }n;|j                  dk(  xs |j                  dk(  xs |j                  |j                  k(  }|su|j                  |j                  k7  rd|j                   d	|j                   d
}nd|j                   d	|j                   d
}t        ||g|z   d      }t        |       %d      }|r ||||d      }|r$| |||&fdd      z  }| |||&fdd      z  }|j                  dkD  r||    ||    }}|j                  dk(  ry |ry  | ||      }t        |t              r|} ||g      }n |j!                         }|j                         }|s|j                  t#        |j%                  t&                    z
  }|j                  dk7  r|j                  n|j                  }d|z  |z  }d| d| d|ddg}t)        j*                  t,        t.              5  t1        ||z
        }t3        j4                  |j                  t2        j6                        r&t1        ||z
        }t3        j8                  |||        ||      } |j;                  d || j=                               z           %|dk7        }! ||!       r	 |&      }"n |||!   t1        ||!         z        }"|j;                  d ||"j=                               z          d d d        ddj?                  |      z   z  t        ||gd      }t        |      y # 1 sw Y   ?xY w# t@        $ r; dd l!}#|#jE                         }$d|$ d  t        ||gd      }tA        |      w xY w)!NTr   )allarrayr
   bool_infr=   maxc                     t        |       S r;   )rr   )rd   s    r9   array2stringz*assert_array_compare.<locals>.array2string=  s    1vrB   nanc                 X   d} ||       } ||      }||k(  j                         j                         dur%t        | |g	d| dz   
d      }t        |      t	        |t
              s|j                  dk(  r |      S t	        |t
              s|j                  dk(  r |      S |S )zHandling nan/inf.

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

        Tz	
x and y z location mismatch:r?   yr   r`   ra   rb   r   )r   itemr   r4   rU   boolndim)r?   r   funchasvalr7   x_idy_idr6   r   r_   r`   rb   r   s           r9   func_assert_same_posz2assert_array_compare.<locals>.func_assert_same_posC  s     !AwAw DL$$&d2AJvh.ABB #C !%% dD!TYY!^;d#tyyA~;KrB    z	
(shapes z, z
 mismatch)z	
(dtypes r   r   F)r   r   c                     | k(  S r;   r   xyr   s    r9   <lambda>z&assert_array_compare.<locals>.<lambda>      bSDj rB   z+infc                     |  k(  S r;   r   r   s    r9   r   z&assert_array_compare.<locals>.<lambda>  r   rB   z-infdtyped   zMismatched elements: z / z (z.3gz%))outzMax absolute difference: zMax relative difference: rJ   zerror during assertion:

z

)#rx   r   r   r
   r   r   r=   r   shaper   r   r4   r   sizerU   r   ravelintrp   r   
contextlibsuppressr3   RuntimeErrorr   r<   
issubdtypeunsignedintegerminimumrS   r   r\   ry   	traceback
format_exc)'
comparisonr?   r   r_   r   r`   rb   	equal_nan	equal_infr   r7   r   r   r
   r=   r   r   oxoyr   condreasonr6   flaggedr5   reduced
n_mismatch
n_elementspercent_mismatchremarkserrorerror2max_abs_errornonzeromax_rel_errorr   efmtr   r   s'      ````                              @@r9   r)   r)   *  s    HHH
A
A B(-e & &Po77agg%<!''QWW*<DGGrM2QWW]Iqww!''7IDww!''!%aggYb	D%aggYb	DA&  #C !%%,*1aeEJG+10 G +10 G <<!gX;7(qAvv{Ac4 DSElGiikG;;=D  GKKdK,C(DDJ)0):J"Z/*<'
|3zl"EUVYDZZ\]G $$Y= AE
=="*<*<= QZFJJuf%8 #E
/,}?Q?Q?S2TT  Q-x=$)#JM$'gQwZ(H$IM/,}?Q?Q?S2TT%, tdii000GR #C !%%S  @  ##%.tfDAF
 os3   EN N CN !C2N=N NN AO!c          	      H    d}t        t        j                  | |||d|       y)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.

    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.
    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.

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

    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)
     x: torch.ndarray([[3, 3, 3, 3, 3],
            [3, 3, 3, 3, 3]])
     y: torch.ndarray(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 dtype("int64"), dtype("float32") mismatch)
     x: torch.ndarray([2, 2, 2])
     y: torch.ndarray([2., 2., 2.])
    TzArrays are not equal)r_   r   r`   r   N)r)   operator__eq__)r?   r   r_   r   r   r7   s         r9   r   r     s,    | 		%rB   c           	      n   	
 d}ddl m	mmm
m 	
fd}t        || |||dz         y)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: 5.999999999994898e-05
    Max relative difference: 2.5713661239633743e-05
     x: torch.ndarray([1.0000, 2.3333,    nan], dtype=float64)
     y: torch.ndarray([1.0000, 2.3334,    nan], dtype=float64)

    >>> 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: torch.ndarray([1.0000, 2.3333,    nan], dtype=float64)
     y: torch.ndarray([1.0000, 2.3333, 5.0000], dtype=float64)

    Tr   )anyfloat_r   numberresult_typec                    	  	t        |             s 	t        |            r]t        |       }t        |      }||k(  j                         sy| j                  |j                  cxk(  rdk(  rn n| |k(  S | |    } ||    } |d      }t        ||      }t        | |z
        } |j                  
      s|j                        }|dd z  z  k  S # t        t        f$ r Y dw xY w)NFri   g      ?r   r   )	rH   r   r   r3   rz   
asanyarrayr   r   astype)r?   r   xinfidyinfidr   zr   r   r   npanyr   r   s         r9   comparez*assert_array_almost_equal.<locals>.compare  s    	VAY5#3&(--/ 66QVV(q(6MvgJvgJ As#q% AJ!''6* A37(++++ ./ 		s   AC &C 6C C'&C'r   )r_   r   r`   rb   N)rx   r   r   r   r   r   r)   )r?   r   r   r_   r   r7   r   r   r   r   r   r   s     `    @@@@@r9   r   r   G  s@    Z RR, ,4 		<wFrB   c           	      H    d}t        t        j                  | |||dd       y)a  
    Raises an AssertionError if two array_like objects are not ordered by less
    than.

    Given two array_like objects, check that the shape is equal and all
    elements of the first object are strictly smaller than those of the
    second object. An exception is raised at shape mismatch or incorrectly
    ordered values. Shape mismatch does not raise if an object has zero
    dimension. In contrast to the standard usage in numpy, NaNs are
    compared, no assertion is raised if both objects have NaNs in the same
    positions.



    Parameters
    ----------
    x : array_like
      The smaller object to check.
    y : array_like
      The larger object to compare.
    err_msg : string
      The error message to be printed in case of failure.
    verbose : bool
        If True, the conflicting values are appended to the error message.

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

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



    Examples
    --------
    >>> np.testing.assert_array_less([1.0, 1.0, np.nan], [1.1, 2.0, np.nan])
    >>> np.testing.assert_array_less([1.0, 1.0, np.nan], [1, 2.0, np.nan])
    Traceback (most recent call last):
        ...
    AssertionError:
    Arrays are not less-ordered
    <BLANKLINE>
    Mismatched elements: 1 / 3 (33.3%)
    Max absolute difference: 1.0
    Max relative difference: 0.5
     x: torch.ndarray([1.,  1., nan], dtype=float64)
     y: torch.ndarray([1.,  2., nan], dtype=float64)

    >>> 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.0
    Max relative difference: 0.6666666666666666
     x: torch.ndarray([1., 4.], dtype=float64)
     y: torch.ndarray(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: torch.ndarray([1., 2., 3.], dtype=float64)
     y: torch.ndarray([4])

    TzArrays are not less-orderedF)r_   r   r`   r   N)r)   r   __lt__)r?   r   r_   r   r7   s        r9   r   r     s,    X 		,rB   c                 ,   d}ddl }t        | t              st        t	        t        |                   t        |t              st        t	        t        |                  || k(  ryt        |j                         j                  | j                  d      |j                  d                  }g }|r-|j                  d      }|j                  d      r&|j                  d      r|g}|j                  d      }|j                  d      r"|j                  |       |j                  d      }|j                  d      st        t	        |            |j                  |       |rF|j                  d      }	|	j                  d      r|j                  |	       n|j                  d|	       |dd |dd k(  r	|j                  |       t        t	        |            |syd	d
j                  |      j!                          }
| |k7  rt        |
      y)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')  # doctest: +SKIP
    >>> np.testing.assert_string_equal('abc', 'abcd')  # doctest: +SKIP
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ...
    AssertionError: Differences in strings:
    - abc+ abcd?    +

    Tr   Nz  z- z? z+ rj   zDifferences in strings:
 )difflibrU   rr   r4   rW   rY   ru   Differr   r]   pop
startswithrS   insertextendr\   rstrip)r~   r   r7   r   diff	diff_listd1ld2d3r6   s              r9   r   r     s   6 fc"T$v,/00gs#T$w-011&  !2!24!8':L:LT:RSD I
XXa[====A!B}}T"XXa[==&$T"X..HHRLXXa[==&HHRLKK2&!"vABQT"X&&%bggi&8&?&?&A%B
CCS!! rB   c                       e Zd Zd Zy)_Dummyc                      y r;   r   )selfs    r9   nopz
_Dummy.nop`  s    rB   N)rZ   
__module____qualname__r  r   rB   r9   r
  r
  _  s    rB   r
  r  c                 :    d}t        j                  | |g|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)_dassertRaisesRegex)exception_classexpected_regexpr}   kwargsr7   s        r9   r   r   g  s'    " R4R6RRrB   c                    |(t        j                  dt        j                   d      }nt        j                  |      }| j                  }ddlm} |j                         D cg c]  } ||      s| }}|D ]_  }	 t        |d      r|j                  }n|j                  }|j                  |      s;|j                  d      rMt        | | ||             a yc c}w # t        $ r Y sw xY w)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_\\.z
-])[Tt]estr   )
isfunctioncompat_func_name_)recompileossep__dict__inspectr  valueshasattrr  rZ   AttributeErrorsearchr   setattr)	cls	decorator	testmatchcls_attrr  _mmethodsfunctionfuncnames	            r9   r   r   |  s    . JJ-xzBC	JJy)	||H #$OO-@bBr@G@ 
8	x!34#44#,, H%h.A.A#.FC9X#67
8  A  		s   $C2C>%C""	C.-C.c                    t         syddl}ddl} |j                  d      j	                  dd      }|}d} |j
                          	 t        j                  |      }t        d      D ]  } | ||      } t        t        j                  |      |k\          |j                          ~y#  |j                          w xY w)zg
    Check that ufuncs don't mishandle refcount of object `1`.
    Used in a few regression tests.
    Tr   Ni'  r   ri      )r&   gcr   r	   reshapedisablesysr1   rw   r   enable)	opr/  r<   bcrc   rcjds	            r9   _assert_valid_refcountr:    s    
 		)$$S#.A	A	ABJJL__Qr 	A1aA	"b()			 			s   AB* *B=c           	          d}fd}	t        |       t        |      }} dddd}
|r| j                  |j                  k(  sJ t        |	| |t        |      ||
       y)a  
    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)``.

    .. 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

    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.

    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)

    Tc                 8    t        j                  | |      S )N)rtolatolr   )r<   isclose)r?   r   r>  r   r=  s     r9   r   z assert_allclose.<locals>.compare	  s    zz!QT	JJrB   zNot equal to tolerance rtol=gz, atol=)r_   r   r`   r   N)r   r   r)   rr   )r~   r   r=  r>  r   r_   r   check_dtyper7   r   r`   s     ```      r9   r    r      sw    B K !(*W*=GF+D874(CF||w}},,,GrB   c                    d}ddl } |j                  |       } |j                  |      }| |j                   |j                  ||kD  ||            z  } |j                   |j                  | |z
        |k        sb |j
                  |       s |j
                  |      rd|z  }t        |       |j                  t        | |            }	d||	fz  }t        |      y)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)  # doctest: +SKIP

    >>> np.testing.assert_array_almost_equal_nulp(x, x*eps + x)  # doctest: +SKIP
    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   rl   r   	nulp_diffr4   )
r?   r   nulpr7   r<   axayrefr6   max_nulps
             r9   r   r     s    b 	B	B
HBHHR"Wb"56
6C266&"&&Q-3&'2??1!33d:C S!! rvvi1o.H?4BRRCS!! (rB   c                     d}ddl }t        | ||      } |j                  ||k        s$t        d|dd |j                  |      dd      |S )a{  
    Check that all items of arrays differ in at most N Units in the Last Place.

    Parameters
    ----------
    a, b : array_like
        Input arrays to be compared.
    maxulp : int, optional
        The maximum number of units in the last place that elements of `a` and
        `b` can differ. Default is 1.
    dtype : dtype, optional
        Data-type to convert `a` and `b` to if given. Default is None.

    Returns
    -------
    ret : ndarray
        Array containing number of representable floating point numbers between
        items in `a` and `b`.

    Raises
    ------
    AssertionError
        If one or more elements differ by more than `maxulp`.

    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)))  # doctest: +SKIP

    Tr   Nz"Arrays are not almost equal up to r@  z ULP (max difference is z ULP))r   rE  r   r4   r   )rd   r5  maxulpr   r7   r<   rets          r9   r   r   ]  sh    T 
Aq%
 C266#- 0
 ;&&,bffSk!_E;
 	
 JrB   c                    ddl |r) j                  | |      }  j                  ||      }n$ j                  |       }  j                  |      } j                  | |      } j                  |       s j                  |      rt	        d       j
                  | g|      }  j
                  |g|      }j                  |  j                  |       <   j                  | j                  |      <   | j                  |j                  k(  s%t        d| j                   d|j                         fd}t        |       }t        |      } ||||      S )a  For each item in x and y, return the number of representable floating
    points between them.

    Parameters
    ----------
    x : array_like
        first input array
    y : array_like
        second input array
    dtype : dtype, optional
        Data-type to convert `x` and `y` to if given. Default is None.

    Returns
    -------
    nulp : array_like
        number of representable floating point numbers between each item in x
        and y.

    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)  # doctest: +SKIP
    1.0
    r   Nr   z'_nulp not implemented for complex arrayz$x and y do not have the same shape: z - c                 V     j                   | |z
  |      } j                  |      S Nr   )r
   r   )rxryvdtr  r<   s       r9   _diffznulp_diff.<locals>._diff  s)    rzz"r'-rvvd|rB   )r   r
   common_typerl   rz   r   r   r=   r   ry   integer_repr)r?   r   r   trT  rQ  rR  r<   s          @r9   rE  rE    s6   @ BJJq&BJJq&BJJqMBJJqMq!Arq_R__Q/!"KLL!AA!AAVVAhbhhqkNVVAhbhhqkN77agg?yAGG9UVV 
aB	aBRrB   c                     | j                  |      }|j                  dk(  s|||dk     z
  ||dk  <   |S |dk  r||z
  }|S )Nri   r   )viewr   )r?   rS  comprQ  s       r9   _integer_reprr[    sT    
 
BGGqLBrAvJ&26

 I 6BIrB   c                    ddl }| j                  |j                  k(  r't        | |j                   |j                  d            S | j                  |j
                  k(  r't        | |j                   |j                  d            S | j                  |j                  k(  r't        | |j                   |j                  d            S t        d| j                         )zQReturn the signed-magnitude interpretation of the binary representation
    of x.r   Ni i   l         zUnsupported dtype )
r   r   float16r[  int16r   int32r   int64ry   )r?   r<   s     r9   rV  rV    s     ww"**Q("((8*<==	
BJJ	Q("((8*<==	
BJJ	Q("((8*<==-aggY788rB   c              #      K   d}t               5 }|j                  |       }d  t        |      dkD  s|d| nd}t        d|z         	 d d d        y # 1 sw Y   y xY ww)NTr    when calling r   zNo warning raised)r(   recordrR   r4   )warning_classnamer7   supr  name_strs         r9   _assert_warns_contextrh    sq     		 AJJ}%1vz262Bv.H !4x!?@@ A A As   A ;A	A AA c                     |st        |       S |d   }|dd }t        | |j                        5   ||i |cddd       S # 1 sw Y   yxY w)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   ri   Nre  )rh  rZ   )rd  r}   r  r   s       r9   r   r     sW    Z $]337D8D	}4==	A %T$V$% % %s   AA
c              #      K   d}t        j                  d      5 }t        j                  d       d  t        |      dkD  r| d|  nd}t	        d| d|       	 d d d        y # 1 sw Y   y xY ww)	NTrc  alwaysr   rb  r   zGot warningsrP   )warningscatch_warningssimplefilterrR   r4   )re  r7   r  rg  s       r9   _assert_no_warnings_contextrq  1  s     		 	 	- Ah'q6A:262Bv.H <zA3!?@@ A A As   A3AA'	A3'A0,A3c                      | s
t               S | d   }| dd } t        |j                        5   || i |cddd       S # 1 sw Y   yxY w)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   ri   Nrj  )rq  rZ   r}   r  r   s      r9   r   r   <  sR    6 *,,7D8D	$$--	8 %T$V$% % %s	   ?Abinary   c              #   &   
K   d}d}t        d      D ]w  
t        
dz   t        
dz   |            D ]T  |dk(  r̈ 
fd}t        f       
d }| |       |

 d	fz  f  |       }|||

 d
fz  f |dd  |       dd |
dz   
dz
   d	fz  f |dd  |       dd |

dz   dz
   d	fz  f  |       dd  |       dd |

dz   dz
   dfz  f  |       dd  |       dd |
dz   
dz
   dfz  f |dk(  sۈ 
fd}|}	t        f       
d }| |        |	       |


 d	fz  f  |       }|| |	       |


 dfz  f  |	       }| |       ||


 dfz  f |dd  |       dd  |	       dd |
dz   

dz
   d	fz  f |dd  |       dd  |	       dd |

dz   
dz
   d	fz  f |dd  |       dd  |	       dd |


dz   dz
   d	fz  f  |       dd  |       dd  |	       dd |
dz   

dz
   dfz  f  |       dd  |       dd  |	       dd |

dz   
dz
   dfz  f  |       dd  |       dd  |	       dd |


dz   dz
   dfz  f W z yw)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, %srO   rj   unaryc                  $    t               d  S rP  r	   r   oss   r9   inpz _gen_alignment_data.<locals>.inp      !!51!"55rB   r   Nzout of placezin placeri   rK   aliasedrt  c                  $    t               d  S rP  ry  rz  s   r9   inp1z!_gen_alignment_data.<locals>.inp1  r~  rB   z	in place1z	in place2)rw   r   r   )r   rY   max_sizeufmtbfmtr}  r   r9  r  inp2r{  r|  s   `         @@r9   _gen_alignment_datar  `  s*    2 :D>D1X Vq1uc!a%23 U	Aw6 QD.qr235$!Q5.)I"IIIEDAq!UJ#????!"gsuSbz4EE"3 ,   #2hab	4EE"3 ,   eCRj#%)TQAq1ueY4W-WWWeABisTQUAq1ueY4W-WWWx6 QD.qr2464641aAun2U+UUUFDFDAq!Q{+K$KKKFDAq!Q{+K$KKK!"gtvcr{DF3BKEE"A :   #2hqr
DF3BKEE"A :   #2hsTVABZEE"A :   fQRj$&"+tvcr{DEED =   fSbk46!":tvcr{DEED =   fSbk46#2;qr
DEED =  ]U	Vs   D
JFJc                       e Zd ZdZy)r!   z/Ignoring this exception due to disabled featureN)rZ   r  r  __doc__r   rB   r9   r!   r!     s    5rB   r!   c               /      K   t        | i |}	 | t        j                  |       y# t        j                  |       w xY w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  tmpdirs      r9   r$   r$     s9      d%f%Fffs   A) AA  Ac               /      K   t        | i |\  }}t        j                  |       	 | t        j                  |       y# t        j                  |       w xY w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   r  closeremove)r}   r  fdpaths       r9   r#   r#     sF      ''HBHHRL

		$		$s   $AA AAAc                   <     e Zd ZdZdZd fd	Z fdZ fdZ xZS )r"   aM  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(  # doctest: +SKIP
    ...         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   c                     t        |      j                  | j                        | _        i | _        t
        |   |       y )Nrl  )setunionclass_modulesmodules_warnreg_copiessuper__init__)r  rc  r  	__class__s      r9   r  z!clear_and_catch_warnings.__init__*  s7    7|))$*<*<=!'rB   c                     | j                   D ]H  }t        |d      s|j                  }|j                         | j                  |<   |j                          J t        |          S N__warningregistry__)r  r!  r  copyr  clearr  	__enter__)r  modmod_regr  s      r9   r  z"clear_and_catch_warnings.__enter__/  s[    << 	 Cs1211,3LLN$$S)		 
 w ""rB   c                     t        |   |  | j                  D ]_  }t        |d      r|j                  j                          || j                  v s8|j                  j                  | j                  |          a y r  )r  __exit__r  r!  r  r  r  update)r  exc_infor  r  s      r9   r  z!clear_and_catch_warnings.__exit__7  so    (#<< 	JCs12''--/d***''..t/C/CC/HI		JrB   )Fr   )	rZ   r  r  r  r  r  r  r  __classcell__)r  s   @r9   r"   r"     s&    (T M(
#J JrB   r"   c                   h    e Zd ZdZddZd ZedddfdZeddfdZeddfd	Z	d
 Z
d ZdddZd Zy)r(   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
    c                 L    d| _         g | _        |dvrt        d      || _        y )NF>   oncerm  modulelocationzunsupported forwarding rule.)_entered_suppressionsry   _forwarding_rule)r  forwarding_rules     r9   r  zsuppress_warnings.__init__  s0      "JJ;<< /rB   c                     t        t        d      rt        j                          y | j                  D ])  }t        |d      s|j                  j                          + y )N_filters_mutatedr  )r!  rn  r  _tmp_modulesr  r  )r  r  s     r9   _clear_registriesz#suppress_warnings._clear_registries  sR    8/0 %%' '' 	3Fv45**002	3rB   r   NFc                 4   |rg }nd }| j                   r|t        j                  d||       nc|j                  j	                  dd      dz   }t        j                  d|||       | j
                  j                  |       | j                          | j                  j                  ||t        j                  |t        j                        ||f       |S | j                  j                  ||t        j                  |t        j                        ||f       |S )Nrm  categorymessage.\.$r  r  r  )r  rn  filterwarningsrZ   replacer  addr  _tmp_suppressionsrS   r  r  
IGNORECASEr  )r  r  r  r  rc  module_regexs         r9   _filterzsuppress_warnings._filter  s    FF==~''8WU%66sEBSH''x !!%%f-&&(""))7BJJw$FPVW 	 %%7BJJw$FPVW rB   c                 .    | j                  |||d       y)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  rc  Nr  r  r  r  r  s       r9   filterzsuppress_warnings.filter  s    ( 	huUrB   c                 ,    | j                  |||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  s       r9   rc  zsuppress_warnings.record  s#    6 ||wvd  
 	
rB   c                    | j                   rt        d      t        j                  | _        t        j
                  | _        | j                  d d  t        _        d| _         g | _        t               | _	        t               | _
        g | _        | j                  D ]}  \  }}}}}||d d = |t        j                  d||       +|j                  j                  dd      dz   }t        j                  d|||       | j                  j!                  |        | j"                  t        _        | j%                          | S )	Nz%cannot enter suppress_warnings twice.Trm  r  r  r  r  r  )r  r   rn  showwarning
_orig_showfilters_filtersr  r  r  
_forwardedlogr  r  rZ   r  r  _showwarningr  )r  catmessr  r  r  r  s          r9   r  zsuppress_warnings.__enter__  s   ==FGG".. ((==+!#E%&*&8&8 
	+"Cq#sF{''3M"||33C?#E''sD !!%%c*
	+  $00 rB   c                     | j                   t        _        | j                  t        _        | j                          d| _        | ` | `y )NF)r  rn  r  r  r  r  r  )r  r  s     r9   r  zsuppress_warnings.__exit__  s7    #== OMrB   )use_warnmsgc                   | j                   | j                  z   d d d   D ]  \  }}	}
}}t        ||      s|
j                  |j                  d         5|?|;t        ||||fi |}| j                  j                  |       |j                  |        y |j                  j                  |      s|;t        ||||fi |}| j                  j                  |       |j                  |        y  | j                  dk(  r.| | j                  ||||g|i | y | j                  |       y | j                  dk(  r|j                  |f}n>| j                  dk(  r|j                  ||f}n| j                  dk(  r|j                  |||f}| j                  v ry | j                  j                  |       | | j                  ||||g|i | y | j                  |       y )NrK   r   rm  r  r  r  )r  r  
issubclassmatchr}   r   r  rS   __file__r   r  r  _orig_showmsgr  r  )r  r  r  filenamelinenor  r}   r  r  r  patternr  recr6   	signatures                  r9   r  zsuppress_warnings._showwarning  s    +/*<*<t?U?U*UbD*
 	%CGS# (C(W]]7<<?-K-W;,#XxCI ,

3 \\,,X6,#XxCI ,

3/	6   H,"8VUdUfU  "";/  F* x0I""h. x:I""j0 x6BI'I&DOOGXxQ$Q&Q{+rB   c                 2     t               fd       }|S )z_
        Function decorator to apply certain suppressions to a whole
        function.
        c                  D    5   | i |cd d d        S # 1 sw Y   y xY wr;   r   )r}   r  r   r  s     r9   new_funcz,suppress_warnings.__call__.<locals>.new_funcQ  s(     -T,V,- - -s   r   )r  r   r  s   `` r9   __call__zsuppress_warnings.__call__K  s"     
t	- 
	- rB   )rm  )rZ   r  r  r  r  r  Warningr  r  rc  r  r  r  r  r   rB   r9   r(   r(   @  s\    HT0
3  '4 4 &r$ V, &r$ 
>> GK2,hrB   r(   c              #   >  K   d}t         sd  y t        t        j                                t        j                          t        j
                         }	 t        d      D ]  }t        j                         dk(  s n t        d      t        j                  t        j                         d  t        j                         }t        j                  d d  }t        j                  d d = t        j                  |       t        j                          |rE| d|  nd}t        dj                  ||t        |      dj!                  d |D                          y # t        j                  d d = t        j                  |       t        j                          w xY ww)	NTr   r   z]Unable to fully collect garbage - perhaps a __del__ method is creating more reference cycles?rb  r   zXReference cycles were found{}: {} objects were collected, of which {} are shown below:{}c           	   3      K   | ]V  }d j                  t        |      j                  t        |      t	        j
                  |      j                  dd             X yw)z
  {} object with id={}:
    {}rJ   z
    N)formatrY   rZ   idr   pformatr  ).0r{  s     r9   	<genexpr>z/_assert_no_gc_cycles_context.<locals>.<genexpr>  sR        8>>Q((1q)11$As   AA)r&   r   r/  	isenabledr1  	get_debugrw   collectr   	set_debugDEBUG_SAVEALLgarbager3  r4   r  rR   r\   )re  r7   gc_debugrc   n_objects_in_cyclesobjects_in_cyclesrg  s          r9   _assert_no_gc_cycles_contextr  Y  sM     BLLNJJL||~Hs 	Azz|q 	 5 
 	R%%& !jjlJJqMJJqM
X
		.2.>^D6*B--3V#%&  / 	.
 	
 	 JJqM
X
		s&   AF%E <AE BF>FFc                      | s
t               S | d   }| dd } t        |j                        5   || i | ddd       y# 1 sw Y   yxY w)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   ri   Nrj  )r  rZ   rs  s      r9   r*   r*     sR    4 +--7D8D	%4==	9 df  s	   	?Ac                      t        j                          t        rQt        j                          t        j                          t        j                          t        j                          yy)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   rB   r9   r+   r+     s9     JJL











 rB   c                      ddl  fd}|S )z:Decorator to skip a test if not enough memory is availabler   Nc                 4     t                fd       }|S )Nc                      t              }|j                  |       	  | i |S # t        $ r j                  d       Y y w xY w)NzMemoryError raised)check_free_memoryskipMemoryErrorxfail)rd   kwr6   
free_bytesr   pytests      r9   wrapperz3requires_memory.<locals>.decorator.<locals>.wrapper  sM    #J/CC 3Q~"~% 3123s   ) AAr   )r   r  r  r  s   ` r9   r&  z"requires_memory.<locals>.decorator  s     	t		3 
		3 rB   )r  )r  r&  r  s   ` @r9   requires_memoryr    s     rB   c                    d}t         j                  j                  |      }|	 t        |      }| dz   d| d}nt               }|d}d	}n| dz   d
|dz   d}|| k  r|S dS # t        $ r}t	        d| d|       d}~ww xY w)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 rP   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.rK   z GB memory required, but z GB available)r  environget_parse_sizery   _get_mem_available)r  env_var	env_valuemem_freerg   r6   s         r9   r  r    s    
 "G

w'I	"9-H #~ !!*41 	
 &' 
 H c>"";HSL>W  Z'31T11  	/y3%@ 	s   A$ $	B-A>>Bc                    dddddddddddddd	d
}t        j                  dj                  dj                  |j	                                     t         j
                        }|j                  | j                               }|r|j                  d      |vrt        d| d      t        t        |j                  d            ||j                  d         z        S )z3Convert memory size strings ('12 GB' etc.) to floatri   i  i@B i ʚ;l    J)   i   i   @l        )r   r5  r   mr@  rW  kbmbgbtbkibmibgibtibz^\s*(\d+|\d+\.\d+)\s*({})\s*$|rj   zvalue z not a valid size)r  r  r  r\   rt   r  r  lowergroupry   r   r   )size_strsuffixessize_rer  s       r9   r	  r	    s     H" jj(//0IJ
G
 	hnn&'A
(*6(->?@@uQWWQZ 8AGGAJ#7788rB   c                     	 ddl } | j                         j                  S # t        t        f$ r Y nw xY wt
        j                  j                  d      ri }t        d      5 }|D ]F  }|j                         }t        |d         dz  ||d   j                  d      j                         <   H 	 ddd       n# 1 sw Y   nxY wd|v r|d   S |d	   |d
   z   S y)z5Return available memory in bytes, or None if unknown.r   Nlinuxz/proc/meminfori   r  :memavailablememfreecached)psutilvirtual_memory	availableImportErrorr"  r2  platformr   opensplitr   stripr  )r%  infoflineps        r9   r
  r
  	  s    $$&000(  ||w'/" 	Aa AJJL03AaD	D0@QqTZZ_**,-A	A 	A 	A
 T!''	?T(^33s     22!AB77C c                 R     t        t        d      s S t                f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                      t        j                         }	 t        j                  d         | i |t        j                  |       S # t        j                  |       w xY wr;   )r2  r2  settrace)r}   r  original_tracer   s      r9   r  z_no_tracing.<locals>.wrapper?	  sE     \\^N-T"T,V,^,^,s   A	 	A )r!  r2  r   )r   r  s   ` r9   _no_tracingr6  5	  s3     3
# 
t	- 
	- rB   c                      	 t        j                  d      j                  d      d   } | S # t        $ r}d} Y d }~| S d }~ww xY w)NCS_GNU_LIBC_VERSIONrM   ri   0.0)r  confstrrsplitrX   )verinsts     r9   _get_glibc_versionr>  K	  sI    jj./66s;A> J  Js   '+ 	A<Ac                 *    t         dk7  xr	 t         | k  S )Nr9  )	_glibcverr>   s    r9   _glibc_older_thanrA  W	  s    /)a-/rB   )r   )zItems are not equal:T)ACTUALDESIRED   )r   T)   r   T)r   Tr      TT)rF  r   Tr;   )gHz>r   Tr   TF)ri   )ri   N)[r  r   r/  r   r  r)  r   r  r  r2  rn  	functoolsr   ior   tempfiler   r   r   rx   _numpyr<   r	   r
   r   r   r   r   r   __all__r   machiner'   implementationre  r%   r!  r,   getattrr&   r   r@   rE   rH   r   r   r   r   r   r)   r   r   r   r   unittestTestCaser
  r  r   r   r:  r    r   r   rE  r[  rV  contextmanagerrh  r   rq  r   r  rX   r!   r$   r#   ro  r"   r(   r  r*   r+   r  r  r	  r
  r6  r>  r@  rA  r   rB   r9   <module>rR     s    	  	   	  
    % #  U U F 
(


 4
4



!
!V
+C./	sM40<NY#( "
DVr&-Rz/za"P p pfg gTrjUpE"P X 
 E]S*,^
< 
	
Tn="@3l<~9 A A3%l A A!%H &Hr qh6i 6    *@Jx66 @JFV Vr 1
 1
h F$,"2J9<2,  	0rB   