
    ^j                     $    d Z ddlZddlZd Zd Zy)z4Helpers for producing efficient wrappers of ufuncs.
    Nc                 z    | j                  d      d   }t        j                  d|      }t        d |D              S )z>Return tuple of num core dims per input from gufunc signature.z->r   z	\((.*?)\)c              3   h   K   | ]*  }|j                         sd n|j                  d      dz    , yw)r   ,   N)stripcount).0gs     S/opt/ringagent/.cad-venv/lib/python3.12/site-packages/scipy/special/_ufunc_tools.py	<genexpr>z$_parse_core_ndims.<locals>.<genexpr>   s*     Ja!''))99Js   02)splitrefindalltuple)	signature	input_siggroupss      r   _parse_core_ndimsr      s6    %a(IZZi0FJ6JJJ    c                    
 j                   t        j                         ndj                  z  

fd}dj                  |      }d|  d| d| d}d|i}t	        ||       ||    }	||	_        |	S )	a7
  Helper to ensure optimal iteration order for ufuncs that use caching.

    This concerns internal caches which are only live over the course of one
    call to a ufunc to avoid repeated computations during the course of the
    loops. See the notes below for more information.

    Parameters
    ----------
    name : str
    arg_names : list[str]
        The function name and arg names are passed in so that the wrapper
        can be generated with the create name and argument names, improving
        documentation and autocomplete.
    docstring : str
    ufunc : numpy.ufunc
    cache_arg_indices : list[int]
       Arguments to ufunc which are used in the kernel to compute an output
       which is being cached for reuse when iterating over other arguments.

    Returns
    -------
    callable
        A wrapper for ufunc which transposes the axes of the inputs to ensure
        iteration precedes in such a way to allow the cache within the ufunc
        kernel to eliminate redundant computation.

    Notes
    -----
    There is a common pattern in ufunc kernels exemplified by the situation
    where some of the arguments are used to compute coeffients of an expansion
    that is taken over one or more of the other arguments. A classic example is
    Mathieu functions, which compute coefficients corresponding to the shape
    parameter q and order m which in principle could be reused for varying
    values of the parameter x.

    It had long been the case that the expensive computation of coefficients is
    repeated unnecessarily across values of x. It is possible to add a cache to
    the ufunc kernel which stores the expansion coefficients and only updates
    if the pointers into the q and m arrays advance during the course of the
    ufunc loops. Such a cache is instantiated each time a ufunc is called and
    only lives during the course of the loops that are carried out for that
    particular call.

    Whether such a cache actually helps depends on the order in which iteration
    occurs. Ideally, one would want q and m to advance most slowly and for the
    iterations over x for fixed q and m to be pushed to the inner most loops.
    This helper replaces each input array (and a pre-allocated output array)
    with a view where the axes which should vary most slowly are transposed to
    the ends and forces computation in C order. This ensures iteration proceeds
    in the optimal order.

    Note that because the pre-allocated output array used internally is C
    contiguous, the output will be C contiguous regardless of contiguity of
    the inputs.

    )r   c                  d     D cg c]  }t        j                  |       c} t         fdD              r   S t               D cg c],  \  }}|   dkD  r|j                  d |     n|j                  . }}}t        j
                  | }t        |      }t               D cg c]M  \  }}|   dkD  r*t        j                  |||j                  |    d  z         nt        j                  ||      O c}}g }g }t        |      D ]<  t        fdD              }|r|j                         ,|j                         > ||z   }	g }
t              D ]I  \  }}|	t        t        |||   z               z   }|
j                  t        j                  ||             K t        d |
D              dj                  z  z   }j                  |      d   }t        j                  ||d	      }t        j                  ||	      } |
|dd
 |S c c}w c c}}w c c}}w )Nc              3   H   K   | ]  }|   j                   |   k(    y wN)ndim)r	   iargs
core_ndimss     r   r   z=_with_cache_optimization.<locals>._wrapper.<locals>.<genexpr>]   s"     HtAw||z!},H   "r   c              3   H   K   | ]  }|   j                      d k(    yw)r   N)strides)r	   r   args_baxs     r   r   z=_with_cache_optimization.<locals>._wrapper.<locals>.<genexpr>x   s*      /0q	!!"%*r   )axesc              3   4   K   | ]  }|j                     y wr   )dtype)r	   args     r   r   z=_with_cache_optimization.<locals>._wrapper.<locals>.<genexpr>   s     93SYY9s   r   C)r%   order)outr)   )npasarrayall	enumerateshapebroadcast_shapeslenbroadcast_torangeappendlist	transposer   noutresolve_dtypesempty)r   r&   r   batch_shapesbatch_shape
batch_ndimvarying_axesconstant_axesis_constantsorted_batch_axesargs_targ_br#   input_dtypes	out_dtype	out_finalout_tr!   r"   cache_arg_indicesr   ufuncs   `                @@r   _wrapperz*_with_cache_optimization.<locals>._wrapperX   sB   +/0C

30 H6GHH$< $D/
3 +5Q-!*;CIIo
1~&J
 
 ))<8%
 $D/
 3 !}q  OOCsyy*Q-/I!IJ&(ooc;&GH
 
# 	(B 4E K $$R(##B'	( )=8 !&) 	:HAu$tj*z!}"<=( D MM",,u489		: 9&99GEJJ<NN((6r:	HH[	E	Y->? 	v5,w 1

s   H!1H&/AH,z, zdef (z):
            return _wrapper(z
)
        rI   )r   r   ninjoinexec__doc__)name	arg_names	docstringrH   rG   rI   arg_strcode	namespacewrapperr   s      ``     @r   _with_cache_optimizationrV      s    J ??& 	%//*%))^ <@ ii	"Gay !$I &		 	
 X&IyoGGONr   )rN   r   numpyr+   r   rV    r   r   <module>rY      s    
 KSr   