
    `i)Q                         d Z ddlmZ ddlZg dZdZ ej        edg d          Zd	 Zd
 Z	d Z
d Zd Z G d de          Z	 	 	 	 	 ddZdS )a  
upfirdn implementation.

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.

    )ceilN)	constantwrapedgesmooth	symmetricreflectantisymmetricantireflectlinea0  
#include <cupy/complex.cuh>

///////////////////////////////////////////////////////////////////////////////
//                              UPFIRDN1D                                    //
///////////////////////////////////////////////////////////////////////////////

template<typename T>
__device__ void _cupy_upfirdn1D( const T *__restrict__ inp,
                                 const T *__restrict__ h_trans_flip,
                                 const int up,
                                 const int down,
                                 const int axis,
                                 const int x_shape_a,
                                 const int h_per_phase,
                                 const int padded_len,
                                 T *__restrict__ out,
                                 const int outW ) {

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

    for ( size_t tid = t; tid < outW; tid += stride ) {

        __builtin_assume( padded_len > 0 );
        __builtin_assume( up > 0 );
        __builtin_assume( down > 0 );
        __builtin_assume( tid > 0 );

        const int x_idx { static_cast<int>( ( tid * down ) / up ) % padded_len };
        int       h_idx { static_cast<int>( ( tid * down ) % up * h_per_phase ) };
        int       x_conv_idx { x_idx - h_per_phase + 1 };

        if ( x_conv_idx < 0 ) {
            h_idx -= x_conv_idx;
            x_conv_idx = 0;
        }

        T temp {};

        int stop = ( x_shape_a < ( x_idx + 1 ) ) ? x_shape_a : ( x_idx + 1 );

        for ( int x_c = x_conv_idx; x_c < stop; x_c++ ) {
            temp += inp[x_c] * h_trans_flip[h_idx];
            h_idx += 1;
        }
        out[tid] = temp;
    }
}

extern "C" __global__ void __launch_bounds__( 512 ) _cupy_upfirdn1D_float32( const float *__restrict__ inp,
                                                                             const float *__restrict__ h_trans_flip,
                                                                             const int up,
                                                                             const int down,
                                                                             const int axis,
                                                                             const int x_shape_a,
                                                                             const int h_per_phase,
                                                                             const int padded_len,
                                                                             float *__restrict__ out,
                                                                             const int outW ) {
    _cupy_upfirdn1D<float>( inp, h_trans_flip, up, down, axis, x_shape_a, h_per_phase, padded_len, out, outW );
}

extern "C" __global__ void __launch_bounds__( 512 ) _cupy_upfirdn1D_float64( const double *__restrict__ inp,
                                                                             const double *__restrict__ h_trans_flip,
                                                                             const int up,
                                                                             const int down,
                                                                             const int axis,
                                                                             const int x_shape_a,
                                                                             const int h_per_phase,
                                                                             const int padded_len,
                                                                             double *__restrict__ out,
                                                                             const int outW ) {
    _cupy_upfirdn1D<double>( inp, h_trans_flip, up, down, axis, x_shape_a, h_per_phase, padded_len, out, outW );
}

extern "C" __global__ void __launch_bounds__( 512 )
    _cupy_upfirdn1D_complex64( const thrust::complex<float> *__restrict__ inp,
                               const thrust::complex<float> *__restrict__ h_trans_flip,
                               const int up,
                               const int down,
                               const int axis,
                               const int x_shape_a,
                               const int h_per_phase,
                               const int padded_len,
                               thrust::complex<float> *__restrict__ out,
                               const int outW ) {
    _cupy_upfirdn1D<thrust::complex<float>>(
        inp, h_trans_flip, up, down, axis, x_shape_a, h_per_phase, padded_len, out, outW );
}

extern "C" __global__ void __launch_bounds__( 512 )
    _cupy_upfirdn1D_complex128( const thrust::complex<double> *__restrict__ inp,
                                const thrust::complex<double> *__restrict__ h_trans_flip,
                                const int up,
                                const int down,
                                const int axis,
                                const int x_shape_a,
                                const int h_per_phase,
                                const int padded_len,
                                thrust::complex<double> *__restrict__ out,
                                const int outW ) {
    _cupy_upfirdn1D<thrust::complex<double>>(
        inp, h_trans_flip, up, down, axis, x_shape_a, h_per_phase, padded_len, out, outW );
}

///////////////////////////////////////////////////////////////////////////////
//                              UPFIRDN2D                                    //
///////////////////////////////////////////////////////////////////////////////

template<typename T>
__device__ void _cupy_upfirdn2D( const T *__restrict__ inp,
                                 const int inpH,
                                 const T *__restrict__ h_trans_flip,
                                 const int up,
                                 const int down,
                                 const int axis,
                                 const int x_shape_a,
                                 const int h_per_phase,
                                 const int padded_len,
                                 T *__restrict__ out,
                                 const int outW,
                                 const int outH ) {

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

    const int stride_y { static_cast<int>( blockDim.x * gridDim.x ) };
    const int stride_x { static_cast<int>( blockDim.y * gridDim.y ) };

    for ( int x = tx; x < outH; x += stride_x ) {
        for ( int y = ty; y < outW; y += stride_y ) {
            int x_idx {};
            int h_idx {};

            __builtin_assume( padded_len > 0 );
            __builtin_assume( up > 0 );
            __builtin_assume( down > 0 );

            if ( axis == 1 ) {
                __builtin_assume( x > 0 );
                x_idx = ( static_cast<int>( x * down ) / up ) % padded_len;
                h_idx = ( x * down ) % up * h_per_phase;
            } else {
                __builtin_assume( y > 0 );
                x_idx = ( static_cast<int>( y * down ) / up ) % padded_len;
                h_idx = ( y * down ) % up * h_per_phase;
            }

            int x_conv_idx { x_idx - h_per_phase + 1 };
            if ( x_conv_idx < 0 ) {
                h_idx -= x_conv_idx;
                x_conv_idx = 0;
            }

            T temp {};

            int stop = ( x_shape_a < ( x_idx + 1 ) ) ? x_shape_a : ( x_idx + 1 );

            for ( int x_c = x_conv_idx; x_c < stop; x_c++ ) {
                if ( axis == 1 ) {
                    temp += inp[y * inpH + x_c] * h_trans_flip[h_idx];
                } else {
                    temp += inp[x_c * inpH + x] * h_trans_flip[h_idx];
                }
                h_idx += 1;
            }
            out[y * outH + x] = temp;
        }
    }
}

extern "C" __global__ void __launch_bounds__( 64 ) _cupy_upfirdn2D_float32( const float *__restrict__ inp,
                                                                            const int inpH,
                                                                            const float *__restrict__ h_trans_flip,
                                                                            const int up,
                                                                            const int down,
                                                                            const int axis,
                                                                            const int x_shape_a,
                                                                            const int h_per_phase,
                                                                            const int padded_len,
                                                                            float *__restrict__ out,
                                                                            const int outW,
                                                                            const int outH ) {
    _cupy_upfirdn2D<float>(
        inp, inpH, h_trans_flip, up, down, axis, x_shape_a, h_per_phase, padded_len, out, outW, outH );
}

extern "C" __global__ void _cupy_upfirdn2D_float64( const double *__restrict__ inp,
                                                    const int inpH,
                                                    const double *__restrict__ h_trans_flip,
                                                    const int up,
                                                    const int down,
                                                    const int axis,
                                                    const int x_shape_a,
                                                    const int h_per_phase,
                                                    const int padded_len,
                                                    double *__restrict__ out,
                                                    const int outW,
                                                    const int outH ) {
    _cupy_upfirdn2D<double>(
        inp, inpH, h_trans_flip, up, down, axis, x_shape_a, h_per_phase, padded_len, out, outW, outH );
}

extern "C" __global__ void __launch_bounds__( 64 )
    _cupy_upfirdn2D_complex64( const thrust::complex<float> *__restrict__ inp,
                               const int inpH,
                               const thrust::complex<float> *__restrict__ h_trans_flip,
                               const int up,
                               const int down,
                               const int axis,
                               const int x_shape_a,
                               const int h_per_phase,
                               const int padded_len,
                               thrust::complex<float> *__restrict__ out,
                               const int outW,
                               const int outH ) {
    _cupy_upfirdn2D<thrust::complex<float>>(
        inp, inpH, h_trans_flip, up, down, axis, x_shape_a, h_per_phase, padded_len, out, outW, outH );
}

extern "C" __global__ void __launch_bounds__( 64 )
    _cupy_upfirdn2D_complex128( const thrust::complex<double> *__restrict__ inp,
                                const int inpH,
                                const thrust::complex<double> *__restrict__ h_trans_flip,
                                const int up,
                                const int down,
                                const int axis,
                                const int x_shape_a,
                                const int h_per_phase,
                                const int padded_len,
                                thrust::complex<double> *__restrict__ out,
                                const int outW,
                                const int outH ) {
    _cupy_upfirdn2D<thrust::complex<double>>(
        inp, inpH, h_trans_flip, up, down, axis, x_shape_a, h_per_phase, padded_len, out, outW, outH );
}
)z
-std=c++11)_cupy_upfirdn1D_float32_cupy_upfirdn1D_float64_cupy_upfirdn1D_complex64_cupy_upfirdn1D_complex128_cupy_upfirdn2D_float32_cupy_upfirdn2D_float64_cupy_upfirdn2D_complex64_cupy_upfirdn2D_complex128)codeoptionsname_expressionsc                    t          |           t          |            |z  z   }t          j        || j                  }| |dt          |           <   |                    d|          j        dddddf                                         }|S )a  Store coefficients in a transposed, flipped arrangement.
    For example, suppose upRate is 3, and the
    input number of coefficients is 10, represented as h[0], ..., h[9].
    Then the internal buffer will look like this::
       h[9], h[6], h[3], h[0],   // flipped phase 0 coefs
       0,    h[7], h[4], h[1],   // flipped phase 1 coefs (zero-padded)
       0,    h[8], h[5], h[2],   // flipped phase 2 coefs (zero-padded)
    N)lencupyzerosdtypereshapeTravel)huph_padlenh_fulls       o/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/cupyx/scipy/signal/_upfirdn.py_pad_hr&   $  s     1vv#a&&2&HZ!'**FF8SVV8^^B##%aaa2g.4466FM    c                 *    |dz
  |z  | z   dz
  |z  dz   S )N    )len_hin_lenr"   downs       r%   _output_lenr.   4  s%    qjB&!+4q88r'   c                  X    t           j                                        } | j        d         S )NMaxGridDimXr   cudaDevice
attributes	device_ids    r%   _get_max_gdxr7   :  #    	  ""I..r'   c                  X    t           j                                        } | j        d         S )NMaxGridDimYr1   r5   s    r%   _get_max_gdyr;   ?  r8   r'   c                  n    t           j                                        } | j        d         }d}|dz  }||fS )NMultiProcessorCounti      r1   )r6   numSMthreadsperblockblockspergrids       r%   _get_tpb_bpgrB   D  s<    	  ""I !67EOBJMM))r'   c                       e Zd Zd Zd ZdS )_UpFIRDnc                 n   t          j        |          }|j        dk    s|j        dk    rt	          d          t          j        |j        |t           j                  | _        t          j        || j                  }t          |          | _
        t          |          | _        | j
        dk     s| j        dk     rt	          d          t          || j
                  | _        t          j        | j                  | _        t          j        | j                  | _        t          |          | _        dS )zHelper for resamplingr)   r   z!h must be 1D with non-zero lengthzBoth up and down must be >= 1N)r   asarrayndimsize
ValueErrorresult_typer   float32_output_typeint_up_downr&   _h_trans_flipascontiguousarrayr   _h_len_orig)selfr!   x_dtyper"   r-   s        r%   __init__z_UpFIRDn.__init__N  s    LOO6Q;;!&A++@AAA ,QWgt|LLLD-..r77YY
8a<<4:>><===#Atx00!\$*<==!3D4FGGq66r'   c                 
   t          j        || j                  }t          | j        |j        |         | j        | j                  }t          |j                  }|||<   t          j	        || j        d          }||j
        z  }|j        |         }t          | j                  | j        z  }|j        |         t          | j                  | j        z  z   dz
  }|j
        dk    rt                      \  }	}
t                              d|j        j                   } ||j        d         dz   dz
  dz  fd|| j        | j        | j        ||||||j        d         f
           n|j
        dk    rd	}	t%          |j        d         |	d         z            }|t'                      k     r|nt'                      }t%          |j        d         |	d         z            }|t)                      k     r|nt)                      }||f}
t                              d
|j        j                   } ||	|
||j        d         | j        | j        | j        ||||||j        d         |j        d         f           nt+          d          |S )z@Apply the prepared filter to the specified axis of a nD signal xC)r   orderr)   _cupy_upfirdn1D_r      )rZ      )   r\   _cupy_upfirdn2D_zupfirdn() requires ndim <= 2)r   rF   rL   r.   rR   shaperN   rO   listemptyrG   r   rP   rB   UPFIRDN_MODULEget_functionr   namer   r7   r;   NotImplementedError)rS   xaxis
output_lenoutput_shapeout	x_shape_ah_per_phase
padded_lenr@   rA   kernelblocksblockspergrid_xblockspergrid_ys                  r%   apply_filterz_UpFIRDn.apply_filter`  s    LD-.. agdmTXtzC C
AG}}'TjT->cJJJaf} GDM	$,--9WT]c$*<&=&=&IJQN
8q==-9^^*O]#00339>335 5FFQWQZ#%)c13V&HJIaL
    X]]$O#)A,);;<<F <>>11|~~  #)A,);;<<F <>>11|~~  -o>M $00339>335 5FF?MGAJ&HJIaLIaL     &&DEEE
