
    `i                        d 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 Z	ej
        ej        ej        gZej        ej        ej        ej        gZej        ej        ej        ej        gZeez   Zeez   Zd eD             Zd eD             Zej        dej        d	ej        d
ej        dej         dej!        diZ"dZ# ej$        e#dd eD             d eD             z   d eD             z             Z%dZ& ej$        e&dd eD             d eD             z             Z'd Z(d Z)d Z*d Z+d Z,d Z-d Z.d Z/d Z0 ej1                    d              Z2d.d"Z3	 d/d#Z4d0d$Z5d1d&Z6	 	 	 d2d'Z7d( Z8d3d*Z9d3d+Z:d3d,Z;d3d-Z<dS )4a  
Peak finding functions.

Some of the functions defined here were ported directly from CuSignal under
terms of the MIT license, under the following notice:

Copyright (c) 2019-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
    N)get_typename)runtime)jitc                 R    t          |           }|dk    rt          j        rd}nd}|S )Nfloat16__halfhalf)r   r   is_hip)dtypetypenames     t/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/cupyx/scipy/signal/_peak_finding.py_get_typenamer   %   s7    E""H9> 	  HHHO    c                 ,    g | ]}t          |          S  r   .0ts     r   
<listcomp>r   7   s     ...1mA...r   c                 ,    g | ]}t          |          S r   r   r   s     r   r   r   8   s     ====##===r                  a'  
#include <cupy/math_constants.h>
#include <cupy/carray.cuh>
#include <cupy/complex.cuh>

template<typename T>
__global__ void local_maxima_1d(
        const int n, const T* __restrict__ x, long long* midpoints,
        long long* left_edges, long long* right_edges) {

    const int orig_idx = blockDim.x * blockIdx.x + threadIdx.x;
    const int idx = orig_idx + 1;

    if(idx >= n - 1) {
        return;
    }

    long long midpoint = -1;
    long long left = -1;
    long long right = -1;

    if(x[idx - 1] < x[idx]) {
        int i_ahead = idx + 1;

        while(i_ahead < n - 1 && x[i_ahead] == x[idx]) {
            i_ahead++;
        }

        if(x[i_ahead] < x[idx]) {
            left = idx;
            right = i_ahead - 1;
            midpoint = (left + right) / 2;
        }
    }

    midpoints[orig_idx] = midpoint;
    left_edges[orig_idx] = left;
    right_edges[orig_idx] = right;
}

template<typename T>
__global__ void peak_prominences(
        const int n, const int n_peaks, const T* __restrict__ x,
        const long long* __restrict__ peaks, const long long wlen,
        T* prominences, long long* left_bases, long long* right_bases) {

    const int idx = blockDim.x * blockIdx.x + threadIdx.x;
    if(idx >= n_peaks) {
        return;
    }

    const long long peak = peaks[idx];
    long long i_min = 0;
    long long i_max = n - 1;

    if(wlen >= 2) {
        i_min = max(peak - wlen / 2, i_min);
        i_max = min(peak + wlen / 2, i_max);
    }

    left_bases[idx] = peak;
    long long i = peak;
    T left_min = x[peak];

    while(i_min <= i && x[i] <= x[peak]) {
        if(x[i] < left_min) {
            left_min = x[i];
            left_bases[idx] = i;
        }
        i--;
    }

    right_bases[idx] = peak;
    i = peak;
    T right_min = x[peak];

    while(i <= i_max && x[i] <= x[peak]) {
        if(x[i] < right_min) {
            right_min = x[i];
            right_bases[idx] = i;
        }
        i++;
    }

    prominences[idx] = x[peak] - max(left_min, right_min);
}

template<>
__global__ void peak_prominences<half>(
        const int n, const int n_peaks, const half* __restrict__ x,
        const long long* __restrict__ peaks, const long long wlen,
        half* prominences, long long* left_bases, long long* right_bases) {

    const int idx = blockDim.x * blockIdx.x + threadIdx.x;
    if(idx >= n_peaks) {
        return;
    }

    const long long peak = peaks[idx];
    long long i_min = 0;
    long long i_max = n - 1;

    if(wlen >= 2) {
        i_min = max(peak - wlen / 2, i_min);
        i_max = min(peak + wlen / 2, i_max);
    }

    left_bases[idx] = peak;
    long long i = peak;
    half left_min = x[peak];

    while(i_min <= i && x[i] <= x[peak]) {
        if(x[i] < left_min) {
            left_min = x[i];
            left_bases[idx] = i;
        }
        i--;
    }

    right_bases[idx] = peak;
    i = peak;
    half right_min = x[peak];

    while(i <= i_max && x[i] <= x[peak]) {
        if(x[i] < right_min) {
            right_min = x[i];
            right_bases[idx] = i;
        }
        i++;
    }

    prominences[idx] = x[peak] - __hmax(left_min, right_min);
}

template<typename T>
__global__ void peak_widths(
        const int n, const T* __restrict__ x,
        const long long* __restrict__ peaks,
        const double rel_height,
        const T* __restrict__ prominences,
        const long long* __restrict__ left_bases,
        const long long* __restrict__ right_bases,
        double* widths, double* width_heights,
        double* left_ips, double* right_ips) {

    const int idx = blockDim.x * blockIdx.x + threadIdx.x;
    if(idx >= n) {
        return;
    }

    long long i_min = left_bases[idx];
    long long i_max = right_bases[idx];
    long long peak = peaks[idx];

    double height = x[peak] - prominences[idx] * rel_height;
    width_heights[idx] = height;

    // Find intersection point on left side
    long long i = peak;
    while (i_min < i && height < x[i]) {
        i--;
    }

    double left_ip = (double) i;
    if(x[i] < height) {
        // Interpolate if true intersection height is between samples
        left_ip += (height - x[i]) / (x[i + 1] - x[i]);
    }

    // Find intersection point on right side
    i = peak;
    while(i < i_max && height < x[i]) {
        i++;
    }

    double right_ip = (double) i;
    if(x[i] < height) {
        // Interpolate if true intersection height is between samples
        right_ip -= (height - x[i]) / (x[i - 1] - x[i]);
    }

    widths[idx] = right_ip - left_ip;
    left_ips[idx] = left_ip;
    right_ips[idx] = right_ip;
}

template<>
__global__ void peak_widths<half>(
        const int n, const half* __restrict__ x,
        const long long* __restrict__ peaks,
        const double rel_height,
        const half* __restrict__ prominences,
        const long long* __restrict__ left_bases,
        const long long* __restrict__ right_bases,
        double* widths, double* width_heights,
        double* left_ips, double* right_ips) {

    const int idx = blockDim.x * blockIdx.x + threadIdx.x;
    if(idx >= n) {
        return;
    }

    long long i_min = left_bases[idx];
    long long i_max = right_bases[idx];
    long long peak = peaks[idx];

    double height = ((double) x[peak]) - ((double) prominences[idx]) * rel_height;
    width_heights[idx] = height;

    // Find intersection point on left side
    long long i = peak;
    while (i_min < i && height < ((double) x[i])) {
        i--;
    }

    double left_ip = (double) i;
    if(((double) x[i]) < height) {
        // Interpolate if true intersection height is between samples
        left_ip += (height - ((double) x[i])) / ((double) (x[i + 1] - x[i]));
    }

    // Find intersection point on right side
    i = peak;
    while(i < i_max && height < ((double) x[i])) {
        i++;
    }

    double right_ip = (double) i;
    if(((double) x[i]) < height) {
        // Interpolate if true intersection height is between samples
        right_ip -= (height - ((double) x[i])) / ((double) (x[i - 1] - x[i]));
    }

    widths[idx] = right_ip - left_ip;
    left_ips[idx] = left_ip;
    right_ips[idx] = right_ip;
}
)z
-std=c++11c                     g | ]}d | d	S )zlocal_maxima_1d<>r   r   xs     r   r   r   4  s$    BBB!----BBBr   c                     g | ]}d | d	S )zpeak_prominences<r   r   r   s     r   r   r   5  s$    222!222r   c                     g | ]}d | d	S )zpeak_widths<r   r   r   s     r   r   r   6  s$    ---QA---r   )codeoptionsname_expressionsa  
#include <cupy/math_constants.h>
#include <cupy/carray.cuh>
#include <cupy/complex.cuh>

template<typename T>
__device__ __forceinline__ bool less( const T &a, const T &b ) {
    return ( a < b );
}

template<typename T>
__device__ __forceinline__ bool greater( const T &a, const T &b ) {
    return ( a > b );
}

template<typename T>
__device__ __forceinline__ bool less_equal( const T &a, const T &b ) {
    return ( a <= b );
}

template<typename T>
__device__ __forceinline__ bool greater_equal( const T &a, const T &b ) {
    return ( a >= b );
}

template<typename T>
__device__ __forceinline__ bool equal( const T &a, const T &b ) {
    return ( a == b );
}

template<typename T>
__device__ __forceinline__ bool not_equal( const T &a, const T &b ) {
    return ( a != b );
}

__device__ __forceinline__ void clip_plus(
        const bool &clip, const int &n, int &plus ) {
    if ( clip ) {
        if ( plus >= n ) {
            plus = n - 1;
        }
    } else {
        if ( plus >= n ) {
            plus -= n;
        }
    }
}

__device__ __forceinline__ void clip_minus(
        const bool &clip, const int &n, int &minus ) {
    if ( clip ) {
        if ( minus < 0 ) {
            minus = 0;
        }
    } else {
        if ( minus < 0 ) {
            minus += n;
        }
    }
}

template<typename T>
__device__ bool compare(const int comp, const T &a, const T &b) {
    if(comp == 0) {
        return less(a, b);
    } else if(comp == 1) {
        return greater(a, b);
    } else if(comp == 2) {
        return less_equal(a, b);
    } else if(comp == 3) {
        return greater_equal(a, b);
    } else if(comp == 4) {
        return equal(a, b);
    } else {
        return not_equal(a, b);
    }
}

template<typename T>
__global__ void boolrelextrema_1D( const int  n,
                                   const int  order,
                                   const bool clip,
                                   const int  comp,
                                   const T *__restrict__ inp,
                                   bool *__restrict__ results) {

    const int tx { static_cast<int>( blockIdx.x * blockDim.x + threadIdx.x ) };
    const int stride { static_cast<int>( blockDim.x * gridDim.x ) };

    for ( int tid = tx; tid < n; tid += stride ) {

        const T data { inp[tid] };
        bool    temp { true };

        for ( int o = 1; o < ( order + 1 ); o++ ) {
            int plus { tid + o };
            int minus { tid - o };

            clip_plus( clip, n, plus );
            clip_minus( clip, n, minus );

            temp &= compare<T>( comp,  data, inp[plus] );
            temp &= compare<T>( comp, data, inp[minus] );
        }
        results[tid] = temp;
    }
}

template<typename T>
__global__ void boolrelextrema_2D( const int  in_x,
                                   const int  in_y,
                                   const int  order,
                                   const bool clip,
                                   const int  comp,
                                   const int  axis,
                                   const T *__restrict__ inp,
                                   bool *__restrict__ results) {

    const int ty { static_cast<int>( blockIdx.x * blockDim.x + threadIdx.x ) };
    const int tx { static_cast<int>( blockIdx.y * blockDim.y + threadIdx.y ) };

    if ( ( tx < in_y ) && ( ty < in_x ) ) {
        int tid { tx * in_x + ty };

        const T data { inp[tid] };
        bool    temp { true };

        for ( int o = 1; o < ( order + 1 ); o++ ) {

            int plus {};
            int minus {};

            if ( axis == 0 ) {
                plus  = tx + o;
                minus = tx - o;

                clip_plus( clip, in_y, plus );
                clip_minus( clip, in_y, minus );

                plus  = plus * in_x + ty;
                minus = minus * in_x + ty;
            } else {
                plus  = ty + o;
                minus = ty - o;

                clip_plus( clip, in_x, plus );
                clip_minus( clip, in_x, minus );

                plus  = tx * in_x + plus;
                minus = tx * in_x + minus;
            }

            temp &= compare<T>( comp, data, inp[plus] );
            temp &= compare<T>( comp, data, inp[minus] );
        }
        results[tid] = temp;
    }
}
c                     g | ]}d | d	S )zboolrelextrema_1D<r   r   r   s     r   r   r     s$    IIIA/1///IIIr   c                     g | ]}d | d	S )zboolrelextrema_2D<r   r   r   s     r   r   r     s$    8881!888r   c                     d |D             }d                     |          }|r| d| dn|}|                     |          }|S )Nc                 6    g | ]}t          |j                  S r   )r   r   )r   args     r   r   z$_get_module_func.<locals>.<listcomp>  s"    EEE=++EEEr   z, <r   )joinget_function)module	func_nametemplate_argsargs_dtypestemplatekernel_namekernels          r   _get_module_funcr5     s^    EE}EEEKyy%%H0=LY,,,,,,9K  --FMr   c           	         | j         d         dz
  }d}||z   dz
  |z  }t          j        |t          j                  }t          j        |t          j                  }t          j        |t          j                  }t	          t
          d|           } ||f|f| j         d         | |||f           |dk    }||         }||         }||         }|||fS )Nr   r      r   r   local_maxima_1d)shapecupyemptyint64r5   PEAKS_MODULE)	r    samplesblock_szn_blocks	midpoints
left_edgesright_edgeslocal_max_kernelpos_idxs	            r   _local_maxima_1drG     s    gaj1nGH("Q&83H
7$*555IG4:666J*WDJ777K'6GKKh[8+gaj!Y
KHJ J J !mG'"IG$Jg&Kj+--r   c                 R   	 | \  }}n# t           t          f$ r | d}}Y nw xY wt          |t          j                  r'|j        |j        k    rt          d          ||         }t          |t          j                  r'|j        |j        k    rt          d          ||         }||fS )a  
    Parse condition arguments for `find_peaks`.

    Parameters
    ----------
    interval : number or ndarray or sequence
        Either a number or ndarray or a 2-element sequence of the former. The
        first value is always interpreted as `imin` and the second,
        if supplied, as `imax`.
    x : ndarray
        The signal with `peaks`.
    peaks : ndarray
        An array with indices used to reduce `imin` and / or `imax` if those
        are arrays.

    Returns
    -------
    imin, imax : number or ndarray or None
        Minimal and maximal value in `argument`.

    Raises
    ------
    ValueError :
        If interval border is given as array and its size does not match the
        size of `x`.
    Nz0array size of lower interval border must match xz0array size of upper interval border must match x)	TypeError
ValueError
isinstancer;   ndarraysize)intervalr    peaksiminimaxs        r   _unpack_condition_argsrR     s    6&
ddz" & & &d& $%% 9BD D DE{$%% 9BD D DE{:s      c                 r    t          j        | j        t                    }|	||| k    z  }|	|| |k    z  }|S )a  
    Evaluate where the generic property of peaks confirms to an interval.

    Parameters
    ----------
    peak_properties : ndarray
        An array with properties for each peak.
    pmin : None or number or ndarray
        Lower interval boundary for `peak_properties`. ``None``
        is interpreted as an open border.
    pmax : None or number or ndarray
        Upper interval boundary for `peak_properties`. ``None``
        is interpreted as an open border.

    Returns
    -------
    keep : bool
        A boolean mask evaluating to true where `peak_properties` confirms
        to the interval.

    See Also
    --------
    find_peaks

    r8   )r;   onesrM   bool)peak_propertiespminpmaxkeeps       r   _select_by_propertyrZ   ,  sJ    4 9_)666D()D()Kr   c                 \   t          j        | |         | |dz
           z
  | |         | |dz            z
  g          }t          j        |j        t                    }|t          j        |d          }|||k    z  }|t          j        |d          }|||k    z  }||d         |d         fS )a  
    Evaluate which peaks fulfill the threshold condition.

    Parameters
    ----------
    x : ndarray
        A 1-D array which is indexable by `peaks`.
    peaks : ndarray
        Indices of peaks in `x`.
    tmin, tmax : scalar or ndarray or None
         Minimal and / or maximal required thresholds. If supplied as ndarrays
         their size must match `peaks`. ``None`` is interpreted as an open
         border.

    Returns
    -------
    keep : bool
        A boolean mask evaluating to true where `peaks` fulfill the threshold
        condition.
    left_thresholds, right_thresholds : ndarray
        Array matching `peak` containing the thresholds of each peak on
        both sides.

    r   r8   Nr   axis)r;   vstackrT   rM   rU   minmax)r    rO   tmintmaxstacked_thresholdsrY   min_thresholdsmax_thresholdss           r   _select_by_peak_thresholdrf   N  s    8 ah519&=&'h519&=&? @ @9UZt,,,D"41==='("41===4'(#A&(:1(===r   c                    | j         d         }t          j        |          }t          j        |t          j                  }t          j        |          }t          |dz
  dd          D ]}||         }||         dk    r|dz
  }	d|	k    r:| |         | |	         z
  |k     r%d||	<   |	dz  }	d|	k    r| |         | |	         z
  |k     %|dz   }	|	|k     r:| |	         | |         z
  |k     r%d||	<   |	dz  }	|	|k     r| |	         | |         z
  |k     %|S )a  
    Evaluate which peaks fulfill the distance condition.

    Parameters
    ----------
    peaks : ndarray
        Indices of peaks in `vector`.
    priority : ndarray
        An array matching `peaks` used to determine priority of each peak. A
        peak with a higher priority value is kept over one with a lower one.
    distance : np.float64
        Minimal distance that peaks must be spaced.

    Returns
    -------
    keep : ndarray[bool]
        A boolean mask evaluating to true where `peaks` fulfill the distance
        condition.

    Notes
    -----
    Declaring the input arrays as C-contiguous doesn't seem to have performance
    advantages.
    r   r8   r   )r:   r;   ceilrT   bool_argsortrange)
rO   prioritydistance
peaks_size	distance_rY   priority_to_positionijks
             r   _select_by_peak_distanceru   w  sG   2 QJ	(##I9Ztz222D  <11 :>2r**   !#7a<<E1ffqE!H,y88DGFA 1ffqE!H,y88 E*nnqE!H!4y!@!@DGFA *nnqE!H!4y!@!@ Kr   c                 f    t          j        | d          } | j        dk    rt          d          | S )zEnsure argument `x` is a 1-D C-contiguous array.

    Returns
    -------
    value : ndarray
        A 1-D C-contiguous array.
    C)orderr   z`x` must be a 1-D array)r;   asarrayndimrJ   values    r   _arg_x_as_expectedr}     s7     Lc***EzQ2333Lr   c                     | d} nld| k     rDt          j        | t           j        d          st          j        |           } t          |           } n"t          d                    |                     | S )zEnsure argument `wlen` is of type `np.intp` and larger than 1.

    Used in `peak_prominences` and `peak_widths`.

    Returns
    -------
    value : np.intp
        The original `value` rounded up to an integer or -1 if `value` was
        None.
    Nrh   r   safez$`wlen` must be larger than 1, was {})r;   can_castr=   mathri   intrJ   formatr{   s    r   _arg_wlen_as_expectedr     st     } 	
U}UDJ77 	%Ie$$EE

? &--) ) 	)Lr   c                 D   t          j        |           } | j        dk    r t          j        g t           j                  } 	 |                     t           j        dd          } n"# t          $ r}t          d          |d}~ww xY w| j        dk    rt          d	          | S )
a3  Ensure argument `peaks` is a 1-D C-contiguous array of dtype('int64').

    Used in `peak_prominences` and `peak_widths` to make `peaks` compatible
    with the signature of the wrapped Cython functions.

    Returns
    -------
    value : ndarray
        A 1-D C-contiguous array with dtype('int64').
    r   r8   rw   F)rx   copyz+cannot safely cast `peaks` to dtype('intp')Nr   z`peaks` must be a 1-D array)	r;   ry   rM   arrayr=   astyperI   rz   rJ   )r|   es     r   _arg_peaks_as_expectedr     s     LEzQ
2TZ000NTZs?? N N NEFFAMNzQ6777Ls   "A$ $
B.A>>Bc                     t           j        j        t           j        j        z  t           j        j        z   }||         }||         }||         }d|k    o||k    o||k    o|| k     }	|	 ||<   d S )Nr   )r   blockIdxr    blockDim	threadIdx)
nrO   
left_basesright_basesouttidi_mini_maxpeakvalids
             r   _check_prominence_invalidr     sl    
,.3<>
)CMO
;CsOEE:DJH5D=HTU]HuqyEyCHHHr   Fc                 D   |rLt          j        t          j        |dk     || j        d         dz
  k                        rt	          d          t          j        |j        d         | j                  }t          j        |j        d         t           j                  }t          j        |j        d         t           j                  }|j        d         }d}||z   dz
  |z  }	t          t          d|           }
 |
|	f|f| j        d         || |||||f           |||fS )Nr   r   zpeaks are not a valid indexr8   r7   peak_prominences)
r;   any
logical_orr:   rJ   r<   r   r=   r5   r>   )r    rO   wlencheckprominencesr   r   r   r@   rA   peak_prom_kernels              r   _peak_prominencesr     s    8$/%!)UQWQZ!^5KLLMM 86777*U[^17;;;KEKN$*===J*U[^4:>>>KAAHHq X-H'6H!LL	h[	
Q5$ZMO O O 
K//r   c                    |dk     rt          d          |t          d          |t          d          |t          d          |j        d         |j        d         cxk    r#|j        d         cxk    r|j        d         k    sn t          d          |j        d         }d}||z   dz
  |z  }	|rl|dk    rft          j        |t          j        	          }
t          |	f|f| j        d         ||||
f           t          j        |
          rt          d
          t          j        |j        d         t          j	        	          }t          j        |j        d         t          j	        	          }t          j        |j        d         t          j	        	          }t          j        |j        d         t          j	        	          }t          t          d|           } ||	f|f|| |||||||||f           ||||fS )Nr   z,`rel_height` must be greater or equal to 0.0zprominences must not be Nonezleft_bases must not be Nonezright_bases must not be Nonez?arrays in `prominence_data` must have the same shape as `peaks`r7   r   r8   zprominence data is invalidpeak_widths)rJ   rI   r:   r;   zerosrj   r   r   r<   float64r5   r>   )r    rO   
rel_heightr   r   r   r   r   r@   rA   invalidwidthswidth_heightsleft_ips	right_ipspeak_widths_kernels                   r   _peak_widthsr     sB   A~~GHHH677756666777KNk/2 $ $ $ $j6Fq6I $ $ $ $ #$ $ $ $ , - - 	- 	AAHHq X-H ;Q*Qdj111!K(WQZ
KA	C 	C 	C 8G 	;9:::ZAdl;;;FJu{1~T\BBBMz%+a.===H
5;q>>>>I),qII	h[	
Auj+z;	)	56 6 6 =(I55r   c                     t          |           } t          |          }t          |          }t          | ||d          S )a  
    Calculate the prominence of each peak in a signal.

    The prominence of a peak measures how much a peak stands out from the
    surrounding baseline of the signal and is defined as the vertical distance
    between the peak and its lowest contour line.

    Parameters
    ----------
    x : sequence
        A signal with peaks.
    peaks : sequence
        Indices of peaks in `x`.
    wlen : int, optional
        A window length in samples that optionally limits the evaluated area
        for each peak to a subset of `x`. The peak is always placed in the
        middle of the window therefore the given length is rounded up to the
        next odd integer. This parameter can speed up the calculation
        (see Notes).

    Returns
    -------
    prominences : ndarray
        The calculated prominences for each peak in `peaks`.
    left_bases, right_bases : ndarray
        The peaks' bases as indices in `x` to the left and right of each peak.
        The higher base of each pair is a peak's lowest contour line.

    Raises
    ------
    ValueError
        If a value in `peaks` is an invalid index for `x`.

    Warns
    -----
    PeakPropertyWarning
        For indices in `peaks` that don't point to valid local maxima in `x`,
        the returned prominence will be 0 and this warning is raised. This
        also happens if `wlen` is smaller than the plateau size of a peak.

    Warnings
    --------
    This function may return unexpected results for data containing NaNs. To
    avoid this, NaNs should either be removed or replaced.

    See Also
    --------
    find_peaks
        Find peaks inside a signal based on peak properties.
    peak_widths
        Calculate the width of peaks.

    Notes
    -----
    Strategy to compute a peak's prominence:

    1. Extend a horizontal line from the current peak to the left and right
       until the line either reaches the window border (see `wlen`) or
       intersects the signal again at the slope of a higher peak. An
       intersection with a peak of the same height is ignored.
    2. On each side find the minimal signal value within the interval defined
       above. These points are the peak's bases.
    3. The higher one of the two bases marks the peak's lowest contour line.
       The prominence can then be calculated as the vertical difference between
       the peaks height itself and its lowest contour line.

    Searching for the peak's bases can be slow for large `x` with periodic
    behavior because large chunks or even the full signal need to be evaluated
    for the first algorithmic step. This evaluation area can be limited with
    the parameter `wlen` which restricts the algorithm to a window around the
    current peak and can shorten the calculation time if the window length is
    short in relation to `x`.
    However, this may stop the algorithm from finding the true global contour
    line if the peak's true bases are outside this window. Instead, a higher
    contour line is found within the restricted window leading to a smaller
    calculated prominence. In practice, this is only relevant for the highest
    set of peaks in `x`. This behavior may even be used intentionally to
    calculate "local" prominences.

    Tr   )r}   r   r   r   )r    rO   r   s      r   r   r   @  sC    b 	1A"5))E &&DQt48888r         ?c                     t          |           } t          |          }|"t          |          }t          | ||d          }t	          | ||g|R ddiS )a  
    Calculate the width of each peak in a signal.

    This function calculates the width of a peak in samples at a relative
    distance to the peak's height and prominence.

    Parameters
    ----------
    x : sequence
        A signal with peaks.
    peaks : sequence
        Indices of peaks in `x`.
    rel_height : float, optional
        Chooses the relative height at which the peak width is measured as a
        percentage of its prominence. 1.0 calculates the width of the peak at
        its lowest contour line while 0.5 evaluates at half the prominence
        height. Must be at least 0. See notes for further explanation.
    prominence_data : tuple, optional
        A tuple of three arrays matching the output of `peak_prominences` when
        called with the same arguments `x` and `peaks`. This data are
        calculated internally if not provided.
    wlen : int, optional
        A window length in samples passed to `peak_prominences` as an optional
        argument for internal calculation of `prominence_data`. This argument
        is ignored if `prominence_data` is given.

    Returns
    -------
    widths : ndarray
        The widths for each peak in samples.
    width_heights : ndarray
        The height of the contour lines at which the `widths` where evaluated.
    left_ips, right_ips : ndarray
        Interpolated positions of left and right intersection points of a
        horizontal line at the respective evaluation height.

    Raises
    ------
    ValueError
        If `prominence_data` is supplied but doesn't satisfy the condition
        ``0 <= left_base <= peak <= right_base < x.shape[0]`` for each peak,
        has the wrong dtype, is not C-contiguous or does not have the same
        shape.

    Warns
    -----
    PeakPropertyWarning
        Raised if any calculated width is 0. This may stem from the supplied
        `prominence_data` or if `rel_height` is set to 0.

    Warnings
    --------
    This function may return unexpected results for data containing NaNs. To
    avoid this, NaNs should either be removed or replaced.

    See Also
    --------
    find_peaks
        Find peaks inside a signal based on peak properties.
    peak_prominences
        Calculate the prominence of peaks.

    Notes
    -----
    The basic algorithm to calculate a peak's width is as follows:

    * Calculate the evaluation height :math:`h_{eval}` with the formula
      :math:`h_{eval} = h_{Peak} - P \cdot R`, where :math:`h_{Peak}` is the
      height of the peak itself, :math:`P` is the peak's prominence and
      :math:`R` a positive ratio specified with the argument `rel_height`.
    * Draw a horizontal line at the evaluation height to both sides, starting
      at the peak's current vertical position until the lines either intersect
      a slope, the signal border or cross the vertical position of the peak's
      base (see `peak_prominences` for an definition). For the first case,
      intersection with the signal, the true intersection point is estimated
      with linear interpolation.
    * Calculate the width as the horizontal distance between the chosen
      endpoints on both sides. As a consequence of this the maximal possible
      width for each peak is the horizontal distance between its bases.

    As shown above to calculate a peak's width its prominence and bases must be
    known. You can supply these yourself with the argument `prominence_data`.
    Otherwise, they are internally calculated (see `peak_prominences`).
    NTr   r   )r}   r   r   r   r   )r    rO   r   prominence_datar   s        r   r   r     sj    j 	1A"5))E$T**+Aud$GGG5*KKKKdKKKr   c	                    t          |           } ||dk     rt          d          t          |           \  }	}
}i }|d||
z
  dz   }t          || |	          \  }}t	          |||          |	         }	||d<   |
|d<   ||d<   fd|                                D             }|Z| |	         }t          || |	          \  }}t	          |||          |	         }	||d<   fd	|                                D             }|\t          || |	          \  }}t          | |	||          \  }}|	         }	||d
<   ||d<   fd|                                D             }|?t          |	| |	         |          |	         }	fd|                                D             }||Dt          |          }|	                    t          g dt          | |	|                               |St          || |	          \  }}t	          |d         ||          |	         }	fd|                                D             }||	                    t          g dt          | |	||d         |d         |d                                        t          || |	          \  }}t	          |d         ||          |	         }	fd|                                D             }|	|fS )a0  
    Find peaks inside a signal based on peak properties.

    This function takes a 1-D array and finds all local maxima by
    simple comparison of neighboring values. Optionally, a subset of these
    peaks can be selected by specifying conditions for a peak's properties.

    Parameters
    ----------
    x : sequence
        A signal with peaks.
    height : number or ndarray or sequence, optional
        Required height of peaks. Either a number, ``None``, an array matching
        `x` or a 2-element sequence of the former. The first element is
        always interpreted as the  minimal and the second, if supplied, as the
        maximal required height.
    threshold : number or ndarray or sequence, optional
        Required threshold of peaks, the vertical distance to its neighboring
        samples. Either a number, ``None``, an array matching `x` or a
        2-element sequence of the former. The first element is always
        interpreted as the  minimal and the second, if supplied, as the maximal
        required threshold.
    distance : number, optional
        Required minimal horizontal distance (>= 1) in samples between
        neighbouring peaks. Smaller peaks are removed first until the condition
        is fulfilled for all remaining peaks.
    prominence : number or ndarray or sequence, optional
        Required prominence of peaks. Either a number, ``None``, an array
        matching `x` or a 2-element sequence of the former. The first
        element is always interpreted as the  minimal and the second, if
        supplied, as the maximal required prominence.
    width : number or ndarray or sequence, optional
        Required width of peaks in samples. Either a number, ``None``, an array
        matching `x` or a 2-element sequence of the former. The first
        element is always interpreted as the  minimal and the second, if
        supplied, as the maximal required width.
    wlen : int, optional
        Used for calculation of the peaks prominences, thus it is only used if
        one of the arguments `prominence` or `width` is given. See argument
        `wlen` in `peak_prominences` for a full description of its effects.
    rel_height : float, optional
        Used for calculation of the peaks width, thus it is only used if
        `width` is given. See argument  `rel_height` in `peak_widths` for
        a full description of its effects.
    plateau_size : number or ndarray or sequence, optional
        Required size of the flat top of peaks in samples. Either a number,
        ``None``, an array matching `x` or a 2-element sequence of the former.
        The first element is always interpreted as the minimal and the second,
        if supplied as the maximal required plateau size.

        .. versionadded:: 1.2.0

    Returns
    -------
    peaks : ndarray
        Indices of peaks in `x` that satisfy all given conditions.
    properties : dict
        A dictionary containing properties of the returned peaks which were
        calculated as intermediate results during evaluation of the specified
        conditions:

        * 'peak_heights'
              If `height` is given, the height of each peak in `x`.
        * 'left_thresholds', 'right_thresholds'
              If `threshold` is given, these keys contain a peaks vertical
              distance to its neighbouring samples.
        * 'prominences', 'right_bases', 'left_bases'
              If `prominence` is given, these keys are accessible. See
              `peak_prominences` for a description of their content.
        * 'width_heights', 'left_ips', 'right_ips'
              If `width` is given, these keys are accessible. See `peak_widths`
              for a description of their content.
        * 'plateau_sizes', left_edges', 'right_edges'
              If `plateau_size` is given, these keys are accessible and contain
              the indices of a peak's edges (edges are still part of the
              plateau) and the calculated plateau sizes.

        To calculate and return properties without excluding peaks, provide the
        open interval ``(None, None)`` as a value to the appropriate argument
        (excluding `distance`).

    Warns
    -----
    PeakPropertyWarning
        Raised if a peak's properties have unexpected values (see
        `peak_prominences` and `peak_widths`).

    Warnings
    --------
    This function may return unexpected results for data containing NaNs. To
    avoid this, NaNs should either be removed or replaced.

    See Also
    --------
    find_peaks_cwt
        Find peaks using the wavelet transformation.
    peak_prominences
        Directly calculate the prominence of peaks.
    peak_widths
        Directly calculate the width of peaks.

    Notes
    -----
    In the context of this function, a peak or local maximum is defined as any
    sample whose two direct neighbours have a smaller amplitude. For flat peaks
    (more than one sample of equal amplitude wide) the index of the middle
    sample is returned (rounded down in case the number of samples is even).
    For noisy signals the peak locations can be off because the noise might
    change the position of local maxima. In those cases consider smoothing the
    signal before searching for peaks or use other peak finding and fitting
    methods (like `find_peaks_cwt`).

    Some additional comments on specifying conditions:

    * Almost all conditions (excluding `distance`) can be given as half-open or
      closed intervals, e.g., ``1`` or ``(1, None)`` defines the half-open
      interval :math:`[1, \infty]` while ``(None, 1)`` defines the interval
      :math:`[-\infty, 1]`. The open interval ``(None, None)`` can be specified
      as well, which returns the matching properties without exclusion of peaks.
    * The border is always included in the interval used to select valid peaks.
    * For several conditions the interval borders can be specified with
      arrays matching `x` in shape which enables dynamic constrains based on
      the sample position.
    * The conditions are evaluated in the following order: `plateau_size`,
      `height`, `threshold`, `distance`, `prominence`, `width`. In most cases
      this order is the fastest one because faster operations are applied first
      to reduce the number of peaks that need to be evaluated later.
    * While indices in `peaks` are guaranteed to be at least `distance` samples
      apart, edges of flat peaks may be closer than the allowed `distance`.
    * Use `wlen` to reduce the time it takes to evaluate the conditions for
      `prominence` or `width` if `x` is large or has many local maxima
      (see `peak_prominences`).
    Nr   z(`distance` must be greater or equal to 1plateau_sizesrC   rD   c                 (    i | ]\  }}||         S r   r   r   keyr   rY   s      r   
<dictcomp>zfind_peaks.<locals>.<dictcomp>  #    LLL:3c5;LLLr   peak_heightsc                 (    i | ]\  }}||         S r   r   r   s      r   r   zfind_peaks.<locals>.<dictcomp>  r   r   left_thresholdsright_thresholdsc                 (    i | ]\  }}||         S r   r   r   s      r   r   zfind_peaks.<locals>.<dictcomp>  r   r   c                 (    i | ]\  }}||         S r   r   r   s      r   r   zfind_peaks.<locals>.<dictcomp>  r   r   )r   r   r   )r   r   c                 (    i | ]\  }}||         S r   r   r   s      r   r   zfind_peaks.<locals>.<dictcomp>  r   r   )r   r   r   r   r   r   r   c                 (    i | ]\  }}||         S r   r   r   s      r   r   zfind_peaks.<locals>.<dictcomp>  r   r   )r}   rJ   rG   rR   rZ   itemsrf   ru   r   updatezipr   r   )r    height	thresholdrn   
prominencewidthr   r   plateau_sizerO   rC   rD   
propertiesr   rW   rX   r   hminhmaxra   rb   r   r   wminwmaxrY   s                            @r   
find_peaksr     s   R 	1A1CDDD%5a%8%8"E:{J#j014+L!UCC
d"=$==d&3
?##-
< $/
=!LLLL9I9I9K9KLLL
x+FAu==
d"<t<<d%1
>"LLLL9I9I9K9KLLL
+Iq%@@
d2KudD3" 3"/o/d(7
$%)9
%&LLLL9I9I9K9KLLL
'qxBBdLLLL9I9I9K9KLLL
!2$T**#888aT222
 
 	 	 	
 +J5AA
d":m#<dDIIdLLLL9I9I9K9KLLL
#@@@E:z-/H#L1:m3LN N
 
 	 	 	 ,E1e<<
d":h#7tDDdLLLL9I9I9K9KLLL
*r   c                    t           |         }|dk    }t          j                                        }|j        d         dz  f}	d}
| j        |         |||| |f}d}| j        dk    r[d}d\  }}| j        d         |z   dz
  |z  }| j        d	         |z   dz
  |z  }||f}
||f}	| j        d         | j        d	         ||||| |f}t          t          ||           } ||	|
|           d S )
NclipMultiProcessorCount   )i   boolrelextrema_1Dr   boolrelextrema_2D)   r   r   )		_modedictr;   cudaDevice
attributesr:   rz   r5   ARGREL_MODULE)data
comparatorr]   rx   moderesultscompr   	device_id
num_blocksr@   	call_argsr3   
block_sz_x
block_sz_y
n_blocks_x
n_blocks_yboolrelextremas                     r   _peak_findingr     s   Z D6>D	  ""I&'<=BDJH
4 %tT7BI%Ky1}})!'
Jjmj014C
jmj014C

+ *-
Z]DJqM5$d7$	 &m[$GGNN:x33333r   r   c                    t          |          |k    s|dk     rt          d          | j        dk     r6t          j        | j        t                    }t          | |||||           n!| j        |         }t          j        d|          }t          j	        | j        t                    }t          j
        | ||          }t          j        d|dz             D ]}	|dk    r8t          j        ||	z   d|dz
  	          }
t          j        ||	z
  dd	          }n
||	z   }
||	z
  }t          j
        | |
|          }t          j
        | ||          }| |||          z  }| |||          z  }|                                 r|c S |S )
a  
    Calculate the relative extrema of `data`.

    Relative extrema are calculated by finding locations where
    ``comparator(data[n], data[n+1:n+order+1])`` is True.

    Parameters
    ----------
    data : ndarray
        Array in which to find the relative extrema.
    comparator : callable
        Function to use to compare two data points.
        Should take two arrays as arguments.
    axis : int, optional
        Axis over which to select from `data`.  Default is 0.
    order : int, optional
        How many points on each side to use for the comparison
        to consider ``comparator(n,n+x)`` to be True.
    mode : str, optional
        How the edges of the vector are treated. 'wrap' (wrap around) or
        'clip' (treat overflow as the same as the last (or first) element).
        Default 'clip'. See cupy.take.

    Returns
    -------
    extrema : ndarray
        Boolean array of the same shape as `data` that is True at an extrema,
        False otherwise.

    See also
    --------
    argrelmax, argrelmin
    r   zOrder must be an int >= 1r   r8   r   r\   r   N)a_mina_max)r   rJ   rz   r;   r<   r:   rU   r   arangerT   taker   r   )r   r   r]   rx   r   r   datalenlocsmainshiftp_locsm_locsplusminuss                 r   _boolrelextremar     s   D 	E

e4555y1}}*TZt444dJeT7CCCC*T"{1g&&)DJd333yt$///[EAI.. 	 	Ev~~4%<t*1A+8 8 84%<qEEE9T6555DIdF666Ezz$---Gzz$...G~  Nr   c                 d    t          j        |           } t          | t           j        |||          S )a  
    Calculate the relative minima of `data`.

    Parameters
    ----------
    data : ndarray
        Array in which to find the relative minima.
    axis : int, optional
        Axis over which to select from `data`.  Default is 0.
    order : int, optional
        How many points on each side to use for the comparison
        to consider ``comparator(n, n+x)`` to be True.
    mode : str, optional
        How the edges of the vector are treated.
        Available options are 'wrap' (wrap around) or 'clip' (treat overflow
        as the same as the last (or first) element).
        Default 'clip'. See cupy.take.


    Returns
    -------
    extrema : tuple of ndarrays
        Indices of the minima in arrays of integers.  ``extrema[k]`` is
        the array of indices of axis `k` of `data`.  Note that the
        return value is a tuple even when `data` is one-dimensional.

    See Also
    --------
    argrelextrema, argrelmax, find_peaks

    Notes
    -----
    This function uses `argrelextrema` with cupy.less as comparator. Therefore
    it requires a strict inequality on both sides of a value to consider it a
    minimum. This means flat minima (more than one sample wide) are not
    detected. In case of one-dimensional `data` `find_peaks` can be used to
    detect all local minima, including flat ones, by calling it with negated
    `data`.

    Examples
    --------
    >>> from cupyx.scipy.signal import argrelmin
    >>> import cupy
    >>> x = cupy.array([2, 1, 2, 3, 2, 0, 1, 0])
    >>> argrelmin(x)
    (array([1, 5]),)
    >>> y = cupy.array([[1, 2, 1, 2],
    ...               [2, 2, 0, 0],
    ...               [5, 3, 4, 4]])
    ...
    >>> argrelmin(y, axis=1)
    (array([0, 2]), array([2, 1]))

    )r;   ry   argrelextremalessr   r]   rx   r   s       r   	argrelminr      s,    n <Dty$t<<<r   c                 d    t          j        |           } t          | t           j        |||          S )a  
    Calculate the relative maxima of `data`.

    Parameters
    ----------
    data : ndarray
        Array in which to find the relative maxima.
    axis : int, optional
        Axis over which to select from `data`.  Default is 0.
    order : int, optional
        How many points on each side to use for the comparison
        to consider ``comparator(n, n+x)`` to be True.
    mode : str, optional
        How the edges of the vector are treated.
        Available options are 'wrap' (wrap around) or 'clip' (treat overflow
        as the same as the last (or first) element).
        Default 'clip'. See cupy.take.

    Returns
    -------
    extrema : tuple of ndarrays
        Indices of the maxima in arrays of integers.  ``extrema[k]`` is
        the array of indices of axis `k` of `data`.  Note that the
        return value is a tuple even when `data` is one-dimensional.

    See Also
    --------
    argrelextrema, argrelmin, find_peaks

    Notes
    -----
    This function uses `argrelextrema` with cupy.greater as comparator.
    Therefore it requires a strict inequality on both sides of a value to
    consider it a maximum. This means flat maxima (more than one sample wide)
    are not detected. In case of one-dimensional `data` `find_peaks` can be
    used to detect all local maxima, including flat ones.

    Examples
    --------
    >>> from cupyx.scipy.signal import argrelmax
    >>> import cupy
    >>> x = cupy.array([2, 1, 2, 3, 2, 0, 1, 0])
    >>> argrelmax(x)
    (array([3, 6]),)
    >>> y = cupy.array([[1, 2, 1, 2],
    ...               [2, 2, 0, 0],
    ...               [5, 3, 4, 4]])
    ...
    >>> argrelmax(y, axis=1)
    (array([0]), array([1]))
    )r;   ry   r   greaterr   s       r   	argrelmaxr   [  s,    h <Dt|T5$???r   c                     t          j        |           } t          | ||||          }|dk    rt          d          t          j        |          S )a  
    Calculate the relative extrema of `data`.

    Parameters
    ----------
    data : ndarray
        Array in which to find the relative extrema.
    comparator : callable
        Function to use to compare two data points.
        Should take two arrays as arguments.
    axis : int, optional
        Axis over which to select from `data`.  Default is 0.
    order : int, optional
        How many points on each side to use for the comparison
        to consider ``comparator(n, n+x)`` to be True.
    mode : str, optional
        How the edges of the vector are treated.
        Available options are 'wrap' (wrap around) or 'clip' (treat overflow
        as the same as the last (or first) element).
        Default 'clip'. See cupy.take.

    Returns
    -------
    extrema : tuple of ndarrays
        Indices of the maxima in arrays of integers.  ``extrema[k]`` is
        the array of indices of axis `k` of `data`.  Note that the
        return value is a tuple even when `data` is one-dimensional.

    See Also
    --------
    argrelmin, argrelmax

    Examples
    --------
    >>> from cupyx.scipy.signal import argrelextrema
    >>> import cupy
    >>> x = cupy.array([2, 1, 2, 3, 2, 0, 1, 0])
    >>> argrelextrema(x, cupy.greater)
    (array([3, 6]),)
    >>> y = cupy.array([[1, 2, 1, 2],
    ...               [2, 2, 0, 0],
    ...               [5, 3, 4, 4]])
    ...
    >>> argrelextrema(y, cupy.less, axis=1)
    (array([0, 2]), array([2, 1]))

    raisez+CuPy `take` doesn't support `mode='raise'`.)r;   ry   r   NotImplementedErrornonzero)r   r   r]   rx   r   r   s         r   r   r     sY    ` <DdJeTBBGw!9; ; 	; <   r   )NF)F)N)r   NN)NNNNNNr   N)r   r   r   )=__doc__r   r;   cupy._core._scalarr   cupy_backends.cuda.apir   cupyxr   r   r   float32r   FLOAT_TYPESint8int16int32r=   	INT_TYPESuint8uint16uint32uint64UNSIGNED_TYPESFLOAT_INT_TYPESTYPES
TYPE_NAMESFLOAT_INT_NAMESr   r   
less_equalgreater_equalequal	not_equalr   PEAKS_KERNEL	RawModuler>   ARGREL_KERNELr   r5   rG   rR   rZ   rf   ru   r}   r   r   	rawkernelr   r   r   r   r   r   r   r   r   r   r   r   r   r   <module>r     sp   6   + + + + + + * * * * * *      
 
 
 |T\4<8Y
DJ
;	*dk4;D	).(.....
==_=== 	IqL!OQJNA	m^ t~	BBzBBB22z2223--*---./ / /^B 	IIIII888889: : :  . . .*, , ,^  D&> &> &>R? ? ?D    4  2   0 0 0 0* %6 %6 %6 %6PT9 T9 T9 T9n[L [L [L [L| 9=BE P P P Pf4 4 40= = = =@8= 8= 8= 8=v5@ 5@ 5@ 5@p7! 7! 7! 7! 7! 7!r   