
    `iP                        d dl Z d dlZd dlZd dlZd dlmZ eZ ej        dddd          Z ej        ddd	d
          Z	d Z
d Zd ZddZddZddZ ej        dddd          Z ej        dddd          ZddZddZdS )     N)_corezS x, raw T bins, int32 n_binszraw U yaD  
    if (x < bins[0] or bins[n_bins - 1] < x) {
        return;
    }
    int high = n_bins - 1;
    int low = 0;

    while (high - low > 1) {
        int mid = (high + low) / 2;
        if (bins[mid] <= x) {
            low = mid;
        } else {
            high = mid;
        }
    }
    atomicAdd(&y[low], U(1));
    cupy_histogram_kernelz,S x, raw T bins, int32 n_bins, raw W weightszraw Y yaM  
    if (x < bins[0] or bins[n_bins - 1] < x) {
        return;
    }
    int high = n_bins - 1;
    int low = 0;

    while (high - low > 1) {
        int mid = (high + low) / 2;
        if (bins[mid] <= x) {
            low = mid;
        } else {
            high = mid;
        }
    }
    atomicAdd(&y[low], (Y)weights[i]);
    cupy_weighted_histogram_kernelc                    | j         t          j        k    r^t          j        d                    | j         t          j                  t          d           |                     t          j                  } |\t          |t          j
                  st          d          |j        | j        k    rt          d          |                                }|                                 } | |fS )z: Check a and weights have matching shapes, and ravel both z1Converting input from {} to {} for compatibility.   )
stacklevelNzweights must be a cupy.ndarrayz(weights should have the same shape as a.)dtypecupybool_warningswarnformatuint8RuntimeWarningastype
isinstancendarray
ValueErrorshaperavel)aweightss     n/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/cupy/_statistics/histogram.py_ravel_and_check_weightsr   =   s     	w$*Ivagtz22$	4 	4 	4 	4 HHTZ  '4<00 	?=>>>=AG##:< < <--//			Ag:    c                 4   |f|\  }}||k    rt          d          t          j        |          rt          j        |          s#t          d                    ||                    n| j        dk    rd}d}nt          |                                           }t          |                                           }t          j        |          rt          j        |          s#t          d                    ||                    ||k    r
|dz
  }|dz   }||fS )	z^
    Determine the outer bin edges to use, from either the data or the range
    argument
    Nz/max must be larger than min in range parameter.z(supplied range of [{}, {}] is not finiter   g        g      ?z,autodetected range of [{}, {}] is not finiteg      ?)	r   numpyisfiniter   sizefloatminmaxr
   )r   range
first_edge	last_edges       r   _get_outer_edgesr&   R   s@   
  %
I	!!AC C Cz** 	,u~i/H/H 	,:AA	+ +, , ,	, 
1
		15577^^
!%%''NN	j)) 	,dmI.F.F 	,>EE	+ +, , ,
 Y#%
O	y  r   c                    d}d}t          |t                    rt          d          t          |t          j                  st          j        |          dk    rt          |t          j                  r|}nt          j        |          }|dd         |dd         k                                    rt          d          t          |t
          j                  rt          j        |          }nt          j        |          dk    r\	 t          j        |          }n# t          $ r t          d          w xY w|dk     rt          d          t          | |          \  }}nt          d	          |kt          j        |||           }t          j        |t          j                  rt          j        |t"                    }t          j        |||dz   d
|          }|S )a5  
    Computes the bins used internally by `histogram`.

    Args:
        a (ndarray): Ravelled data array
        bins (int or ndarray): Forwarded argument from `histogram`.
        range (None or tuple): Forwarded argument from `histogram`.

    Returns:
        bin_edges (ndarray): Array of bin edges
    Nz+only integer and array bins are implemented   z1`bins` must increase monotonically, when an arrayr   z0`bins` must be an integer, a string, or an arrayz(`bins` must be positive, when an integerz `bins` must be 1d, when an arrayT)endpointr	   )r   strNotImplementedErrorr
   r   r   ndimasarrayanyr   operatorindex	TypeErrorr&   result_type
issubdtypeintegerr    linspace)r   binsr#   n_equal_bins	bin_edgesr$   r%   bin_types           r   _get_bin_edgesr;   s   s    LI$ =!9; ; 	;	D$,	'	' =5:d+;+;q+@+@dDL)) 	,IId++IcrcNYqrr]*//11 	ECE E Ei// 	0Y//I	D		Q			D#>$//LL 	D 	D 	DBD D D	D !GHHH 0E : :
II;<<< #J	1==?8T\22 	9'%88H M	<!#3+ + +	 s   D   D:
   Fc                    | j         j        dk    rt          d          t          | t          j                  st          d          t          | |          \  } }t          | ||          }|At	          j	        |j
        dz
  t          j                  }t          | ||j
        |           nHt	          j        |j         t          j                  p#t	          j        |j         t          j                  }|st          d          |j         j        dk    rmt	          j	        |j
        dz
  t          j                  }t!          | ||j
        |j        |j                   t!          | ||j
        |j        |j                   nr|j         j        dv r$t	          j	        |j
        dz
  t&                    }n(t	          j	        |j
        dz
  t          j                  }t!          | ||j
        ||           |rMt	          j        t	          j        |          t          j                  }||z  |                                z  |fS ||fS )	a3  Computes the histogram of a set of data.

    Args:
        x (cupy.ndarray): Input array.
        bins (int or cupy.ndarray): If ``bins`` is an int, it represents the
            number of bins. If ``bins`` is an :class:`~cupy.ndarray`, it
            represents a bin edges.
        range (2-tuple of float, optional): The lower and upper range of the
            bins.  If not provided, range is simply ``(x.min(), x.max())``.
            Values outside the range are ignored. The first element of the
            range must be less than or equal to the second. `range` affects the
            automatic bin computation as well. While bin width is computed to
            be optimal based on the actual data within `range`, the bin count
            will fill the entire range including portions containing no data.
        density (bool, optional): If False, the default, returns the number of
            samples in each bin. If True, returns the probability *density*
            function at the bin, ``bin_count / sample_count / bin_volume``.
        weights (cupy.ndarray, optional): An array of weights, of the same
            shape as `x`.  Each value in `x` only contributes its associated
            weight towards the bin count (instead of 1).
    Returns:
        tuple: ``(hist, bin_edges)`` where ``hist`` is a :class:`cupy.ndarray`
        storing the values of the histogram, and ``bin_edges`` is a
        :class:`cupy.ndarray` storing the bin edges.

    .. warning::

        This function may synchronize the device.

    .. seealso:: :func:`numpy.histogram`
    czcomplex number is not supportedzx must be a cupy.ndarrayNr(   r	   zJonly weights with dtype that can be cast to float or complex are supportedbui)r	   kindr,   r   r
   r   r   r   r;   zerosr   int64_histogram_kernelcan_castfloat64
complex128_weighted_histogram_kernelrealimagintarraydiffsum)	xr7   r#   r   densityr9   ysimple_weightsdbs	            r   	histogramrT      s3   B 	w|s!"CDDDa&& 53444)!W55JAwq$..IJy~)<<< 	!Y	:::: M'-66 :M'-99 	  	!% ! ! ! =$$
9>A-T_EEEA&9inglAFD D D&9inglAFD D D D }!U**Jy~1===Jy~1FFF&9ingq: : :  +Z	),,dl;;2v**i<r   c                     t           t          j                  r, j        dk    r ddt          j        f           j        \  }}n t          j         d            j        \  }}t          j        |t                    }|dgz  |dgz  }|t          j
        |          }	 t          |          }	|	|k    rt          d          n# t          $ r	 ||gz  }Y nw xY w|d|z  }n"t          |          |k    rt          d          t          |          D ]}
t          j        ||
                   dk    r||
         dk     r"t          d	                    |
                    t!           dd|
f         ||
                   \  }}t          ||
         dz             }t          j        |||          |
<   nt          j        ||
                   dk    rt          ||
         t          j                  st          d
          ||
         |
<   |
         dd         |
         dd         k                                    r"t          d                    |
                    n"t          d                    |
                    t          |
                   dz   ||
<   t          j        |
                   ||
<   t)           fdt          |          D                       }t          |          D ]4}
 dd|
f         |
         d         k    }||
         |xx         dz  cc<   5t          j        ||          }t          j        ||t          j        |                    }|                    |          }|                    t4                    }|t7          dd          fz  }||         }|r]|                                }t          |          D ]4}
dg|z  }||
         dz
  ||
<   |||
                             |          z  }5||z  }t%          |j        t          j
        |          dz
  k              rt;          d          |fS )a  Compute the multidimensional histogram of some data.

    Args:
        sample (cupy.ndarray): The data to be histogrammed. (N, D) or (D, N)
            array

            Note the unusual interpretation of sample when an array_like:

            * When an array, each row is a coordinate in a D-dimensional
              space - such as ``histogramdd(cupy.array([p1, p2, p3]))``.
            * When an array_like, each element is the list of values for single
              coordinate - such as ``histogramdd((X, Y, Z))``.

            The first form should be preferred.
        bins (int or tuple of int or cupy.ndarray): The bin specification:

            * A sequence of arrays describing the monotonically increasing bin
              edges along each dimension.
            * The number of bins for each dimension (nx, ny, ... =bins)
            * The number of bins for all dimensions (nx=ny=...=bins).
        range (sequence, optional): A sequence of length D, each an optional
            (lower, upper) tuple giving the outer bin edges to be used if the
            edges are not given explicitly in `bins`. An entry of None in the
            sequence results in the minimum and maximum values being used for
            the corresponding dimension. The default, None, is equivalent to
            passing a tuple of D None values.
        weights (cupy.ndarray): An array of values `w_i` weighing each sample
            `(x_i, y_i, z_i, ...)`. The values of the returned histogram are
            equal to the sum of the weights belonging to the samples falling
            into each bin.
        density (bool, optional): If False, the default, returns the number of
            samples in each bin. If True, returns the probability *density*
            function at the bin, ``bin_count / sample_count / bin_volume``.

    Returns:
        tuple:
        H (cupy.ndarray):
            The multidimensional histogram of sample x. See
            normed and weights for the different possible semantics.
        edges (list of cupy.ndarray):
            A list of D arrays describing the bin
            edges for each dimension.

    .. warning::

        This function may synchronize the device.

    .. seealso:: :func:`numpy.histogramdd`
    r(   Nr)   )axiszFThe dimension of bins must be equal to the dimension of the  sample x.)Nz0range argument must have one entry per dimensionr   z,`bins[{}]` must be positive, when an integerzarray-like bins not supportedz:`bins[{}]` must be monotonically increasing, when an arrayz'`bins[{}]` must be a scalar or 1d arrayc              3   f   K   | ]+}t          j        |         d d |f         d          V  ,d S )Nright)side)r
   searchsorted).0iedgessamples     r   	<genexpr>zhistogramdd.<locals>.<genexpr>k  s[          	%(F111a4Lw???     r   )	minlength   zInternal Shape Error)r   r
   r   r-   newaxisr   stackr   emptyrK   r.   lenr   r2   _ranger   r&   r6   r/   rM   tupleravel_multi_indexbincountprodreshaper   r    slicerN   RuntimeError)r^   r7   r#   r   rP   nsamplesr-   nbindedgesnbinsr\   sminsmaxnumncounton_edgexyhistcoresr   r]   s   `                    @r   histogramddr{      s   d &$,'' &;!AAAt|O,F$$F,,,$;tS!!DD6METF]F,w''	D		D==   
    tf}
 }$	Ut		KLLL D\\ ( (9T!W""Aw{{ BII!LL   *&A,aAAJD$d1gk""C}T455E!HHYtAw1$$d1gt|44 B !@AAAAwE!Ha"a,1133  "F1II   9@@CC   eAh--!#QIeAh''q		           F D\\    A,%(2,.q	'a 
		-	-B =W
40@0@AAAD <<D ;;uD 5B<</!D:D HHJJ 	3 	3AC$JEAw{E!H&)++E222DD	
4:t,,q0011 31222;s   &$C CCc                    	 t          |          }n# t          $ r d}Y nw xY w|dk    r8|dk    r2t          |t          j                  r	|x}}||g}nt          d          t          | |g||||          \  }	}
|	|
d         |
d         fS )a  Compute the bi-dimensional histogram of two data samples.

    Args:
        x (cupy.ndarray): The first array of samples to be histogrammed.
        y (cupy.ndarray): The second array of samples to be histogrammed.
        bins (int or tuple of int or cupy.ndarray): The bin specification:

            * A sequence of arrays describing the monotonically increasing bin
              edges along each dimension.
            * The number of bins for each dimension (nx, ny)
            * The number of bins for all dimensions (nx=ny=bins).
        range (sequence, optional): A sequence of length two, each an optional
            (lower, upper) tuple giving the outer bin edges to be used if the
            edges are not given explicitly in `bins`. An entry of None in the
            sequence results in the minimum and maximum values being used for
            the corresponding dimension. The default, None, is equivalent to
            passing a tuple of two None values.
        weights (cupy.ndarray): An array of values `w_i` weighing each sample
            `(x_i, y_i)`. The values of the returned histogram are equal to the
            sum of the weights belonging to the samples falling into each bin.
        density (bool, optional): If False, the default, returns the number of
            samples in each bin. If True, returns the probability *density*
            function at the bin, ``bin_count / sample_count / bin_volume``.

    Returns:
        tuple:
        H (cupy.ndarray):
            The multidimensional histogram of sample x. See
            normed and weights for the different possible semantics.
        edges0 (tuple of cupy.ndarray):
            A list of D arrays describing the bin
            edges for the first dimension.
        edges1 (tuple of cupy.ndarray):
            A list of D arrays describing the bin
            edges for the second dimension.

    .. warning::

        This function may synchronize the device.

    .. seealso:: :func:`numpy.histogram2d`
    r(   ra   z%array-like bins not supported in CuPyr   )re   r2   r   r
   r   r   r{   )rO   rQ   r7   r#   r   rP   nxedgesyedgesrx   r]   s              r   histogram2dr     s    VII    	Avv!q&&dDL)) 	F""FVF#DDDEEEq!fdE7GDDKD%q58##s    !!zS xz	raw U binzatomicAdd(&bin[x], U(1))cupy_bincount_kernelzS x, T wzatomicAdd(&bin[x], w) cupy_bincount_with_weight_kernelc                    | j         dk    rt          d          | j         dk     rt          d          | j        j        dk    rt	          d          | dk                                     rt          d          || j        |j        k    rt          d	          |$t          |          }|dk     rt          d
          t          t          j	        |                     dz   }|t          ||          }|2t          j
        |ft          j                  }t          | |           n2t          j
        |ft          j                  }t          | ||           |S )a,  Count number of occurrences of each value in array of non-negative ints.

    Args:
        x (cupy.ndarray): Input array.
        weights (cupy.ndarray): Weights array which has the same shape as
            ``x``.
        minlength (int): A minimum number of bins for the output array.

    Returns:
        cupy.ndarray: The result of binning the input array. The length of
        output is equal to ``max(cupy.max(x) + 1, minlength)``.

    .. warning::

        This function may synchronize the device.

    .. seealso:: :func:`numpy.bincount`

    r(   !object too deep for desired array+object of too small depth for desired arrayfzx must be int arrayr   z3The first argument of bincount must be non-negativeNz0The weights and list don't have the same length.zminlength must be non-negativer?   )r-   r   r	   rA   r2   r/   r   rK   r
   r"   rB   r   intp_bincount_kernelrF   _bincount_with_weight_kernel)rO   r   r`   r   bs        r   ri   ri     sV   ( 	vzz<===vzzFGGGw|s-...	A{{}} PNOOOqw'-77LMMM	NN	q===>>>tx{{aD4##Jwej111 	AJwem444$Q333Hr   c                    | j         j        dk    rt          d          |j        dk    rt	          d          |j        dk     rt	          d          |rdnd}t
          j        j                            || |dd	          S )