r'   N)__name__
__module____qualname__rU   rq   r*   r'   r%   rD   rD   M  s7        " " "$K K K K Kr'   rD   r)   r   r   c                     |d}|dk    s|dk    rt          d|d|d          t          | |j        t          |          t          |                    }|                    ||          S )a  
    Upsample, FIR filter, and downsample.

    Parameters
    ----------
    h : array_like
        1-dimensional FIR (finite-impulse response) filter coefficients.
    x : array_like
        Input signal array.
    up : int, optional
        Upsampling rate. Default is 1.
    down : int, optional
        Downsampling rate. Default is 1.
    axis : int, optional
        The axis of the input data array along which to apply the
        linear filter. The filter is applied to each subarray along
        this axis. Default is -1.
    mode : str, optional
        This parameter is not implemented for values other than ``"constant"``.
    cval : float, optional
        This parameter is not implemented for values other than 0.

    Returns
    -------
    y : ndarray
        The output signal array. Dimensions will be the same as `x` except
        for along `axis`, which will change size according to the `h`,
        `up`,  and `down` parameters.

    Notes
    -----
    The algorithm is an implementation of the block diagram shown on page 129
    of the Vaidyanathan text [1]_ (Figure 4.3-8d).

    The direct approach of upsampling by factor of P with zero insertion,
    FIR filtering of length ``N``, and downsampling by factor of Q is
    O(N*Q) per output sample. The polyphase implementation used here is
    O(N/P).

    See Also
    --------
    scipy.signal.upfirdn

    References
    ----------
    .. [1] P. P. Vaidyanathan, Multirate Systems and Filter Banks,
       Prentice Hall, 1993.
    Nr   r   zmode=z
 and cval=z not implemented.)rd   rD   r   rM   rq   )r!   re   r"   r-   rf   modecvalufds           r%   upfirdnry     s{    r |zTQYY!"IT"I"I"I"I"IJJJ
1ags2wwD		
2
2CAt$$$r'   )r)   r)   r   r   r   )__doc__mathr   r   _upfirdn_modesUPFIRDN_KERNEL	RawModulera   r&   r.   r7   r;   rB   objectrD   ry   r*   r'   r%   <module>r      s'   8         m`  		 	 	     9 9 9/ / /
/ / /
* * *^ ^ ^ ^ ^v ^ ^ ^H 		
			
@% @% @% @% @% @%r'   