
    Wh.                    V   U d Z ddlmZ ddlZddlmZmZ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 dd	lmZmZ d
dgZerddlZddlmZmZmZ ddlmZ neZddZ ed      Z ed      Z i Z!de"d<   ddddd	 	 	 	 	 	 	 	 	 	 	 ddZ#	 	 	 	 	 	 	 	 ddZ$ G d de      Z%	 	 	 	 	 	 ddZ&y)z]
Public testing utilities.

See also _lib._testing for additional private testing utilities.
    )annotationsN)CallableIterableIteratorSequence)wraps)
ModuleType)TYPE_CHECKINGAny	ParamSpecTypeVarcast   )is_dask_namespaceis_jax_namespacelazy_xp_functionpatch_lazy_xp_functions)GraphKeySchedulerGetCallable)overridec                    | S N )funcs    c/var/www/html/jupyter_env/lib/python3.12/site-packages/sklearn/externals/array_api_extra/testing.pyr   r      s        PTzdict[object, dict[str, Any]]_ufuncs_tagsTallow_dask_computejax_jitstatic_argnumsstatic_argnamesc               R    ||||d}	 || _         y# t        $ r |t        | <   Y yw xY w)a_  
    Tag a function to be tested on lazy backends.

    Tag a function so that when any tests are executed with ``xp=jax.numpy`` the
    function is replaced with a jitted version of itself, and when it is executed with
    ``xp=dask.array`` the function will raise if it attempts to materialize the graph.
    This will be later expanded to provide test coverage for other lazy backends.

    In order for the tag to be effective, the test or a fixture must call
    :func:`patch_lazy_xp_functions`.

    Parameters
    ----------
    func : callable
        Function to be tested.
    allow_dask_compute : int, optional
        Number of times `func` is allowed to internally materialize the Dask graph. This
        is typically triggered by ``bool()``, ``float()``, or ``np.asarray()``.

        Set to 1 if you are aware that `func` converts the input parameters to NumPy and
        want to let it do so at least for the time being, knowing that it is going to be
        extremely detrimental for performance.

        If a test needs values higher than 1 to pass, it is a canary that the conversion
        to NumPy/bool/float is happening multiple times, which translates to multiple
        computations of the whole graph. Short of making the function fully lazy, you
        should at least add explicit calls to ``np.asarray()`` early in the function.
        *Note:* the counter of `allow_dask_compute` resets after each call to `func`, so
        a test function that invokes `func` multiple times should still work with this
        parameter set to 1.

        Default: 0, meaning that `func` must be fully lazy and never materialize the
        graph.
    jax_jit : bool, optional
        Set to True to replace `func` with ``jax.jit(func)`` after calling the
        :func:`patch_lazy_xp_functions` test helper with ``xp=jax.numpy``. Set to False
        if `func` is only compatible with eager (non-jitted) JAX. Default: True.
    static_argnums : int | Sequence[int], optional
        Passed to jax.jit. Positional arguments to treat as static (compile-time
        constant). Default: infer from `static_argnames` using
        `inspect.signature(func)`.
    static_argnames : str | Iterable[str], optional
        Passed to jax.jit. Named arguments to treat as static (compile-time constant).
        Default: infer from `static_argnums` using `inspect.signature(func)`.

    See Also
    --------
    patch_lazy_xp_functions : Companion function to call from the test or fixture.
    jax.jit : JAX function to compile a function for performance.

    Examples
    --------
    In ``test_mymodule.py``::

      from array_api_extra.testing import lazy_xp_function from mymodule import myfunc

      lazy_xp_function(myfunc)

      def test_myfunc(xp):
          a = xp.asarray([1, 2])
          # When xp=jax.numpy, this is the same as `b = jax.jit(myfunc)(a)`
          # When xp=dask.array, crash on compute() or persist()
          b = myfunc(a)

    Notes
    -----
    In order for this tag to be effective, the test function must be imported into the
    test module globals without its namespace; alternatively its namespace must be
    declared in a ``lazy_xp_modules`` list in the test module globals.

    Example 1::

      from mymodule import myfunc

      lazy_xp_function(myfunc)

      def test_myfunc(xp):
          x = myfunc(xp.asarray([1, 2]))

    Example 2::

      import mymodule

      lazy_xp_modules = [mymodule]
      lazy_xp_function(mymodule.myfunc)

      def test_myfunc(xp):
          x = mymodule.myfunc(xp.asarray([1, 2]))

    A test function can circumvent this monkey-patching system by using a namespace
    outside of the two above patterns. You need to sanitize your code to make sure this
    only happens intentionally.

    Example 1::

      import mymodule
      from mymodule import myfunc

      lazy_xp_function(myfunc)

      def test_myfunc(xp):
          a = xp.asarray([1, 2])
          b = myfunc(a)  # This is wrapped when xp=jax.numpy or xp=dask.array
          c = mymodule.myfunc(a)  # This is not

    Example 2::

      import mymodule

      class naked:
          myfunc = mymodule.myfunc

      lazy_xp_modules = [mymodule]
      lazy_xp_function(mymodule.myfunc)

      def test_myfunc(xp):
          a = xp.asarray([1, 2])
          b = mymodule.myfunc(a)  # This is wrapped when xp=jax.numpy or xp=dask.array
          c = naked.myfunc(a)  # This is not
    r!   N)_lazy_xp_functionAttributeErrorr    )r   r"   r#   r$   r%   tagss         r   r   r   '   s>    B 1(*	D"!% "!T"s    &&c          
        t        t        | j                        }|gt        t        t           t	        |dg             	 	 dfd}t        |      r6 |       D ]+  \  }}}}|d   }t        ||      }	|j                  |||	       - yt        |      r`ddl	}
 |       D ]Q  \  }}}}|d   st        t        dt        f   |
j                  ||d   |d	   
            }	|j                  |||	       S yy)a  
    Test lazy execution of functions tagged with :func:`lazy_xp_function`.

    If ``xp==jax.numpy``, search for all functions which have been tagged with
    :func:`lazy_xp_function` in the globals of the module that defines the current test,
    as well as in the ``lazy_xp_modules`` list in the globals of the same module,
    and wrap them with :func:`jax.jit`. Unwrap them at the end of the test.

    If ``xp==dask.array``, wrap the functions with a decorator that disables
    ``compute()`` and ``persist()`` and ensures that exceptions and warnings are raised
    eagerly.

    This function should be typically called by your library's `xp` fixture that runs
    tests on multiple backends::

        @pytest.fixture(params=[numpy, array_api_strict, jax.numpy, dask.array])
        def xp(request, monkeypatch):
            patch_lazy_xp_functions(request, monkeypatch, xp=request.param)
            return request.param

    but it can be otherwise be called by the test itself too.

    Parameters
    ----------
    request : pytest.FixtureRequest
        Pytest fixture, as acquired by the test itself or by one of its fixtures.
    monkeypatch : pytest.MonkeyPatch
        Pytest fixture, as acquired by the test itself or by one of its fixtures.
    xp : array_namespace
        Array namespace to be tested.

    See Also
    --------
    lazy_xp_function : Tag a function to be tested on lazy backends.
    pytest.FixtureRequest : `request` test function parameter.
    lazy_xp_modulesc               3  j  K   D ]  } | j                   j                         D ]r  \  }}d }t        j                  t              5  |j
                  }d d d        |0t        j                  t        t              5  t        |   }d d d        |k| |||f t  y # 1 sw Y   KxY w# 1 sw Y   %xY wwr   )	__dict__items
contextlibsuppressr(   r'   KeyError	TypeErrorr    )modnamer   r)   modss       r   iter_taggedz,patch_lazy_xp_functions.<locals>.iter_tagged   s       		0C!ll002 0
d.2((8 211D2<#,,XyA 2+D12#tT4//0		02 22 2s<   AB3B(B39
B'
B3B3B$ B3'B0,B3r"   r   Nr#   .r$   r%   )r$   r%   )returnzDIterator[tuple[ModuleType, str, Callable[..., Any], dict[str, Any]]])r   r	   modulelistgetattrr   
_dask_wrapsetattrr   jaxr   r   jit)requestmonkeypatchxpr3   r6   r4   r   r)   nwrappedr=   r5   s              @r   r   r      s   N z7>>
*CN$tJ'6G)LMND0L0 %0] 	4!CtT)*A q)GT73	4
 
"	%0] 	8!CtTIS#X&GG'+,<'=(,->(?   ##Cw7	8 
r   c                  J    e Zd ZU dZded<   ded<   ded<   d
dZedd       Zy	)CountingDaskSchedulera  
    Dask scheduler that counts how many times `dask.compute` is called.

    If the number of times exceeds 'max_count', it raises an error.
    This is a wrapper around Dask's own 'synchronous' scheduler.

    Parameters
    ----------
    max_count : int
        Maximum number of allowed calls to `dask.compute`.
    msg : str
        Assertion to raise when the count exceeds `max_count`.
    intcount	max_countstrmsgc                .    d| _         || _        || _        y )Nr   )rG   rH   rJ   )selfrH   rJ   s      r   __init__zCountingDaskScheduler.__init__  s    
"r   c                    dd l }| xj                  dz  c_        | j                  | j                  k  sJ | j                          |j                  ||fi |S )Nr   r   )daskrG   rH   rJ   get)rL   dskkeyskwargsrO   s        r   __call__zCountingDaskScheduler.__call__  sK    

a
 zzT^^+5TXX5+txxT,V,,r   N)rH   rF   rJ   rI   )rQ   r   rR   zSequence[Key] | KeyrS   r   r7   r   )__name__
__module____qualname____doc____annotations__rM   r   rT   r   r   r   rE   rE     s1     JN	H
 - -r   rE   c           	          ddl t         dt                     }rd nd}ddz    d| d	| d
dz    d	t               d fd       }|S )z
    Wrap `func` to raise if it attempts to call `dask.compute` more than `n` times.

    After the function returns, materialize the graph in order to re-raise exceptions.
    r   NrU   zonly up to noz,Called `dask.compute()` or `dask.persist()` r   z times, but z* calls are allowed. Set `lazy_xp_function(z, allow_dask_compute=zA)` to allow for more (but note that this will harm performance). c                     t              }j                  j                  d|i      5   | i |}d d d        j                  d      d   S # 1 sw Y   xY w)N	schedulerthreads)r]   r   )rE   configsetpersist)argsrS   r]   outrO   r   rJ   rB   s       r   wrapperz_dask_wrap.<locals>.wrapper9  sb    )!S1	[[__k956 	(''C	( ||C9|5a88	( 	(s   	AA)rb   zP.argsrS   zP.kwargsr7   r   )rO   r:   rI   r   )r   rB   	func_namen_strrd   rO   rJ   s   ``   @@r   r;   r;   &  s     j#d)4I!"k!E
6q1ug >g &K'<QUG DI	I  4[9 9 Nr   )r   objectr7   rg   )r   zCallable[..., Any]r"   rF   r#   boolr$   zint | Sequence[int] | Noner%   zstr | Iterable[str] | Noner7   None)r?   zpytest.FixtureRequestr@   zpytest.MonkeyPatchrA   r	   r7   ri   )r   Callable[P, T]rB   rF   r7   rj   )'rX   
__future__r   r/   collections.abcr   r   r   r   	functoolsr   typesr	   typingr
   r   r   r   r   _lib._utils._compatr   r   __all__pytestdask.typingr   r   r   typing_extensionsr   rg   r   r   r    rY   r   r   rE   r;   r   r   r   <module>ru      s   #  B B   ? ? D8
9<<* " cNCL-/* /  1526I"
I" I" 	I"
 /I" 0I" 
I"XL8"L81CL8LVL8	L8^!-0 !-H
 r   