
    `i]T                        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 ddZddZ	ddZ
dd	Zdd
ZddZddZddZej        j                            dddd          ZddZd dZddddZd!dZd"dZddZddZdS )#    N)_routines_math)_fusion_thread_local)internalFc                     t          j                    rE|rt          d          |t          j        }nt          j        }t          j        || |||          S |                     ||||          S )a  Returns the sum of an array along given axes.

    Args:
        a (cupy.ndarray): Array to take sum.
        axis (int or sequence of ints): Axes along which the sum is taken.
        dtype: Data type specifier.
        out (cupy.ndarray): Output array.
        keepdims (bool): If ``True``, the specified axes are remained as axes
            of length one.

    Returns:
        cupy.ndarray: The result array.

    .. seealso:: :func:`numpy.sum`

    z3cupy.sum does not support `keepdims` in fusion yet.Naxisdtypeout)r   	is_fusingNotImplementedError_mathsum_auto_dtype_sum_keep_dtypecall_reductionsumar   r	   r
   keepdimsfuncs         f/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/cupy/_math/sumprod.pyr   r      s    " %'' 	6 	G%EG G G='DD(D#2!$e6 6 6 	6 55uc8,,,    c                     t          j                    rE|rt          d          |t          j        }nt          j        }t          j        || |||          S |                     ||||          S )a  Returns the product of an array along given axes.

    Args:
        a (cupy.ndarray): Array to take product.
        axis (int or sequence of ints): Axes along which the product is taken.
        dtype: Data type specifier.
        out (cupy.ndarray): Output array.
        keepdims (bool): If ``True``, the specified axes are remained as axes
            of length one.

    Returns:
        cupy.ndarray: The result array.

    .. seealso:: :func:`numpy.prod`

    z4cupy.prod does not support `keepdims` in fusion yet.Nr   )r   r   r   r   _prod_auto_dtype_prod_keep_dtyper   prodr   s         r   r   r   +   s    " %'' 	6 	H%FH H H=)DD)D#2!$e6 6 6 	6 66$sH---r   c                    t          j                    r`|rt          d          | j        j        dv rt
          j        }n|t
          j        }nt
          j        }t          j	        || |||          S t          j
        | ||||          S )a  Returns the sum of an array along given axes treating Not a Numbers
    (NaNs) as zero.

    Args:
        a (cupy.ndarray): Array to take sum.
        axis (int or sequence of ints): Axes along which the sum is taken.
        dtype: Data type specifier.
        out (cupy.ndarray): Output array.
        keepdims (bool): If ``True``, the specified axes are remained as axes
            of length one.

    Returns:
        cupy.ndarray: The result array.

    .. seealso:: :func:`numpy.nansum`

    z6cupy.nansum does not support `keepdims` in fusion yet.FDNr   )r   r   r   r	   charr   _nansum_complex_dtype_nansum_auto_dtype_nansum_keep_dtyper   _nansumr   s         r   nansumr#   K   s    $ %'' 6 	J%HJ J J7<4.DD]+DD+D#2!$e6 6 6 	6 =D%h777r   c                     t          j                    rE|rt          d          |t          j        }nt          j        }t          j        || |||          S t          j        | ||||          S )a  Returns the product of an array along given axes treating Not a Numbers
    (NaNs) as zero.

    Args:
        a (cupy.ndarray): Array to take product.
        axis (int or sequence of ints): Axes along which the product is taken.
        dtype: Data type specifier.
        out (cupy.ndarray): Output array.
        keepdims (bool): If ``True``, the specified axes are remained as axes
            of length one.

    Returns:
        cupy.ndarray: The result array.

    .. seealso:: :func:`numpy.nanprod`

    z7cupy.nanprod does not support `keepdims` in fusion yet.Nr   )r   r   r   r   _nanprod_auto_dtype_nanprod_keep_dtyper   _nanprodr   s         r   nanprodr(   n   s    $ %'' 	6 	K%IK K K=,DD,D#2!$e6 6 6 	6 >!T5#x888r   c                 P    t          j        | |t           j        j        ||          S )a  Returns the cumulative sum of an array along a given axis.

    Args:
        a (cupy.ndarray): Input array.
        axis (int): Axis along which the cumulative sum is taken. If it is not
            specified, the input is flattened.
        dtype: Data type specifier.
        out (cupy.ndarray): Output array.

    Returns:
        cupy.ndarray: The result array.

    .. seealso:: :func:`numpy.cumsum`

    )r   	scan_corescan_opSCAN_SUMr   r   r	   r
   s       r   cumsumr.      s!      ?1dEM$:E3GGGr   c                 P    t          j        | |t           j        j        ||          S )a  Returns the cumulative product of an array along a given axis.

    Args:
        a (cupy.ndarray): Input array.
        axis (int): Axis along which the cumulative product is taken. If it is
            not specified, the input is flattened.
        dtype: Data type specifier.
        out (cupy.ndarray): Output array.

    Returns:
        cupy.ndarray: The result array.

    .. seealso:: :func:`numpy.cumprod`

    )r   r*   r+   	SCAN_PRODr-   s       r   cumprodr1      s!      ?1dEM$;UCHHHr   c                 L    t          | d|          } t          | |||          S )a  Returns the cumulative sum of an array along a given axis treating Not a
    Numbers (NaNs) as zero.

    Args:
        a (cupy.ndarray): Input array.
        axis (int): Axis along which the cumulative sum is taken. If it is not
            specified, the input is flattened.
        dtype: Data type specifier.
        out (cupy.ndarray): Output array.

    Returns:
        cupy.ndarray: The result array.

    .. seealso:: :func:`numpy.nancumsum`
    r   r
   r   )_replace_nanr.   r-   s       r   	nancumsumr5      s/      	Qs###A!$e5555r   c                 L    t          | d|          } t          | |||          S )a  Returns the cumulative product of an array along a given axis treating
    Not a Numbers (NaNs) as one.

    Args:
        a (cupy.ndarray): Input array.
        axis (int): Axis along which the cumulative product is taken. If it is
            not specified, the input is flattened.
        dtype: Data type specifier.
        out (cupy.ndarray): Output array.

    Returns:
        cupy.ndarray: The result array.

    .. seealso:: :func:`numpy.nancumprod`
       r3   r   )r4   r1   r-   s       r   
