
    `iN                         d Z ddlZddlmZ ddlZddlmZmZmZm	Z	m
Z
mZ ddlmZ ddlmZ ddlmZ ddlmZ dd	lmZmZ dd
lmZmZmZmZ ddlmZ d ZddZddZ 	 	 ddZ!dS )a  
Signal sampling 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)gcd)fftrfftfftfreqifftirfft	ifftshift)cheby1)firwin)zpk2sos)dlti)upfirdn_output_len)sosfiltfiltfiltfiltsosfiltlfilter)
get_windowc                     t          | |          }| |z  } ||z  }t          | |          }d|z  }d|z  }t          d|z  dz   ||          }|S )a  
    Design a prototype FIR low-pass filter using the window method
    for use in polyphase rational resampling.

    Parameters
    ----------
    up : int
        The upsampling factor.
    down : int
        The downsampling factor.
    window : string or tuple
        Desired window to use to design the low-pass filter.
        See below for details.

    Returns
    -------
    h : array
        The computed FIR filter coefficients.

    See Also
    --------
    resample_poly : Resample up or down using the polyphase method.

    Notes
    -----
    The argument `window` specifies the FIR low-pass filter design.
    The functions `cusignal.get_window` and `cusignal.firwin`
    are called to generate the appropriate filter coefficients.

    The returned array of coefficients will always be of data type
    `complex128` to maintain precision. For use in lower-precision
    filter operations, this array should be converted to the desired
    data type before providing it to `cusignal.resample_poly`.

          ?
         window)r   maxr   )updownr   g_max_ratef_chalf_lenhs           p/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/cupyx/scipy/signal/_resample.py_design_resample_polyr%   ,   si    P 
RB2IBRKD 2t}}H
.C H}Hq8|aV444AH    iirTc                    t          j        |           } t          j        |          }|t          j        |          }| j        }t          j        |t           j                  r|j        t           j        k    rt           j	        }|dk    rT|
d|z  }d|z  }t          |dz   d|z  d          d}	}t          j        ||	          }t          j        |	|	          }	nq|d
k    r4d}
|d}t          |dd|z  d          }t          j        ||	          }n7t          |t                    r|                                }|j        j        d         dk    r%|                                }|j        |j        }	}d}nt)          t          j        |j                            s?t)          t          j        |j                            st          j        |j                  r%d}
|                                }|j        |j        }	}nHd}
t/          |j        |j        |j                  }t          j        ||	          }nt3          d          t5          d          g| j        z  }|dk    rs||	z  }|rt9          | d|||          }n| j        |         |z  t;          | j        |         |z            z   }t=          || d||          }t5          d|d          ||<   ng|r)|
rt?          || |          }n<tA          ||	| |          }n(|
rtC          || |          }ntE          ||	| |          }t5          dd|          ||<   |tG          |                   S )a  
    Downsample the signal after applying an anti-aliasing filter.

    By default, an order 8 Chebyshev type I filter is used. A 30 point FIR
    filter with Hamming window is used if `ftype` is 'fir'.

    Parameters
    ----------
    x : array_like
        The signal to be downsampled, as an N-dimensional array.
    q : int
        The downsampling factor. When using IIR downsampling, it is recommended
        to call `decimate` multiple times for downsampling factors higher than
        13.
    n : int, optional
        The order of the filter (1 less than the length for 'fir'). Defaults to
        8 for 'iir' and 20 times the downsampling factor for 'fir'.
    ftype : str {'iir', 'fir'} or ``dlti`` instance, optional
        If 'iir' or 'fir', specifies the type of lowpass filter. If an instance
        of an `dlti` object, uses that object to filter before downsampling.
    axis : int, optional
        The axis along which to decimate.
    zero_phase : bool, optional
        Prevent phase shift by filtering with `filtfilt` instead of `lfilter`
        when using an IIR filter, and shifting the outputs back by the filter's
        group delay when using an FIR filter. The default value of ``True`` is
        recommended, since a phase shift is generally not desired.

    Returns
    -------
    y : ndarray
        The down-sampled signal.

    See Also
    --------
    resample : Resample up or down using the FFT method.
    resample_poly : Resample using polyphase filtering and an FIR filter.
    Nfirr   r   r   r   hammingr   )dtyper'   T   g?g?sos)outputr   Fzinvalid ftype)axisr   )r   r   r0   r0   )$cupyasarrayoperatorindexr,   
issubdtypeinexacttypefloat16float64r   r
   
isinstancer   _as_zpkpolesshape_as_tfnumdenany	iscomplexgainr   zeros
ValueErrorslicendimresample_polyboolr   r   r   r   r   tuple)xqnftyper0   
zero_phaseresult_typer"   baiir_use_sosr.   systemslyn_outs                   r$   decimaterY   c   sY   P 	QAqA}N1'K?;55 #

dl
*
*l~~9AvHHAac26)444b1L+...L+...	%9AQcAge444l3k222	E4	 	  *<a A%%\\^^F:vzqAEE$...// 
	7T^FL1122
	7,,
	7  K\\^^F:vzqAAK&,fkBBC,s+666CC)))
++	B~~E 	0aAD;;;AA GDMQ&agdma.?)@)@@E1666AT5$//BtHH  		0 1QT222Q14000 0C...Aq!$///tQ''4U2YY<r&   timec                    |dvr"t          d                    |                    t          j        |           } | j        |         }t          j        |           }|dk    r&|rt          | |          }nt          | |          }n| }|t          |          r |t          |                    }	nUt          |t          j                  r|j        |fk    rt          d          |}	nt          t          ||                    }	dg| j        z  }
|j        |         |
|<   |rh|	                                }|ddxx         |dd	d         z  cc<   |ddxx         d
z  cc<   ||d|
|                                      |
          z  }n||	                    |
          z  }t#          | j                  }|r|dz  dz   ||<   n|||<   t          j        ||j                  }t)          ||          }|dz  dz   }t+          d          g| j        z  }t+          d	|          ||<   |t-          |                   |t-          |          <   |sA|dk    r;t+          ||z
  d          ||<   |t-          |                   |t-          |          <   |dz  d	k    r||k     r|r:t+          |dz  |dz  dz             ||<   |t-          |          xx         dz  cc<   nt+          | dz  | dz  dz             ||<   |t-          |          xx         |t-          |                   z  cc<   n||k     rt+          |dz  |dz  dz             ||<   |t-          |          xx         d
z  cc<   |sI|t-          |                   }t+          ||dz  z
  ||dz  z
  dz             ||<   ||t-          |          <   |rt/          |||          }nt1          ||d          }|t3          |          t3          |          z  z  }||S t          j        d	|          |d         |d	         z
  z  |z  t3          |          z  |d	         z   }||fS )a  
    Resample `x` to `num` samples using Fourier method along the given axis.

    The resampled signal starts at the same value as `x` but is sampled
    with a spacing of ``len(x) / num * (spacing of x)``.  Because a
    Fourier method is used, the signal is assumed to be periodic.

    Parameters
    ----------
    x : array_like
        The data to be resampled.
    num : int
        The number of samples in the resampled signal.
    t : array_like, optional
        If `t` is given, it is assumed to be the sample positions
        associated with the signal data in `x`.
    axis : int, optional
        The axis of `x` that is resampled.  Default is 0.
    window : array_like, callable, string, float, or tuple, optional
        Specifies the window applied to the signal in the Fourier
        domain.  See below for details.
    domain : string, optional
        A string indicating the domain of the input `x`:

        ``time``
           Consider the input `x` as time-domain. (Default)
        ``freq``
           Consider the input `x` as frequency-domain.

    Returns
    -------
    resampled_x or (resampled_x, resampled_t)
        Either the resampled array, or, if `t` was given, a tuple
        containing the resampled array and the corresponding resampled
        positions.

    See Also
    --------
    decimate : Downsample the signal after applying an FIR or IIR filter.
    resample_poly : Resample using polyphase filtering and an FIR filter.

    Notes
    -----
    The argument `window` controls a Fourier-domain window that tapers
    the Fourier spectrum before zero-padding to alleviate ringing in
    the resampled values for sampled signals you didn't intend to be
    interpreted as band-limited.

    If `window` is a function, then it is called with a vector of inputs
    indicating the frequency bins (i.e. fftfreq(x.shape[axis]) ).

    If `window` is an array of the same length as `x.shape[axis]` it is
    assumed to be the window to be applied directly in the Fourier
    domain (with dc and low-frequency first).

    For any other type of `window`, the function `cusignal.get_window`
    is called to generate the window.

    The first sample of the returned vector is the same as the first
    sample of the input vector.  The spacing between samples is changed
    from ``dx`` to ``dx * len(x) / num``.

    If `t` is not None, then it represents the old sample positions,
    and the new sample positions will be returned as well as the new
    samples.

    As noted, `resample` uses FFT transformations, which can be very
    slow if the number of input or output samples is large and prime;
    see `scipy.fftpack.fft`.

    Examples
    --------
    Note that the end of the resampled data rises to meet the first
    sample of the next cycle:

    >>> import cupy as cp
    >>> import cupyx.scipy.signal import resample

    >>> x = cupy.linspace(0, 10, 20, endpoint=False)
    >>> y = cupy.cos(-x**2/6.0)
    >>> f = resample(y, 100)
    >>> xnew = cupy.linspace(0, 10, 100, endpoint=False)

    >>> import matplotlib.pyplot as plt
    >>> plt.plot(cupy.asnumpy(x), cupy.asnumpy(y), 'go-', cupy.asnumpy(xnew),                 cupy.asnumpy(f), '.-', 10, cupy.asnumpy(y[0]), 'ro')
    >>> plt.legend(['data', 'resampled'], loc='best')
    >>> plt.show()
    )rZ   freqz;Acceptable domain flags are 'time' or 'freq', not domain={}rZ   r1   Nz(window must have the same length as datar   r(   r   g      ?r   g       @T)r0   overwrite_x)rF   formatr2   r3   r>   	isrealobjr   r   callabler   r;   ndarrayr	   r   rH   copyreshapelistrE   r,   minrG   rK   r   r   floatarange)rL   r@   tr0   r   domainNx
real_inputXW
newshape_WW_realnewshapeYNnyqrV   temprW   new_ts                       r$   resamplerv      s   t %%% 228&..B B 	B 	QA	
B ""J 	"QT"""AAAD!!!AA F 	2wr{{##AA-- 	2|u$$ !KLLLAA*VR0011AS16\
74=
4 	'VVXXF122JJJ&Ab/)JJJ122JJJ#JJJ)D))*22:>>>AA:&&&A AG}}H A
8QW%%A 	CA
q&1*C
++	BQ}}BtHU2YY<AeBiiL (q55S1Wd++BtHU2YY<AeBiiL 	1uzz88 - Aq!tax004%))" !!QA	224%))%)),#XXQT1a4!8,,BtHeBiiLLLCLLL $r| QT3q!t8a<884#%))  1!St$$$4000%**uRyy
 !AyAs##qtad{3b85::E!L%xr&   kaiserg      @constantc                    |dk    s|t          d          t          j        |           } t          |          }t          |          }|dk     s|dk     rt          d          t	          ||          }||z  }||z  }||cxk    rdk    rn n|                                 S | j        |         |z  }||z  t          ||z            z   }t          |t          t          j
        f          rAt          j        |          }|j        dk    rt          d          |j        dz
  dz  }	||z  }
n'dt          ||          z  }	|t          |||          z  }
||	|z  z
  }d	}|	|z   |z  }t          t!          |
          |z   |z   | j        |         ||          ||z   k     r<|dz  }t          t!          |
          |z   |z   | j        |         ||          ||z   k     <t          j        t          j        ||
j                  |
t          j        ||
j                  f          }
||z   }t)          |
| |||          }t+          d          g| j        z  }t+          ||          ||<   |t-          |                   S )
a  
    Resample `x` along the given axis using polyphase filtering.

    The signal `x` is upsampled by the factor `up`, a zero-phase low-pass
    FIR filter is applied, and then it is downsampled by the factor `down`.
    The resulting sample rate is ``up / down`` times the original sample
    rate. Values beyond the boundary of the signal are assumed to be zero
    during the filtering step.

    Parameters
    ----------
    x : array_like
        The data to be resampled.
    up : int
        The upsampling factor.
    down : int
        The downsampling factor.
    axis : int, optional
        The axis of `x` that is resampled. Default is 0.
    window : string, tuple, or array_like, optional
        Desired window to use to design the low-pass filter, or the FIR filter
        coefficients to employ. See below for details.
    padtype : string, optional
        `constant`, `line`, `mean`, `median`, `maximum`, `minimum` or any of
        the other signal extension modes supported by
        `cupyx.scipy.signal.upfirdn`. Changes assumptions on values beyond
        the boundary. If `constant`, assumed to be `cval` (default zero).
        If `line` assumed to continue a linear trend defined by the first and
        last points. `mean`, `median`, `maximum` and `minimum` work as in
        `cupy.pad` and assume that the values beyond the boundary are the mean,
        median, maximum or minimum respectively of the array along the axis.
    cval : float, optional
        Value to use if `padtype='constant'`. Default is zero.

    Returns
    -------
    resampled_x : array
        The resampled array.

    See Also
    --------
    decimate : Downsample the signal after applying an FIR or IIR filter.
    resample : Resample up or down using the FFT method.

    Notes
    -----
    This polyphase method will likely be faster than the Fourier method
    in `cusignal.resample` when the number of samples is large and
    prime, or when the number of samples is large and `up` and `down`
    share a large greatest common denominator. The length of the FIR
    filter used will depend on ``max(up, down) // gcd(up, down)``, and
    the number of operations during polyphase filtering will depend on
    the filter length and `down` (see `cusignal.upfirdn` for details).

    The argument `window` specifies the FIR low-pass filter design.

    If `window` is an array_like it is assumed to be the FIR filter
    coefficients. Note that the FIR filter is applied after the upsampling
    step, so it should be designed to operate on a signal at a sampling
    frequency higher than the original by a factor of `up//gcd(up, down)`.
    This function's output will be centered with respect to this array, so it
    is best to pass a symmetric filter with an odd number of samples if, as
    is usually the case, a zero-phase filter is desired.

    For any other type of `window`, the functions `cusignal.get_window`
    and `cusignal.firwin` are called to generate the appropriate filter
    coefficients.

    The first sample of the returned vector is the same as the first
    sample of the input vector. The spacing between samples is changed
    from ``dx`` to ``dx * down / float(up)``.

    Examples
    --------
    Note that the end of the resampled data rises to meet the first
    sample of the next cycle for the FFT method, and gets closer to zero
    for the polyphase method:

    >>> import cupy
    >>> import cupyx.scipy.signal import resample, resample_poly

    >>> x = cupy.linspace(0, 10, 20, endpoint=False)
    >>> y = cupy.cos(-x**2/6.0)
    >>> f_fft = resample(y, 100)
    >>> f_poly = resample_poly(y, 100, 20)
    >>> xnew = cupy.linspace(0, 10, 100, endpoint=False)

    >>> import matplotlib.pyplot as plt
    >>> plt.plot(cupy.asnumpy(xnew), cupy.asnumpy(f_fft), 'b.-',                  cupy.asnumpy(xnew), cupy.asnumpy(f_poly), 'r.-')
    >>> plt.plot(cupy.asnumpy(x), cupy.asnumpy(y), 'ko-')
    >>> plt.plot(10, cupy.asnumpy(y[0]), 'bo', 10, 0., 'ro')  # boundaries
    >>> plt.legend(['resample', 'resamp_poly', 'data'], loc='best')
    >>> plt.show()
    ry   Nz7padtype and cval arguments are not supported by upfirdnr   zup and down must be >= 1zwindow must be 1-Dr   r   r   )rF   r2   r3   intr   rb   r>   rJ   r;   rd   ra   rH   sizer   r%   r   lenconcatenaterE   r,   r   rG   rK   )rL   r   r   r0   r   padtypecvalr   rX   r"   r#   	n_pre_pad
