
    (phB                   ^   S SK Jr  S SKrS SKrS SKJr  S SKrS SKrS SKJ	r	  S SK
Jr  S SKJr  SSKJr  SS	KJr  SS
KJrJrJr  S SKJrJr  S SKJr  S SKJr  S SKrS SKJ r   SSK!J"r"  SSK#J$r$J%r%J&r&J'r'J(r(  SSK)J*r*J+r+J,r,  SSK-J.r.  SSK/J/r/  / SQr0S SSS.r1S S SSSSSS.r2S r3S r4STS jr5S r6SUS jr7SVS jr8S r9SWS! jr:SWS" jr;S# r<SXS$ jr=S% r>SXS& jr?SYS' jr@S( rAS) rBS* rCS+ rDSZS, jrES[S- jrFSUS. jrGS/ rHSTS0 jrIS\S1 jrJS]S2 jrKS]S3 jrLS^S4 jrMS_S6 jrNSTS7 jrOS8 rPS`S9 jrQSTS: jrRSaSS S;S5S<.         SbS= jjjrSS> rTScS? jrUSdS@ jrVSWSA jrWSB rXSdSC jrYSdSD jrZSE r[SdSF jr\SeSG jr]  SfSH jr^SI r_   Sg       ShSJ jjr`SK raSL rbS_SM jrc  SiSN jrdSO reSP rfS_SQ jrgSjSR jrhSkSS jrig)l    )annotationsN)prod)Literal)	ArrayLike)cKDTree   )	_sigtools)dlti)upfirdn_output_len_upfirdn_modes)linalgfft)ndimage)_init_nd_shape_and_axes)lambertw)
get_window)
axis_sliceaxis_reverseodd_exteven_ext	const_ext)cheby1_validate_soszpk2sos)firwin)_sosfilt)!	correlatecorrelation_lagscorrelate2dconvolve
convolve2dfftconvolve
oaconvolveorder_filtermedfilt	medfilt2dwienerlfilterlfilticsosfilt
deconvolvehilberthilbert2envelopeunique_rootsinvresinvreszresidueresiduezresampleresample_polydetrend
lfilter_zi
sosfilt_zisosfiltfiltchoose_conv_methodfiltfiltdecimatevectorstrength   )validsamefull   )fillpadwrapcircularsymm	symmetricreflectc                R     [         U    $ ! [         a  n[        S5      UeS nAff = f)N5Acceptable mode flags are 'valid', 'same', or 'full'.)	_modedictKeyError
ValueError)modees     L/var/www/html/venv/lib/python3.13/site-packages/scipy/signal/_signaltools.py_valfrommoderS   .   s6    7 7 / 056	77s    
&!&c                X     [         U    S-  $ ! [         a  n[        S5      UeS nAff = f)Nr?   zZAcceptable boundary flags are 'fill', 'circular' (or 'wrap'), and 'symmetric' (or 'symm').)_boundarydictrN   rO   )boundaryrQ   s     rR   _bvalfromboundaryrW   6   sB    MX&!++ M E FKL	MMs    
)$)c                   ^^ U S:w  a  gT(       d  gUc  [        [        T5      5      n[        UU4S jU 5       5      n[        UU4S jU 5       5      nU(       d  U(       d  [        S5      eU(       + $ )a  Determine if inputs arrays need to be swapped in `"valid"` mode.

If in `"valid"` mode, returns whether or not the input arrays need to be
swapped depending on whether `shape1` is at least as large as `shape2` in
every calculated dimension.

This is important for some of the correlation and convolution
implementations in this module, where the larger array input needs to come
before the smaller array input when operating in this mode.

Note that if the mode provided is not 'valid', False is immediately
returned.

r@   Fc              3  :   >#    U  H  nTU   TU   :  v   M     g 7fN .0ishape1shape2s     rR   	<genexpr>&_inputs_swap_needed.<locals>.<genexpr>V        3dfQi6!9$d   c              3  :   >#    U  H  nTU   TU   :  v   M     g 7frZ   r[   r\   s     rR   ra   rb   W   rc   rd   zOFor 'valid' mode, one must be at least as large as the other in every dimension)rangelenallrO   )rP   r_   r`   axesok1ok2s    ``   rR   _inputs_swap_neededrl   >   sk     w|S[!
3d3
3C
3d3
3C3 D E 	E 7N    c                   [         R                  " U 5      R                  n[         R                  " U[         R                  5      (       d  U[         R
                  [         R                  [         R                  [         R                  [         R                  [         R                  4;   d$  SU SU S3n[        R                  " U[        SS9  ggg)z/Warn if arr.dtype is object or longdouble.
    dtype=z is not supported by z and will raise an error in SciPy 1.17.0. Supported dtypes are: boolean, integer, `np.float16`,`np.float32`, `np.float64`, `np.complex64`, `np.complex128`.   category
stacklevelN)npasarraydtype
issubdtypeintegerbool_float16float32float64	complex64
complex128warningswarnDeprecationWarning)arrnamedtmsgs       rR   _reject_objectsr   `   s     
C		BMM"bjj))bhh

BJJ

llBMM3 3 RD-dV 4K L 	
 	c$61E3 *rm   c                   [         R                  " U 5      n [         R                  " U5      n[        U S5        [        US5        U R                  UR                  s=:X  a  S:X  a  O  OXR	                  5       -  $ U R                  UR                  :w  a  [        S5      e [        U   nUS;   a  [        U [        U5      X#5      $ US:X  Ga  [        XU5      (       a  [         R                  " XU5      $ US:H  =(       a    UR                  U R                  :  =(       d     [        X R                  UR                  5      nU(       a  XpUS	:X  aq  [        U R                  UR                  5       VVs/ s H  u  pxXx-
  S
-   PM     n	nn[         R                   " XR"                  5      n
[$        R&                  " XX5      nO[        U R                  UR                  5       VVs/ s H  u  pxXx-   S
-
  PM     n	nn[         R(                  " XR"                  5      n[+        S U R                   5       5      nU R-                  5       X'   US:X  a!  [         R                   " XR"                  5      n
O1US:X  a+  [         R                   " U R                  U R"                  5      n
[$        R&                  " XW
U5      nU(       a  [        U5      nU$ [        S5      e! [         a  n[        S5      UeSnAff = fs  snnf s  snnf )a  
Cross-correlate two N-dimensional arrays.

Cross-correlate `in1` and `in2`, with the output size determined by the
`mode` argument.

Parameters
----------
in1 : array_like
    First input.
in2 : array_like
    Second input. Should have the same number of dimensions as `in1`.
mode : str {'full', 'valid', 'same'}, optional
    A string indicating the size of the output:

    ``full``
       The output is the full discrete linear cross-correlation
       of the inputs. (Default)
    ``valid``
       The output consists only of those elements that do not
       rely on the zero-padding. In 'valid' mode, either `in1` or `in2`
       must be at least as large as the other in every dimension.
    ``same``
       The output is the same size as `in1`, centered
       with respect to the 'full' output.
method : str {'auto', 'direct', 'fft'}, optional
    A string indicating which method to use to calculate the correlation.

    ``direct``
       The correlation is determined directly from sums, the definition of
       correlation.
    ``fft``
       The Fast Fourier Transform is used to perform the correlation more
       quickly (only available for numerical arrays.)
    ``auto``
       Automatically chooses direct or Fourier method based on an estimate
       of which is faster (default).  See `convolve` Notes for more detail.

       .. versionadded:: 0.19.0

Returns
-------
correlate : array
    An N-dimensional array containing a subset of the discrete linear
    cross-correlation of `in1` with `in2`.

See Also
--------
choose_conv_method : contains more documentation on `method`.
correlation_lags : calculates the lag / displacement indices array for 1D
    cross-correlation.

Notes
-----
The correlation z of two d-dimensional arrays x and y is defined as::

    z[...,k,...] = sum[..., i_l, ...] x[..., i_l,...] * conj(y[..., i_l - k,...])

This way, if x and y are 1-D arrays and ``z = correlate(x, y, 'full')``
then

.. math::

      z[k] = (x * y)(k - N + 1)
           = \sum_{l=0}^{||x||-1}x_l y_{l-k+N-1}^{*}

for :math:`k = 0, 1, ..., ||x|| + ||y|| - 2`

where :math:`||x||` is the length of ``x``, :math:`N = \max(||x||,||y||)`,
and :math:`y_m` is 0 when m is outside the range of y.

``method='fft'`` only works for numerical arrays as it relies on
`fftconvolve`. In certain cases (i.e., arrays of objects or when
rounding integers can lose precision), ``method='direct'`` is always used.

When using "same" mode with even-length inputs, the outputs of `correlate`
and `correlate2d` differ: There is a 1-index offset between them.

Examples
--------
Implement a matched filter using cross-correlation, to recover a signal
that has passed through a noisy channel.

>>> import numpy as np
>>> from scipy import signal
>>> import matplotlib.pyplot as plt
>>> rng = np.random.default_rng()

>>> sig = np.repeat([0., 1., 1., 0., 1., 0., 0., 1.], 128)
>>> sig_noise = sig + rng.standard_normal(len(sig))
>>> corr = signal.correlate(sig_noise, np.ones(128), mode='same') / 128

>>> clock = np.arange(64, len(sig), 128)
>>> fig, (ax_orig, ax_noise, ax_corr) = plt.subplots(3, 1, sharex=True)
>>> ax_orig.plot(sig)
>>> ax_orig.plot(clock, sig[clock], 'ro')
>>> ax_orig.set_title('Original signal')
>>> ax_noise.plot(sig_noise)
>>> ax_noise.set_title('Signal with noise')
>>> ax_corr.plot(corr)
>>> ax_corr.plot(clock, corr[clock], 'ro')
>>> ax_corr.axhline(0.5, ls=':')
>>> ax_corr.set_title('Cross-correlated with rectangular pulse')
>>> ax_orig.margins(0, 0.1)
>>> fig.tight_layout()
>>> plt.show()

Compute the cross-correlation of a noisy signal with the original signal.

>>> x = np.arange(128) / 128
>>> sig = np.sin(2 * np.pi * x)
>>> sig_noise = sig + rng.standard_normal(len(sig))
>>> corr = signal.correlate(sig_noise, sig)
>>> lags = signal.correlation_lags(len(sig), len(sig_noise))
>>> corr /= np.max(corr)

>>> fig, (ax_orig, ax_noise, ax_corr) = plt.subplots(3, 1, figsize=(4.8, 4.8))
>>> ax_orig.plot(sig)
>>> ax_orig.set_title('Original signal')
>>> ax_orig.set_xlabel('Sample Number')
>>> ax_noise.plot(sig_noise)
>>> ax_noise.set_title('Signal with noise')
>>> ax_noise.set_xlabel('Sample Number')
>>> ax_corr.plot(lags, corr)
>>> ax_corr.set_title('Cross-correlated signal')
>>> ax_corr.set_xlabel('Lag')
>>> ax_orig.margins(0, 0.1)
>>> ax_noise.margins(0, 0.1)
>>> ax_corr.margins(0, 0.1)
>>> fig.tight_layout()
>>> plt.show()

r   r   /in1 and in2 should have the same dimensionalityrL   N)r   autodirectrB   r@   r   c              3  :   #    U  H  n[        S U5      v   M     g7f)r   N)slice)r]   r^   s     rR   ra   correlate.<locals>.<genexpr>%  s     6IquQ{{Is   rA   7Acceptable method flags are 'auto', 'direct', or 'fft'.)rt   ru   r   ndimconjrO   rM   rN   r!   _reverse_and_conj_np_conv_okr   sizerl   shapezipemptyrv   r	   _correlateNDzerostuplecopy)in1in2rP   methodvalrQ   swapped_inputsr^   jpsoutz
in1zpaddedscs                 rR   r   r   p   si   L **S/C
**S/CC%C%
xx388 q XXZ	SXX	JKK7o  .s3TBB	8	s&&<<$//  6>D3880C J-dIIsyyI 	 7?(+CIIsyy(AB(A!%!)(ABB((2yy)C&&s:A ),CIIsyy(AB(A!%!)(ABB "ii0J6CII66B XXZJNv~hhr99-hhsyy#))4&&zSAA!!$A  0 1 	1g  7 / 056	770 C Cs$   !	K 3K5$K;
K2!K--K2c                   US:X  a  [         R                  " U* S-   U 5      nU$ US:X  aR  [         R                  " U* S-   U 5      nUR                  S-  nU S-  nU S-  S:X  a  X4U-
  XE-    nU$ X4U-
  XE-   S-    n U$ US:X  a?  X-
  nUS:  a  [         R                  " US-   5      nU$ [         R                  " US5      n U$ [        SU S35      e)	aK  
Calculates the lag / displacement indices array for 1D cross-correlation.

Parameters
----------
in1_len : int
    First input size.
in2_len : int
    Second input size.
mode : str {'full', 'valid', 'same'}, optional
    A string indicating the size of the output.
    See the documentation `correlate` for more information.

Returns
-------
lags : array
    Returns an array containing cross-correlation lag/displacement indices.
    Indices can be indexed with the np.argmax of the correlation to return
    the lag/displacement.

See Also
--------
correlate : Compute the N-dimensional cross-correlation.

Notes
-----
Cross-correlation for continuous functions :math:`f` and :math:`g` is
defined as:

.. math::

    \left ( f\star g \right )\left ( \tau \right )
    \triangleq \int_{t_0}^{t_0 +T}
    \overline{f\left ( t \right )}g\left ( t+\tau \right )dt

Where :math:`\tau` is defined as the displacement, also known as the lag.

Cross correlation for discrete functions :math:`f` and :math:`g` is
defined as:

.. math::
    \left ( f\star g \right )\left [ n \right ]
    \triangleq \sum_{-\infty}^{\infty}
    \overline{f\left [ m \right ]}g\left [ m+n \right ]

Where :math:`n` is the lag.

Examples
--------
Cross-correlation of a signal with its time-delayed self.

>>> import numpy as np
>>> from scipy import signal
>>> rng = np.random.default_rng()
>>> x = rng.standard_normal(1000)
>>> y = np.concatenate([rng.standard_normal(100), x])
>>> correlation = signal.correlate(x, y, mode="full")
>>> lags = signal.correlation_lags(x.size, y.size, mode="full")
>>> lag = lags[np.argmax(correlation)]
rB   r   rA   r?   r   r@   zMode z is invalid)rt   aranger   rO   )in1_lenin2_lenrP   lagsmid	lag_bounds         rR   r   r   :  s   ~ v~ yy'Aw/< K; 
 yy'Aw/ii1n qL	Q;!Y8D" K Y(9:D K 
 %	>99Y]+D
 K 99Y*D K 5k233rm   c                   [         R                  " U5      n[         R                  " U R                  5      nX!-
  S-  nX1-   n[	        [        U5      5       Vs/ s H  n[        X5   XE   5      PM     nnU [        U5         $ s  snf )Nr?   )rt   ru   arrayr   rf   rg   r   r   )r   newshape	currshapestartindendindkmyslices          rR   	_centeredr     sv    zz(#H#I$*H F6;CK6HI6HuX[&),6HGIuW~ Js   BFc                  ^^^	 U R                   mUR                   m	TSL n[        U STS9u  nmU(       d  [        T5      (       d  [        S5      eT Vs/ s H  nTU   S:w  d  M  T	U   S:w  d  M  UPM     snmU(       a  TR	                  5         [        UUU	4S j[        U R                  5       5       5      (       d  [        ST ST	 35      e[        UTT	TS9(       a  XpXT4$ s  snf )	aB  Handle the axes argument for frequency-domain convolution.

Returns the inputs and axes in a standard form, eliminating redundant axes,
swapping the inputs if necessary, and checking for various potential
errors.

Parameters
----------
in1 : array
    First input.
in2 : array
    Second input.
mode : str {'full', 'valid', 'same'}, optional
    A string indicating the size of the output.
    See the documentation `fftconvolve` for more information.
axes : list of ints
    Axes over which to compute the FFTs.
sorted_axes : bool, optional
    If `True`, sort the axes.
    Default is `False`, do not sort.

Returns
-------
in1 : array
    The first input, possible swapped with the second input.
in2 : array
    The second input, possible swapped with the first input.
axes : list of ints
    Axes over which to compute the FFTs.

N)r   ri   z#when provided, axes cannot be emptyr   c              3     >#    U  H5  oT;  d  M
  TU   TU   :H  =(       d    TU   S :H  =(       d    TU   S :H  v   M7     g7fr   Nr[   )r]   ari   s1s2s     rR   ra   '_init_freq_conv_axes.<locals>.<genexpr>  sG      :'1D= :r!u1~9A!9r!uz9's
   	A 0A z%incompatible shapes for in1 and in2: z and ri   )	r   r   rg   rO   sortrh   rf   r   rl   )
r   r   rP   ri   sorted_axesnoaxes_r   r   r   s
      `    @@rR   _init_freq_conv_axesr     s    @ 
B	BT\F%cDAGAt#d))>?? 9t!r!uzAbeqjAt9D		 :chh: : : DbT+ , 	, 4Rd3ST> :s   C'%C'0C'c                >   [        U5      (       d  X-  $ U R                  R                  S:H  =(       d    UR                  R                  S:H  nU(       a/  U Vs/ s H!  n[        R                  " X6   U(       + 5      PM#     nnOUnU(       d   [        R
                  [        R                  pO[        R                  [        R                  pU" XUS9n
U" XUS9nU	" X-  XrS9nU(       a)  [        U Vs/ s H  n[        U5      PM     sn5      nX   nU$ s  snf s  snf )a  Convolve two arrays in the frequency domain.

This function implements only base the FFT-related operations.
Specifically, it converts the signals to the frequency domain, multiplies
them, then converts them back to the time domain.  Calculations of axes,
shapes, convolution mode, etc. are implemented in higher level-functions,
such as `fftconvolve` and `oaconvolve`.  Those functions should be used
instead of this one.

Parameters
----------
in1 : array_like
    First input.
in2 : array_like
    Second input. Should have the same number of dimensions as `in1`.
axes : array_like of ints
    Axes over which to compute the FFTs.
shape : array_like of ints
    The sizes of the FFTs.
calc_fast_len : bool, optional
    If `True`, set each value of `shape` to the next fast FFT length.
    Default is `False`, use `axes` as-is.

Returns
-------
out : array
    An N-dimensional array containing the discrete linear convolution of
    `in1` with `in2`.

cr   )rg   rv   kindsp_fftnext_fast_lenrfftnirfftnfftnifftnr   r   )r   r   ri   r   calc_fast_lencomplex_resultr   fshaper   ifftsp1sp2retszfslices                  rR   _freq_domain_convr     s    > t99yiinn+Dsyy~~/DN IMNHL1F  ~+=> 	 N LL&--TKKT
c
%C
c
%C
sy&
,CE2Ebb	E23kJ'N  3s   (D3Dc                P   US:X  a  U R                  5       $ US:X  a  [        X5      R                  5       $ US:X  a\  [        U R                  5       Vs/ s H#  nXT;  a  U R                  U   OX   X%   -
  S-   PM%     nn[        X5      R                  5       $ [        S5      es  snf )a  Calculate the convolution result shape based on the `mode` argument.

Returns the result sliced to the correct size for the given mode.

Parameters
----------
ret : array
    The result array, with the appropriate shape for the 'full' mode.
s1 : list of int
    The shape of the first input.
s2 : list of int
    The shape of the second input.
mode : str {'full', 'valid', 'same'}
    A string indicating the size of the output.
    See the documentation `fftconvolve` for more information.
axes : list of ints
    Axes over which to compute the convolution.

Returns
-------
ret : array
    A copy of `res`, sliced to the correct size for the given `mode`.

rB   rA   r@   r   z4acceptable mode flags are 'valid', 'same', or 'full')r   r   rf   r   r   rO   )r   r   r   rP   ri   r   shape_valids          rR   _apply_conv_moder      s    2 v~xxz	!&&((	 %chh1 /1 ()}syy|"%"%-!:KK / 	 1*//11 . / 	/	1s   *B#c                n   [         R                  " U 5      n [         R                  " U5      nU R                  UR                  s=:X  a
  S:X  a   X-  $   U R                  UR                  :w  a  [        S5      eU R                  S:X  d  UR                  S:X  a  [         R
                  " / 5      $ [        XX#SS9u  pnU R                  nUR                  n[        U R                  5       Vs/ s H%  nXc;  a  [        XF   XV   45      OXF   XV   -   S-
  PM'     nn[        XX7SS9n[        XXRU5      $ s  snf )a  Convolve two N-dimensional arrays using FFT.

Convolve `in1` and `in2` using the fast Fourier transform method, with
the output size determined by the `mode` argument.

This is generally much faster than `convolve` for large arrays (n > ~500),
but can be slower when only a few output values are needed, and can only
output float arrays (int or object array inputs will be cast to float).

As of v0.19, `convolve` automatically chooses this method or the direct
method based on an estimation of which is faster.

Parameters
----------
in1 : array_like
    First input.
in2 : array_like
    Second input. Should have the same number of dimensions as `in1`.
mode : str {'full', 'valid', 'same'}, optional
    A string indicating the size of the output:

    ``full``
       The output is the full discrete linear convolution
       of the inputs. (Default)
    ``valid``
       The output consists only of those elements that do not
       rely on the zero-padding. In 'valid' mode, either `in1` or `in2`
       must be at least as large as the other in every dimension.
    ``same``
       The output is the same size as `in1`, centered
       with respect to the 'full' output.
axes : int or array_like of ints or None, optional
    Axes over which to compute the convolution.
    The default is over all axes.

Returns
-------
out : array
    An N-dimensional array containing a subset of the discrete linear
    convolution of `in1` with `in2`.

See Also
--------
convolve : Uses the direct convolution or FFT convolution algorithm
           depending on which is faster.
oaconvolve : Uses the overlap-add method to do convolution, which is
             generally faster when the input arrays are large and
             significantly different in size.

Examples
--------
Autocorrelation of white noise is an impulse.

>>> import numpy as np
>>> from scipy import signal
>>> rng = np.random.default_rng()
>>> sig = rng.standard_normal(1000)
>>> autocorr = signal.fftconvolve(sig, sig[::-1], mode='full')

>>> import matplotlib.pyplot as plt
>>> fig, (ax_orig, ax_mag) = plt.subplots(2, 1)
>>> ax_orig.plot(sig)
>>> ax_orig.set_title('White noise')
>>> ax_mag.plot(np.arange(-len(sig)+1,len(sig)), autocorr)
>>> ax_mag.set_title('Autocorrelation')
>>> fig.tight_layout()
>>> fig.show()

Gaussian blur implemented using FFT convolution.  Notice the dark borders
around the image, due to the zero-padding beyond its boundaries.
The `convolve2d` function allows for other types of image boundaries,
but is far slower.

>>> from scipy import datasets
>>> face = datasets.face(gray=True)
>>> kernel = np.outer(signal.windows.gaussian(70, 8),
...                   signal.windows.gaussian(70, 8))
>>> blurred = signal.fftconvolve(face, kernel, mode='same')

>>> fig, (ax_orig, ax_kernel, ax_blurred) = plt.subplots(3, 1,
...                                                      figsize=(6, 15))
>>> ax_orig.imshow(face, cmap='gray')
>>> ax_orig.set_title('Original')
>>> ax_orig.set_axis_off()
>>> ax_kernel.imshow(kernel, cmap='gray')
>>> ax_kernel.set_title('Gaussian kernel')
>>> ax_kernel.set_axis_off()
>>> ax_blurred.imshow(blurred, cmap='gray')
>>> ax_blurred.set_title('Blurred')
>>> ax_blurred.set_axis_off()
>>> fig.show()

r   r   Fr   r   Tr   )rt   ru   r   rO   r   r   r   r   rf   maxr   r   )	r   r   rP   ri   r   r   r^   r   r   s	            rR   r#   r#   F  s   | **S/C
**S/C
xx388 q y !	SXX	JKK	Q#((a-xx|)#D6;=NCd 
B	B CHHo'% %&MS"% ruru}q7HH% 
 ' Cd
FCCRt44's   ,,D2c                n   X-   S-
  SX4nX:X  d  U S:X  d  US:X  a  U$ X:  a  XpSnOSnXS-  :  a  U$ US-
  nU* [        SS[        R                  -  U-  -  SS9R                  -  n[        R
                  " [        R                  " U5      5      nX`:  a  U$ U(       d
  Xa-
  S-   nUnO	UnXa-
  S-   nXdXx4$ )a  Calculate the optimal FFT lengths for overlap-add convolution.

The calculation is done for a single dimension.

Parameters
----------
s1 : int
    Size of the dimension for the first array.
s2 : int
    Size of the dimension for the second array.

Returns
-------
block_size : int
    The size of the FFT blocks.
overlap : int
    The amount of overlap between two blocks.
in1_step : int
    The size of each step for the first array.
in2_step : int
    The size of each step for the first array.

r   NTFr?   )r   )r   mathrQ   realr   r   ceil)	r   r   fallbackswappedoverlapopt_size
block_sizein1_stepin2_steps	            rR   _calc_oa_lensr     s    2 ar&H 
x27bAg	wB 
Tzl dGxQtvvXg%5!6"=BBBH%%dii&9:J =?=?22rm   c                *
  ^^#^$ [         R                  " U 5      n [         R                  " U5      nU R                  UR                  s=:X  a
  S:X  a   X-  $   U R                  UR                  :w  a  [        S5      eU R                  S:X  d  UR                  S:X  a  [         R
                  " / 5      $ U R                  UR                  :X  a  [        XUTS9$ [        XUTSS9u  pmU R                  m#UR                  m$T(       d  X-  n[        UT#T$UT5      $ [        U R                  5       Vs/ s H  nUT;  a  SOT#U   T$U   -   S-
  PM     nnUU#U$4S j[        U R                  5       5       n[        U6 u  ppU
T#:X  a  UT$:X  a  [        XUTS9$ / n/ n/ n/ n[        U R                  5       H  nUT;  a  US	/-  nUS	/-  nM  T#U   X   :  aF  [        R                  " T#U   S-   X   -  5      nX   X   -
  U-  Xe   :  a  US-  nUX   -  T#U   -
  nOSnSnT$U   X   :  aF  [        R                  " T$U   S-   X   -  5      nX   X   -
  U-  Xe   :  a  US-  nUX   -  T$U   -
  nOSnSnUU/-  nUU/-  nUSU4/-  nUSU4/-  nM     [        S
 U 5       5      (       d  [         R                  " XSSS9n [        S U 5       5      (       d  [         R                  " XSSS9n[!        T5       VVs/ s H  u  nnUU-   PM     nnnU Vs/ s H  nUS-   PM
     nn[#        U
5      n[#        U5      n[!        U5       H.  u  nnUR%                  UX   5        UR%                  UX   5        M0     U R&                  " U6 n UR&                  " U6 nT Vs/ s H  oXU   PM	     nn[)        XUUSS9n[        TUU5       H  u  nnnU	U   nUc  M  [         R*                  " UU* /U5      u  nn[         R*                  " US/U5      S   n[         R*                  " UU/U5      S   n[         R*                  " US/U5      S   nUU-  nM     [        UR                  5       Vs/ s HA  oUU;  d  M
  UU;  a  UR                  U   O!UR                  U   UR                  US-
     -  PMC     n nUR&                  " U 6 n[-        U V!s/ s H  n![/        U!5      PM     sn!5      n"UU"   n[        UT#T$UT5      $ s  snf s  snnf s  snf s  snf s  snf s  sn!f )a	  Convolve two N-dimensional arrays using the overlap-add method.

Convolve `in1` and `in2` using the overlap-add method, with
the output size determined by the `mode` argument.

This is generally much faster than `convolve` for large arrays (n > ~500),
and generally much faster than `fftconvolve` when one array is much
larger than the other, but can be slower when only a few output values are
needed or when the arrays are very similar in shape, and can only
output float arrays (int or object array inputs will be cast to float).

Parameters
----------
in1 : array_like
    First input.
in2 : array_like
    Second input. Should have the same number of dimensions as `in1`.
mode : str {'full', 'valid', 'same'}, optional
    A string indicating the size of the output:

    ``full``
       The output is the full discrete linear convolution
       of the inputs. (Default)
    ``valid``
       The output consists only of those elements that do not
       rely on the zero-padding. In 'valid' mode, either `in1` or `in2`
       must be at least as large as the other in every dimension.
    ``same``
       The output is the same size as `in1`, centered
       with respect to the 'full' output.
axes : int or array_like of ints or None, optional
    Axes over which to compute the convolution.
    The default is over all axes.

Returns
-------
out : array
    An N-dimensional array containing a subset of the discrete linear
    convolution of `in1` with `in2`.

See Also
--------
convolve : Uses the direct convolution or FFT convolution algorithm
           depending on which is faster.
fftconvolve : An implementation of convolution using FFT.

Notes
-----
.. versionadded:: 1.4.0

References
----------
.. [1] Wikipedia, "Overlap-add_method".
       https://en.wikipedia.org/wiki/Overlap-add_method
.. [2] Richard G. Lyons. Understanding Digital Signal Processing,
       Third Edition, 2011. Chapter 13.10.
       ISBN 13: 978-0137-02741-5

Examples
--------
Convolve a 100,000 sample signal with a 512-sample filter.

>>> import numpy as np
>>> from scipy import signal
>>> rng = np.random.default_rng()
>>> sig = rng.standard_normal(100000)
>>> filt = signal.firwin(512, 0.01)
>>> fsig = signal.oaconvolve(sig, filt)

>>> import matplotlib.pyplot as plt
>>> fig, (ax_orig, ax_mag) = plt.subplots(2, 1)
>>> ax_orig.plot(sig)
>>> ax_orig.set_title('White noise')
>>> ax_mag.plot(fsig)
>>> ax_mag.set_title('Filtered noise')
>>> fig.tight_layout()
>>> fig.show()

r   r   )rP   ri   Tr   Nr   c              3  l   >#    U  H)  nUT;  a  S S TU   TU   4O[        TU   TU   5      v   M+     g7fr   N)r   )r]   r^   ri   r   r   s     rR   ra   oaconvolve.<locals>.<genexpr>  sG      K:IQ 01}b"beRU+"2a5"Q%01:Is   14r   r   c              3  *   #    U  H	  oS :H  v   M     g7fr   Nr[   r]   curpads     rR   ra   r          8iFi   constant)rP   constant_valuesc              3  *   #    U  H	  oS :H  v   M     g7fr   r[   r   s     rR   ra   r     r   r   Fr   r   )rt   ru   r   rO   r   r   r   r#   r   r   rf   r   r   r   rh   rE   	enumeratelistinsertreshaper   splitr   r   )%r   r   rP   ri   r   r^   shape_finaloptimal_sizesr   overlapsr   r   nsteps1nsteps2	pad_size1	pad_size2	curnstep1curpad1	curnstep2curpad2iax
split_axesfft_axesreshape_size1reshape_size2	fft_shapeaxax_fftax_splitr   overpartret_overpart	shape_retisliceslice_finalr   r   s%      `                               @@rR   r$   r$   +  sT   ` **S/C
**S/C
xx388 q y !	SXX	JKK	Q#((a-xx|	cii	3$T::)#D$6:<NCd 
B	BiRT488 /4CHHo?.= D=4a52a5=1$%.=  ?K:?/KM !-0J 2~(b.3$T:: GGII388_D=&!I&!Ia58;		2a57HK"78I+Y6GQ	+be3GIGa58;		2a57HK"78I+Y6GQ	+be3GIGI;I;q'l^#	q'l^#	; B 8i888ffS*aH8i888ffS*aH '0o6oFAs#a%oJ6!+,#AH, NMNMJ'3S'*-S'*- ( ++}
%C
++}
%C )--1AI-
Ch	
OC !$D(J ?FH2,?xj&9X88HrdH5a8xxgY7:xxqc8<Q?  !@  /B)Qj-@-(!211cii!n,-)  B ++y
!C [A[6v[ABK
k
CCRt44M?z 7, ."B Bs*   / S6:S;TT$	T1;TTc                    [        U [        R                  5      (       a  U R                  R                  U;   $ U  H  nUR                  R                  U;  d  M    g   g)a:  
See if a list of arrays are all numeric.

Parameters
----------
arrays : array or list of arrays
    arrays to check if numeric.
kinds : string-like
    The dtypes of the arrays to be checked. If the dtype.kind of
    the ndarrays are not in this string the function returns False and
    otherwise returns True.
FT)
isinstancert   ndarrayrv   r   )arrayskindsarray_s      rR   _numeric_arraysr    sN     &"**%%||  E))<<E)  rm   c                ~   US:X  a%  [        X5       VVs/ s H  u  p4X4-   S-
  PM     nnnOKUS:X  a.  [        X5       VVs/ s H  u  p4[        X4-
  5      S-   PM     nnnOUS:X  a  U nO[        SU 35      eXpv[        U 5      S:X  aW  US   US   pvUS:X  a  Xg-  nOUS:X  a  Xv:  a
  Xv-
  S-   U-  O	Xg-
  S-   U-  nOUS:X  a  Xg:  a  Xg-  OXg-  US-  US-   S-  -  -
  nOUS:X  a+  [	        [        U5      [        U5      5      [        U5      -  nONUS:X  a+  [	        [        U5      [        U5      5      [        U5      -  nOUS:X  a  [        U5      [        U5      -  n[        X5       VVs/ s H  u  p4X4-   S-
  PM     n	nn[        U	5      n
SU
-  [        R                  " U
5      -  nUW4$ s  snnf s  snnf s  snnf )	a]  
Find the number of operations required for direct/fft methods of
convolution. The direct operations were recorded by making a dummy class to
record the number of operations by overriding ``__mul__`` and ``__add__``.
The FFT operations rely on the (well-known) computational complexity of the
FFT (and the implementation of ``_freq_domain_conv``).

rB   r   r@   rA   z?Acceptable mode flags are 'valid', 'same', or 'full', not mode=r   r?   rp   )r   absrO   rg   min_prodrt   log)x_shapeh_shaperP   nr   	out_shaper   r   
direct_opsfull_out_shapeNfft_opss               rR   	_conv_opsr*    s    v~+.w+@A+@41QUQY+@	A		03G0EF0ESZ!^0E	F			 99=@ A 	A 
7|qA1B6>JW_/1x"'A++bgkR=OJV^%'W"''R1W"q&Q$??  6>U2Yb	2U95EEJW_U2Yb	2U95EEJV^rU2Y.J,/,AB,ADAaeai,ANBnA!ebffQiGJ= BF2 Cs   F- F3,F9c                *   [        U R                  UR                  U5      u  p4U R                  S:X  a  SOSnU R                  S:X  a+  SSU4SSU4UR                  U R                  ::  a  SS	U4OS
S.OSSU4SSU4SSU4S.nXb   u  pxn	Xs-  X-  U	-   :  $ )an  
See if using fftconvolve or convolve is faster.

Parameters
----------
x : np.ndarray
    Signal
h : np.ndarray
    Kernel
mode : str
    Mode passed to convolve

Returns
-------
fft_faster : bool

Notes
-----
See docstring of `choose_conv_method` for details on tuning hardware.

See pull request 11031 for more detail:
https://github.com/scipy/scipy/pull/11031.

r   gMbPg-C6g^]B> >g
"]=g{$R>gen=gr0 <,>gg=)gd[֠+>g@jHI>gh㈵)r@   rB   rA   g.w'>gvlV>gG[*!>gʑQ>gVN+!>g4RP>)r*  r   r   r   )
xhrP   r)  r&  offset	constantsO_fftO_directO_offsets
             rR   _fftconv_fasterr3  ;  s    2 $AGGQWWd;GffkUuF 
1 $]F;!=&9vv "=&95 !*f5V4V4  !*EX?X2X===rm   c                \    [        SSS5      4U R                  -  nX   R                  5       $ )zG
Reverse array `x` in all dimensions and perform the complex conjugate
Nr   )r   r   r   )r,  reverses     rR   r   r   e  s-     T4$&/G:??rm   c                    U R                   UR                   s=:X  a  S:X  a*  O  gUS;   a  gUS:X  a  U R                  UR                  :  $ gg)a)  
See if numpy supports convolution of `volume` and `kernel` (i.e. both are
1D ndarrays and of the appropriate shape).  NumPy's 'same' mode uses the
size of the larger input, while SciPy's uses the size of the first input.

Invalid mode strings will return False and be caught by the calling func.
r   )rB   r@   TrA   FN)r   r   )volumekernelrP   s      rR   r   r   m  sP     {{fkk&Q&  $$V^;;&++--  rm   c                    [         R                  " X5      nSn[        SS5       H!  nSU-  nUR                  U5      nUS:  d  M!    O   US:  a  UnO!WS-  nUR                  X&5      n[	        U5      nUW-  n	U	$ )a  
Returns the time the statement/function took, in seconds.

Faster, less precise version of IPython's timeit. `stmt` can be a statement
written as a string or a callable.

Will do only 1 loop (like IPython's timeit) with no repetitions
(unlike IPython) for very slow functions.  For fast functions, only does
enough loops to take 5 ms, which seems to produce similar results (on
Windows at least), and avoids doing an extraneous cycle that isn't
measured.

r   
   gMb@?r   )timeitTimerrf   repeatr  )
stmtsetupr=  timerr,  pnumberbestrsecs
             rR   _timeit_fastrF  ~  s     LL%E 	
A1b\QLL 	>	 
 	1u"LL(1v
-CJrm   c           
     <  ^^^	^
 [         R                  " U 5      m
[         R                  " U5      m[        T
S5        [        TS5        U(       a3  0 nS H  m	[        UU	UU
4S j5      UT	'   M     US   US   :  a  SOSnXT4$ [	        T
T4 Vs/ s H  n[        U/SS9PM     sn5      (       a  [        [         R                  " T
5      R                  5       5      [        [         R                  " T5      R                  5       5      -  nU[        [        T
R                  TR                  5      5      -  nUS[         R                  " S	5      R                  -  S
-
  :  a  g[        T
T/SS9(       a  g[        T
T/5      (       a  [        T
TT5      (       a  ggs  snf )as  
Find the fastest convolution/correlation method.

This primarily exists to be called during the ``method='auto'`` option in
`convolve` and `correlate`. It can also be used to determine the value of
``method`` for many different convolutions of the same dtype/shape.
In addition, it supports timing the convolution to adapt the value of
``method`` to a particular set of inputs and/or hardware.

Parameters
----------
in1 : array_like
    The first argument passed into the convolution function.
in2 : array_like
    The second argument passed into the convolution function.
mode : str {'full', 'valid', 'same'}, optional
    A string indicating the size of the output:

    ``full``
       The output is the full discrete linear convolution
       of the inputs. (Default)
    ``valid``
       The output consists only of those elements that do not
       rely on the zero-padding.
    ``same``
       The output is the same size as `in1`, centered
       with respect to the 'full' output.
measure : bool, optional
    If True, run and time the convolution of `in1` and `in2` with both
    methods and return the fastest. If False (default), predict the fastest
    method using precomputed values.

Returns
-------
method : str
    A string indicating which convolution method is fastest, either
    'direct' or 'fft'
times : dict, optional
    A dictionary containing the times (in seconds) needed for each method.
    This value is only returned if ``measure=True``.

See Also
--------
convolve
correlate

Notes
-----
Generally, this method is 99% accurate for 2D signals and 85% accurate
for 1D signals for randomly chosen input sizes. For precision, use
``measure=True`` to find the fastest method by timing the convolution.
This can be used to avoid the minimal overhead of finding the fastest
``method`` later, or to adapt the value of ``method`` to a particular set
of inputs.

Experiments were run on an Amazon EC2 r5a.2xlarge machine to test this
function. These experiments measured the ratio between the time required
when using ``method='auto'`` and the time required for the fastest method
(i.e., ``ratio = time_auto / min(time_fft, time_direct)``). In these
experiments, we found:

* There is a 95% chance of this ratio being less than 1.5 for 1D signals
  and a 99% chance of being less than 2.5 for 2D signals.
* The ratio was always less than 2.5/5 for 1D/2D signals respectively.
* This function is most inaccurate for 1D convolutions that take between 1
  and 10 milliseconds with ``method='direct'``. A good proxy for this
  (at least in our experiments) is ``1e6 <= in1.size * in2.size <= 1e7``.

The 2D results almost certainly generalize to 3D/4D/etc because the
implementation is the same (the 1D implementation is different).

All the numbers above are specific to the EC2 machine. However, we did find
that this function generalizes fairly decently across hardware. The speed
tests were of similar quality (and even slightly better) than the same
tests performed on the machine to tune this function's numbers (a mid-2014
15-inch MacBook Pro with 16GB RAM and a 2.5GHz Intel i7 processor).

There are cases when `fftconvolve` supports the inputs but this function
returns `direct` (e.g., to protect against floating point integer
precision).

.. versionadded:: 0.19

Examples
--------
Estimate the fastest method for a given input:

>>> import numpy as np
>>> from scipy import signal
>>> rng = np.random.default_rng()
>>> img = rng.random((32, 32))
>>> filter = rng.random((8, 8))
>>> method = signal.choose_conv_method(img, filter, mode='same')
>>> method
'fft'

This can then be applied to other arrays of the same dtype and shape:

>>> img2 = rng.random((32, 32))
>>> filter2 = rng.random((8, 8))
>>> corr2 = signal.correlate(img2, filter2, mode='same', method=method)
>>> conv2 = signal.convolve(img2, filter2, mode='same', method=method)

The output of this function (``method``) works with `correlate` and
`convolve`.

r;   )r   r   c                    > [        TT TTS9$ )N)rP   r   )r!   )r8  r   rP   r7  s   rR   <lambda>$choose_conv_method.<locals>.<lambda>  s    &&.262Crm   r   r   ui)r  r?   floatr   b)rt   ru   r   rF  anyr  intr  r   r  r   finfonmantr3  )r   r   rP   measuretimeschosen_methodr,  	max_valuer8  r   r7  s     `     @@@rR   r;   r;     s_   X ZZ_FZZ_FF01F01'F( *C DE&M ( "'uh!?X##
 vv6FG6FOQCt,6FGHHv**,-BFF6N4F4F4H0II	SV[[&++677	q"((7+111A55's3'((66400 Hs   Fc                   [         R                  " U 5      n[         R                  " U5      n[        US5        [        US5        UR                  UR                  s=:X  a
  S:X  a   XE-  $   UR                  UR                  :w  a  [	        S5      e[        X$R                  UR                  5      (       a  XTpTUS:X  a
  [        XEUS9nUS:X  a  [        XEUS9n[         R                  " XE5      nUR                  S;   a  [         R                  " U5      n[         R                  " UR                  S   5      (       d(  [         R                  " UR                  S   5      (       a  [        R                   " S["        S	S
9  UR%                  U5      $ US:X  a?  ['        XEU5      (       a  [         R(                  " XEU5      $ [+        U[-        U5      US5      $ [	        S5      e)az  
Convolve two N-dimensional arrays.

Convolve `in1` and `in2`, with the output size determined by the
`mode` argument.

Parameters
----------
in1 : array_like
    First input.
in2 : array_like
    Second input. Should have the same number of dimensions as `in1`.
mode : str {'full', 'valid', 'same'}, optional
    A string indicating the size of the output:

    ``full``
       The output is the full discrete linear convolution
       of the inputs. (Default)
    ``valid``
       The output consists only of those elements that do not
       rely on the zero-padding. In 'valid' mode, either `in1` or `in2`
       must be at least as large as the other in every dimension.
    ``same``
       The output is the same size as `in1`, centered
       with respect to the 'full' output.
method : str {'auto', 'direct', 'fft'}, optional
    A string indicating which method to use to calculate the convolution.

    ``direct``
       The convolution is determined directly from sums, the definition of
       convolution.
    ``fft``
       The Fourier Transform is used to perform the convolution by calling
       `fftconvolve`.
    ``auto``
       Automatically chooses direct or Fourier method based on an estimate
       of which is faster (default).  See Notes for more detail.

       .. versionadded:: 0.19.0

Returns
-------
convolve : array
    An N-dimensional array containing a subset of the discrete linear
    convolution of `in1` with `in2`.

Warns
-----
RuntimeWarning
    Use of the FFT convolution on input containing NAN or INF will lead
    to the entire output being NAN or INF. Use method='direct' when your
    input contains NAN or INF values.

See Also
--------
numpy.polymul : performs polynomial multiplication (same operation, but
                also accepts poly1d objects)
choose_conv_method : chooses the fastest appropriate convolution method
fftconvolve : Always uses the FFT method.
oaconvolve : Uses the overlap-add method to do convolution, which is
             generally faster when the input arrays are large and
             significantly different in size.

Notes
-----
By default, `convolve` and `correlate` use ``method='auto'``, which calls
`choose_conv_method` to choose the fastest method using pre-computed
values (`choose_conv_method` can also measure real-world timing with a
keyword argument). Because `fftconvolve` relies on floating point numbers,
there are certain constraints that may force ``method='direct'`` (more detail
in `choose_conv_method` docstring).

Examples
--------
Smooth a square pulse using a Hann window:

>>> import numpy as np
>>> from scipy import signal
>>> sig = np.repeat([0., 1., 0.], 100)
>>> win = signal.windows.hann(50)
>>> filtered = signal.convolve(sig, win, mode='same') / sum(win)

>>> import matplotlib.pyplot as plt
>>> fig, (ax_orig, ax_win, ax_filt) = plt.subplots(3, 1, sharex=True)
>>> ax_orig.plot(sig)
>>> ax_orig.set_title('Original pulse')
>>> ax_orig.margins(0, 0.1)
>>> ax_win.plot(win)
>>> ax_win.set_title('Filter impulse response')
>>> ax_win.margins(0, 0.1)
>>> ax_filt.plot(filtered)
>>> ax_filt.set_title('Filtered signal')
>>> ax_filt.margins(0, 0.1)
>>> fig.tight_layout()
>>> fig.show()

r   r   z5volume and kernel should have the same dimensionalityr   rP   r   >   r^   uzuUse of fft convolution on input with NAN or inf results in NAN or inf output. Consider using method='direct' instead.r?   rq   r   r   )rt   ru   r   r   rO   rl   r   r;   r#   result_typer   aroundisnanflatisinfr   r   RuntimeWarningastyper   r!   r   r   )r   r   rP   r   r7  r8  r   rY  s           rR   r!   r!   /  s   D ZZ_FZZ_FFK(FK({{fkk&Q& '		# * + 	+ 4v||<<#F>&t4nnV4z)))C.C88CHHQK  BHHSXXa[$9$9MM 6 $2aA
 zz+&&	8	vt,,;;vt44!26!:D(KK 0 1 	1rm   c                   [         R                  " U5      nUR                   H  nUS-  S:w  d  M  [        S5      e   [         R                  " U 5      n [         R                  " U R
                  [         R                  5      (       dG  U R
                  [         R                  [         R                  4;   d  [        SU R
                   S35      e[        R                  " XUSS9nU$ )a  
Perform an order filter on an N-D array.

Perform an order filter on the array in. The domain argument acts as a
mask centered over each pixel. The non-zero elements of domain are
used to select elements surrounding each input pixel which are placed
in a list. The list is sorted, and the output for that pixel is the
element corresponding to rank in the sorted list.

Parameters
----------
a : ndarray
    The N-dimensional input array.
domain : array_like
    A mask array with the same number of dimensions as `a`.
    Each dimension should have an odd number of elements.
rank : int
    A non-negative integer which selects the element from the
    sorted list (0 corresponds to the smallest element, 1 is the
    next smallest element, etc.).

Returns
-------
out : ndarray
    The results of the order filter in an array with the same
    shape as `a`.

Examples
--------
>>> import numpy as np
>>> from scipy import signal
>>> x = np.arange(25).reshape(5, 5)
>>> domain = np.identity(3)
>>> x
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])
>>> signal.order_filter(x, domain, 0)
array([[  0,   0,   0,   0,   0],
       [  0,   0,   1,   2,   0],
       [  0,   5,   6,   7,   0],
       [  0,  10,  11,  12,   0],
       [  0,   0,   0,   0,   0]])
>>> signal.order_filter(x, domain, 2)
array([[  6,   7,   8,   9,   4],
       [ 11,  12,  13,  14,   9],
       [ 16,  17,  18,  19,  14],
       [ 21,  22,  23,  24,  19],
       [ 20,  21,  22,  23,  24]])

r?   r   zHEach dimension of domain argument should have an odd number of elements.ro   z! is not supported by order_filterr   )	footprintrP   )rt   ru   r   rO   rw   rv   rx   r{   r|   r   rank_filter)r   domainrankdimsizeresults        rR   r%   r%     s    l ZZF<<aKA F G G  
 	

1AMM!''2::..ww2::rzz226!''*KLMM  FLFMrm   c                8   [         R                  " U 5      n [         R                  " U R                  [         R                  5      (       dG  U R                  [         R
                  [         R                  4;   d  [        SU R                   S35      eUc  S/U R                  -  n[         R                  " U5      nUR                  S:X  a/  [         R                  " UR                  5       U R                  5      n[        U R                  5       H  nX   S-  S:w  d  M  [        S5      e   [        S [        XR                  5       5       5      (       a  [         R"                  " S	SS
9  [$        R&                  " U5      n[(        R*                  " XS-  USS9nU$ )ay  
Perform a median filter on an N-dimensional array.

Apply a median filter to the input array using a local window-size
given by `kernel_size`. The array will automatically be zero-padded.

Parameters
----------
volume : array_like
    An N-dimensional input array.
kernel_size : array_like, optional
    A scalar or an N-length list giving the size of the median filter
    window in each dimension.  Elements of `kernel_size` should be odd.
    If `kernel_size` is a scalar, then this scalar is used as the size in
    each dimension. Default size is 3 for each dimension.

Returns
-------
out : ndarray
    An array the same size as input containing the median filtered
    result.

Warns
-----
UserWarning
    If array size is smaller than kernel size along any dimension

See Also
--------
scipy.ndimage.median_filter
scipy.signal.medfilt2d

Notes
-----
The more general function `scipy.ndimage.median_filter` has a more
efficient implementation of a median filter and therefore runs much faster.

For 2-dimensional images with ``uint8``, ``float32`` or ``float64`` dtypes,
the specialised function `scipy.signal.medfilt2d` may be faster.

ro   z is not supported by medfiltrp   r[   r?   r   *Each element of kernel_size should be odd.c              3  .   #    U  H  u  pX:  v   M     g 7frZ   r[   )r]   r   ss      rR   ra   medfilt.<locals>.<genexpr>9  s     
<;TQ15;s   zBkernel_size exceeds volume extent: the volume will be zero-padded.)rs   r   )r   rP   )rt   
atleast_1drw   rv   rx   r{   r|   rO   r   ru   r   r=  itemrf   rN  r   r   r   r   r   r   rb  )r7  kernel_sizer   r   rf  s        rR   r&   r&     s=   T ]]6"FMM&,,

33||

BJJ776&,,/KLMMcFKK'**[)KBii 0 0 2FKK@6;;NQ1$IJJ   
<Sll;
<<< %!"	$ 99[!D  &02F Mrm   c                ~   [         R                  " U 5      n Uc  S/U R                  -  n[         R                  " U5      nUR                  S:X  a/  [         R                  " UR                  5       U R                  5      n[        R                  " U5      n[        U [         R                  " U5      S5      U-  n[        U S-  [         R                  " U5      S5      U-  US-  -
  nUc)  [         R                  " [         R                  " U5      SS9nX-
  nUSX%-  -
  -  nXd-  n[         R                  " XR:  XF5      nU$ )a"  
Perform a Wiener filter on an N-dimensional array.

Apply a Wiener filter to the N-dimensional array `im`.

Parameters
----------
im : ndarray
    An N-dimensional array.
mysize : int or array_like, optional
    A scalar or an N-length list giving the size of the Wiener filter
    window in each dimension.  Elements of mysize should be odd.
    If mysize is a scalar, then this scalar is used as the size
    in each dimension.
noise : float, optional
    The noise-power to use. If None, then noise is estimated as the
    average of the local variance of the input.

Returns
-------
out : ndarray
    Wiener filtered result with the same shape as `im`.

Notes
-----
This implementation is similar to wiener2 in Matlab/Octave.
For more details see [1]_

References
----------
.. [1] Lim, Jae S., Two-Dimensional Signal and Image Processing,
       Englewood Cliffs, NJ, Prentice Hall, 1990, p. 548.

Examples
--------
>>> from scipy.datasets import face
>>> from scipy.signal import wiener
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> rng = np.random.default_rng()
>>> img = rng.random((40, 40))    #Create a random image
>>> filtered_img = wiener(img, (5, 5))  #Filter the image
>>> f, (plot1, plot2) = plt.subplots(1, 2)
>>> plot1.imshow(img)
>>> plot2.imshow(filtered_img)
>>> plt.show()

rp   r[   rA   r?   r   axisr   )rt   ru   r   r   r=  rm  r   r   r   onesmeanravelwhere)immysizenoiser   lMeanlVarresr   s           rR   r(   r(   E  s   b 
BB~rwwZZF||r6;;="''2 99VDb"''&/62T9E bAgrwwv7$>!KD }Q/:CACLC
((4<
,CJrm   c                f   [         R                  " U 5      n [         R                  " U5      nU R                  UR                  s=:X  a  S:X  d  O  [        S5      e[	        X R
                  UR
                  5      (       a  Xp[        U5      n[        U5      n[        R                  " XSXVU5      nU$ )ab	  
Convolve two 2-dimensional arrays.

Convolve `in1` and `in2` with output size determined by `mode`, and
boundary conditions determined by `boundary` and `fillvalue`.

Parameters
----------
in1 : array_like
    First input.
in2 : array_like
    Second input. Should have the same number of dimensions as `in1`.
mode : str {'full', 'valid', 'same'}, optional
    A string indicating the size of the output:

    ``full``
       The output is the full discrete linear convolution
       of the inputs. (Default)
    ``valid``
       The output consists only of those elements that do not
       rely on the zero-padding. In 'valid' mode, either `in1` or `in2`
       must be at least as large as the other in every dimension.
    ``same``
       The output is the same size as `in1`, centered
       with respect to the 'full' output.
boundary : str {'fill', 'wrap', 'symm'}, optional
    A flag indicating how to handle boundaries:

    ``fill``
       pad input arrays with fillvalue. (default)
    ``wrap``
       circular boundary conditions.
    ``symm``
       symmetrical boundary conditions.

fillvalue : scalar, optional
    Value to fill pad input arrays with. Default is 0.

Returns
-------
out : ndarray
    A 2-dimensional array containing a subset of the discrete linear
    convolution of `in1` with `in2`.

Examples
--------
Compute the gradient of an image by 2D convolution with a complex Scharr
operator.  (Horizontal operator is real, vertical is imaginary.)  Use
symmetric boundary condition to avoid creating edges at the image
boundaries.

>>> import numpy as np
>>> from scipy import signal
>>> from scipy import datasets
>>> ascent = datasets.ascent()
>>> scharr = np.array([[ -3-3j, 0-10j,  +3 -3j],
...                    [-10+0j, 0+ 0j, +10 +0j],
...                    [ -3+3j, 0+10j,  +3 +3j]]) # Gx + j*Gy
>>> grad = signal.convolve2d(ascent, scharr, boundary='symm', mode='same')

>>> import matplotlib.pyplot as plt
>>> fig, (ax_orig, ax_mag, ax_ang) = plt.subplots(3, 1, figsize=(6, 15))
>>> ax_orig.imshow(ascent, cmap='gray')
>>> ax_orig.set_title('Original')
>>> ax_orig.set_axis_off()
>>> ax_mag.imshow(np.absolute(grad), cmap='gray')
>>> ax_mag.set_title('Gradient magnitude')
>>> ax_mag.set_axis_off()
>>> ax_ang.imshow(np.angle(grad), cmap='hsv') # hsv is cyclic, like angles
>>> ax_ang.set_title('Gradient orientation')
>>> ax_ang.set_axis_off()
>>> fig.show()

r?   z)convolve2d inputs must both be 2-D arraysr   )
rt   ru   r   rO   rl   r   rS   rW   r	   _convolve2d)r   r   rP   rV   	fillvaluer   bvalr   s           rR   r"   r"     s    V **S/C
**S/C88sxx$1$DEE4CII66S
t
CX&D


!S	
BCJrm   c                   [         R                  " U 5      n [         R                  " U5      nU R                  UR                  s=:X  a  S:X  d  O  [        S5      e[	        X R
                  UR
                  5      nU(       a  Xp[        U5      n[        U5      n[        R                  " XR                  5       SXgU5      nU(       a  USSS2SSS24   nU$ )a
  
Cross-correlate two 2-dimensional arrays.

Cross correlate `in1` and `in2` with output size determined by `mode`, and
boundary conditions determined by `boundary` and `fillvalue`.

Parameters
----------
in1 : array_like
    First input.
in2 : array_like
    Second input. Should have the same number of dimensions as `in1`.
mode : str {'full', 'valid', 'same'}, optional
    A string indicating the size of the output:

    ``full``
       The output is the full discrete linear cross-correlation
       of the inputs. (Default)
    ``valid``
       The output consists only of those elements that do not
       rely on the zero-padding. In 'valid' mode, either `in1` or `in2`
       must be at least as large as the other in every dimension.
    ``same``
       The output is the same size as `in1`, centered
       with respect to the 'full' output.
boundary : str {'fill', 'wrap', 'symm'}, optional
    A flag indicating how to handle boundaries:

    ``fill``
       pad input arrays with fillvalue. (default)
    ``wrap``
       circular boundary conditions.
    ``symm``
       symmetrical boundary conditions.

fillvalue : scalar, optional
    Value to fill pad input arrays with. Default is 0.

Returns
-------
correlate2d : ndarray
    A 2-dimensional array containing a subset of the discrete linear
    cross-correlation of `in1` with `in2`.

Notes
-----
When using "same" mode with even-length inputs, the outputs of `correlate`
and `correlate2d` differ: There is a 1-index offset between them.

Examples
--------
Use 2D cross-correlation to find the location of a template in a noisy
image:

>>> import numpy as np
>>> from scipy import signal, datasets, ndimage
>>> rng = np.random.default_rng()
>>> face = datasets.face(gray=True) - datasets.face(gray=True).mean()
>>> face = ndimage.zoom(face[30:500, 400:950], 0.5)  # extract the face
>>> template = np.copy(face[135:165, 140:175])  # right eye
>>> template -= template.mean()
>>> face = face + rng.standard_normal(face.shape) * 50  # add noise
>>> corr = signal.correlate2d(face, template, boundary='symm', mode='same')
>>> y, x = np.unravel_index(np.argmax(corr), corr.shape)  # find the match

>>> import matplotlib.pyplot as plt
>>> fig, (ax_orig, ax_template, ax_corr) = plt.subplots(3, 1,
...                                                     figsize=(6, 15))
>>> ax_orig.imshow(face, cmap='gray')
>>> ax_orig.set_title('Original')
>>> ax_orig.set_axis_off()
>>> ax_template.imshow(template, cmap='gray')
>>> ax_template.set_title('Template')
>>> ax_template.set_axis_off()
>>> ax_corr.imshow(corr, cmap='gray')
>>> ax_corr.set_title('Cross-correlation')
>>> ax_corr.set_axis_off()
>>> ax_orig.plot(x, y, 'ro')
>>> fig.show()

r?   z*correlate2d inputs must both be 2-D arraysr   Nr   )rt   ru   r   rO   rl   r   rS   rW   r	   r}  r   )	r   r   rP   rV   r~  r   r   r  r   s	            rR   r    r      s    d **S/C
**S/C88sxx$1$EFF(yy#))DNS
t
CX&D


XXZCy
IC$B$"*oJrm   c                   [         R                  " U 5      nUR                  R                  [         R                  [         R
                  [         R                  4;  a  [        X!5      $ Uc  S/S-  n[         R                  " U5      nUR                  S:X  a%  [         R                  " UR                  5       S5      nU H  nUS-  S:w  d  M  [        S5      e   [        R                  " X!5      $ )a  
Median filter a 2-dimensional array.

Apply a median filter to the `input` array using a local window-size
given by `kernel_size` (must be odd). The array is zero-padded
automatically.

Parameters
----------
input : array_like
    A 2-dimensional input array.
kernel_size : array_like, optional
    A scalar or a list of length 2, giving the size of the
    median filter window in each dimension.  Elements of
    `kernel_size` should be odd.  If `kernel_size` is a scalar,
    then this scalar is used as the size in each dimension.
    Default is a kernel of size (3, 3).

Returns
-------
out : ndarray
    An array the same size as input containing the median filtered
    result.

See Also
--------
scipy.ndimage.median_filter

Notes
-----
This is faster than `medfilt` when the input dtype is ``uint8``,
``float32``, or ``float64``; for other types, this falls back to
`medfilt`. In some situations, `scipy.ndimage.median_filter` may be
faster than this function.

Examples
--------
>>> import numpy as np
>>> from scipy import signal
>>> x = np.arange(25).reshape(5, 5)
>>> x
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])

# Replaces i,j with the median out of 5*5 window

>>> signal.medfilt2d(x, kernel_size=5)
array([[ 0,  0,  2,  0,  0],
       [ 0,  3,  7,  4,  0],
       [ 2,  8, 12,  9,  4],
       [ 0,  8, 12,  9,  0],
       [ 0,  0, 12,  0,  0]])

# Replaces i,j with the median out of default 3*3 window

>>> signal.medfilt2d(x)
array([[ 0,  1,  2,  3,  0],
       [ 1,  6,  7,  8,  4],
       [ 6, 11, 12, 13,  9],
       [11, 16, 17, 18, 14],
       [ 0, 16, 17, 18,  0]])

# Replaces i,j with the median out of default 5*3 window

>>> signal.medfilt2d(x, kernel_size=[5,3])
array([[ 0,  1,  2,  3,  0],
       [ 0,  6,  7,  8,  3],
       [ 5, 11, 12, 13,  8],
       [ 5, 11, 12, 13,  8],
       [ 0, 11, 12, 13,  0]])

# Replaces i,j with the median out of default 3*5 window

>>> signal.medfilt2d(x, kernel_size=[3,5])
array([[ 0,  0,  2,  1,  0],
       [ 1,  5,  7,  6,  3],
       [ 6, 10, 12, 11,  8],
       [11, 15, 17, 16, 13],
       [ 0, 15, 17, 16,  0]])

# As seen in the examples,
# kernel numbers must be odd and not exceed original array dim

rp   r?   r[   r   rh  )rt   ru   rv   typeubyter{   r|   r&   r   r=  rm  rO   r	   
_medfilt2d)inputrn  imager   s       rR   r'   r'   P  s    p JJuE {{"**bjjAAu**cAg**[)KBii 0 0 2A61H?IJJ  33rm   r   c                  ^  [         R                  " T 5      m [         R                  " U5      n[        US5        [        US5        [        T S5        [        U5      S:X  GaK  [         R                  " T 5      m [         R                  " U5      nT R
                  S:w  a  UR
                  S:w  a  [        S5      e[        U5      nT X/nUGb  [         R                  " U5      nUR
                  UR
                  :w  a  [        S5      e[        UR                  5      nT R                  S   S-
  Xc'   [        U5      nUR                  U:w  a  UR
                  S/-  nUS:  a  X4R
                  -  n[        UR
                  5       H  nX:X  a(  UR                  U   Xh   :X  a  UR                  U   Xx'   M0  X:w  a(  UR                  U   Xh   :X  a  UR                  U   Xx'   M]  X:w  a  UR                  U   S:X  a  SXx'   M{  [        SU SUR                   S35      e   [         R                  R                  R                  XFU5      nUR!                  U5        [         R"                  " U6 n	U	R$                  S	;  a  ['        S
U	 S35      e[         R(                  " T U	S9m [         R                  " XS9nT US   -  m [         R                  " X)S9n[         R*                  " U 4S jX25      n
U
R
                  [-        S5      /-  nUb0  [-        UR                  U   5      X'   U
[        U5      ==   U-  ss'   [-        U
R                  U   [        T 5      -
  S-   5      X'   U
[        U5         nUc  U$ [-        U
R                  U   [        T 5      -
  S-   S5      X'   U
[        U5         nX4$ Uc  [.        R0                  " T XU5      $ [.        R0                  " T XX45      $ )a  
Filter data along one-dimension with an IIR or FIR filter.

Filter a data sequence, `x`, using a digital filter.  This works for many
fundamental data types (including Object type).  The filter is a direct
form II transposed implementation of the standard difference equation
(see Notes).

The function `sosfilt` (and filter design using ``output='sos'``) should be
preferred over `lfilter` for most filtering tasks, as second-order sections
have fewer numerical problems.

Parameters
----------
b : array_like
    The numerator coefficient vector in a 1-D sequence.
a : array_like
    The denominator coefficient vector in a 1-D sequence.  If ``a[0]``
    is not 1, then both `a` and `b` are normalized by ``a[0]``.
x : array_like
    An N-dimensional input array.
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.
zi : array_like, optional
    Initial conditions for the filter delays.  It is a vector
    (or array of vectors for an N-dimensional input) of length
    ``max(len(a), len(b)) - 1``.  If `zi` is None or is not given then
    initial rest is assumed.  See `lfiltic` for more information.

Returns
-------
y : array
    The output of the digital filter.
zf : array, optional
    If `zi` is None, this is not returned, otherwise, `zf` holds the
    final filter delay values.

See Also
--------
lfiltic : Construct initial conditions for `lfilter`.
lfilter_zi : Compute initial state (steady state of step response) for
             `lfilter`.
filtfilt : A forward-backward filter, to obtain a filter with zero phase.
savgol_filter : A Savitzky-Golay filter.
sosfilt: Filter data using cascaded second-order sections.
sosfiltfilt: A forward-backward filter using second-order sections.

Notes
-----
The filter function is implemented as a direct II transposed structure.
This means that the filter implements::

   a[0]*y[n] = b[0]*x[n] + b[1]*x[n-1] + ... + b[M]*x[n-M]
                         - a[1]*y[n-1] - ... - a[N]*y[n-N]

where `M` is the degree of the numerator, `N` is the degree of the
denominator, and `n` is the sample number.  It is implemented using
the following difference equations (assuming M = N)::

     a[0]*y[n] = b[0] * x[n]               + d[0][n-1]
       d[0][n] = b[1] * x[n] - a[1] * y[n] + d[1][n-1]
       d[1][n] = b[2] * x[n] - a[2] * y[n] + d[2][n-1]
     ...
     d[N-2][n] = b[N-1]*x[n] - a[N-1]*y[n] + d[N-1][n-1]
     d[N-1][n] = b[N] * x[n] - a[N] * y[n]

where `d` are the state variables.

The rational transfer function describing this filter in the
z-transform domain is::

                         -1              -M
             b[0] + b[1]z  + ... + b[M] z
     Y(z) = -------------------------------- X(z)
                         -1              -N
             a[0] + a[1]z  + ... + a[N] z

Examples
--------
Generate a noisy signal to be filtered:

>>> import numpy as np
>>> from scipy import signal
>>> import matplotlib.pyplot as plt
>>> rng = np.random.default_rng()
>>> t = np.linspace(-1, 1, 201)
>>> x = (np.sin(2*np.pi*0.75*t*(1-t) + 2.1) +
...      0.1*np.sin(2*np.pi*1.25*t + 1) +
...      0.18*np.cos(2*np.pi*3.85*t))
>>> xn = x + rng.standard_normal(len(t)) * 0.08

Create an order 3 lowpass butterworth filter:

>>> b, a = signal.butter(3, 0.05)

Apply the filter to xn.  Use lfilter_zi to choose the initial condition of
the filter:

>>> zi = signal.lfilter_zi(b, a)
>>> z, _ = signal.lfilter(b, a, xn, zi=zi*xn[0])

Apply the filter again, to have a result filtered at an order the same as
filtfilt:

>>> z2, _ = signal.lfilter(b, a, z, zi=zi*z[0])

Use filtfilt to apply the filter:

>>> y = signal.filtfilt(b, a, xn)

Plot the original signal and the various filtered versions:

>>> plt.figure
>>> plt.plot(t, xn, 'b', alpha=0.75)
>>> plt.plot(t, z, 'r--', t, z2, 'r', t, y, 'k')
>>> plt.legend(('noisy signal', 'lfilter, once', 'lfilter, twice',
...             'filtfilt'), loc='best')
>>> plt.grid(True)
>>> plt.show()

r)   r   z+object of too small depth for desired arrayNr   z"Unexpected shape for zi: expected z, found .fdgFDGOinput type '' not supportedrv   c                2   > [         R                  " TU 5      $ rZ   )rt   r!   )yrM  s    rR   rI  lfilter.<locals>.<lambda>n  s    Q1Brm   )rt   rl  r   rg   ru   r   rO   _validate_xr   r   r   rf   strideslibstride_tricks
as_stridedappendrY  charNotImplementedErrorr   apply_along_axisr   r	   _linear_filter)rM  r   r,  rq  ziinputsexpected_shaper  r   rv   out_fullindr   zfs   `             rR   r)   r)     sR   x 	aA
aAAy!Ay!Ay!
1v{ JJqMJJqM66Q;166Q;JKKNQ> BBww!&&  !NOO!!'']N#$771:>N ">2Nxx>)''TF*!8GGODrwwAyRXXa[N4E%E%'ZZ]
rxx{n6G'G%'ZZ]
rxx{a'7%&
()M,:+;8BHH:Q*P Q Q ( VV))44R5<>MM"'::Y&%UG?&KLLHHQe$JJq&	QqT	JJq&&&'BDLmmuT{m+>bhhtn-CIU3Z B& (...Q7!;<	uSz":JhnnT2SV;a?FCI%*%B7N:++AqT::++AqT>>rm   c                   [         R                  " U5      S-
  n[         R                  " U 5      S-
  n[        XT5      n[         R                  " U5      nUcu  [         R                  " [         R                  " U 5      [         R                  " U5      U5      nUR
                  S;   a  [         R                  n[         R                  " XWS9nO[         R                  " U5      n[         R                  " [         R                  " U 5      [         R                  " U5      X#5      nUR
                  S;   a  [         R                  nUR                  U5      n[         R                  " U5      nX:  a+  [         R                  U[         R                  " XX-
  5      4   nUR                  U5      n[         R                  " Xg5      n	[         R                  " U5      nX:  a+  [         R                  U[         R                  " XH-
  5      4   n[        U5       H'  n
[         R                  " X
S-   S USXZ-
   -  SS9X'   M)     [        U5       H/  n
X==   [         R                  " XS-   S USXJ-
   -  SS9-  ss'   M1     U	$ )a  
Construct initial conditions for lfilter given input and output vectors.

Given a linear filter (b, a) and initial conditions on the output `y`
and the input `x`, return the initial conditions on the state vector zi
which is used by `lfilter` to generate the output given the input.

Parameters
----------
b : array_like
    Linear filter term.
a : array_like
    Linear filter term.
y : array_like
    Initial conditions.

    If ``N = len(a) - 1``, then ``y = {y[-1], y[-2], ..., y[-N]}``.

    If `y` is too short, it is padded with zeros.
x : array_like, optional
    Initial conditions.

    If ``M = len(b) - 1``, then ``x = {x[-1], x[-2], ..., x[-M]}``.

    If `x` is not given, its initial conditions are assumed zero.

    If `x` is too short, it is padded with zeros.

Returns
-------
zi : ndarray
    The state vector ``zi = {z_0[-1], z_1[-1], ..., z_K-1[-1]}``,
    where ``K = max(M, N)``.

See Also
--------
lfilter, lfilter_zi

r   Nbuir  r   rp  )rt   r   r   ru   rY  r   r|   r   r_  r_rf   sum)rM  r   r  r,  r(  MKrY  Lr  ms              rR   r*   r*     s   P 	
QA

QAA	A


1AynnRZZ]BJJqM1Eu$**KHHQ*JJqMnnRZZ]BJJqM1Hu$**KHH[!GGAJ5a!%()A	A	!	!B

AuEE!RXXae_$%1XqQy1Vae9,15  1X
a%&	AfquI-A66  Irm   c                   [         R                  " U 5      n[         R                  " U5      nUR                  S:  a  [        S5      eUR                  S:  a  [        S5      e[	        U5      n[	        U5      nXT:  a  / nUnXg4$ [         R
                  " XE-
  S-   [        5      nSUS'   [        X#U5      nU[        X6SS9-
  nXg4$ )a  Deconvolves ``divisor`` out of ``signal`` using inverse filtering.

Returns the quotient and remainder such that
``signal = convolve(divisor, quotient) + remainder``

Parameters
----------
signal : (N,) array_like
    Signal data, typically a recorded signal
divisor : (N,) array_like
    Divisor data, typically an impulse response or filter that was
    applied to the original signal

Returns
-------
quotient : ndarray
    Quotient, typically the recovered original signal
remainder : ndarray
    Remainder

See Also
--------
numpy.polydiv : performs polynomial division (same operation, but
                also accepts poly1d objects)

Examples
--------
Deconvolve a signal that's been filtered:

>>> from scipy import signal
>>> original = [0, 1, 0, 0, 1, 1, 0, 0]
>>> impulse_response = [2, 1]
>>> recorded = signal.convolve(impulse_response, original)
>>> recorded
array([0, 2, 1, 0, 2, 3, 1, 0, 0])
>>> recovered, remainder = signal.deconvolve(recorded, impulse_response)
>>> recovered
array([ 0.,  1.,  0.,  0.,  1.,  1.,  0.,  0.])

r   zsignal must be 1-D.zdivisor must be 1-D.r   rB   rW  )	rt   rl  r   rO   rg   r   rL  r)   r!   )	signaldivisornumdenr(  Dquotremr  s	            rR   r,   r,     s    R --
C
--
 C
xx!|.//
xx!|/00CACAu 9	 E*as'HSV449rm   c                F   [         R                  " U 5      n [         R                  " U 5      (       a  [        S5      eUc  U R                  U   nUS::  a  [        S5      e[
        R                  " XUS9n[         R                  " XR                  S9nUS-  S:X  a  S=US'   XAS-  '   SUSUS-  & OSUS'   SUSUS-   S-  & U R                  S:  a9  [         R                  /U R                  -  n[        S5      XR'   U[        U5         n[
        R                  " X4-  US9n U $ )	a  FFT-based computation of the analytic signal.

The analytic signal is calculated by filtering out the negative frequencies and
doubling the amplitudes of the positive frequencies in the FFT domain.
The imaginary part of the result is the hilbert transform of the real-valued input
signal.

The transformation is done along the last axis by default.

Parameters
----------
x : array_like
    Signal data.  Must be real.
N : int, optional
    Number of Fourier components.  Default: ``x.shape[axis]``
axis : int, optional
    Axis along which to do the transformation.  Default: -1.

Returns
-------
xa : ndarray
    Analytic signal of `x`, of each 1-D array along `axis`

Notes
-----
The analytic signal ``x_a(t)`` of a real-valued signal ``x(t)``
can be expressed as [1]_

.. math:: x_a = F^{-1}(F(x) 2U) = x + i y\ ,

where `F` is the Fourier transform, `U` the unit step function,
and `y` the Hilbert transform of `x`. [2]_

In other words, the negative half of the frequency spectrum is zeroed
out, turning the real-valued signal into a complex-valued signal.  The Hilbert
transformed signal can be obtained from ``np.imag(hilbert(x))``, and the
original signal from ``np.real(hilbert(x))``.

References
----------
.. [1] Wikipedia, "Analytic signal".
       https://en.wikipedia.org/wiki/Analytic_signal
.. [2] Wikipedia, "Hilbert Transform".
       https://en.wikipedia.org/wiki/Hilbert_transform
.. [3] Leon Cohen, "Time-Frequency Analysis", 1995. Chapter 2.
.. [4] Alan V. Oppenheim, Ronald W. Schafer. Discrete-Time Signal
       Processing, Third Edition, 2009. Chapter 12.
       ISBN 13: 978-1292-02572-8

See Also
--------
envelope: Compute envelope of a real- or complex-valued signal.

Examples
--------
In this example we use the Hilbert transform to determine the amplitude
envelope and instantaneous frequency of an amplitude-modulated signal.

Let's create a chirp of which the frequency increases from 20 Hz to 100 Hz and
apply an amplitude modulation:

>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from scipy.signal import hilbert, chirp
...
>>> duration, fs = 1, 400  # 1 s signal with sampling frequency of 400 Hz
>>> t = np.arange(int(fs*duration)) / fs  # timestamps of samples
>>> signal = chirp(t, 20.0, t[-1], 100.0)
>>> signal *= (1.0 + 0.5 * np.sin(2.0*np.pi*3.0*t) )

The amplitude envelope is given by the magnitude of the analytic signal. The
instantaneous frequency can be obtained by differentiating the
instantaneous phase in respect to time. The instantaneous phase corresponds
to the phase angle of the analytic signal.

>>> analytic_signal = hilbert(signal)
>>> amplitude_envelope = np.abs(analytic_signal)
>>> instantaneous_phase = np.unwrap(np.angle(analytic_signal))
>>> instantaneous_frequency = np.diff(instantaneous_phase) / (2.0*np.pi) * fs
...
>>> fig, (ax0, ax1) = plt.subplots(nrows=2, sharex='all', tight_layout=True)
>>> ax0.set_title("Amplitude-modulated Chirp Signal")
>>> ax0.set_ylabel("Amplitude")
>>> ax0.plot(t, signal, label='Signal')
>>> ax0.plot(t, amplitude_envelope, label='Envelope')
>>> ax0.legend()
>>> ax1.set(xlabel="Time in seconds", ylabel="Phase in rad", ylim=(0, 120))
>>> ax1.plot(t[1:], instantaneous_frequency, 'C2-', label='Instantaneous Phase')
>>> ax1.legend()
>>> plt.show()

x must be real.Nr   N must be positive.rp  r  r?   r   )rt   ru   iscomplexobjrO   r   r   r   r   rv   r   newaxisr   r   r   )r,  r(  rq  Xfr-  r  s         rR   r-   r-   	  s   z 	

1A	q*++yGGDMAv.//	At	$B
((#A1uz!qay!AF!!QUqLvvzzzlQVV#$K	eCjMBF&AHrm   c                   [         R                  " U 5      n U R                  S:  a  [        S5      e[         R                  " U 5      (       a  [        S5      eUc  U R
                  nOv[        U[        5      (       a  US::  a  [        S5      eX4nOL[        U5      S:w  d2  [         R                  " [         R                  " U5      S:*  5      (       a  [        S5      e[        R                  " XSS	9n[         R                  " US   UR                  S
9n[         R                  " US   UR                  S
9nX44 HA  nUR
                  S   nUS-  S:X  a  S=US'   XVS-  '   SUSUS-  & M1  SUS'   SUSUS-   S-  & MC     USS2[         R                  4   U[         R                  SS24   -  nU R                  nUS:  a$  USS2[         R                  4   nUS-  nUS:  a  M$  [        R                   " X%-  SS	9n U $ )a  
Compute the '2-D' analytic signal of `x`

Parameters
----------
x : array_like
    2-D signal data.
N : int or tuple of two ints, optional
    Number of Fourier components. Default is ``x.shape``

Returns
-------
xa : ndarray
    Analytic signal of `x` taken along axes (0,1).

References
----------
.. [1] Wikipedia, "Analytic signal",
    https://en.wikipedia.org/wiki/Analytic_signal

r?   zx must be 2-D.r  Nr   r  z@When given as a tuple, N must hold exactly two positive integers)r   r   r   r  r   )rt   
atleast_2dr   rO   r  r   r  rO  rg   rN  ru   r   fft2r   rv   r  ifft2)r,  r(  r  h1h2r-  N1r   s           rR   r.   r.   	  s   , 	aAvvz)**	q*++yGG	As		6233F	Q1rzz!}122 1 2 	2 
Q	'B	!A$bhh	'B	!A$bhh	'BXWWQZ6Q; !!AaD11W:AaaLAaD!"AaaA  	1bjj=Brzz1}--A	A
a%am	Q a% 	RV&)AHrm   lowpass)n_outsquaredresidualrq  c               "	   U R                   * Us=::  a  U R                   :  d   O  [        SU< SU R                  < S35      eU R                  U   S:  d  [        SU R                  < SU< S35      e[        U5      S:w  d  [	        S U 5       5      (       d  [        S	U< S
35      e[        U[        5      (       a  SU:  d  Ub  [        SU< S35      eUS;  a  [        SU< S35      eU R                  U   nUc  UOUnX&-  n[        US   b  US   OUS-  * US   b  US   OUS-   S-  5      nU* S-  UR                  s=::  a  UR                  s=:  a  US-   S-  ::  d&  O  [        SSU R                  U   < SU< S3-   5      e[        R                  " XS5      n [        R                  " U 5      (       a  [        R                  " U 5      n	O[        R                  " U [        R                   " U R"                  SS 5      R$                  S9n	[        R                   " U 5      U	SSUS-  S-   24'   UR                  S:  a  U	SU4==   S-  ss'   O+UR                  S:  a  U	SSUR                  24==   S-  ss'   UR                  Ss=::  a  UR                  :  d   O  [        R&                  " U	SU4   US9U-  n
O\[        UR                  US-  -   UR                  US-  -   5      n[        R&                  " [        R(                  " U	SS9SU4   US9U-  n
U(       d  [        R*                  " U
5      OU
R,                  S-  U
R.                  S-  -   n[        R                  " USU5      nUc  U$ UR                  Ss=::  a  UR                  :  d
  O  SU	SU4'   O'Su  U	SSUR                  24'   U	SUR                  S24'   US:X  aM  UR                  S:  a  SU	SUR                  US-   S-  24'   O#Su  U	SUR                  S24'   U	SSUS-   S-  24'   U[        R                  " U 5      (       a  [        R&                  " XS9O[        R0                  " XS9-  n[        R2                  " U[        R                  " USU5      4SS9$ )a,  Compute the envelope of a real- or complex-valued signal.

Parameters
----------
z : ndarray
    Real- or complex-valued input signal, which is assumed to be made up of ``n``
    samples and having sampling interval ``T``. `z` may also be a multidimensional
    array with the time axis being defined by `axis`.
bp_in : tuple[int | None, int | None], optional
    2-tuple defining the frequency band ``bp_in[0]:bp_in[1]`` of the input filter.
    The corner frequencies are specified as integer multiples of ``1/(n*T)`` with
    ``-n//2 <= bp_in[0] < bp_in[1] <= (n+1)//2`` being the allowed frequency range.
    ``None`` entries are replaced with ``-n//2`` or ``(n+1)//2`` respectively. The
    default of ``(1, None)`` removes the mean value as well as the negative
    frequency components.
n_out : int | None, optional
    If not ``None`` the output will be resampled to `n_out` samples. The default
    of ``None`` sets the output to the same length as the input `z`.
squared : bool, optional
    If set, the square of the envelope is returned. The bandwidth of the squared
    envelope is often smaller than the non-squared envelope bandwidth due to the
    nonlinear nature of the utilized absolute value function. I.e., the embedded
    square root function typically produces addiational harmonics.
    The default is ``False``.
residual : Literal['lowpass', 'all', None], optional
    This option determines what kind of residual, i.e., the signal part which the
    input bandpass filter removes, is returned. ``'all'`` returns everything except
    the contents of the frequency band ``bp_in[0]:bp_in[1]``, ``'lowpass'``
    returns the contents of the frequency band ``< bp_in[0]``. If ``None`` then
    only the envelope is returned. Default: ``'lowpass'``.
axis : int, optional
   Axis of `z` over which to compute the envelope. Default is last the axis.

Returns
-------
ndarray
    If parameter `residual` is ``None`` then an array ``z_env`` with the same shape
    as the input `z` is returned, containing its envelope. Otherwise, an array with
    shape ``(2, *z.shape)``, containing the arrays ``z_env`` and ``z_res``, stacked
    along the first axis, is returned.
    It allows unpacking, i.e., ``z_env, z_res = envelope(z, residual='all')``.
    The residual ``z_res`` contains the signal part which the input bandpass filter
    removed, depending on the parameter `residual`. Note that for real-valued
    signals, a real-valued residual is returned. Hence, the negative frequency
    components of `bp_in` are ignored.

Notes
-----
Any complex-valued signal :math:`z(t)` can be described by a real-valued
instantaneous amplitude :math:`a(t)` and a real-valued instantaneous phase
:math:`\phi(t)`, i.e., :math:`z(t) = a(t) \exp\!\big(j \phi(t)\big)`. The
envelope is defined as the absolute value of the amplitude :math:`|a(t)| = |z(t)|`,
which is at the same time the absolute value of the signal. Hence, :math:`|a(t)|`
"envelopes" the class of all signals with amplitude :math:`a(t)` and arbitrary
phase :math:`\phi(t)`.
For real-valued signals, :math:`x(t) = a(t) \cos\!\big(\phi(t)\big)` is the
analogous formulation. Hence, :math:`|a(t)|` can be determined by converting
:math:`x(t)` into an analytic signal :math:`z_a(t)` by means of a Hilbert
transform, i.e.,
:math:`z_a(t) = a(t) \cos\!\big(\phi(t)\big) + j a(t) \sin\!\big(\phi(t) \big)`,
which produces a complex-valued signal with the same envelope :math:`|a(t)|`.

The implementation is based on computing the FFT of the input signal and then
performing the necessary operations in Fourier space. Hence, the typical FFT
caveats need to be taken into account:

* The signal is assumed to be periodic. Discontinuities between signal start and
  end can lead to unwanted results due to Gibbs phenomenon.
* The FFT is slow if the signal length is prime or very long. Also, the memory
  demands are typically higher than a comparable FIR/IIR filter based
  implementation.
* The frequency spacing ``1 / (n*T)`` for corner frequencies of the bandpass filter
  corresponds to the frequencies produced by ``scipy.fft.fftfreq(len(z), T)``.

If the envelope of a complex-valued signal `z` with no bandpass filtering is
desired, i.e., ``bp_in=(None, None)``, then the envelope corresponds to the
absolute value. Hence, it is more efficient to use ``np.abs(z)`` instead of this
function.

Although computing the envelope based on the analytic signal [1]_ is the natural
method for real-valued signals, other methods are also frequently used. The most
popular alternative is probably the so-called "square-law" envelope detector and
its relatives [2]_. They do not always compute the correct result for all kinds of
signals, but are usually correct and typically computationally more efficient for
most kinds of narrowband signals. The definition for an envelope presented here is
common where instantaneous amplitude and phase are of interest (e.g., as described
in [3]_). There exist also other concepts, which rely on the general mathematical
idea of an envelope [4]_: A pragmatic approach is to determine all upper and lower
signal peaks and use a spline interpolation to determine the curves [5]_.


References
----------
.. [1] "Analytic Signal", Wikipedia,
   https://en.wikipedia.org/wiki/Analytic_signal
.. [2] Lyons, Richard, "Digital envelope detection: The good, the bad, and the
   ugly", IEEE Signal Processing Magazine 34.4 (2017): 183-187.
   `PDF <https://community.infineon.com/gfawx74859/attachments/gfawx74859/psoc135/46469/1/R.%20Lyons_envelope_detection_v3.pdf>`__
.. [3] T.G. Kincaid, "The complex representation of signals.",
   TIS R67# MH5, General Electric Co. (1966).
   `PDF <https://apps.dtic.mil/sti/tr/pdf/ADA953296.pdf>`__
.. [4] "Envelope (mathematics)", Wikipedia,
   https://en.wikipedia.org/wiki/Envelope_(mathematics)
.. [5] Yang, Yanli. "A signal theoretic approach for envelope analysis of
   real-valued signals." IEEE Access 5 (2017): 5623-5630.
   `PDF <https://ieeexplore.ieee.org/iel7/6287639/6514899/07891054.pdf>`__


See Also
--------
hilbert: Compute analytic signal by means of Hilbert transform.


Examples
--------
The following plot illustrates the envelope of a signal with variable frequency and
a low-frequency drift. To separate the drift from the envelope, a 4 Hz highpass
filter is used. The low-pass residuum of the input bandpass filter is utilized to
determine an asymmetric upper and lower bound to enclose the signal. Due to the
smoothness of the resulting envelope, it is down-sampled from 500 to 40 samples.
Note that the instantaneous amplitude ``a_x`` and the computed envelope ``x_env``
are not perfectly identical. This is due to the signal not being perfectly periodic
as well as the existence of some spectral overlapping of ``x_carrier`` and
``x_drift``. Hence, they cannot be completely separated by a bandpass filter.

>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from scipy.signal.windows import gaussian
>>> from scipy.signal import envelope
...
>>> n, n_out = 500, 40  # number of signal samples and envelope samples
>>> T = 2 / n  # sampling interval for 2 s duration
>>> t = np.arange(n) * T  # time stamps
>>> a_x = gaussian(len(t), 0.4/T)  # instantaneous amplitude
>>> phi_x = 30*np.pi*t + 35*np.cos(2*np.pi*0.25*t)  # instantaneous phase
>>> x_carrier = a_x * np.cos(phi_x)
>>> x_drift = 0.3 * gaussian(len(t), 0.4/T)  # drift
>>> x = x_carrier + x_drift
...
>>> bp_in = (int(4 * (n*T)), None)  # 4 Hz highpass input filter
>>> x_env, x_res = envelope(x, bp_in, n_out=n_out)
>>> t_out = np.arange(n_out) * (n / n_out) * T
...
>>> fg0, ax0 = plt.subplots(1, 1, tight_layout=True)
>>> ax0.set_title(r"$4\,$Hz Highpass Envelope of Drifting Signal")
>>> ax0.set(xlabel="Time in seconds", xlim=(0, n*T), ylabel="Amplitude")
>>> ax0.plot(t, x, 'C0-', alpha=0.5, label="Signal")
>>> ax0.plot(t, x_drift, 'C2--', alpha=0.25, label="Drift")
>>> ax0.plot(t_out, x_res+x_env, 'C1.-', alpha=0.5, label="Envelope")
>>> ax0.plot(t_out, x_res-x_env, 'C1.-', alpha=0.5, label=None)
>>> ax0.grid(True)
>>> ax0.legend()
>>> plt.show()

The second example provides a geometric envelope interpretation of complex-valued
signals: The following two plots show the complex-valued signal as a blue
3d-trajectory and the envelope as an orange round tube with varying diameter, i.e.,
as :math:`|a(t)| \exp(j\rho(t))`, with :math:`\rho(t)\in[-\pi,\pi]`. Also, the
projection into the 2d real and imaginary coordinate planes of trajectory and tube
is depicted. Every point of the complex-valued signal touches the tube's surface.

The left plot shows an analytic signal, i.e, the phase difference between
imaginary and real part is always 90 degrees, resulting in a spiraling trajectory.
It can be seen that in this case the real part has also the expected envelope,
i.e., representing the absolute value of the instantaneous amplitude.

The right plot shows the real part of that analytic signal being interpreted
as a complex-vauled signal, i.e., having zero imaginary part. There the resulting
envelope is not as smooth as in the analytic case and the instantaneous amplitude
in the real plane is not recovered. If ``z_re`` had been passed as a real-valued
signal, i.e., as ``z_re = z.real`` instead of ``z_re = z.real + 0j``, the result
would have been identical to the left plot. The reason for this is that real-valued
signals are interpreted as being the real part of a complex-valued analytic signal.

>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from scipy.signal.windows import gaussian
>>> from scipy.signal import envelope
...
>>> n, T = 1000, 1/1000  # number of samples and sampling interval
>>> t = np.arange(n) * T  # time stamps for 1 s duration
>>> f_c = 3  # Carrier frequency for signal
>>> z = gaussian(len(t), 0.3/T) * np.exp(2j*np.pi*f_c*t)  # analytic signal
>>> z_re = z.real + 0j  # complex signal with zero imaginary part
...
>>> e_a, e_r = (envelope(z_, (None, None), residual=None) for z_ in (z, z_re))
...
>>> # Generate grids to visualize envelopes as 2d and 3d surfaces:
>>> E2d_t, E2_amp = np.meshgrid(t, [-1, 1])
>>> E2d_1 = np.ones_like(E2_amp)
>>> E3d_t, E3d_phi = np.meshgrid(t, np.linspace(-np.pi, np.pi, 300))
>>> ma = 1.8  # maximum axis values in real and imaginary direction
...
>>> fg0 = plt.figure(figsize=(6.2, 4.))
>>> ax00 = fg0.add_subplot(1, 2, 1, projection='3d')
>>> ax01 = fg0.add_subplot(1, 2, 2, projection='3d', sharex=ax00,
...                        sharey=ax00, sharez=ax00)
>>> ax00.set_title("Analytic Signal")
>>> ax00.set(xlim=(0, 1), ylim=(-ma, ma), zlim=(-ma, ma))
>>> ax01.set_title("Real-valued Signal")
>>> for z_, e_, ax_ in zip((z, z.real), (e_a, e_r), (ax00, ax01)):
...     ax_.set(xlabel="Time $t$", ylabel="Real Amp. $x(t)$",
...             zlabel="Imag. Amp. $y(t)$")
...     ax_.plot(t, z_.real, 'C0-', zs=-ma, zdir='z', alpha=0.5, label="Real")
...     ax_.plot_surface(E2d_t, e_*E2_amp, -ma*E2d_1, color='C1', alpha=0.25)
...     ax_.plot(t, z_.imag, 'C0-', zs=+ma, zdir='y', alpha=0.5, label="Imag.")
...     ax_.plot_surface(E2d_t, ma*E2d_1, e_*E2_amp, color='C1', alpha=0.25)
...     ax_.plot(t, z_.real, z_.imag, 'C0-', label="Signal")
...     ax_.plot_surface(E3d_t, e_*np.cos(E3d_phi), e_*np.sin(E3d_phi),
...                      color='C1', alpha=0.5, shade=True, label="Envelope")
...     ax_.view_init(elev=22.7, azim=-114.3)
>>> fg0.subplots_adjust(left=0.08, right=0.97, wspace=0.15)
>>> plt.show()
zInvalid parameter axis=z for z.shape=!r   z"z.shape[axis] not > 0 for z.shape=z, axis=r?   c              3  X   #    U  H   n[        U[        5      =(       d    US L v   M"     g 7frZ   )r  rO  )r]   b_s     rR   ra   envelope.<locals>.<genexpr>
  s%     !VPU":b##6#D"*#DPUs   (*zbp_in=z2 isn't a 2-tuple of type (int | None, int | None)!Nzn_out=z# is not a positive integer or None!)r  rh   Nz	residual=z! not in ['lowpass', 'all', None]!r   z9`-n//2 <= bp_in[0] < bp_in[1] <= (n+1)//2` does not hold zfor n=z.shape[axis]=z and bp_in=r   r  .)r$  r   r   r  rp  )r   rO   r   rg   rh   r  rO  r   startstoprt   moveaxisr  r   r   
zeros_likerfftr\  rv   r   fftshiftr  r   imagirfftstack)r   bp_inr  r  r  rq  r$  fakbpZz_bbbp_shiftz_envz_ress                 rR   r/   r/   	  s   t VVGt$aff$3dWN!''1EFFGGDMA>aggZx$JKK
5zQc!VPU!VVVFE8#UVWWs##E	emFE8#FGHH//IH;&GHII	AAEE
)C	58/uQxq!tW 8/uQxacAX
?BBERXX33AaC!83T0!''$-!1uha@A B 	B 	AR A	qJJqMMM!6;;qvvbqz#:#@#@A"KKN#y1qy.88a<c2gJ!OJWWq[c1RWW9n"HH#BGG#{{1S"W:/#5AqD"''AqD.9{{6??126sH}EORUU 'BFF4LTYY!^dii1n-LEKKr4(E HH#BGG##r'
.2+#xx-!CN+977Q;)*Ac277AaCA:%%&8<5Ac2889nqaQ1n!45booa.@.@6;;q*<<+-E88UBKKr489BBrm   c                    [         R                  " U 5      n [         R                  " [        U 5      5      n[         R                  " XS5      U4$ )a  Sort roots based on magnitude.

Parameters
----------
p : array_like
    The roots to sort, as a 1-D array.

Returns
-------
p_sorted : ndarray
    Sorted roots.
indx : ndarray
    Array of indices needed to sort the input `p`.

Examples
--------
>>> from scipy import signal
>>> vals = [1, 4, 1+1.j, 3]
>>> p_sorted, indx = signal.cmplx_sort(vals)
>>> p_sorted
array([1.+0.j, 1.+1.j, 3.+0.j, 4.+0.j])
>>> indx
array([0, 2, 3, 1])
r   )rt   ru   argsortr  take)rA  indxs     rR   _cmplx_sortr  
  s9    2 	

1A::c!fD771A$$rm   c                d   US;   a  [         R                  nO9US;   a  [         R                  nO"US;   a  [         R                  nO[	        S5      e[         R
                  " U 5      n [         R                  " [        U 5      S45      n[         R                  " U 5      USS2S4'   [         R                  " U 5      USS2S4'   [        U5      n/ n/ n[         R                  " [        U 5      [        S	9n[        [        U 5      5       Hv  n	X   (       a  M  UR                  XI   U5      n
U
 Vs/ s H  oU   (       a  M  UPM     n
nUR                  U" X
   5      5        UR                  [        U
5      5        S
X'   Mx     [         R
                  " U5      [         R
                  " U5      4$ s  snf )a  Determine unique roots and their multiplicities from a list of roots.

Parameters
----------
p : array_like
    The list of roots.
tol : float, optional
    The tolerance for two roots to be considered equal in terms of
    the distance between them. Default is 1e-3. Refer to Notes about
    the details on roots grouping.
rtype : {'max', 'maximum', 'min', 'minimum', 'avg', 'mean'}, optional
    How to determine the returned root if multiple roots are within
    `tol` of each other.

      - 'max', 'maximum': pick the maximum of those roots
      - 'min', 'minimum': pick the minimum of those roots
      - 'avg', 'mean': take the average of those roots

    When finding minimum or maximum among complex roots they are compared
    first by the real part and then by the imaginary part.

Returns
-------
unique : ndarray
    The list of unique roots.
multiplicity : ndarray
    The multiplicity of each root.

Notes
-----
If we have 3 roots ``a``, ``b`` and ``c``, such that ``a`` is close to
``b`` and ``b`` is close to ``c`` (distance is less than `tol`), then it
doesn't necessarily mean that ``a`` is close to ``c``. It means that roots
grouping is not unique. In this function we use "greedy" grouping going
through the roots in the order they are given in the input `p`.

This utility function is not specific to roots but can be used for any
sequence of values for which uniqueness and multiplicity has to be
determined. For a more general routine, see `numpy.unique`.

Examples
--------
>>> from scipy import signal
>>> vals = [0, 1.3, 1.31, 2.8, 1.25, 2.2, 10.3]
>>> uniq, mult = signal.unique_roots(vals, tol=2e-2, rtype='avg')

Check which roots have multiplicity larger than 1:

>>> uniq[mult > 1]
array([ 1.305])
r   maximumr  minimumavgrs  J`rtype` must be one of {'max', 'maximum', 'min', 'minimum', 'avg', 'mean'}r?   Nr   r   r  T)rt   r   r  rs  rO   ru   r   rg   r   r  r   r   boolrf   query_ball_pointr  )rA  tolrtypereducepointstreep_uniquep_multiplicityusedr^   groupr,  s               rR   r0   r0   
  s[   h ""	$	$	/	! O P 	P 	

1AXXs1vqk"F771:F1a4L771:F1a4L6?DHN88CF$'D3q6]7%%fi5!1EqaE1qx()c%j)  ::hN!;;; 2s   -F->F-c                   [         R                  " U 5      n [         R                  " U5      n[         R                  " [         R                  " U5      S5      n[        XU5      u  pV[	        XVSS9u  px[        U5      S:X  a  Sn	O[         R                  " X(5      n	[        X5       H  u  p[         R                  " XU-  5      n	M      X4$ )a   Compute b(s) and a(s) from partial fraction expansion.

If `M` is the degree of numerator `b` and `N` the degree of denominator
`a`::

          b(s)     b[0] s**(M) + b[1] s**(M-1) + ... + b[M]
  H(s) = ------ = ------------------------------------------
          a(s)     a[0] s**(N) + a[1] s**(N-1) + ... + a[N]

then the partial-fraction expansion H(s) is defined as::

           r[0]       r[1]             r[-1]
       = -------- + -------- + ... + --------- + k(s)
         (s-p[0])   (s-p[1])         (s-p[-1])

If there are any repeated roots (closer together than `tol`), then H(s)
has terms like::

      r[i]      r[i+1]              r[i+n-1]
    -------- + ----------- + ... + -----------
    (s-p[i])  (s-p[i])**2          (s-p[i])**n

This function is used for polynomials in positive powers of s or z,
such as analog filters or digital filters in controls engineering.  For
negative powers of z (typical for digital filters in DSP), use `invresz`.

Parameters
----------
r : array_like
    Residues corresponding to the poles. For repeated poles, the residues
    must be ordered to correspond to ascending by power fractions.
p : array_like
    Poles. Equal poles must be adjacent.
k : array_like
    Coefficients of the direct polynomial term.
tol : float, optional
    The tolerance for two roots to be considered equal in terms of
    the distance between them. Default is 1e-3. See `unique_roots`
    for further details.
rtype : {'avg', 'min', 'max'}, optional
    Method for computing a root to represent a group of identical roots.
    Default is 'avg'. See `unique_roots` for further details.

Returns
-------
b : ndarray
    Numerator polynomial coefficients.
a : ndarray
    Denominator polynomial coefficients.

See Also
--------
residue, invresz, unique_roots

fTinclude_powersr   	rt   rl  
trim_zeros_group_poles_compute_factorsrg   polymulr   polyaddrD  rA  r   r  r  unique_polesmultiplicityfactorsdenominator	numeratorr3   factors               rR   r1   r1   H  s    p 	aA
aA
bmmA&,A!-ae!<L+L;?AG 1v{	JJq.	q?JJyF*:;	 + !!rm   c                   [         R                  " S/5      nU/n[        U SSS2   USSS2   5       HW  u  pV[         R                  " SU* /5      n[        U5       H  n[         R                  " X75      nM     UR                  U5        MY     USSS2   n/ n	[         R                  " S/5      n[        XU5       H  u  pVn
[         R                  " SU* /5      n/ n[        U5       HK  nUS:X  d  U(       a%  UR                  [         R                  " X:5      5        [         R                  " X75      nMM     U	R                  [        U5      5        M     X4$ )z>Compute the total polynomial divided by factors for each root.r   r   r   N)rt   r   r   rf   r  r  extendreversed)rootsr  r  currentsuffixespolemultmonomialr   r  suffixblockr^   s                rR   r  r    s'   hhsmGyH%1R.,r!Bw*?@
88QJ'tAjj3G  	 A
 "~HGhhsmG!%x@F88QJ'tAAvRZZ89jj3G  	x' A rm   c                   [        X5      u  p4UR                  U R                  5      n/ n[        XU5       GH  u  pgnUS:X  a>  UR	                  [
        R                  " X&5      [
        R                  " X5      -  5        MK  UR                  5       n	[
        R                  " SU* /5      n
[
        R                  " X5      u  p/ n[        U5       HP  n[
        R                  " X5      u  pUS   US   -  n[
        R                  " XU-  5      n	UR	                  U5        MR     UR                  [        U5      5        GM
     [
        R                  " U5      $ )Nr   r   )r  r_  rv   r   r  rt   polyvalr   r   polydivrf   polysubr  r  ru   )polesr  r  denominator_factorsr   residuesr  r  r  numerr  dr
  r$  rD  s                  rR   _compute_residuesr    s   -eB  -IH!%"57F19OOBJJy7JJv45 6 NN$ExxTE
+H

64IFE4[::e6aD1Q4K

5f*5Q	 ! OOHUO,#7& ::hrm   c                   [         R                  " U 5      n [         R                  " U5      n[         R                  " U R                  [         R                  5      (       d4  [         R                  " UR                  [         R                  5      (       a+  U R                  [        5      n UR                  [        5      nO*U R                  [        5      n UR                  [        5      n[         R                  " [         R                  " U 5      S5      n [         R                  " [         R                  " U5      S5      nUR                  S:X  a  [        S5      e[         R                  " U5      nU R                  S:X  aC  [         R                  " UR                  5      [        U5      S   [         R                   " / 5      4$ [#        U 5      [#        U5      :  a  [         R$                  " S5      nO[         R&                  " X5      u  pP[)        XBUS9u  pg[        U5      u  phXx   n[+        XgU 5      n	Sn
[-        Xg5       H  u  pXXU-   & X-  n
M     XS   -  XE4$ )aj
  Compute partial-fraction expansion of b(s) / a(s).

If `M` is the degree of numerator `b` and `N` the degree of denominator
`a`::

          b(s)     b[0] s**(M) + b[1] s**(M-1) + ... + b[M]
  H(s) = ------ = ------------------------------------------
          a(s)     a[0] s**(N) + a[1] s**(N-1) + ... + a[N]

then the partial-fraction expansion H(s) is defined as::

           r[0]       r[1]             r[-1]
       = -------- + -------- + ... + --------- + k(s)
         (s-p[0])   (s-p[1])         (s-p[-1])

If there are any repeated roots (closer together than `tol`), then H(s)
has terms like::

      r[i]      r[i+1]              r[i+n-1]
    -------- + ----------- + ... + -----------
    (s-p[i])  (s-p[i])**2          (s-p[i])**n

This function is used for polynomials in positive powers of s or z,
such as analog filters or digital filters in controls engineering.  For
negative powers of z (typical for digital filters in DSP), use `residuez`.

See Notes for details about the algorithm.

Parameters
----------
b : array_like
    Numerator polynomial coefficients.
a : array_like
    Denominator polynomial coefficients.
tol : float, optional
    The tolerance for two roots to be considered equal in terms of
    the distance between them. Default is 1e-3. See `unique_roots`
    for further details.
rtype : {'avg', 'min', 'max'}, optional
    Method for computing a root to represent a group of identical roots.
    Default is 'avg'. See `unique_roots` for further details.

Returns
-------
r : ndarray
    Residues corresponding to the poles. For repeated poles, the residues
    are ordered to correspond to ascending by power fractions.
p : ndarray
    Poles ordered by magnitude in ascending order.
k : ndarray
    Coefficients of the direct polynomial term.

See Also
--------
invres, residuez, numpy.poly, unique_roots

Notes
-----
The "deflation through subtraction" algorithm is used for
computations --- method 6 in [1]_.

The form of partial fraction expansion depends on poles multiplicity in
the exact mathematical sense. However there is no way to exactly
determine multiplicity of roots of a polynomial in numerical computing.
Thus you should think of the result of `residue` with given `tol` as
partial fraction expansion computed for the denominator composed of the
computed poles with empirically determined multiplicity. The choice of
`tol` can drastically change the result if there are close poles.

References
----------
.. [1] J. F. Mahoney, B. D. Sivazlian, "Partial fractions expansion: a
       review of computational methodology and efficiency", Journal of
       Computational and Applied Mathematics, Vol. 9, 1983.
r  r   Denominator `a` is zero.r  r  )rt   ru   rw   rv   complexfloatingr_  complexrL  r  rl  r   rO   r  r   r   r  r   rg   r   r  r0   r  r   )rM  r   r  r  r  r   r  r  orderr  indexr  r  s                rR   r3   r3     s   X 	

1A


1A
aggr1122}}QWWb&8&899HHWHHWHHUOHHUO
bmmA&,A
bmmA&,Avv{344HHQKEvv{xx$k%&8&;RXXb\II
1vAHHQKzz!!-eE!JL%l3L&L Q?HE,5
$(eDL! 6 d?E$$rm   c                   [         R                  " U 5      n [         R                  " U5      n[         R                  " U R                  [         R                  5      (       d4  [         R                  " UR                  [         R                  5      (       a+  U R                  [        5      n UR                  [        5      nO*U R                  [        5      n UR                  [        5      n[         R                  " [         R                  " U 5      S5      n [         R                  " [         R                  " U5      S5      nUR                  S:X  a  [        S5      eUS   S:X  a  [        S5      e[         R                  " U5      nU R                  S:X  aC  [         R                  " UR                  5      [        U5      S   [         R                   " / 5      4$ U SSS2   nUSSS2   n[#        U5      [#        U5      :  a  [         R$                  " S5      nO[         R&                  " XV5      u  pu[)        XBUS9u  p[        U5      u  pX   n	[+        SU-  X5      nSn[         R$                  " [#        U5      [,        S	9n[/        X5       H,  u  pXXU-   & S[         R0                  " U5      -   XX-   & X-  nM.     X* U-  US   -  -  nXUSSS2   4$ )
aF  Compute partial-fraction expansion of b(z) / a(z).

If `M` is the degree of numerator `b` and `N` the degree of denominator
`a`::

            b(z)     b[0] + b[1] z**(-1) + ... + b[M] z**(-M)
    H(z) = ------ = ------------------------------------------
            a(z)     a[0] + a[1] z**(-1) + ... + a[N] z**(-N)

then the partial-fraction expansion H(z) is defined as::

             r[0]                   r[-1]
     = --------------- + ... + ---------------- + k[0] + k[1]z**(-1) ...
       (1-p[0]z**(-1))         (1-p[-1]z**(-1))

If there are any repeated roots (closer than `tol`), then the partial
fraction expansion has terms like::

         r[i]              r[i+1]                    r[i+n-1]
    -------------- + ------------------ + ... + ------------------
    (1-p[i]z**(-1))  (1-p[i]z**(-1))**2         (1-p[i]z**(-1))**n

This function is used for polynomials in negative powers of z,
such as digital filters in DSP.  For positive powers, use `residue`.

See Notes of `residue` for details about the algorithm.

Parameters
----------
b : array_like
    Numerator polynomial coefficients.
a : array_like
    Denominator polynomial coefficients.
tol : float, optional
    The tolerance for two roots to be considered equal in terms of
    the distance between them. Default is 1e-3. See `unique_roots`
    for further details.
rtype : {'avg', 'min', 'max'}, optional
    Method for computing a root to represent a group of identical roots.
    Default is 'avg'. See `unique_roots` for further details.

Returns
-------
r : ndarray
    Residues corresponding to the poles. For repeated poles, the residues
    are ordered to correspond to ascending by power fractions.
p : ndarray
    Poles ordered by magnitude in ascending order.
k : ndarray
    Coefficients of the direct polynomial term.

See Also
--------
invresz, residue, unique_roots
rM  r   r  z6First coefficient of determinant `a` must be non-zero.Nr   r  r   r  )rt   ru   rw   rv   r  r_  r  rL  r  rl  r   rO   r  r   r   r  r   rg   r   r  r0   r  rO  r   r   )rM  r   r  r  r  b_reva_revk_revr  r  r  r  r  powersr  r  s                   rR   r4   r4   :  s6   p 	

1A


1A
aggr1122}}QWWb&8&899HHWHHWHHUOHHUO
bmmA&,A
bmmA&,Avv{344	
1 % & 	& HHQKEvv{xx$k%&8&;RXXb\IIddGEddGE
5zCJzz%/!-eE!JL%l3L&L \!1<GHEXXc(m3/F,5
$(eDL!%&4%8U\" 6
 F"U1X--HE$B$K''rm   c                j   US;   a  [         R                  nO9US;   a  [         R                  nO"US;   a  [         R                  nO[	        S5      e/ n/ nU S   nU/n[        S[        U 5      5       Hb  n[        X   U-
  5      U::  a  UR                  U5        M*  UR                  U" U5      5        UR                  [        U5      5        X   nU/nMd     UR                  U" U5      5        UR                  [        U5      5        [         R                  " U5      [         R                  " U5      4$ )Nr  r  r  r  r   r   )
rt   r   r  rs  rO   rf   rg   r  r  ru   )	r  r  r  r  uniquer  r  r
  r^   s	            rR   r  r    s   ""	$	$	/	! O P 	P FL8DFE1c%j!ux$3&LLMM&-(E
+8DFE " MM&- E
#::frzz,777rm   c           	        [         R                  " U 5      n [         R                  " U5      n[         R                  " [         R                  " U5      S5      n[        XU5      u  pV[	        XVSS9u  px[        U5      S:X  a  Sn	O#[         R                  " USSS2   USSS2   5      n	[        X5       H$  u  p[         R                  " XUSSS2   -  5      n	M&     U	SSS2   U4$ )a  Compute b(z) and a(z) from partial fraction expansion.

If `M` is the degree of numerator `b` and `N` the degree of denominator
`a`::

            b(z)     b[0] + b[1] z**(-1) + ... + b[M] z**(-M)
    H(z) = ------ = ------------------------------------------
            a(z)     a[0] + a[1] z**(-1) + ... + a[N] z**(-N)

then the partial-fraction expansion H(z) is defined as::

             r[0]                   r[-1]
     = --------------- + ... + ---------------- + k[0] + k[1]z**(-1) ...
       (1-p[0]z**(-1))         (1-p[-1]z**(-1))

If there are any repeated roots (closer than `tol`), then the partial
fraction expansion has terms like::

         r[i]              r[i+1]                    r[i+n-1]
    -------------- + ------------------ + ... + ------------------
    (1-p[i]z**(-1))  (1-p[i]z**(-1))**2         (1-p[i]z**(-1))**n

This function is used for polynomials in negative powers of z,
such as digital filters in DSP.  For positive powers, use `invres`.

Parameters
----------
r : array_like
    Residues corresponding to the poles. For repeated poles, the residues
    must be ordered to correspond to ascending by power fractions.
p : array_like
    Poles. Equal poles must be adjacent.
k : array_like
    Coefficients of the direct polynomial term.
tol : float, optional
    The tolerance for two roots to be considered equal in terms of
    the distance between them. Default is 1e-3. See `unique_roots`
    for further details.
rtype : {'avg', 'min', 'max'}, optional
    Method for computing a root to represent a group of identical roots.
    Default is 'avg'. See `unique_roots` for further details.

Returns
-------
b : ndarray
    Numerator polynomial coefficients.
a : ndarray
    Denominator polynomial coefficients.

See Also
--------
residuez, unique_roots, invres

rM  Tr  r   Nr   r  r  s               rR   r2   r2     s    n 	aA
aA
bmmA&,A!-ae!<L+L;?AG 1v{	JJq2wDbD(9:	q?JJyF4R4L*@A	 + TrT?K''rm   c                   US;  a  [        SU 35      e[        R                  " U 5      n U R                  U   n[        R                  " U 5      nUS:X  a1  U(       a  [
        R                  " XS9nO[
        R                  " XS9nOU nUGb  [        U5      (       a  U" [
        R                  " U5      5      n	O][        U[        R                  5      (       a  UR                  U4:w  a  [        S5      eUn	O[
        R                  " [        XF5      5      n	S/U R                  -  n
UR                  U   X'   U(       aK  U	R                  5       nUSS=== USS	S2   -  sss& USS=== S
-  sss& XSX    R!                  U
5      -  nOXR!                  U
5      -  n[#        U R                  5      nU(       a  US-  S-   X'   OXU'   [        R$                  " XR&                  5      n[)        X5      nUS-  S-   n[+        S5      /U R                  -  n[+        S	U5      UU'   U[-        U5         U[-        U5      '   U(       d1  US:  a+  [+        X-
  S5      UU'   U[-        U5         U[-        U5      '   US-  S	:X  a  X:  as  U(       a/  [+        US-  US-  S-   5      UU'   U[-        U5      ==   S-  ss'   O[+        U* S-  U* S-  S-   5      UU'   U[-        U5      ==   U[-        U5         -  ss'   OrXa:  am  [+        US-  US-  S-   5      UU'   U[-        U5      ==   S
-  ss'   U(       d8  U[-        U5         n[+        XS-  -
  XS-  -
  S-   5      UU'   UU[-        U5      '   U(       a  [
        R.                  " XUS9nO[
        R0                  " XSS9nU[3        U5      [3        U5      -  -  nUc  U$ [        R4                  " S	U5      US   US	   -
  -  U-  [3        U5      -  US	   -   nUU4$ )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 equally spaced 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 `scipy.signal.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 is used solely to calculate the resampled
positions `resampled_t`

As noted, `resample` uses FFT transformations, which can be very 
slow if the number of input or output samples is large and prime; 
see :func:`~scipy.fft.fft`. In such cases, it can be faster to first downsample 
a signal of length ``n`` with :func:`~scipy.signal.resample_poly` by a factor of 
``n//num`` before using `resample`. Note that this approach changes the 
characteristics of the antialiasing filter.

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

>>> import numpy as np
>>> from scipy import signal

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

>>> import matplotlib.pyplot as plt
>>> plt.plot(x, y, 'go-', xnew, f, '.-', 10, y[0], 'ro')
>>> plt.legend(['data', 'resampled'], loc='best')
>>> plt.show()

Consider the following signal  ``y`` where ``len(y)`` is a large  prime number:

>>> N = 55949
>>> freq = 100
>>> x = np.linspace(0, 1, N)
>>> y = np.cos(2 * np.pi * freq * x)

Due to ``N`` being prime,

>>> num = 5000
>>> f = signal.resample(signal.resample_poly(y, 1, N // num), num)

runs significantly faster than

>>> f = signal.resample(y, num)
)timefreqz9Acceptable domain flags are 'time' or 'freq', not domain=r%  rp  Nz(window must have the same length as datar   r   r   g      ?r?   g       @T)rq  overwrite_x)rO   rt   ru   r   	isrealobjr   r  r   callablefftfreqr  r  	ifftshiftr   r   r   r   r   r   rv   r  r   r   r  r   rL  r   )r,  r  trq  windowrc  Nx
real_inputXW
newshape_WW_realr   Yr(  nyqsltempr  new_ts                       rR   r5   r5     s   R %% 006x9 : 	: 	

1A	
B aJA)A

1(A Fv~~b)*A

++||u$ !KLLA  F!78AS166\
774=
VVXF12J&Ab/)J12J#J))*22:>>A:&&A AGG}HA
77#A 	CA
q&1*C
+	BQ}BtHU2Y<AeBiLq5SWd+BtHU2Y<AeBiL 	1uz8 Aq!tax04%)" !!QA	24%)%),XQT1a4!8,BtHeBiLCLr| T3!t8a<84#%) LLd+KK$7%*uRy
 !Ay		!S!QqTAaD[1B6sCadJ%xrm   c           	        [         R                  " U 5      n U[        U5      :w  a  [        S5      eU[        U5      :w  a  [        S5      e[        U5      n[        U5      nUS:  d  US:  a  [        S5      eUb  US:w  a  [        SU5      e[        R
                  " X5      nX-  nX'-  nXs=:X  a  S:X  a   U R                  5       $   U R                  U   nX-  n	X-  [        X-  5      -   n	[        U[        [         R                  -  5      (       aF  [         R                  " U5      nUR                  S:  a  [        S5      eUR                  S-
  S	-  n
UnO[        X5      nS
U-  nSU-  n
[         R                   " U R"                  [         R$                  5      (       a+  ['        S	U
-  S-   UUS9R)                  U R"                  5      nOp[         R                   " U R"                  [         R*                  5      (       a+  ['        S	U
-  S-   UUS9R)                  U R"                  5      nO['        S	U
-  S-   UUS9nX-  nX*U-  -
  nSnX-   U-  n[-        [/        U5      U-   U-   UX5      U	U-   :  a*  US-  n[-        [/        U5      U-   U-   UX5      U	U-   :  a  M*  [         R0                  " [         R2                  " XR"                  S9U[         R2                  " XR"                  S945      nUU	-   n[         R4                  [         R6                  [         R8                  [         R:                  S.nSSS.nUU;   a  UU   " XSS9nO@U[<        ;   a  SU0nUS:X  a
  Uc  SnUUS'   O![        SSR?                  [<        5      -   5      eUU;   a  U W-
  n [A        XX4SU0UD6n[C        S5      /U R                  -  n[C        UU5      UU'   U[E        U5         nUU;   a  UW-  nU$ )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. By default, 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 `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 `np.pad` and assume that the values
    beyond the boundary are the mean, median, maximum or minimum
    respectively of the array along the axis.

    .. versionadded:: 1.4.0
cval : float, optional
    Value to use if `padtype='constant'`. Default is zero.

    .. versionadded:: 1.4.0

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 `scipy.signal.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 `scipy.signal.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 `scipy.signal.get_window`
and `scipy.signal.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
--------
By default, 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 numpy as np
>>> from scipy import signal
>>> import matplotlib.pyplot as plt

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

>>> plt.plot(xnew, f_fft, 'b.-', xnew, f_poly, 'r.-')
>>> plt.plot(x, y, 'ko-')
>>> plt.plot(10, y[0], 'bo', 10, 0., 'ro')  # boundaries
>>> plt.legend(['resample', 'resamp_poly', 'data'], loc='best')
>>> plt.show()

This default behaviour can be changed by using the padtype option:

>>> N = 5
>>> x = np.linspace(0, 1, N, endpoint=False)
>>> y = 2 + x**2 - 1.7*np.sin(x) + .2*np.cos(11*x)
>>> y2 = 1 + x**3 + 0.1*np.sin(x) + .1*np.cos(11*x)
>>> Y = np.stack([y, y2], axis=-1)
>>> up = 4
>>> xr = np.linspace(0, 1, N*up, endpoint=False)

>>> y2 = signal.resample_poly(Y, up, 1, padtype='constant')
>>> y3 = signal.resample_poly(Y, up, 1, padtype='mean')
>>> y4 = signal.resample_poly(Y, up, 1, padtype='line')

>>> for i in [0,1]:
...     plt.figure()
...     plt.plot(xr, y4[:,i], 'g.', label='line')
...     plt.plot(xr, y3[:,i], 'y.', label='mean')
...     plt.plot(xr, y2[:,i], 'r.', label='constant')
...     plt.plot(x, Y[:,i], 'k-')
...     plt.legend()
>>> plt.show()

zup must be an integerzdown must be an integerr   zup and down must be >= 1Nr   z#cval has no effect when padtype is zwindow must be 1-Dr?         ?r:  r-  r   r  )rs  medianr  r  )rP   cvalT)rq  keepdimsrP   r=  z8padtype must be one of: maximum, mean, median, minimum, z, rq  )#rt   ru   rO  rO   r   gcdr   r   r  r  r   r  r   r   r   r   rw   rv   r  r   r_  floatingr   rg   concatenater   rs  r<  aminamaxr   joinr   r   r   )r,  updownrq  r-  padtyper=  g_n_inr  half_lenr-  max_ratef_c	n_pre_pad
n_post_padn_pre_removen_pre_remove_endfuncsupfirdn_kwargsbackground_valuesr  keepy_keeps                           rR   r6   r6     s   x 	

1A	SW}011s4y233	RBt9D	Av344Gz1>HH
 
"	BIBKD	Qvvx 774=DIEMD..E&4"**,..&!;;?122KK!O) r=8m===""4"455q8|a'$&&,fQWWo ]]177BKK00q8|a'$&&,fQWWo  q8|a'$&AGA 4'IJ(T1L
c!fy(:5t "',"67a
 c!fy(:5t "',"67 	'':A77;= 	>A#e+ WW		BGG5E(!4N%!'N1$G	N	" '*j |%)N6"FIIn%&' 	' %!! 	b<T<^<A$K?166!D|%56DJuT{^F %##Mrm   c                   [         R                  " U 5      n [         R                  " U5      nU R                  S:  a  [        S5      eUR                  S:  a  [        S5      eUR                  (       + n[         R                  " U 5      n [         R                  " U5      nUS:*  R                  5       (       a  [        S5      e[         R                  " [         R                  " S[         R                  -  UR                  -  U 5      5      n[         R                  " USS9n[        U5      n[         R                  " U5      nU(       a
  US   nUS   nXV4$ )a7  
Determine the vector strength of the events corresponding to the given
period.

The vector strength is a measure of phase synchrony, how well the
timing of the events is synchronized to a single period of a periodic
signal.

If multiple periods are used, calculate the vector strength of each.
This is called the "resonating vector strength".

Parameters
----------
events : 1D array_like
    An array of time points containing the timing of the events.
period : float or array_like
    The period of the signal that the events should synchronize to.
    The period is in the same units as `events`.  It can also be an array
    of periods, in which case the outputs are arrays of the same length.

Returns
-------
strength : float or 1D array
    The strength of the synchronization.  1.0 is perfect synchronization
    and 0.0 is no synchronization.  If `period` is an array, this is also
    an array with each element containing the vector strength at the
    corresponding period.
phase : float or array
    The phase that the events are most strongly synchronized to in radians.
    If `period` is an array, this is also an array with each element
    containing the phase for the corresponding period.

References
----------
van Hemmen, JL, Longtin, A, and Vollmayr, AN. Testing resonating vector
    strength: Auditory system, electric fish, and noise.
    Chaos 21, 047508 (2011);
    :doi:`10.1063/1.3670512`.
van Hemmen, JL.  Vector strength after Goldberg, Brown, and von Mises:
    biological and mathematical perspectives.  Biol Cybern.
    2013 Aug;107(4):385-96. :doi:`10.1007/s00422-013-0561-7`.
van Hemmen, JL and Vollmayr, AN.  Resonating vector strength: what happens
    when we vary the "probing" frequency while keeping the spike times
    fixed.  Biol Cybern. 2013 Aug;107(4):491-94.
    :doi:`10.1007/s00422-013-0560-8`.
r   z)events cannot have dimensions more than 1z)period cannot have dimensions more than 1r   zperiods must be positivey               @rp  )rt   ru   r   rO   r  rN  expdotpiTrs  r  angle)eventsperiodscalarperiodvectors
vectormeanstrengthphases          rR   r>   r>     s   ^ ZZFZZF{{QDEE{{QDEE {{?L]]6"F]]6"F!344 ffRVVBruuHVXX-v67G q)J:HHHZ E A;a?rm   c                   US;  a  [        S5      e[        R                  " U 5      n U R                  R                  nUS;  a  SnUS;   a  U [        R
                  " XSS9-
  nU$ U R                  nXq   n[        R                  " [        R                  " [        R                  " [        R                  " SX85      5      5      5      n[        R                  " X8:  5      (       a  [        S	5      e[        U5      n	US:  a  X-   n[        R                  " XS5      n
U
R                  nU
R                  US
5      n
U(       d  U
R                  5       n
U
R                  R                  S;  a  U
R!                  U5      n
[#        [        U5      S-
  5       H  nX<S-      X<   -
  n[        R$                  " US4U5      n[        R&                  " SUS-   US9U-  USS2S4'   [)        X<   X<S-      5      n[*        R,                  " XU   5      u  nnnnX   UU-  -
  X'   M     U
R                  U5      n
[        R                  " U
SU5      nU$ )a
  Remove linear or constant trend along axis from data.

Parameters
----------
data : array_like
    The input data.
axis : int, optional
    The axis along which to detrend the data. By default this is the
    last axis (-1).
type : {'linear', 'constant'}, optional
    The type of detrending. If ``type == 'linear'`` (default),
    the result of a linear least-squares fit to `data` is subtracted
    from `data`.
    If ``type == 'constant'``, only the mean of `data` is subtracted.
bp : array_like of ints, optional
    A sequence of break points. If given, an individual linear fit is
    performed for each part of `data` between two break points.
    Break points are specified as indices into `data`. This parameter
    only has an effect when ``type == 'linear'``.
overwrite_data : bool, optional
    If True, perform in place detrending and avoid a copy. Default is False

Returns
-------
ret : ndarray
    The detrended input data.

Notes
-----
Detrending can be interpreted as subtracting a least squares fit polynomial:
Setting the parameter `type` to 'constant' corresponds to fitting a zeroth degree
polynomial, 'linear' to a first degree polynomial. Consult the example below.

See Also
--------
numpy.polynomial.polynomial.Polynomial.fit: Create least squares fit polynomial.


Examples
--------
The following example detrends the function :math:`x(t) = \sin(\pi t) + 1/4`:

>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from scipy.signal import detrend
...
>>> t = np.linspace(-0.5, 0.5, 21)
>>> x = np.sin(np.pi*t) + 1/4
...
>>> x_d_const = detrend(x, type='constant')
>>> x_d_linear = detrend(x, type='linear')
...
>>> fig1, ax1 = plt.subplots()
>>> ax1.set_title(r"Detrending $x(t)=\sin(\pi t) + 1/4$")
>>> ax1.set(xlabel="t", ylabel="$x(t)$", xlim=(t[0], t[-1]))
>>> ax1.axhline(y=0, color='black', linewidth=.5)
>>> ax1.axvline(x=0, color='black', linewidth=.5)
>>> ax1.plot(t, x, 'C0.-',  label="No detrending")
>>> ax1.plot(t, x_d_const, 'C1x-', label="type='constant'")
>>> ax1.plot(t, x_d_linear, 'C2+-', label="type='linear'")
>>> ax1.legend()
>>> plt.show()

Alternatively, NumPy's `~numpy.polynomial.polynomial.Polynomial` can be used for
detrending as well:

>>> pp0 = np.polynomial.Polynomial.fit(t, x, deg=0)  # fit degree 0 polynomial
>>> np.allclose(x_d_const, x - pp0(t))  # compare with constant detrend
True
>>> pp1 = np.polynomial.Polynomial.fit(t, x, deg=1)  # fit degree 1 polynomial
>>> np.allclose(x_d_linear, x - pp1(t))  # compare with linear detrend
True

Note that `~numpy.polynomial.polynomial.Polynomial` also allows fitting higher
degree polynomials. Consult its documentation on how to extract the polynomial
coefficients.
)linearlr   r   z*Trend type must be 'linear' or 'constant'.dfDFr  )r   r   T)r>  r   z>Breakpoints must be less than length of data along given axis.r   r   r?   r  N)rO   rt   ru   rv   r  rs  r   r   r"  rA  rl  rN  rg   r  r   r   r_  rf   rr  r   r   r   lstsq)datarq  r  r  overwrite_datarv   r   dshaper(  rnknewdatanewdata_shaper  NptsAr6  coefresidsrd  rj  s                       rR   r7   r7      s   ` 33EFF::dDJJOOEF  RWWT$77
LWWRYYr~~bmmAr.EFGH66"&>> 9 : :
 &k!8:D++d!,//!R(llnG==V+nnU+G s2w{#A!e9ru$Dq	5)Aii4!859D@AadGrubQi(B$*LLBK$@!D&$!+D0GK $ //-0kk'1d+
rm   c                   [         R                  " U 5      n U R                  S:w  a  [        S5      e[         R                  " U5      nUR                  S:w  a  [        S5      e[	        U5      S:  a(  US   S:X  a  USS n[	        U5      S:  a  US   S:X  a  M  UR
                  S:  a  [        S5      eUS   S:w  a  XS   -  n XS   -  n[        [	        U5      [	        U 5      5      n[	        U5      U:  a?  [         R                  U[         R                  " U[	        U5      -
  UR                  S	94   nOM[	        U 5      U:  a>  [         R                  U [         R                  " U[	        U 5      -
  U R                  S	94   n [         R                  " US-
  [         R                  " X5      S	9[        R                  " U5      R                  -
  nU SS USS U S   -  -
  n[         R                  R                  X45      nU$ )
an	  
Construct initial conditions for lfilter for step response steady-state.

Compute an initial state `zi` for the `lfilter` function that corresponds
to the steady state of the step response.

A typical use of this function is to set the initial state so that the
output of the filter starts at the same value as the first element of
the signal to be filtered.

Parameters
----------
b, a : array_like (1-D)
    The IIR filter coefficients. See `lfilter` for more
    information.

Returns
-------
zi : 1-D ndarray
    The initial state for the filter.

See Also
--------
lfilter, lfiltic, filtfilt

Notes
-----
A linear filter with order m has a state space representation (A, B, C, D),
for which the output y of the filter can be expressed as::

    z(n+1) = A*z(n) + B*x(n)
    y(n)   = C*z(n) + D*x(n)

where z(n) is a vector of length m, A has shape (m, m), B has shape
(m, 1), C has shape (1, m) and D has shape (1, 1) (assuming x(n) is
a scalar).  lfilter_zi solves::

    zi = A*zi + B

In other words, it finds the initial condition for which the response
to an input of all ones is a constant.

Given the filter coefficients `a` and `b`, the state space matrices
for the transposed direct form II implementation of the linear filter,
which is the implementation used by scipy.signal.lfilter, are::

    A = scipy.linalg.companion(a).T
    B = b[1:] - a[1:]*b[0]

assuming ``a[0]`` is 1.0; if ``a[0]`` is not 1, `a` and `b` are first
divided by a[0].

Examples
--------
The following code creates a lowpass Butterworth filter. Then it
applies that filter to an array whose values are all 1.0; the
output is also all 1.0, as expected for a lowpass filter.  If the
`zi` argument of `lfilter` had not been given, the output would have
shown the transient signal.

>>> from numpy import array, ones
>>> from scipy.signal import lfilter, lfilter_zi, butter
>>> b, a = butter(5, 0.25)
>>> zi = lfilter_zi(b, a)
>>> y, zo = lfilter(b, a, ones(10), zi=zi)
>>> y
array([1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])

Another example:

>>> x = array([0.5, 0.5, 0.5, 0.0, 0.0, 0.0, 0.0])
>>> y, zf = lfilter(b, a, x, zi=zi*x[0])
>>> y
array([ 0.5       ,  0.5       ,  0.5       ,  0.49836039,  0.48610528,
    0.44399389,  0.35505241])

Note that the `zi` argument to `lfilter` was computed using
`lfilter_zi` and scaled by ``x[0]``.  Then the output `y` has no
transient until the input drops from 0.5 to 0.0.

r   zNumerator b must be 1-D.zDenominator a must be 1-D.r   g        Nz3There must be at least one nonzero `a` coefficient.r:  r  )rt   rl  r   rO   rg   r   r   r  r   rv   eyerY  r   	companionrZ  solve)rM  r   r$  IminusABr  s         rR   r8   r8     s   v 	aAvv{344
aAvv{566
a&1*1abE a&1*1vvzNOOts{!H!HCFCFA 1vzEE!RXXa#a&j889	Q!EE!RXXa#a&j889ffQU".."67&:J:J1:M:O:OOG	!"!"!A		$B Irm   c                   [         R                  " U 5      n U R                  S:w  d  U R                  S   S:w  a  [	        S5      eU R
                  R                  S;   a  U R                  [         R                  5      n U R                  S   n[         R                  " US4U R
                  S9nSn[        U5       HF  nXS	S
24   nXS
S	24   nU[        XV5      -  X$'   X5R                  5       UR                  5       -  -  nMH     U$ )ai  
Construct initial conditions for sosfilt for step response steady-state.

Compute an initial state `zi` for the `sosfilt` function that corresponds
to the steady state of the step response.

A typical use of this function is to set the initial state so that the
output of the filter starts at the same value as the first element of
the signal to be filtered.

Parameters
----------
sos : array_like
    Array of second-order filter coefficients, must have shape
    ``(n_sections, 6)``. See `sosfilt` for the SOS filter format
    specification.

Returns
-------
zi : ndarray
    Initial conditions suitable for use with ``sosfilt``, shape
    ``(n_sections, 2)``.

See Also
--------
sosfilt, zpk2sos

Notes
-----
.. versionadded:: 0.16.0

Examples
--------
Filter a rectangular pulse that begins at time 0, with and without
the use of the `zi` argument of `scipy.signal.sosfilt`.

>>> import numpy as np
>>> from scipy import signal
>>> import matplotlib.pyplot as plt

>>> sos = signal.butter(9, 0.125, output='sos')
>>> zi = signal.sosfilt_zi(sos)
>>> x = (np.arange(250) < 100).astype(int)
>>> f1 = signal.sosfilt(sos, x)
>>> f2, zo = signal.sosfilt(sos, x, zi=zi)

>>> plt.plot(x, 'k--', label='x')
>>> plt.plot(f1, 'b', alpha=0.5, linewidth=2, label='filtered')
>>> plt.plot(f2, 'g', alpha=0.25, linewidth=4, label='filtered with zi')
>>> plt.legend(loc='best')
>>> plt.show()

r?   r      z!sos must be shape (n_sections, 6)r  r   r  r:  Nrp   )rt   ru   r   r   rO   rv   r   r_  r|   r   rf   r8   r  )sos
n_sectionsr  scalesectionrM  r   s          rR   r9   r9     s    l **S/C
xx1}		!)<==
yy~~jj$1J	:q/	3BE$!j.. 	1557"" % Irm   c           	        [         R                  " U 5      n [         R                  " U5      n[        [        U 5      [        U5      5      S-
  nUS:X  a?  U S   US   -  S-  nXb-  nU[         R                  " / 5      [         R                  " / 5      4$ US:w  d  X2R
                  S-
  :w  a$  [         R                  " X#UR
                  S-
  5      nUR                  S   nUb	  USU-  ::  a  Un	OUn	[         R                  " X45      n
[         R                  " U5      nSUS'   [        X[         R                  " U	5      US9S   U
SS2S4'   [        SU5       H  nU
SU* 2S4   XS2U4'   M     U
SSS2   n[        XU
SSS2   SS9nUSSS2   nX:X  a  [         R                  " X-
  X-
  45      nO8[         R                  " SU	-  SU-  45      nX-
  USU	2SU24'   X-
  UU	S2US24'   [        XU5      n[        XUSSSS24   5      SSSS24   n[        XUSSSS24   5      SSSS24   n[        XU5      nUU-
  nX:X  a  UnO*USSU	24   nUSU	* S24   n[         R                  " UU4SS9nUR
                  S:X  a  [        R                  " UU5      S   nO|UR                  SUR                  S   5      R                   n[        R                  " UU5      S   R                   nUR                  UR                  SS UR                  S   4-   5      nX:X  a  [         R                  " X45      nO4[         R                  " SU	-  SU-  45      nUUSU	2SU24'   UUU	S2US24'   UR#                  UR                   5      nUnX:X  a  UU-  nO2USSU	24==   USSU	24   -  ss'   USU	* S24==   USU	* S24   -  ss'   USSU24   nUSU* S24   n US:w  d  X2R
                  S-
  :w  al  [         R                  " UX2R
                  S-
  5      n[         R                  " U X2R
                  S-
  5      n [         R                  " UX2R
                  S-
  5      nUUU 4$ )	a  Forward-backward IIR filter that uses Gustafsson's method.

Apply the IIR filter defined by ``(b,a)`` to `x` twice, first forward
then backward, using Gustafsson's initial conditions [1]_.

Let ``y_fb`` be the result of filtering first forward and then backward,
and let ``y_bf`` be the result of filtering first backward then forward.
Gustafsson's method is to compute initial conditions for the forward
pass and the backward pass such that ``y_fb == y_bf``.

Parameters
----------
b : scalar or 1-D ndarray
    Numerator coefficients of the filter.
a : scalar or 1-D ndarray
    Denominator coefficients of the filter.
x : ndarray
    Data to be filtered.
axis : int, optional
    Axis of `x` to be filtered.  Default is -1.
irlen : int or None, optional
    The length of the nonnegligible part of the impulse response.
    If `irlen` is None, or if the length of the signal is less than
    ``2 * irlen``, then no part of the impulse response is ignored.

Returns
-------
y : ndarray
    The filtered data.
x0 : ndarray
    Initial condition for the forward filter.
x1 : ndarray
    Initial condition for the backward filter.

Notes
-----
Typically the return values `x0` and `x1` are not needed by the
caller.  The intended use of these return values is in unit tests.

References
----------
.. [1] F. Gustaffson. Determining the initial states in forward-backward
       filtering. Transactions on Signal Processing, 46(4):988-992, 1996.

r   r   r?   r   N)r  rp  .)rt   rl  r   rg   r   r   swapaxesr   r   r)   rf   hstackrA  r   rg  r   rZ  rX  )!rM  r   r,  rq  irlenr  r|  r  r$  r  Obsr  r   ObsrSSrr  y_fy_fby_by_bfdelta_y_bf_fbdeltastart_mend_mic_optdelta2dic_opt0r1  wicy_optx0x1s!                                    rR   _filtfilt_gustr  S  sc   b 	aA
aAAA!#Ez1!q I"((2,,,rzTVVaZ'KK!, 	
A}QuW ((A:
C	%BBqEbhhqkb1!4C1I1e_1"a[BE
  tt9D 	c$B$ia(A 
4R4B 	vIIrx*+ HHac1U7^$"1"fuf*!"ef*
 !
C1S$B$Y(dd3D
!#tt)
%c4R4i
0C1D4KMvRaR(cA23h'/b9
 zzQa'* --EKKO466,,q'*1-//Sb!1QWWR[N!BC 	vIIrj!HHac1U7^$"1"fuf*!"ef* **QSS/C Evc2A2g#c2A2g,&cA23h3sQBCx=(	VeV	B	eVW	BrzTVVaZ'[[T66A:.[[T66A:.E4!4"b=rm   c                Z   [         R                  " U 5      n [         R                  " U5      n[         R                  " U5      nUS;  a  [        S5      eUS:X  a  [	        XX#US9u  pn
U$ [        XEX#[        [        U5      [        U 5      5      S9u  p[        X5      nS/UR                  -  nUR                  X'   [         R                  " X5      n[        USUS9n[        XXX-  S9u  nn[        US	US
9n[        X[        XS9X=U-  S9u  nn[        XS9nUS:  a  [        XU* US9nU$ )a7  
Apply a digital filter forward and backward to a signal.

This function applies a linear digital filter twice, once forward and
once backwards.  The combined filter has zero phase and a filter order
twice that of the original.

The function provides options for handling the edges of the signal.

The function `sosfiltfilt` (and filter design using ``output='sos'``)
should be preferred over `filtfilt` for most filtering tasks, as
second-order sections have fewer numerical problems.

Parameters
----------
b : (N,) array_like
    The numerator coefficient vector of the filter.
a : (N,) array_like
    The denominator coefficient vector of the filter.  If ``a[0]``
    is not 1, then both `a` and `b` are normalized by ``a[0]``.
x : array_like
    The array of data to be filtered.
axis : int, optional
    The axis of `x` to which the filter is applied.
    Default is -1.
padtype : str or None, optional
    Must be 'odd', 'even', 'constant', or None.  This determines the
    type of extension to use for the padded signal to which the filter
    is applied.  If `padtype` is None, no padding is used.  The default
    is 'odd'.
padlen : int or None, optional
    The number of elements by which to extend `x` at both ends of
    `axis` before applying the filter.  This value must be less than
    ``x.shape[axis] - 1``.  ``padlen=0`` implies no padding.
    The default value is ``3 * max(len(a), len(b))``.
method : str, optional
    Determines the method for handling the edges of the signal, either
    "pad" or "gust".  When `method` is "pad", the signal is padded; the
    type of padding is determined by `padtype` and `padlen`, and `irlen`
    is ignored.  When `method` is "gust", Gustafsson's method is used,
    and `padtype` and `padlen` are ignored.
irlen : int or None, optional
    When `method` is "gust", `irlen` specifies the length of the
    impulse response of the filter.  If `irlen` is None, no part
    of the impulse response is ignored.  For a long signal, specifying
    `irlen` can significantly improve the performance of the filter.

Returns
-------
y : ndarray
    The filtered output with the same shape as `x`.

See Also
--------
sosfiltfilt, lfilter_zi, lfilter, lfiltic, savgol_filter, sosfilt

Notes
-----
When `method` is "pad", the function pads the data along the given axis
in one of three ways: odd, even or constant.  The odd and even extensions
have the corresponding symmetry about the end point of the data.  The
constant extension extends the data with the values at the end points. On
both the forward and backward passes, the initial condition of the
filter is found by using `lfilter_zi` and scaling it by the end point of
the extended data.

When `method` is "gust", Gustafsson's method [1]_ is used.  Initial
conditions are chosen for the forward and backward passes so that the
forward-backward filter gives the same result as the backward-forward
filter.

The option to use Gustaffson's method was added in scipy version 0.16.0.

References
----------
.. [1] F. Gustaffson, "Determining the initial states in forward-backward
       filtering", Transactions on Signal Processing, Vol. 46, pp. 988-992,
       1996.

Examples
--------
The examples will use several functions from `scipy.signal`.

>>> import numpy as np
>>> from scipy import signal
>>> import matplotlib.pyplot as plt

First we create a one second signal that is the sum of two pure sine
waves, with frequencies 5 Hz and 250 Hz, sampled at 2000 Hz.

>>> t = np.linspace(0, 1.0, 2001)
>>> xlow = np.sin(2 * np.pi * 5 * t)
>>> xhigh = np.sin(2 * np.pi * 250 * t)
>>> x = xlow + xhigh

Now create a lowpass Butterworth filter with a cutoff of 0.125 times
the Nyquist frequency, or 125 Hz, and apply it to ``x`` with `filtfilt`.
The result should be approximately ``xlow``, with no phase shift.

>>> b, a = signal.butter(8, 0.125)
>>> y = signal.filtfilt(b, a, x, padlen=150)
>>> np.abs(y - xlow).max()
9.1086182074789912e-06

We get a fairly clean result for this artificial example because
the odd extension is exact, and with the moderately long padding,
the filter's transients have dissipated by the time the actual data
is reached.  In general, transient effects at the edges are
unavoidable.

The following example demonstrates the option ``method="gust"``.

First, create a filter.

>>> b, a = signal.ellip(4, 0.01, 120, 0.125)  # Filter to be applied.

`sig` is a random input signal to be filtered.

>>> rng = np.random.default_rng()
>>> n = 60
>>> sig = rng.standard_normal(n)**3 + 3*rng.standard_normal(n).cumsum()

Apply `filtfilt` to `sig`, once using the Gustafsson method, and
once using padding, and plot the results for comparison.

>>> fgust = signal.filtfilt(b, a, sig, method="gust")
>>> fpad = signal.filtfilt(b, a, sig, padlen=50)
>>> plt.plot(sig, 'k-', label='input')
>>> plt.plot(fgust, 'b-', linewidth=4, label='gust')
>>> plt.plot(fpad, 'c-', linewidth=1.5, label='pad')
>>> plt.legend(loc='best')
>>> plt.show()

The `irlen` argument can be used to improve the performance
of Gustafsson's method.

Estimate the impulse response length of the filter.

>>> z, p, k = signal.tf2zpk(b, a)
>>> eps = 1e-9
>>> r = np.max(np.abs(p))
>>> approx_impulse_len = int(np.ceil(np.log(eps) / np.log(r)))
>>> approx_impulse_len
137

Apply the filter to a longer signal, with and without the `irlen`
argument.  The difference between `y1` and `y2` is small.  For long
signals, using `irlen` gives a significant performance improvement.

>>> x = rng.standard_normal(4000)
>>> y1 = signal.filtfilt(b, a, x, method='gust')
>>> y2 = signal.filtfilt(b, a, x, method='gust', irlen=approx_impulse_len)
>>> print(np.max(np.abs(y1 - y2)))
2.875334415008979e-10

)rE   gustzmethod must be 'pad' or 'gust'.r  )rq  r  ntapsr   r  rq  rq  r  r   r  rq  rp  r   r  r  rq  )rt   rl  ru   rO   r  _validate_padr   rg   r8   r   r   r   r   r)   r   )rM  r   r,  rq  rG  padlenr   r  r  z1z2edgeextr  zi_shaper  r  y0s                     rR   r<   r<     s2   | 	aA
aA


1A_$:;;"1UC	r gq$'AA$79ID 
A	B
 sQVV|HWWHN	B	!B	Cad	+B aCrw7GQ 
ARd	+BaL6T2gNGQ 	Q"AaxqD5t<Hrm   c                   U S;  a  [        SU  S35      eU c  SnUc  US-  nOUnUR                  U   U::  a  [        SU-  5      eU b:  US:  a4  U S:X  a  [        X%US9nXV4$ U S	:X  a  [        X%US9nXV4$ [	        X%US9n XV4$ UnXV4$ )
z'Helper to validate padding for filtfilt)evenoddr   NzUnknown value 'zG' given to padtype. padtype must be 'even', 'odd', 'constant', or None.r   rp   zJThe length of the input vector x must be greater than padlen, which is %d.r  rp  r  )rO   r   r   r   r   )rG  r  r,  rq  r  r  r  s          rR   r  r    s    77?7) 4O O P 	P ~qy 	wwt} 57;< = 	= tax f1.C 9 !-C
 9 A$/C 9 9rm   c                h    [         R                  " U 5      n U R                  S:X  a  [        S5      eU $ )Nr   zx must be at least 1-D)rt   ru   r   rO   )r,  s    rR   r  r    s+    


1Avv{122Hrm   c                   [        U S5        [        US5        Ub  [        US5        [        U5      n[        U 5      u  p[        UR                  5      nSXR'   [        U/U-   5      nX/nUb%  UR                  [        R                  " U5      5        [        R                  " U6 nUR                  S;  a  [        SU S35      eUbN  [        R                  " X75      nUR                  U:w  a%  [        SX!R                  XEUR                  4-  5      eSnO[        R                  " XWS9nS	nX!R                  -  n[        R                   " XS
5      n[        R                   " USUS-   /SS
/5      nUR                  UR                  p[        R"                  " US
UR                  S
   45      n[        R                  " XSS9n[        R$                  " [        R"                  " US
US45      5      nU R'                  US	S9n [)        XU5        Xl        [        R                   " US
U5      nU(       a*  Xl        [        R                   " USS
/SUS-   /5      nX4nU$ UnU$ )a  
Filter data along one dimension using cascaded second-order sections.

Filter a data sequence, `x`, using a digital IIR filter defined by
`sos`.

Parameters
----------
sos : array_like
    Array of second-order filter coefficients, must have shape
    ``(n_sections, 6)``. Each row corresponds to a second-order
    section, with the first three columns providing the numerator
    coefficients and the last three providing the denominator
    coefficients.
x : array_like
    An N-dimensional input array.
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.
zi : array_like, optional
    Initial conditions for the cascaded filter delays.  It is a (at
    least 2D) vector of shape ``(n_sections, ..., 2, ...)``, where
    ``..., 2, ...`` denotes the shape of `x`, but with ``x.shape[axis]``
    replaced by 2.  If `zi` is None or is not given then initial rest
    (i.e. all zeros) is assumed.
    Note that these initial conditions are *not* the same as the initial
    conditions given by `lfiltic` or `lfilter_zi`.

Returns
-------
y : ndarray
    The output of the digital filter.
zf : ndarray, optional
    If `zi` is None, this is not returned, otherwise, `zf` holds the
    final filter delay values.

See Also
--------
zpk2sos, sos2zpk, sosfilt_zi, sosfiltfilt, freqz_sos

Notes
-----
The filter function is implemented as a series of second-order filters
with direct-form II transposed structure. It is designed to minimize
numerical precision errors for high-order filters.

.. versionadded:: 0.16.0

Examples
--------
Plot a 13th-order filter's impulse response using both `lfilter` and
`sosfilt`, showing the instability that results from trying to do a
13th-order filter in a single stage (the numerical error pushes some poles
outside of the unit circle):

>>> import matplotlib.pyplot as plt
>>> from scipy import signal
>>> b, a = signal.ellip(13, 0.009, 80, 0.05, output='ba')
>>> sos = signal.ellip(13, 0.009, 80, 0.05, output='sos')
>>> x = signal.unit_impulse(700)
>>> y_tf = signal.lfilter(b, a, x)
>>> y_sos = signal.sosfilt(sos, x)
>>> plt.plot(y_tf, 'r', label='TF')
>>> plt.plot(y_sos, 'k', label='SOS')
>>> plt.legend(loc='best')
>>> plt.show()

r+   r?   r  r  r  zyInvalid zi shape. With axis=%r, an input with shape %r, and an sos array with %d sections, zi must have shape %r, got %r.Tr  Fr   r   r   C)r  )r   )r   r  r   r   r   r   r  rt   ru   rY  r  r  r   rO   r   r   r  r   ascontiguousarrayr_  r   )rz  r,  rq  r  r{  
x_zi_shaper  rv   	return_zir"  r  r   s               rR   r+   r+     s"   L C#Ay!	~I&AA#C(OCaggJJ
|j01JXF	~bjjn%NNF#Ezz"!L"GHH	~XXb 88z! ; #GGZRXXNO P P 	XXj.	&&=D
AR A	R!TAXR	1BX


1r1772;'(A
%A			bjjb*a-@A	BB
**U*
'CSRG
Ar4 A[[b"X4!8}5g J Jrm   c                   [        U 5      u  p[        U5      nSU-  S-   nU[        U SS2S4   S:H  R                  5       U SS2S4   S:H  R                  5       5      -  n[	        X4XUS9u  px[        U 5      n	S/UR                  -  n
SX'   U/U
-   U	l        [        USUS9n[        XX)U-  S9u  p[        US	US
9n[        U [        XS9X)U-  S9u  p[        XS9nUS:  a  [        XU* US9nU$ )a
  
A forward-backward digital filter using cascaded second-order sections.

See `filtfilt` for more complete information about this method.

Parameters
----------
sos : array_like
    Array of second-order filter coefficients, must have shape
    ``(n_sections, 6)``. Each row corresponds to a second-order
    section, with the first three columns providing the numerator
    coefficients and the last three providing the denominator
    coefficients.
x : array_like
    The array of data to be filtered.
axis : int, optional
    The axis of `x` to which the filter is applied.
    Default is -1.
padtype : str or None, optional
    Must be 'odd', 'even', 'constant', or None.  This determines the
    type of extension to use for the padded signal to which the filter
    is applied.  If `padtype` is None, no padding is used.  The default
    is 'odd'.
padlen : int or None, optional
    The number of elements by which to extend `x` at both ends of
    `axis` before applying the filter.  This value must be less than
    ``x.shape[axis] - 1``.  ``padlen=0`` implies no padding.
    The default value is::

        3 * (2 * len(sos) + 1 - min((sos[:, 2] == 0).sum(),
                                    (sos[:, 5] == 0).sum()))

    The extra subtraction at the end attempts to compensate for poles
    and zeros at the origin (e.g. for odd-order filters) to yield
    equivalent estimates of `padlen` to those of `filtfilt` for
    second-order section filters built with `scipy.signal` functions.

Returns
-------
y : ndarray
    The filtered output with the same shape as `x`.

See Also
--------
filtfilt, sosfilt, sosfilt_zi, freqz_sos

Notes
-----
.. versionadded:: 0.18.0

Examples
--------
>>> import numpy as np
>>> from scipy.signal import sosfiltfilt, butter
>>> import matplotlib.pyplot as plt
>>> rng = np.random.default_rng()

Create an interesting signal to filter.

>>> n = 201
>>> t = np.linspace(0, 1, n)
>>> x = 1 + (t < 0.5) - 0.25*t**2 + 0.05*rng.standard_normal(n)

Create a lowpass Butterworth filter, and use it to filter `x`.

>>> sos = butter(4, 0.125, output='sos')
>>> y = sosfiltfilt(sos, x)

For comparison, apply an 8th order filter using `sosfilt`.  The filter
is initialized using the mean of the first four values of `x`.

>>> from scipy.signal import sosfilt, sosfilt_zi
>>> sos8 = butter(8, 0.125, output='sos')
>>> zi = x[:4].mean() * sosfilt_zi(sos8)
>>> y2, zo = sosfilt(sos8, x, zi=zi)

Plot the results.  Note that the phase of `y` matches the input, while
`y2` has a significant phase delay.

>>> plt.plot(t, x, alpha=0.5, label='x(t)')
>>> plt.plot(t, y, label='y(t)')
>>> plt.plot(t, y2, label='y2(t)')
>>> plt.legend(framealpha=1, shadow=True)
>>> plt.grid(alpha=0.25)
>>> plt.xlabel('t')
>>> plt.show()

r?   r   Nr      r  r  r  r   r  rp  r  )r   r  r  r  r  r9   r   r   r   r+   r   )rz  r,  rq  rG  r  r{  r  r  r  r  r  x_0r  r  y_0s                  rR   r:   r:   n  s   r $C(OCAA 
NQE	S#ad)q.%%'#ad)q.)=)=)?@@Egq$)+ID 
CBsQVV|HHN|h&BH
Sqt
,CcT3h7GQ
Qbt
,Cc<5D#XNGQQ"AaxqD5t<Hrm   c                   [         R                  " U 5      n [        R                  " U5      nUb  [        R                  " U5      nU R                  n[         R
                  " U[         R                  5      (       a  UR                  [         R                  :X  a  [         R                  nUS:X  aI  Uc
  SU-  nSU-  n[        US-   SU-  SS9Sp[         R                  " XS	9n[         R                  " XS	9n	GOUS
:X  a,  Sn
Uc  Sn[        USSU-  SS9n[         R                  " XS	9nGOe[        U[        5      (       GaD  UR                  5       nUR                  R                   S   S:X  a*  UR#                  5       nUR$                  UR&                  pSnO[)        [         R*                  " UR                  5      5      (       dS  [)        [         R*                  " UR                  5      5      (       d%  [         R*                  " UR,                  5      (       a*  Sn
UR#                  5       nUR$                  UR&                  pOMSn
[/        UR0                  UR                  UR,                  5      n[         R                  " XS	9nO[3        S5      e[5        S5      /U R6                  -  nUS:X  ab  WW	-  nU(       a  [9        U SXUS9nOU R                   U   U-  [;        U R                   U   U-  5      -   n[=        XSXS9n[5        SUS5      X'   OQU(       a  W
(       a  [?        WXS9nO)[A        WW	XS9nOW
(       a  [C        WXS9nO[E        WW	XS9n[5        SSU5      X'   U[G        U5         $ )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.

    .. versionadded:: 0.18.0

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.

Notes
-----
The ``zero_phase`` keyword was added in 0.18.0.
The possibility to use instances of ``dlti`` as ``ftype`` was added in
0.18.0.

Examples
--------

>>> import numpy as np
>>> from scipy import signal
>>> import matplotlib.pyplot as plt

Define wave parameters.

>>> wave_duration = 3
>>> sample_rate = 100
>>> freq = 2
>>> q = 5

Calculate number of samples.

>>> samples = wave_duration*sample_rate
>>> samples_decimated = int(samples/q)

Create cosine wave.

>>> x = np.linspace(0, wave_duration, samples, endpoint=False)
>>> y = np.cos(x*np.pi*freq*2)

Decimate cosine wave.

>>> ydem = signal.decimate(y, q)
>>> xnew = np.linspace(0, wave_duration, samples_decimated, endpoint=False)

Plot original and decimated waves.

>>> plt.plot(x, y, '.-', xnew, ydem, 'o-')
>>> plt.xlabel('Time, Seconds')
>>> plt.legend(['data', 'decimated'], loc='best')
>>> plt.show()

Nfirr:  r?   r   r:  hammingr;  r  iirT   g?g?rz  )outputr   Fzinvalid ftype)rq  r-  )rE  rF  rq  rp  )$rt   ru   operatorr  rv   rw   inexactr  rz   r|   r   r   r  r
   _as_zpkr  r   _as_tfr  r  rN  	iscomplexgainr   r   rO   r   r   r6   r  r   r:   r<   r+   r)   r   )r,  qr$  ftyperq  
zero_phaserY  rJ  rM  r   iir_use_sosrz  systemr6  r  r  s                   rR   r=   r=     s   j 	

1AqA}NN1''K==bjj11


bjj
(jj~9AvHHAac26)4b1JJq,JJq,	%9AQcAge4jj0	E4	 	 <<a A%\\^F::vzzqE",,v||,--R\\&,,/00fkk**K\\^F::vzzqK&,,fkkBC**S4C))
+	B~EaA;A GGDMQ&aggdma.?)@@E6AT5$/BH Q2Q10C.Aq!/tQ'U2Y<rm   rZ   )rB   r   )rB   )F)rB   N)buifc)passr  rp   )rB   F)NN)rB   rD   r   )rp   r   )Nr   )r   )r   
np.ndarrayr  ztuple[int | None, int | None]r  z
int | Noner  r  r  zLiteral['lowpass', 'all', None]rq  rO  returnr  )MbP?r  )r  r  )Nr   Nr%  )r   )kaiserg      @r   N)r   rd  r   F)rh  r  rq  rO  r  zLiteral['linear', 'constant']r  zArrayLike | intri  r  r  r  )r   r  NrE   N)r   r  N)Nr  r   T)j
__future__r   r  r   r   r   r;  r   typingr   numpy._typingr   scipy.spatialr    r	   _ltisysr
   _upfirdnr   r   r   scipyr   r   r   r   scipy.fft._helperr   numpyrt   scipy.specialr   windowsr   _arraytoolsr   r   r   r   r   _filter_designr   r   r   _fir_filter_designr   r   __all__rM   rU   rS   rW   rl   r   r   r   r   r   r   r   r#   r   r$   r  r*  r3  r   r   rF  r;   r!   r%   r&   r(   r"   r    r'   r)   r*   r,   r-   r.   r/   r  r0   r1   r  r  r3   r4   r  r2   r5   r6   r>   r7   r8   r9   r  r<   r  r  r+   r:   r=   r[   rm   rR   <module>r     sh   #       # !   : : '  5  "  O O : : & 5 A.	1aQA/7MDF G1T`F:z9x#/Ls5ll3^M5`*(V'>T" FK\J1ZBJAHHVWtcLi4XE?PK\9xsl7tSC!%u9BSCSC04SC6SC SC !+SCj%<T<nH"V2 6p%ff(R8>G(TL^ />+/TnK\ +-2:<A|/||59|FP|~EPIXpf CHGTDrjnb^rm   