
    
9jX                    \   S SK Jr  S SKrS SKrS SKrS SKrS SKJr  S SKJr  S SK	J
r
  S SK	Jr  S SK	Jr  \r\R                  " SS	S
S5      r\R                  " SSSS5      rS rS rS rSS jrS S jrS!S jr\R                  " SSSS5      r\R                  " SSSS5      rS"S jrS#S jrg)$    )annotationsN)_core)_accelerator)cub)common)runtimez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                   U R                   [        R                  :X  aa  [        R                  " SR                  U R                   [        R                  5      [        SS9  U R                  [        R                  5      n Ub_  [        U[        R                  5      (       d  [        S5      eUR                  U R                  :w  a  [        S5      eUR                  5       nU R                  5       n X4$ )z9Check a and weights have matching shapes, and ravel both z1Converting input from {} to {} for compatibility.   )
stacklevelz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     T/home/wildlama/miniconda3/lib/python3.13/site-packages/cupy/_statistics/histogram.py_ravel_and_check_weightsr   C   s     	ww$**Ivaggtzz2$	4 HHTZZ '4<<00=>>==AGG#:< <--/		A:    c                    Ube  Uu  p#X#:  a  [        S5      e[        R                  " U5      (       a  [        R                  " U5      (       d  [        SR                  X#5      5      eOU R                  S:X  a  SnSnOpU R                  5       nU R                  5       n[        R                  " U5      (       a  [        R                  " U5      (       d  [        SR                  X#5      5      eX#:X  a
  US-
  nUS-   nX#4$ )zR
Determine the outer bin edges to use, from either the data or the range
argument
z/max must be larger than min in range parameter.z(supplied range of [{}, {}] is not finiter      z,autodetected range of [{}, {}] is not finiteg      ?)r   numpyisfiniter   sizeminmaxr   )r   range
first_edge	last_edges       r   _get_outer_edgesr+   X   s    
  %
!AC Cz**u~~i/H/H:AA+, , 0I 
1
	UUW
EEG	j))dmmI.F.F>EE+, ,
 #%