nancumprodr8      s/      	Qs###A14u#6666r   z
T a, T valzT outz(if (a == a) {out = a;} else {out = val;}cupy_replace_nanc                 t    || j         |j         k    rt          j        |           }t          | ||           |S N)r	   cupy
empty_like_replace_nan_kernel)r   valr
   s      r   r4   r4      s;    
{ag**oa  3$$$Jr   r7   c                    |dk    r| S |dk     rt          dt          |          z             t          j        |           } | j        }t          j        ||          }g }|ot          j        |          }|j        dk    r;t          | j                  }d||<   t          j	        |t          |                    }|                    |           |                    |            |ot          j        |          }|j        dk    r;t          | j                  }d||<   t          j	        |t          |                    }|                    |           t          |          dk    rt          j        ||          } t          d          g|z  }t          d          g|z  }	t          dd          ||<   t          dd          |	|<   t          |          }t          |	          }	| j        t           j        k    rt          j        nt          j        }
t)          |          D ]} |
| |         | |	                   } | S )a1  Calculate the n-th discrete difference along the given axis.

    Args:
        a (cupy.ndarray): Input array.
        n (int): The number of times values are differenced. If zero, the input
            is returned as-is.
        axis (int): The axis along which the difference is taken, default is
            the last axis.
        prepend (int, float, cupy.ndarray): Value to prepend to ``a``.
        append (int, float, cupy.ndarray): Value to append to ``a``.

    Returns:
        cupy.ndarray: The result array.

    .. seealso:: :func:`numpy.diff`
    r   z#order must be non-negative but got Nr7   r@   )
ValueErrorreprr<   
asanyarrayndimr   _normalize_axis_indexlistshapebroadcast_totupleappendlenconcatenateslicer	   numpybool_	not_equalsubtractrange)r   nr   prependrK   ndcombinedrH   slice1slice2op_s               r   diffr\      s   $ 	Avv1uu1DGG;= = 	= 	A	
B)$33DH/'**<1MMEE$K'u>>G   OOA((;!MMEE$K&vuU||<<F
8}}qXt,,Dkk]RFDkk]RFD>>F4Lr??F4L6]]F6]]F7ek11t}B1XX % %Bqy!F)$$Hr   )r   
edge_orderc                   t          j        |           } | j        }t          j        ||d          }t          |          }t          |          }|dk    rdg|z  }n[|dk    r%t          j        |d                   dk    r||z  }n0||k    rt          |          }t          |          D ]\  }	}
t          j        |
          dk    rt          j        |
          dk    rt          d          t          |
          | j	        ||	                  k    rt          d          t          j        |
j        t          j                  r|
                    t          j                  }