a~  Finds the indices of the bins to which each value in input array belongs.

    .. note::

        In order to avoid device synchronization, digitize does not raise
        an exception when the array is not monotonic

    Args:
        x (cupy.ndarray): Input array.
        bins (cupy.ndarray): Array of bins.
            It has to be 1-dimensional and monotonic increasing or decreasing.
        right (bool):
            Indicates whether the intervals include the right or the left bin
            edge.

    Returns:
        cupy.ndarray: Output array of indices, of same shape as ``x``.

    .. seealso:: :func:`numpy.digitize`
    r>   zx may not be complexr(   r   r   leftrX   NF)	r	   rA   r2   r-   r   r
   _sortingsearch_searchsorted)rO   r7   rX   rY   s       r   digitizer     s    , 	w|s.///y1}}<===y1}}FGGG '66D=--dAtT5IIIr   )r<   NNF)r<   NNN)NN)F)r0   r   r   r
   r   r#   rf   ElementwiseKernelrD   rH   r   r&   r;   rT   r{   r   r   r   ri   r    r   r   <module>r      s             
 ,E+#" )  . 5U42" %)& & .  *! ! !B8 8 8vL L L L^Z Z Z Zz8$ 8$ 8$ 8$v +5*	;    7u6& (  ( 1 1 1 1h J  J  J  J  J  Jr   