n_post_padn_pre_removen_pre_remove_endrW   keeps                    r$   rI   rI     s   D * 0EG G 	G 	QA	RBt99D	Avv3444
 
RB2IBRKD	TQvvxxGDMBETMD...E&4.// 9f%%;??1222K!O)KB%&r4888 x$&IJy(T1L 	CFFY&3QWT]BMM
,
	 	 	a
 	CFFY&3QWT]BMM
,
	 	
 		Iqw	'	'DJz17,K,KL	N 	NA#e+ 	1b$%%A$KK=16!D|%566DJU4[[>r&   )Nr'   r(   T)Nr   NrZ   )r   rw   ry   N)"__doc__r4   mathr   r2   cupyx.scipy.fftr   r   r   r   r   r	   %cupyx.scipy.signal._iir_filter_designr
   %cupyx.scipy.signal._fir_filter_designr   *cupyx.scipy.signal._iir_filter_conversionsr   cupyx.scipy.signal._ltisysr   cupyx.scipy.signal._upfirdnr   r   cupyx.scipy.signal._signaltoolsr   r   r   r   #cupyx.scipy.signal.windows._windowsr   r%   rY   rv   rI    r&   r$   <module>r      s   6         F F F F F F F F F F F F F F F F 8 8 8 8 8 8 8 8 8 8 8 8 > > > > > > + + + + + + < < < < < < < <- - - - - - - - - - - - : : : : : :4 4 4nq q q qh} } } }@ />+/U U U U U Ur&   