t          j        |
          }||d         k                                    r|d         }|||	<   nt%          d          |d	k    rt          d
          g }t'          d          g|z  }t'          d          g|z  }t'          d          g|z  }t'          d          g|z  }| j        }t          j        |t          j                  rnJt          j        |t          j                  r|                     t          j                  } t          j        }t+          ||          D ]#\  }}| j	        |         |dz   k     rt          d          t          j        | |          }t          j        |          dk    }t'          dd          ||<   t'          dd          ||<   t'          dd          ||<   t'          d	d          ||<   |rB| t/          |                   | t/          |                   z
  d|z  z  |t/          |          <   n|dd         }|dd         }||z   }| ||z  z  }||z
  ||z  z  }|||z  z  }dg|z  }d||<   t/          |          x|_	        x|_	        |_	        || t/          |                   z  || t/          |                   z  z   || t/          |                   z  z   |t/          |          <   |dk    rd||<   d||<   d||<   |r|n|d         }| t/          |                   | t/          |                   z
  |z  |t/          |          <   d||<   d||<   d||<   |r|n|d         }| t/          |                   | t/          |                   z
  |z  |t/          |          <   nid||<   d||<   d||<   d	||<   |rd|z  }d|z  }d|z  }n5|d         }|d         }||z   }d|z  |z    ||z  z  }|||z  z  }| ||z  z  }|| t/          |                   z  || t/          |                   z  z   || t/          |                   z  z   |t/          |          <   d||<   d||<   d||<   d||<   |rd|z  }d|z  }d|z  }n4|d         }|d         }||z   }|||z  z  }| ||z  z  }d|z  |z   ||z  z  }|| t/          |                   z  || t/          |                   z  z   || t/          |                   z  z   |t/          |          <   |                    |           t'          d          ||<   t'          d          ||<   t'          d          ||<   t'          d          ||<   %|dk    r|d         S |S )a  Return the gradient of an N-dimensional array.

    The gradient is computed using second order accurate central differences
    in the interior points and either first or second order accurate one-sides
    (forward or backwards) differences at the boundaries.
    The returned gradient hence has the same shape as the input array.

    Args:
        f (cupy.ndarray): An N-dimensional array containing samples of a scalar
            function.
        varargs (list of scalar or array, optional): Spacing between f values.
            Default unitary spacing for all dimensions. Spacing can be
            specified using:

            1. single scalar to specify a sample distance for all dimensions.
            2. N scalars to specify a constant sample distance for each
               dimension. i.e. `dx`, `dy`, `dz`, ...
            3. N arrays to specify the coordinates of the values along each
               dimension of F. The length of the array must match the size of
               the corresponding dimension
            4. Any combination of N scalars/arrays with the meaning of 2. and
               3.

            If `axis` is given, the number of varargs must equal the number of
            axes. Default: 1.
        edge_order ({1, 2}, optional): The gradient is calculated using N-th
            order accurate differences at the boundaries. Default: 1.
        axis (None or int or tuple of ints, optional): The gradient is
            calculated only along the given axis or axes. The default
            (axis = None) is to calculate the gradient for all the axes of the
            input array. axis may be negative, in which case it counts from the
            last to the first axis.

    Returns:
        gradient (cupy.ndarray or list of cupy.ndarray): A set of ndarrays
        (or a single ndarray if there is only one dimension) corresponding
        to the derivatives of f with respect to each dimension. Each
        derivative has the same shape as f.

    .. seealso:: :func:`numpy.gradient`
    F)	sort_axesr         ?r7   z&distances must be either scalars or 1dzGwhen 1d, distances must match the length of the corresponding dimensionzinvalid number of arguments   z)'edge_order' greater than 2 not supportedNzlShape of array too small to calculate a numerical gradient, at least (edge_order + 1) elements are required.r	   r@          @g      g      g      ?g       g      ?)r<   rD   rE   r   _normalize_axis_indicesrL   rG   	enumeraterB   rH   rO   
issubdtyper	   integerastypefloat64r\   all	TypeErrorrN   inexactzipr=   rJ   rK   )fr   r]   varargsrE   axeslen_axesrT   dxi	distancesdiffxoutvalsrX   rY   slice3slice4otypeax_dxr
   uniform_spacingdx1dx2dx_sumr   bcrH   dx_0dx_ns                                 r   gradientr   *  sM   T 	A6D+D$%HHHD4yyHGAAvvUX	
aDIgaj))Q..x	
h']]%bMM 	 	LAyy##q((9%%** !IJJJ9~~a!111 @   	?? < &,,U];;	Ii((E q!&&(( !aBqEE'	* 5666A~~DEEE
 G Dkk]T!FDkk]T!FDkk]T!FDkk]T!FGEu}-- 
 E5=11 	(''A4}} e# e#e74=:>))C  
 oau--- )E**a/ Q||tT2tQ||tQ~~t 	8"#E&MM"2QuV}}5E"Ee"Cf "+C)C3YF#,'AssSy)AsV|$AC$JEE$K*/,,6AG6ag"#af&6"6"#af&6"6#7"#af&6"6#7Cf
 ??F4LF4LF4L+955qD"#E&MM"2QuV}}5E"E!MCfF4LF4LF4L+:55rD"#E&MM"2QuV}}5E"E!MCf F4LF4LF4LF4L 