O	  r    c                   SnSn[        U[        5      (       a  [        S5      e[        U[        R                  5      (       d  [
        R                  " U5      S:X  a  [        U[        R                  5      (       a  UnO[
        R                  " U5      nUSS USS :  R                  5       (       a  [        S5      e[        U[
        R                  5      (       a  [        R                  " U5      nO[[
        R                  " U5      S:X  a6   [        R                  " U5      nUS:  a  [        S5      e[        X5      u  pVO[        S	5      eUbw  [        R                  " WWU 5      n[        R                  " U[        R                   5      (       a  [        R                  " U["        5      n[        R$                  " XVUS-   S
US9nU$ ! [         a    [        S5      ef = f)a  
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 implementedr"   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integerfloatlinspace)r   binsr(   n_equal_bins	bin_edgesr)   r*   bin_types           r   _get_bin_edgesr@   y   s    LI$!9; 	;	D$,,	'	'5::d+;q+@dDLL))Id+IcrNYqr]*//11CE Ei//Y/I	D	Q		D#>>$/L !GHH 0 :
I;<< ##J	1=??8T\\22''%8H MM<!#3+	 -  	DBD D	Ds   G G"c                	   U R                   R                  S:X  a  [        S5      e[        U [        R
                  5      (       d  [        S5      e[        X5      u  p[        XU5      nUGcn  [        R                  " UR                  S-
  [        R                  S9n[        R                  " 5        GH  nU[        R                  :X  d  M  U R                  S::  d  M,  UR                  S::  d  M>  [        U[        R
                  5      (       d   e[        R                   " U R                   [        R"                  5      (       a  [$        nOy[        R&                  " UR                   U R                   5      nU[        R(                  :X  a*  [*        R,                  " 5       (       d  [        R.                  nU R1                  USS9n UR1                  US	S9n	U R                   R                  S
;   a  U	S==   S-  ss'   O;U R                   R                  S:X  a!  U	S   n
[        R2                  " XS-   5      U	S'   [4        R6                  (       a  UR1                  [        R8                  SS9n[:        R<                  " XU	5      nUc  GM  Un[4        R6                  (       a  UR1                  [        R                  SS9n  GO   [?        XUR                  U5        GO[        R@                  " UR                   [        RB                  5      =(       d/    [        R@                  " UR                   [        RD                  5      nU(       d  [        S5      eUR                   R                  S:X  a  [        R                  " UR                  S-
  [        RD                  S9n[G        XUR                  URH                  URH                  5        [G        XUR                  URJ                  URJ                  5        OUR                   R                  S;   a'  [        R                  " UR                  S-
  [L        S9nO0[        R                  " UR                  S-
  [        RB                  S9n[G        XUR                  XF5        U(       aP  [        RN                  " [        RP                  " U5      [        RB                  5      nXm-  URS                  5       -  U4$ Xe4$ )a  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.ndarrayr"   r   F)copyTuir-   fzJonly weights with dtype that can be cast to float or complex are supportedbui)*r   kindr0   r   r   r   r   r   r@   zerosr%   int64r   get_routine_acceleratorsACCELERATOR_CUBr#   r8   r9   r:   r7   float16r   _is_fp16_supportedfloat32r   	nextafterr   is_hipuint64r   cub_histogram_histogram_kernelcan_castfloat64
complex128_weighted_histogram_kernelrealimagintarraydiffsum)xr<   r(   densityr   r>   yacceleratorr?   acc_bin_edgelastoutsimple_weightsdbs                 r   	histogramri      so   B 	ww||s!"CDDa&&344)!5JAq.IJJy~~)<'@@BK |;;;*,:1M ")T\\::::##AGGU]];;$H$00!''JH EMM1 & 9 9 ; ;#(==6A(//t/D 77<<4' $)$WW\\S('+D'+~~d1H'EL$>>59A''l;;A>>%8AE CH aINNA> MM'--6 :MM'--9 	 % ! ! ==$

9>>A-T__EA&inngllAFFD&inngllAFFD }}!!U*JJy~~1=JJy~~1F&inng: ZZ		),dll;v**<r    c                  ^ ^ [        T [        R                  5      (       a6  T R                  S:X  a  T SS2[        R                  4   m T R
                  u  pVO#[        R                  " T SS9m T R
                  u  pV[        R                  " U[        5      nUS/-  mUS/-  nUb  [        R                  " U5      n [        U5      n	X:w  a  [        S5      e Uc  SU-  nO[        U5      U:w  a  [        S5      e[        U5       GHZ  n
[        R                  " X   5      S:X  ad  X   S:  a  [        S	R                  U
5      5      e[!        T SS2U
4   X*   5      u  p[        X   S-   5      n[        R"                  " XU5      TU
'   O[        R                  " X   5      S:X  ar  [        X   [        R                  5      (       d  [        S
5      eX   TU
'   TU
   SS TU
   SS :  R%                  5       (       a  [        SR                  U
5      5      eO[        SR                  U
5      5      e[        TU
   5      S-   Xz'   [        R&                  " TU
   5      X'   GM]     [)        UU 4S j[        U5       5       5      n[        U5       H$  n
T SS2U
4   TU
   S   :H  nX   U==   S-  ss'   M&     [        R*                  " X5      n[        R,                  " UU[        R.                  " U5      S9nUR1                  U5      nUR3                  [4        5      nU[7        SS5      4-  nUU   nU(       aM  UR9                  5       n[        U5       H)  n
S/U-  nXz   S-
  UU
'   UX   R1                  U5      -  nM+     UU-  n[%        UR
                  [        R                  " U5      S-
  :g  5      (       a  [;        S5      eUT4$ ! [         a	    Xa/-  n GNf = f)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  d   >#    U  H%  n[         R                  " TU   TS S 2U4   SS9v   M'     g 7f)Nright)side)r   searchsorted).0iedgessamples     r   	<genexpr>histogramdd.<locals>.<genexpr>  s5       A 	%(F1a4Lw?s   -0)	minlength   zInternal Shape Error)r   r   r   r1   newaxisr   stackr#   emptyr\   r2   lenr   r6   _ranger   r+   r;   r3   r^   tupleravel_multi_indexbincountprodreshaper   r:   slicer_   RuntimeError)rs   r<   r(   r   ra   nsamplesr1   nbindedgesnbinsrq   sminsmaxnumncounton_edgexyhistcoresr   rr   s   `                    @r   histogramddr   $  s   d &$,,'';;!At||O,F$F,;;tS!DD6METF]F,,w'	D	=   }$	Ut	KLL D\99TW"w{ BII!L  *&A,AJDdgk"C}}T5E!HYYtw1$dgt||44 !@AAwE!Ha"a,1133 "F1I  4 9@@C  eAh-!#IIeAh'	1 6    F D\A,%(2,.	'a	  
			-B ==W

40@AD <<D ;;uD 5B</!D:DHHJAC$JEw{E!H&)++E22D  		
4::t,q0011122;e  f}s   <O	 	OOc                     [        U5      nUS:w  a7  US:w  a1  [        U[        R                  5      (       a  U=pxXx/nO[        S5      e[        X/X#XE5      u  pXS   U
S   4$ ! [         a    Sn Nef = f)aR  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"   rw   z%array-like bins not supported in CuPyr   )r{   r6   r   r   r   r   r   )r`   rb   r<   r(   r   ra   nxedgesyedgesr   rr   s              r   histogram2dr     s    VI 	Av!q&dDLL))""F#DDEEqfd7DKDq58##  s   A$ $A32A3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                   U R                   S:  a  [        S5      eU R                   S:  a  [        S5      eU R                  R                  S:X  a  [	        S5      eU S:  R                  5       (       a  [        S5      eUb%  U R                  UR                  :w  a  [        S5      eUb  [        U5      nUS:  a  [        S	5      e[        [        R                  " U 5      5      S-   nUb  [        X25      nUc  [        R                  " U4[        R                  S
9n[        R                  " 5        Hl  n[        R                   (       a  M  U[        R"                  :X  d  M0  U R$                  S::  d  MB  US::  d  MJ  [&        R(                  " XUS-   5      nUc  Mi  Un  U$    [+        X5         U$ [        R                  " U4[        R,                  S
9n[/        XU5        U$ )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 arrayrG   zx must be int arrayr   z3The first argument of bincount must be non-negativez0The weights and list don't have the same length.zminlength must be non-negativerC   rD   )r1   r   r   rI   r6   r3   r   r\   r   r'   rJ   r#   intpr   rL   r   rR   rM   r%   r   rT   _bincount_kernelrW   _bincount_with_weight_kernel)r`   r   rv   r%   brc   rf   s          r   r   r     s   ( 	vvz<==vvzFGGww||s-..	A{{}}NOOqww'--7LMM	N	q==>>txx{aD4#JJwejj1'@@BK NNN#|'C'CC*,1C''d1f5;A H% C Q"
 H JJwemm4$Q3Hr    c                &   U R                   R                  S:X  a  [        S5      eUR                  S:  a  [	        S5      eUR                  S:  a  [	        S5      eU(       a  SOSn[
        R                  R                  R                  XUSS	5      $ )
aF  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`
rB   zx may not be complexr"   r   r   leftrm   NF)	r   rI   r6   r1   r   r   _sortingsearch_searchsorted)r`   r<   rm   rn   s       r   digitizer   G  sz    , 	ww||s.//yy1}<==yy1}FGG 6D==--dtT5IIr    )
   NFN)r   NNF)r   NNN)NN)F)
__future__r   r4   r   r#   r   r   
cupy._corer   	cupy.cudar   r   r   r(   r|   ElementwiseKernelrU   rY   r   r+   r@   ri   r   r   r   r   r   r    r    r   <module>r      s    "      #    
 ++#" ) . #442" %)& .*!B8vm`Zz8$v **	;   %66& ( <~ Jr    