
    Џkhl2                       U d Z ddlmZ ddlZddlZddlZddl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
lmZ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 Z" ed      Z$ ed      Z%i Z&de'd<    G d dejP                        Z)e)jT                  Z*dde*e*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IteratorSequence)wraps)
ModuleType)TYPE_CHECKINGAny	ParamSpecTypeVarcast   )is_dask_namespaceis_jax_namespace)jax_autojitpickle_flattenpickle_unflattenlazy_xp_functionpatch_lazy_xp_functions)GraphKeySchedulerGetCallable)overridec                    | S N )funcs    ^/var/www/teggl/fontify/venv/lib/python3.12/site-packages/scipy/_lib/array_api_extra/testing.pyr   r       s        PTzdict[object, dict[str, Any]]_ufuncs_tagsc                      e Zd ZdZdZy)
Deprecatedz&Unique type for deprecated parameters.r   N)__name__
__module____qualname____doc__
DEPRECATEDr   r   r   r$   r$   *   s
    0Jr   r$   FT)allow_dask_computejax_jitstatic_argnumsstatic_argnamesc                   |t         us|t         urt        j                  dt        d       ||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 : bool | int, optional
        Whether `func` is allowed to internally materialize the Dask graph, or maximum
        number of times it is allowed to do so. 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.

        Set to True to allow `func` to materialize the graph an unlimited number
        of times.

        Default: False, meaning that `func` must be fully lazy and never materialize the
        graph.
    jax_jit : bool, optional
        Set to True to replace `func` with a smart variant of ``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.

        Unlike with vanilla ``jax.jit``, all arguments and return types that are not JAX
        arrays are treated as static; the function can accept and return arbitrary
        wrappers around JAX arrays. This difference is because, in real life, most users
        won't wrap the function directly with ``jax.jit`` but rather they will use it
        within their own code, which is itself then wrapped by ``jax.jit``, and
        internally consume the function's outputs.

        In other words, the pattern that is being tested is::

            >>> @jax.jit
            ... def user_func(x):
            ...     y = user_prepares_inputs(x)
            ...     z = func(y, some_static_arg=True)
            ...     return user_consumes(z)

        Default: True.
    static_argnums :
        Deprecated; ignored
    static_argnames :
        Deprecated; ignored

    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 similar to `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
    z{The `static_argnums` and `static_argnames` parameters are deprecated and ignored. They will be removed in a future version.   )
stacklevel)r*   r+   N)r)   warningswarnDeprecationWarning_lazy_xp_functionAttributeErrorr"   )r   r*   r+   r,   r-   tagss         r   r   r   3   sc    d Z'?*+LI 	
 1D
"!% "!T"s   ; AAc          	       
 t        t        | j                        }|gt        t        t           t	        |dg             
	 	 d

fd}t        |      rC |       D ]8  \  }}}}|d   }|du rd}n|du rd}t        ||      }	|j                  |||	       : y	t        |      r6 |       D ]+  \  }}}}|d   st        |      }	|j                  |||	       - 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suppressr5   r4   KeyError	TypeErrorr"   )modnamer   r6   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*   Ti@B Fr   r+   N)returnzDIterator[tuple[ModuleType, str, Callable[..., Any], dict[str, Any]]])
r   r   modulelistgetattrr   
_dask_wrapsetattrr   r   )requestmonkeypatchxpr@   rC   rA   r   r6   nwrappedrB   s             @r   r   r      s    N z7>>
*CN$tJ'6G)LMND0L0 %0] 	4!CtT)*ADye q)GT73	4 
"	%0] 	8!CtTI%d+##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   )rR   rS   rU   )selfrS   rU   s      r   __init__zCountingDaskScheduler.__init__5  s    
"r   c                    dd l }| xj                  dz  c_        | j                  | j                  k  sJ | j                          |j                  ||fi |S )Nr   r   )daskrR   rS   rU   get)rW   dskkeyskwargsrZ   s        r   __call__zCountingDaskScheduler.__call__:  sK    

a
 zzT^^+5TXX5+txxT,V,,r   N)rS   rQ   rU   rT   )r\   r   r]   zSequence[Key] | Keyr^   r
   rD   r
   )r%   r&   r'   r(   __annotations__rX   r   r_   r   r   r   rP   rP   "  s1     JN	H
 - -r   rP   c           	          ddl ddlm 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   Nr%   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        t        j                        \  }}j                  |d      d   }t        ||      S # 1 sw Y   DxY w)N	schedulerthreads)rd   r   )rP   configsetr   Arraypersistr   )argsr^   rd   outarraysrestdarZ   r   rU   rM   s         r   wrapperz_dask_wrap.<locals>.wrapperZ  s    )!S1	[[__k956 	(''C	( &c2884f	:1=--	( 	(s   	A77B )rj   zP.argsr^   zP.kwargsrD   r!   )rZ   
dask.arrayarrayrG   rT   r   )r   rM   	func_namen_strro   rn   rZ   rU   s   ``   @@@r   rH   rH   F  s     j#d)4I!"k!E
6q1ug >g &K'<QUG DI	I  4[
. 
. 
. Nr   )r   zCallable[..., Any]r*   z
bool | intr+   boolr,   r$   r-   r$   rD   None)rJ   zpytest.FixtureRequestrK   zpytest.MonkeyPatchrL   r   rD   ru   )r   Callable[P, T]rM   rQ   rD   rv   )/r(   
__future__r   r<   enumr1   collections.abcr   r   r   	functoolsr   typesr   typingr	   r
   r   r   r   _lib._utils._compatr   r   _lib._utils._helpersr   r   r   __all__pytestdask.typingr   r   r   typing_extensionsr   objectr    r!   r"   r`   Enumr$   r)   r   r   rP   rH   r   r   r   <module>r      sA   #    8 8   ? ? D O O8
9<<* " cNCL-/* /  ""
 &+!+",c"
c" #c" 	c"
 c"  c" 
c"LF8"F81CF8LVF8	F8R!-0 !-H!
! !!r   