,5L%K5LAhAhsCi#o&#.9cCi(DC6N+"#af&6"6"#af&6"6#7"#af&6"6#7Cf F4LF4LF4LF4L 
9%K5L%KBiBisSF^,GsSy)3Y_8"#af&6"6"#af&6"6#7"#af&6"6#7Cf 	s T{{tT{{tT{{tT{{t1}}qzr   c                    t          | t          j                  st          d          |                                 } | j        }||| dd         | dd         z
  S |d}nrt          |t          j                  st          d          t          j        ||d          st          d	          |                                }t          |          }|d}nrt          |t          j                  st          d
          t          j        ||d          st          d          |                                }t          |          }t          t          |           dz
  d          }t          j	        ||z   |z   | j                  }|dk    r||d|<   |dk    r
||||z   d<   t          j
        | dd         | dd         ||||z                       |S )a  
    Calculates the difference between consecutive elements of an array.

    Args:
        arr (cupy.ndarray): Input array.
        to_end (cupy.ndarray, optional): Numbers to append at the end
            of the returned differences.
        to_begin (cupy.ndarray, optional): Numbers to prepend at the
            beginning of the returned differences.

    Returns:
        cupy.ndarray: New array consisting differences among succeeding
        elements.

    .. seealso:: :func:`numpy.ediff1d`
    z$`arr` should be of type cupy.ndarrayNr7   r@   r   z)`to_begin` should be of type cupy.ndarray	same_kind)castingzSdtype of `to_begin` must be compatible with input `arr` under the `same_kind` rule.z'`to_end` should be of type cupy.ndarrayzQdtype of `to_end` must be compatible with input `arr` under the `same_kind` rule.rb   )
isinstancer<   ndarrayrm   ravelr	   can_castrL   maxemptyrR   )arrto_endto_begin	dtype_reql_beginl_endl_diffresults           r   ediff1dr      s   " c4<(( @>??? ))++C 	I FN122wSbS!!(DL11 	IGHHH}Xy+FFF 	L K L L L >>##h--~&$,// 	GEFFF}VYDDD 	L K L L L F SAq!!FZ(50	BBBF {{#xxqyy$*w  !M#abb'3ss8VGGf4D,D%EFFFMr   r`   c                    t          | t          j                  st          d          ||}nt          |t          j                  st          d          |j        dk    r@t          |          }dg| j        z  }|j        d         ||<   |                    |          }nt          ||          }| j        }t          d          g|z  }t          d          g|z  }t          dd          ||<   t          dd          ||<   || t          |                   | t          |                   z   z  dz  }		 |	
                    |          }
n0# t          $ r# t          j                            |	|          }
Y nw xY w|
S )	a  
    Integrate along the given axis using the composite trapezoidal rule.
    Integrate `y` (`x`) along the given axis.

    Args:
        y (cupy.ndarray): Input array to integrate.
        x (cupy.ndarray): Sample points over which to integrate. If None equal
            spacing `dx` is assumed.
        dx (float): Spacing between sample points, used if `x` is None, default
            is 1.
        axis (int): The axis along which the integral is taken, default is
            the last axis.

    Returns:
        cupy.ndarray: Definite integral as approximated by the trapezoidal
        rule.

    .. seealso:: :func:`numpy.trapz`
    z"`y` should be of type cupy.ndarrayNz"`x` should be of type cupy.ndarrayr7   r   )r   r@   rd   )r   r<   r   rm   rE   r\   rH   reshaperN   rJ   r   rB   addreduce)yxrt   r   drH   rV   rX   rY   productrets              r   trapzr   F  sv   ( a&& ><===y!T\** 	B@AAA6Q;;QAC!&LE'!*E$K		%  AAQT"""A	
BDkk]RFDkk]RFD>>F4Lr??F4L1U6]]#af&667#=G-kk$ - - -hoogt,,-Js   9E *E<;E<c                 \    t          j        dt                     t          | ||||          S )NzPlease use `prod` instead.)warningswarnDeprecationWarningr   )r   r   r	   r
   r   s        r   r   r   w  s,    M.0BCCC4X...r   c                 Z    t          j        dt                     t          | |||          S )NzPlease use `cumprod` instead.)r   r   r   r1   r-   s       r   
cumproductr   |  s*    M13EFFF1dE3'''r   )NNNF)NNNr;   )r7   r@   NN)NN)Nr`   r@   )r   rO   r<   
cupy._corer   r   r   r   r   r   r#   r(   r.   r1   r5   r8   _core_kernelElementwiseKernelr>   r4   r\   r   r   r   r   r    r   r   <module>r      s      . . . . . . + + + + + +      - - - -@. . . .@ 8  8  8  8F9 9 9 9BH H H H&I I I I&6 6 6 6(7 7 7 7( j(::'E  
   > > > >B  $ S S S S Sl@ @ @ @L. . . .b/ / / /
( ( ( ( ( (r   