a
    BCCfg                    @   s  d dl Z d dlZd dlmZ d dlZd dlZd dlmZ ddlm	Z	 ddl
mZ ddlmZmZmZ d dlmZmZ d d	lmZ d d
lmZ d dlZd dlmZ ddlmZ ddlmZmZm Z m!Z!m"Z" ddl#m$Z$m%Z%m&Z& ddl'm(Z( ddl)m)Z) g dZ*d dddZ+d d ddddddZ,dd Z-dd Z.dddZ/dddZ0dd d!Z1d"d# Z2dd%d&Z3dd'd(Z4d)d* Z5dd+d,Z6d-d. Z7dd/d0Z8dd2d3Z9d4d5 Z:d6d7 Z;d8d9 Z<d:d; Z=dd>d?Z>dd@dAZ?ddBdCZ@dDdE ZAddFdGZBddHdIZCddKdLZDddMdNZEddOdPZFddRdSZGddTdUZHdVdW ZIddXdYZJddZd[ZKd\ZLd]d^ ZMd_d` ZNddcddZOddfdgZPddhdiZQdjdk ZRddldmZSddndoZTdpdq ZUddrdsZVddudvZWddydzZXd{d| ZYdd~dZZdd Z[dd Z\dddZ]dddZ^dd Z_dd Z`dddZadddZbdddZcdS )    N)prod)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
cmplx_sort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wrapZcircularZsymmZ	symmetricZreflectc              
   C   s>   z
t |  W S  ty8 } ztd|W Y d }~n
d }~0 0 d S )N5Acceptable mode flags are 'valid', 'same', or 'full'.)	_modedictKeyError
ValueError)modee rI   U/var/www/html/django/DPS/env/lib/python3.9/site-packages/scipy/signal/_signaltools.py_valfrommode*   s    
rK   c              
   C   sB   zt |  d> W S  ty< } ztd|W Y d }~n
d }~0 0 d S )Nr;   zZAcceptable boundary flags are 'fill', 'circular' (or 'wrap'), and 'symmetric' (or 'symm').)_boundarydictrE   rF   )boundaryrH   rI   rI   rJ   _bvalfromboundary2   s    rN   c                    sn   | dkrdS  sdS |du r(t t }t fdd|D }t fdd|D }|sh|shtd| S )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<   FNc                 3   s   | ]} | | kV  qd S NrI   .0ishape1shape2rI   rJ   	<genexpr>R       z&_inputs_swap_needed.<locals>.<genexpr>c                 3   s   | ]}|  | kV  qd S rO   rI   rP   rS   rI   rJ   rV   S   rW   zOFor 'valid' mode, one must be at least as large as the other in every dimension)rangelenallrF   )rG   rT   rU   axesZok1Zok2rI   rS   rJ   _inputs_swap_needed:   s    r\   r>   autoc              
   C   s  t | } t |}| j|j  kr,dkr<n n| |  S | j|jkrPtdzt| }W n. ty } ztd|W Y d}~n
d}~0 0 |dv rt| t|||S |dkrt	| ||rt 
| ||S |dkr|j| jkpt|| j|j}| r||  } }|dkr@d	d
 t| j|jD }t || j}t| |||}	ndd
 t| j|jD }t || j}
tdd | jD }|  |
|< |dkrt || j}n|dkrt | j| j}t|
|||}	|rt|	}	|	S tddS )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   /in1 and in2 should have the same dimensionalityrC   N)r   r]   directr>   r<   c                 S   s   g | ]\}}|| d  qS r   rI   rQ   rR   jrI   rI   rJ   
<listcomp>  rW   zcorrelate.<locals>.<listcomp>c                 S   s   g | ]\}}|| d  qS r`   rI   ra   rI   rI   rJ   rc     rW   c                 s   s   | ]}t d |V  qdS )r   NslicerP   rI   rI   rJ   rV     rW   zcorrelate.<locals>.<genexpr>r=   7Acceptable method flags are 'auto', 'direct', or 'fft'.)npasarrayndimconjrF   rD   rE   r   _reverse_and_conj_np_conv_okr   sizer\   shapezipemptydtyper   Z_correlateNDzerostuplecopy)in1in2rG   methodvalrH   swapped_inputsZpsoutzZ
in1zpaddedscrI   rI   rJ   r   \   sP     






r   c                 C   s   |dkrt | d | }n|dkrt | d | }|jd }| d }| d dkrj||| ||  }q||| || d  }n4|dkr| | }|dkrt |d }nt |d}|S )a  
    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)]
    r>   r   r=   r;   r   r<   )rg   arangerm   )Zin1_lenZin2_lenrG   ZlagsmidZ	lag_boundrI   rI   rJ   r   $  s    ?
r   c                    sR   t |}t | j}|| d |   fddtt D }| t| S )Nr;   c                    s   g | ]}t |  | qS rI   rd   )rQ   kZendindZstartindrI   rJ   rc     rW   z_centered.<locals>.<listcomp>)rg   rh   arrayrn   rX   rY   rs   )ZarrnewshapeZ	currshapeZmyslicerI   r   rJ   	_centered  s    
r   Fc                    s   | j |j  du }t| d d\} |s:t s:tdfdd D  |rZ   t fddt| jD std d	 t| d
r||  } }| | fS )a  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)rn   r[   z#when provided, axes cannot be emptyc                    s(   g | ] } | d kr| d kr|qS r`   rI   rQ   a)s1s2rI   rJ   rc     rW   z(_init_freq_conv_axes.<locals>.<listcomp>c                 3   s>   | ]6}| vr| | kp4| d kp4| d kV  qdS )r   NrI   r   r[   r   r   rI   rJ   rV     s   
z'_init_freq_conv_axes.<locals>.<genexpr>z%incompatible shapes for in1 and in2: z and r[   )	rn   r   rY   rF   sortrZ   rX   ri   r\   )ru   rv   rG   r[   sorted_axesZnoaxes_rI   r   rJ   _init_freq_conv_axes  s(     
r   c                    s   t |s| | S | jjdkp&|jjdk |rB fdd|D }n} sZtjtj }}ntjtj }}|| ||d}||||d}	|||	 ||d}
|rtdd D }|
| }
|
S )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`.

    cc                    s   g | ]}t |   qS rI   )sp_fftnext_fast_lenr   Zcomplex_resultrn   rI   rJ   rc     s   z%_freq_domain_conv.<locals>.<listcomp>r   c                 S   s   g | ]}t |qS rI   rd   )rQ   szrI   rI   rJ   rc     rW   )	rY   rq   kindr   ZrfftnZirfftnZfftnZifftnrs   )ru   rv   r[   rn   calc_fast_lenZfshaper   ifftZsp1Zsp2retZfslicerI   r   rJ   _freq_domain_conv  s$    r   c                    sf   |dkr  S |dkr&t  S |dkrZ fddtjD }t|  S tddS )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`.

    r>   r=   r<   c                    s2   g | ]*}| vrj | n| |  d  qS r`   rn   r   r[   r   r   r   rI   rJ   rc   &  s   z$_apply_conv_mode.<locals>.<listcomp>z4acceptable mode flags are 'valid', 'same', or 'full'N)rt   r   rX   ri   rF   )r   r   r   rG   r[   Zshape_validrI   r   rJ   _apply_conv_mode  s    r   c                    s   t | } t |}| j|j  kr,dkr8n n| | S | j|jkrNtdn| jdksb|jdkrlt g S t| || dd\} } | j|j fddt| jD }t	| | |dd}t
|| S )	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   c                    s<   g | ]4}| vr$t | | fn| |  d  qS r`   )maxrP   r   rI   rJ   rc     s   zfftconvolve.<locals>.<listcomp>Tr   )rg   rh   ri   rF   rm   r   r   rn   rX   r   r   )ru   rv   rG   r[   rn   r   rI   r   rJ   r   .  s$    ^




r   c           	      C   s   | | d d| |f}| |ks,| dks,|dkr0|S || krH||  } }d}nd}|| d kr\|S |d }| t ddtj |  ddj }tt|}|| kr|S |s|| d }|}n|}|| d }||||fS )a<  Calculate the optimal FFT lengths for overlapp-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   mathrH   realr   r   ceil)	r   r   fallbackZswappedoverlapZopt_size
block_sizein1_stepin2_steprI   rI   rJ   _calc_oa_lens  s(    
6"r   c                    sL  t | } t |}| j|j  kr,dkr8n n| | S | j|jkrNtdn:| jdksb|jdkrlt g S | j|jkrt| || dS t| || dd\} } | j|j s| | t	| S  fddt
| jD } fdd	t
| jD }t| \}}}|kr4|kr4t| || dS g }	g }
g }g }t
| jD ]8}| vrv|d
g7 }|d
g7 }qN| || krt| d ||  }| ||  | || k r|d7 }|||  |  }nd}d}| || krNt| d ||  }| ||  | || k r8|d7 }|||  |  }nd}d}|	|g7 }	|
|g7 }
|d|fg7 }|d|fg7 }qNtdd	 |D st j| |ddd} tdd	 |D st j||ddd}dd t D dd D t|}t|}tD ]*\}}|||	|  |||
|  q| j| } |j| }fdd D }t| ||ddt D ]|\}}}|| }|du rq~t | g|\}t |dg|d }t |g|d }t |dg|d }||7 }q~fddt
jD }j| tdd |D }| t	| S )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^   )rG   r[   Tr   c                    s,   g | ]$}| vrd n| |  d qS )Nr   rI   rP   r   rI   rJ   rc   z  s   zoaconvolve.<locals>.<listcomp>c                 3   s<   | ]4}| vr"d d | | fnt | | V  qdS )r   N)r   rP   r   rI   rJ   rV     s   zoaconvolve.<locals>.<genexpr>r   r   r   c                 s   s   | ]}|d kV  qdS r   NrI   rQ   ZcurpadrI   rI   rJ   rV     rW   constant)rG   Zconstant_valuesc                 s   s   | ]}|d kV  qdS r   rI   r   rI   rI   rJ   rV     rW   c                 S   s   g | ]\}}|| qS rI   rI   )rQ   rR   iaxrI   rI   rJ   rc     rW   c                 S   s   g | ]}|d  qS r`   rI   )rQ   r   rI   rI   rJ   rc     rW   c                    s   g | ]} | qS rI   rI   rP   )r   rI   rJ   rc     rW   Fr   Nr   c                    s>   g | ]6}|vr| vr"j | nj | j |d    qS r`   r   rP   )fft_axesr   
split_axesrI   rJ   rc     s   
c                 S   s   g | ]}t |qS rI   rd   )rQ   islicerI   rI   rJ   rc     rW   )rg   rh   ri   rF   rm   r   rn   r   r   r   rX   ro   r   r   rZ   rA   	enumeratelistinsertreshaper   splitrs   )ru   rv   rG   r[   Zshape_finalZoptimal_sizesoverlapsr   r   Znsteps1Znsteps2Z	pad_size1Z	pad_size2rR   Z	curnstep1Zcurpad1Z	curnstep2Zcurpad2Zreshape_size1Zreshape_size2r   Z	fft_shapeaxZax_fftZax_splitr   ZoverpartZret_overpartZ	shape_retZslice_finalrI   )r[   r   r   r   r   r   r   rJ   r      s    P













r    buifcc                 C   s:   t | tjkr| jj|v S | D ]}|jj|vr dS qdS )ab  
    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)typerg   ndarrayrq   r   )ZarrayskindsZarray_rI   rI   rJ   _numeric_arrays  s    r   c           
      C   s  |dkrdd t | |D }n:|dkr<dd t | |D }n|dkrJ| }ntd| | | }}t| dkr|d	 |d	  }}|dkr|| }nf|dkr||kr|| d | n|| d | }n4|dkr||k r|| n|| |d
 |d d
   }nf|dkr tt|t|t| }n@|dkrFtt|t|t| }n|dkr`t|t| }dd t | |D }t|}d| t| }	|	|fS )au  
    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``).

    r>   c                 S   s   g | ]\}}|| d  qS r`   rI   rQ   nr   rI   rI   rJ   rc     rW   z_conv_ops.<locals>.<listcomp>r<   c                 S   s    g | ]\}}t || d  qS r`   )absr   rI   rI   rJ   rc     rW   r=   z?Acceptable mode flags are 'valid', 'same', or 'full', not mode=r   r   r;   c                 S   s   g | ]\}}|| d  qS r`   rI   r   rI   rI   rJ   rc     rW      )ro   rF   rY   min_prodrg   log)
x_shapeZh_shaperG   Z	out_shaper   r   
direct_opsZfull_out_shapeNfft_opsrI   rI   rJ   	_conv_ops  s<    	

*


r   c           
      C   s   t | j|j|\}}| jdkr"dnd}| jdkr^dd|fdd|f|j| jkrVdd	|fnd
dndd|fdd|fdd|fd}|| \}}}	|| || |	 k S )a  
    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<   r>   r=   g.w'>gvlV>gG[*!>gʑQ>gVN+!>g4RP>)r   rn   ri   rm   )
xhrG   r   r   offset	constantsZO_fftZO_directZO_offsetrI   rI   rJ   _fftconv_faster#  s"    
r   c                 C   s    t dddf| j }| |  S )zO
    Reverse array `x` in all dimensions and perform the complex conjugate
    Nr   )re   ri   rj   )r   reverserI   rI   rJ   rk   M  s    rk   c                 C   sF   | j |j   krdkr>n n"|dv r(dS |dkrB| j|jkS ndS dS )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   )r>   r<   Tr=   FN)ri   rm   )volumekernelrG   rI   rI   rJ   rl   U  s    rl   passr   c           
      C   st   t | |}d}tddD ]"}d| }| |}|dkr q>q|dkrL|}n|d9 }|||}t|}|| }	|	S )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TimerrX   repeatr   )
stmtsetupr   timerr   pnumberbestrsecrI   rI   rJ   _timeit_fastf  s    
r   c                    s   t | t | |r`i }dD ]t fdd|< q |d |d k rTdnd}||fS tdd  fD rtt  tt    }|ttj j9 }|dt 	d	j
 d
 krdS t gddrdS t grt rdS dS )a  
    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_   c                      s   t  dS )N)rG   rw   )r   rI   r   rw   rG   r   rI   rJ   <lambda>  s   z$choose_conv_method.<locals>.<lambda>r   r_   c                 S   s   g | ]}t |gd dqS )Zuir   )r   rQ   r   rI   rI   rJ   rc     rW   z&choose_conv_method.<locals>.<listcomp>r;   floatr   br   )rg   rh   r   anyintr   r   r   rm   ZfinfoZnmantr   r   )ru   rv   rG   measuretimesZchosen_methodZ	max_valuerI   r   rJ   r7     s&    l

$r7   c                 C   s0  t | }t |}|j|j  kr,dkr8n n|| S |j|jkrLtdt||j|jrf|| }}|dkr|t|||d}|dkrt|||d}t ||}|j	dv rt 
|}t |jd st |jd rtjdtdd	 ||S |d
kr$t|||rt |||S t|t||d
S tddS )a  
    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   z5volume and kernel should have the same dimensionalityr]   rG   r   >   urR   zuUse of fft convolution on input with NAN or inf results in NAN or inf output. Consider using method='direct' instead.r;   )category
stacklevelr_   rf   N)rg   rh   ri   rF   r\   rn   r7   r   result_typer   ZaroundisnanZflatisinfwarningswarnRuntimeWarningastyperl   r   r   rk   )ru   rv   rG   rw   r   r   rz   r   rI   rI   rJ   r     s2    b




 

r   c                 C   s   t |}|jD ]}|d dkrtdqt | } | jtdfv rpd| j d}tj|tdd t	
| ||}ntj| ||dd	}|S )
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.Zfloat128z(Using order_filter with arrays of dtype > is deprecated in SciPy 1.11 and will be removed in SciPy 1.14r   r   )Z	footprintrG   )rg   rh   rn   rF   rq   objectr   r   DeprecationWarningr   _order_filterNDr   rank_filter)r   domainrankZdimsizemesgresultrI   rI   rJ   r!     s    6



r!   c           	      C   sJ  t | } |du rdg| j }t |}|jdkrDt | | j}t| jD ]}|| d dkrNtdqNt	dd t
|| jD rtjd	dd
 t j|| jd}t j|dd}|d }| jt jt jt jt jt jfv rtd| j d| jjdv r&d| j d}tj|tdd
 t| ||}n t|}tj| |d |dd}|S )a  
    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.

    Nr   rI   r;   r   *Each element of kernel_size should be odd.c                 s   s   | ]\}}||kV  qd S rO   rI   )rQ   r   srI   rI   rJ   rV     rW   zmedfilt.<locals>.<genexpr>zBkernel_size exceeds volume extent: the volume will be zero-padded.r   rq   r   axiszdtype=z is not supported by medfilt)Ogz#Using medfilt with arrays of dtype r   r   )rm   rG   )rg   
atleast_1dri   rh   rn   r   itemrX   rF   r   ro   r   r   onesrq   r   Zbool_Z	complex64Z
complex128Zclongdoublefloat16charr   r   r   r   r   r   )	r   kernel_sizer   r   Znumelsorderr   r   rm   rI   rI   rJ   r"     s:    *




r"   c                 C   s   t | } |du rdg| j }t |}|jdkrDt | | j}t| t |dt j|dd }t| d t |dt j|dd |d  }|du rt j	t 
|dd}| | }|d||  9 }||7 }t ||k ||}|S )	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()

    Nr   rI   r=   r   r   r;   r   )rg   rh   ri   rn   r   r  r   r  r   meanZravelwhere)ZimZmysizenoiseZlMeanZlVarresrz   rI   rI   rJ   r$   7  s&    1


 r$   r@   c                 C   sx   t | } t |}| j|j  kr,dks6n tdt|| j|jrP||  } }t|}t|}t	| |d|||}|S )a^
  
    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   )
rg   rh   ri   rF   r\   rn   rK   rN   r   _convolve2d)ru   rv   rG   rM   	fillvaluerx   bvalrz   rI   rI   rJ   r     s    K


r   c           	      C   s   t | } t |}| j|j  kr,dks6n tdt|| j|j}|rT||  } }t|}t|}t	| |
 d|||}|r|ddddddf }|S )ag  
    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
    >>> from scipy import datasets
    >>> rng = np.random.default_rng()
    >>> face = datasets.face(gray=True) - datasets.face(gray=True).mean()
    >>> template = np.copy(face[300:365, 670:750])  # 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   )rg   rh   ri   rF   r\   rn   rK   rN   r   r  rj   )	ru   rv   rG   rM   r  ry   rx   r  rz   rI   rI   rJ   r     s    R


r   c                 C   s   t | }|jjt jt jt jfvr,t||S |du r>dgd }t |}|jdkrbt 	|
 d}|D ]}|d dkrftdqft||S )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

    Nr   r;   rI   r   r   )rg   rh   rq   r   ZubyteZfloat32float64r"   rn   r   r  rF   r   Z
_medfilt2d)inputr	  imagerm   rI   rI   rJ   r#   B  s    X





r#   r   c                    s  t   t |}t|dkrt   t |} jdkrR|jdkrRtdt|} ||g}|durt |}|j|jkrtdt|j} jd d ||< t	|}|j|kr|jdg }|dk r||j7 }t
|jD ]}||kr|j| || kr|j| ||< q||krD|j| || krD|j| ||< q||krh|j| dkrhd||< qtd| d|j dqt jj|||}|| t j| }	|	jdvrtd	|	 t j |	d
 t j||	d
} |d   t j||	d
}t  fdd||}
|
jtdg }|durLt|j| ||< |
t	|  |7  < t|
j| t  d ||< |
t	| }|du r|S t|
j| t  d d||< |
t	| }||fS n,|du rt |||S t ||||S dS )aF  
    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   z+object of too small depth for desired arrayNr   z"Unexpected shape for zi: expected z, found .fdgFDGOinput type '%s' not supportedr   c                    s   t  | S rO   )rg   r   )yr   rI   rJ   r   [  rW   zlfilter.<locals>.<lambda>)rg   r  rY   rh   ri   rF   _validate_xr   rn   rs   rX   strideslibZstride_tricksZ
as_stridedappendr   r  NotImplementedErrorr   Zapply_along_axisre   r   Z_linear_filter)r   r   r   r  ziinputsZexpected_shaper  r   rq   Zout_fullindrz   zfrI   r  rJ   r%     st    |













 

r%   c              
   C   s  t |d }t | d }t||}t |}|du rrt t | t ||}|jdv rbt j}t j||d}njt |}t t | t |||}|jdv rt j}||}t |}||k rt j	|t || f }||}t ||}	t |}||k rt j	|t || f }t
|D ]4}
t j| |
d d |d||
   dd|	|
< q&t
|D ]<}
|	|
  t j||
d d |d||
   dd8  < qd|	S )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   r   )rg   rm   r   rh   r   r   r  rr   r   r_rX   sum)r   r   r  r   r   MKr   Lr  mrI   rI   rJ   r&   q  s6    (









2:r&   c           	      C   s   t | }t |}|jdkr&td|jdkr8tdt|}t|}||krZg }|}n:t || d t}d|d< t|||}|t||dd }||fS )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   r>   r   )	rg   r  ri   rF   rY   rr   r   r%   r   )	signalZdivisornumdenr   Dquotremr  rI   rI   rJ   r(     s     )



r(   c                 C   s   t | } t | rtd|du r.| j| }|dkr>tdtj| ||d}t j||jd}|d dkrd |d< ||d < d|d|d < nd|d< d|d|d d < | j	dkrt j
g| j	 }td||< |t| }tj|| |d} | S )	ao  
    Compute the analytic signal, using the Hilbert transform.

    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 signal ``x(t)`` is:

    .. 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`. [1]_

    In other words, the negative half of the frequency spectrum is zeroed
    out, turning the real-valued signal into a complex 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] Leon Cohen, "Time-Frequency Analysis", 1995. Chapter 2.
    .. [3] Alan V. Oppenheim, Ronald W. Schafer. Discrete-Time Signal
           Processing, Third Edition, 2009. Chapter 12.
           ISBN 13: 978-1292-02572-8

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

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

    >>> duration = 1.0
    >>> fs = 400.0
    >>> samples = int(fs*duration)
    >>> t = np.arange(samples) / fs

    We create a chirp of which the frequency increases from 20 Hz to 100 Hz and
    apply an amplitude modulation.

    >>> 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 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)
    >>> ax0.plot(t, signal, label='signal')
    >>> ax0.plot(t, amplitude_envelope, label='envelope')
    >>> ax0.set_xlabel("time in seconds")
    >>> ax0.legend()
    >>> ax1.plot(t[1:], instantaneous_frequency)
    >>> ax1.set_xlabel("time in seconds")
    >>> ax1.set_ylim(0.0, 120.0)
    >>> fig.tight_layout()

    x must be real.Nr   N must be positive.r   r   r;   r   )rg   rh   iscomplexobjrF   rn   r   r   rr   rq   ri   newaxisre   rs   r   )r   r   r  Xfr   r!  rI   rI   rJ   r)     s(    U



r)   c                 C   s  t | } | jdkrtdt | r.td|du r>| j}nLt|trb|dkrXtd||f}n(t|dkst 	t 
|dkrtdtj| |dd	}t j|d |jd
}t j|d |jd
}||fD ]^}|jd }|d dkrd |d< ||d < d|d|d < qd|d< d|d|d d < q|ddt jf |t jddf  }| j}|dkr||ddt jf }|d8 }qTtj|| dd	} | S )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.r0  Nr   r1  z@When given as a tuple, N must hold exactly two positive integers)r   r   r   r   r   )rg   
atleast_2dri   rF   r2  rn   
isinstancer   rY   r   rh   r   Zfft2rr   rq   r3  Zifft2)r   r   r4  Zh1Zh2r   ZN1r   rI   rI   rJ   r*   i	  s<    




 
$
r*   zcmplx_sort was deprecated in SciPy 1.12 and will be removed
in SciPy 1.15. The exact equivalent for a numpy array argument is
>>> def cmplx_sort(p):
...    idx = np.argsort(abs(p))
...    return np.take(p, idx, 0), idx
c                 C   s   t jttdd t| S )Nr;   r   )r   r   _msg_cplx_sortr   _cmplx_sort)r   rI   rI   rJ   r+   	  s    r+   c                 C   s*   t | } t t| }t | |d|fS )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   )rg   rh   Zargsortr   Ztake)r   ZindxrI   rI   rJ   r8  	  s    
r8  MbP?r   c           
         s  |dv rt j}n(|dv r t j}n|dv r0t j}ntdt | } t t| df}t | |dddf< t 	| |dddf< t
|}g }g }t jt| td	 tt| D ]X} | rq||| |}	 fd
d|	D }	||| |	  |t|	 d |	< qt |t |fS )ah  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avgr  J`rtype` must be one of {'max', 'maximum', 'min', 'minimum', 'avg', 'mean'}r;   Nr   r   r   c                    s   g | ]} | s|qS rI   rI   r   usedrI   rJ   rc   
  rW   z unique_roots.<locals>.<listcomp>T)rg   r   r   r  rF   rh   rp   rY   r   imagr   rr   boolrX   Zquery_ball_pointr  )
r   tolrtypereduceZpointstreeZp_uniqueZp_multiplicityrR   grouprI   rA  rJ   r,   	  s0    4

r,   r?  c                 C   s   t | } t |}t t |d}t|||\}}t||dd\}}t|dkrZd}	nt ||}	t| |D ]\}
}t |	|
| }	qp|	|fS )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   	rg   r  
trim_zeros_group_poles_compute_factorsrY   polymulro   Zpolyaddr   r   r   rE  rF  unique_polesmultiplicityfactorsdenominator	numeratorr/   factorrI   rI   rJ   r-   $
  s    8


r-   c                 C   s  t dg}|g}t| ddd |ddd D ]<\}}t d| g}t|D ]}t ||}qP|| q0|ddd }g }	t dg}t| ||D ]d\}}}
t d| g}g }t|D ].}|dks|r|t ||
 t ||}q|	t| q|	|fS )z>Compute the total polynomial divided by factors for each root.r   r   r   N)rg   r   ro   rX   rQ  r  extendreversed)rootsrT  rL  currentsuffixespolemultmonomialr   rU  suffixblockrR   rI   rI   rJ   rP  o
  s&    &rP  c                 C   s   t | |\}}|| j}g }t| ||D ]\}}}|dkr\|t||t||  q*| }	td| g}
t	||
\}}g }t
|D ]>}t	|	|
\}	}|d |d  }t|	|| }	|| q|t| q*t|S )Nr   r   )rP  r   rq   ro   r  rg   Zpolyvalrt   r   polydivrX   ZpolysubrY  rZ  rh   )polesrT  rW  Zdenominator_factorsr   residuesr^  r_  rX  Znumerr`  drb  r   r   rI   rI   rJ   _compute_residues
  s*    
rg  c                 C   sj  t | } t |}t | jt js4t |jt jrJ| t} |t}n| t} |t}t t 	| d} t t 	|d}|j
dkrtdt |}| j
dkrt |jt|d t g fS t| t|k rt d}nt | |\}} t|||d\}}t|\}}|| }t||| }	d}
t||D ]"\}}|||
|
| < |
|7 }
q4|	|d  ||fS )aZ  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.
    rJ  r   Denominator `a` is zero.rE  rF  )rg   rh   
issubdtyperq   complexfloatingr   complexr   rN  r  rm   rF   r[  rr   rn   r8  r   rY   rp   rc  r,   rg  ro   )r   r   rE  rF  rd  r   rS  rT  r
  re  indexr^  r_  rI   rI   rJ   r/   
  s8    L







 r/   c                 C   s  t | } t |}t | jt js4t |jt jrJ| t} |t}n| t} |t}t t 	| d} t t 	|d}|j
dkrtdn|d dkrtdt |}| j
dkrt |jt|d t g fS | ddd }|ddd }t|t|k rt d}nt ||\}}t|||d\}}	t|\}}
|	|
 }	td| |	|}d}t jt|td	}t||	D ]<\}}||||| < dt | |||| < ||7 }q~|| | |d  9 }|||ddd fS )
a  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
    r   r   rh  z6First coefficient of determinant `a` must be non-zero.Nr   ri  r   r   )rg   rh   rj  rq   rk  r   rl  r   rN  r  rm   rF   r[  rr   rn   r8  r   rY   rp   rc  r,   rg  r   ro   r}   )r   r   rE  rF  rd  Zb_revZa_revZk_revrS  rT  r
  re  rm  Zpowersr^  r_  rI   rI   rJ   r0     sF    8








 r0   c           	      C   s   |dv rt j}n(|dv r t j}n|dv r0t j}ntdg }g }| d }|g}tdt| D ]N}t| | | |kr|| q\||| |t| | | }|g}q\||| |t| t 	|t 	|fS )Nr:  r<  r>  r@  r   r   )
rg   r   r   r  rF   rX   rY   r   r  rh   )	rd  rE  rF  rG  uniquerT  r^  rb  rR   rI   rI   rJ   rO    s*    rO  c              	   C   s   t | } t |}t t |d}t|||\}}t||dd\}}t|dkrZd}	n t |ddd |ddd }	t| |D ]"\}
}t |	|
|ddd  }	q|	ddd |fS )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

    r   TrK  r   Nr   rM  rR  rI   rI   rJ   r.     s    7


 r.   timec                 C   s~  |dvrt d| t| } | j| }t| }|dkr`|rPtj| |d}qdtj| |d}n| }|dur@t|r|t	|}	n6t
|tjr|j|fkrt d|}	ntt||}	dg| j }
|j| |
|< |r2|	 }|dd  |dd	d 7  < |dd  d
9  < ||d|
|  |
9 }n||	|
9 }t| j}|rb|d d ||< n|||< t||j}t||}|d d }tdg| j }td	|||< |t| |t|< |s|dkrt|| d||< |t| |t|< |d d	kr||k r|rDt|d |d d ||< |t|  d9  < n:t| d | d d ||< |t|  |t| 7  < nx||k rt|d |d d ||< |t|  d
9  < |s|t| }t||d  ||d  d ||< ||t|< |rtj|||d}ntj||dd}|t|t| 9 }|du rB|S td	||d |d	   | t| |d	  }||fS dS )a[  
    Resample `x` to `num` samples using Fourier method along the given axis.

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

    Parameters
    ----------
    x : array_like
        The data to be resampled.
    num : int
        The number of samples in the resampled signal.
    t : array_like, optional
        If `t` is given, it is assumed to be the 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 `scipy.fft.fft`.

    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()
    )ro  freqz9Acceptable domain flags are 'time' or 'freq', not domain=ro  r   Nz(window must have the same length as datar   r   r   g      ?r;   g       @T)r  Zoverwrite_x)rF   rg   rh   rn   Z	isrealobjr   Zrfftr   callableZfftfreqr6  r   Z	ifftshiftr   ri   rt   r   r   rr   rq   r   re   rs   Zirfftr   r   r}   )r   r+  tr  windowr   ZNxZ
real_inputXWZ
newshape_WZW_realr   Yr   Znyqsltempr  Znew_trI   rI   rJ   r1     s    V








"
0r1   Zkaiserg      @r   c                 C   s  t | } |t|krtd|t|kr2tdt|}t|}|dk sR|dk rZtd|durt|dkrttd|t||}|| }|| }||  krdkrn n|  S | j| }|| }	|	| t|	|  }	t	|t
t jfrt |}|jdkrtd|jd d	 }
|}n8t||}d
| }d| }
td	|
 d ||d| j}||9 }||
|  }d}|
| | }tt|| | ||||	| k r|d7 }qvt t j||jd|t j||jdf}||	 }t jt jt jt jd}ddd}||v r|| | |dd}nF|tv rHd|i}|dkrZ|du r>d}||d< ntddt ||v rl| | } t|| ||fd|i|}tdg| j }t||||< |t| }||v r||7 }|S )a/  
    Resample `x` along the given axis using polyphase filtering.

    The signal `x` is upsampled by the factor `up`, a zero-phase low-pass
    FIR filter is applied, and then it is downsampled by the factor `down`.
    The resulting sample rate is ``up / down`` times the original sample
    rate. 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   rs  r   r   )r  medianr=  r;  )rG   cvalT)r  keepdimsrG   r}  z8padtype must be one of: maximum, mean, median, minimum, z, r  ) rg   rh   r   rF   r   gcdrt   rn   rD  r6  r   r   r   ri   rm   r   r   r   rq   r   rY   concatenaterr   r  r|  ZaminZamaxr	   joinr   re   rs   )r   updownr  rs  padtyper}  Zg_Zn_inn_outhalf_lenr   Zmax_rateZf_cZ	n_pre_padZ
n_post_padZn_pre_removeZn_pre_remove_endfuncsZupfirdn_kwargsZbackground_valuesr  ZkeepZy_keeprI   rI   rJ   r2     s    |












r2   c                 C   s   t | } t |}| jdkr&td|jdkr8td|j }t | } t |}|dk rhtdt t dt j |j	 | }t j
|dd}t|}t |}|r|d }|d }||fS )a  
    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               @r   )rg   rh   ri   rF   r5  r   expdotpiTr  r   Zangle)eventsZperiodZscalarperiodZvectorsZ
vectormeanZstrengthZphaserI   rI   rJ   r:   t  s&    /






r:   linearc                 C   s  |dvrt dt| } | jj}|dvr.d}|dv rN| tj| |dd }|S | j}|| }ttt	t
d||}t||krt d	t|}	|dk r||	 }t| |d}
|
j}|
|d
}
|s|
 }
|
jjdvr|
|}
tt|d D ]}||d  ||  }t|df|}tjd|d |d| |dddf< t|| ||d  }t||
| \}}}}|
| ||  |
|<  q|
|}
t|
d|}|S dS )a:  
    Remove linear 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.

    Examples
    --------
    >>> import numpy as np
    >>> from scipy import signal
    >>> rng = np.random.default_rng()
    >>> npoints = 1000
    >>> noise = rng.standard_normal(npoints)
    >>> x = 3 + 2*np.linspace(0, 1, npoints) + noise
    >>> (signal.detrend(x) - noise).max()
    0.06  # random

    )r  lr   r   z*Trend type must be 'linear' or 'constant'.ZdfDFrf  )r   r   T)r~  r   z>Breakpoints must be less than length of data along given axis.r   r   r;   r   N)rF   rg   rh   rq   r  r  rn   r   rn  r  r  r   rY   moveaxisr   rt   r   rX   r  r}   re   r
   lstsq)datar  r   bpZoverwrite_datarq   r   Zdshaper   ZrnknewdataZnewdata_shaper)  ZNptsArw  ZcoefZresidsr   r   rI   rI   rJ   r3     sD    )
 
$
r3   c                 C   s^  t | } | jdkrtdt |}|jdkr8tdt|dkr^|d dkr^|dd }q8|jdk rptd|d dkr| |d  } ||d  }tt|t| }t||k rt j|t j|t| |j	d	f }n0t| |k rt j| t j|t|  | j	d	f } t j
|d t || d	t|j }| dd |dd | d   }t j||}|S )
a\
  
    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.rz  r   )rg   r  ri   rF   rY   rm   r   r$  rr   rq   eyer   r
   Z	companionr  Zsolve)r   r   r   ZIminusABr  rI   rI   rJ   r4     s,    [




$"& r4   c                 C   s   t | } | jdks"| jd dkr*td| jjdv rB| t j} | jd }t j	|df| jd}d}t
|D ]J}| |d	d
f }| |d
d	f }|t|| ||< || |  9 }ql|S )a  
    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   rz  Nr   )rg   rh   ri   rn   rF   rq   r   r   r  rp   rX   r4   r%  )sos
n_sectionsr  scalesectionr   r   rI   rI   rJ   r5     s    6

r5   c           !      C   s,  t | } t |}tt| t|d }|dkrd| d |d  d }|| }|t g t g fS |dksz||jd krt |||jd }|jd }|du s|d| kr|}	n|}	t |	|f}
t |}d|d< t	| |t |	|dd |
dddf< t
d|D ]$}|
d| df |
|d|f< q|
ddd }t	| ||
ddd dd}|ddd }|	|krt ||
 || f}nFt d|	 d| f}||
 |d|	d|f< || ||	d|df< t	| ||}t	| ||ddddf ddddf }t	| ||ddddf ddddf }t	| ||}|| }|	|krJ|}n4|dd|	f }|d|	 df }t j||fdd}|jdkrt||d }nF|d|jd j}t||d j}||jdd |jd f }|	|krt ||f}n>t d|	 d| f}||d|	d|f< |||	d|df< ||j}|}|	|kr^||7 }nL|dd|	f  |dd|	f 7  < |d|	 df  |d|	 df 7  < |dd|f }|d| df } |dks||jd kr"t |||jd }t | ||jd } t |||jd }||| fS )	a7  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  r   .)rg   r  r   rY   r   ri   Zswapaxesrn   rr   r%   rX   Zhstackr  r
   r  r   r  r  )!r   r   r   r  irlenr
  r  r  r   r)  ZObsr  r   ZObsrSZSrr&  Zy_fZy_fbZy_bZy_bfZdelta_y_bf_fbdeltaZstart_mZend_mZic_optZdelta2dZic_opt0ru  ZwicZy_optx0x1rI   rI   rJ   _filtfilt_gust  sx    1




&"

((
 


$(r  oddrA   c              	   C   s&  t | } t |}t |}|dvr.td|dkrRt| ||||d\}}	}
|S t||||tt|t| d\}}t| |}dg|j	 }|j
||< t ||}t|d|d}t| ||||| d\}}t|d	|d
}t| |t||d||| d\}}t||d}|dkr"t||| |d}|S )a+  
    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

    )rA   gustzmethod must be 'pad' or 'gust'.r  )r  r  ntapsr   stopr  r  r  r   startr  r   r   r  r  r  )rg   r  rh   rF   r  _validate_padr   rY   r4   ri   rm   r   r   r%   r   )r   r   r   r  r  padlenrw   r  r  Zz1Zz2edgeextr  zi_shaper  r"  Zy0rI   rI   rJ   r8     s0     






"
r8   c                 C   s   | dvrt d|  | du r d}|du r2|d }n|}|j| |krPt d| | dur|dkr| dkrxt|||d}q| d	krt|||d}qt|||d}n|}||fS )
z'Helper to validate padding for filtfilt)evenr  r   NzYUnknown value '%s' given to padtype.  padtype must be 'even', 'odd', 'constant', or None.Nr   r   zJThe length of the input vector x must be greater than padlen, which is %d.r  r   r  )rF   rn   r   r   r   )r  r  r   r  r  r  r  rI   rI   rJ   r  k  s*    
r  c                 C   s    t | } | jdkrtd| S )Nr   zx must be at least 1-D)rg   rh   ri   rF   )r   rI   rI   rJ   r    s    

r  c                 C   s  t |}t| \} }t|j}d||< t|g| }| |g}|durT|t| tj| }|j	dvrtt
d| |durt||}|j|krtd||j|||jf d}ntj||d}d}||j }t||d	}t|d
|d gdd	g}|j|j }	}
t|d	|jd	 f}tj||dd}tt|d	|df}| j|dd} t| || |	|_t|d	|}|r|
|_t|dd	gd
|d g}||f}n|}|S )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, sosfreqz

    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;   Nr  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
  )rt   )r  r   r   rn   rs   r  rg   rh   r   r  r  r   rF   rr   ri   r  r   Zascontiguousarrayr   r   )r  r   r  r  r  Z
x_zi_shaper   rq   Z	return_zir   r  rz   rI   rI   rJ   r'     sJ    F





r'   c                 C   s  t | \} }t|}d| d }|t| dddf dk | dddf dk 8 }t|||||d\}}t| }	dg|j }
d|
|< |g|
 |	_t|d|d}t	| |||	| d\}}t|d	|d
}t	| t
||d||	| d\}}t
||d}|dkrt||| |d}|S )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, sosfreqz

    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  r   r  )r   r  r   r%  r  r5   ri   rn   r   r'   r   )r  r   r  r  r  r  r  r  r  r  r  Zx_0r  r"  Zy_0rI   rI   rJ   r6     s&    Y6

 
r6   iirTc                 C   s  t | } t|}|dur&t|}| j}t |t jrF|jt jkrLt j	}|dkr|du rld| }d| }t
|d d| ddd }}	t j||d	}t j|	|d	}	n|d
krd}
|du rd}t|dd| dd}t j||d	}nt|tr| }|jjd dkr$| }|j|j }}	d}nrtt |jsVtt |jsVt |jrrd}
| }|j|j }}	n$d}
t|j|j|j}t j||d	}ntdtdg| j }|dkr ||	 }|rt| d|||d}nB| j| | t| j| |  }t|| d||d}td|d||< nd|rN|
r<t|| |d}nt ||	| |d}n&|
rdt!|| |d}nt"||	| |d}tdd|||< |t#| S )a	  
    Downsample the signal after applying an anti-aliasing filter.

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

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

        .. 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()

    NZfirr   r;   r   rz  Zhammingr{  r   r  T   g?g?r  )outputr   Fzinvalid ftype)r  rs  )r  r  r  r   )$rg   rh   operatorrm  rq   rj  Zinexactr   r  r  r   r   r6  r   Z_as_zpkrd  rn   Z_as_tfr+  r,  r   Z	iscomplexZgainr   rr   rF   re   ri   r2   rD  r   r6   r8   r'   r%   rs   )r   qr   Zftyper  Z
zero_phaser   r  r   r   Ziir_use_sosr  systemrw  r  r  rI   rI   rJ   r9   v  sr    U





 r9   )N)r>   r]   )r>   )F)F)r>   N)r>   N)r   )r   r   r   )r>   F)r>   r]   )N)NN)r>   r@   r   )r>   r@   r   )r   )r   N)N)Nr   )N)r9  r   )r9  r?  )F)r9  r?  )r9  r?  )r9  r?  )Nr   Nro  )r   ry  r   N)r   r  r   F)r   N)r   r  NrA   N)r   N)r   r  N)Nr  r   T)dr  r   r   r   r   r   Zscipy.spatialr    r   Z_ltisysr   Z_upfirdnr   r   r	   Zscipyr
   r   r   r   Zscipy.fft._helperr   numpyrg   Zscipy.specialr   windowsr   Z_arraytoolsr   r   r   r   r   Z_filter_designr   r   r   Z_fir_filter_designr   r   __all__rD   rL   rK   rN   r\   r   r   r   r   r   r   r   r   r    r   r   r   rk   rl   r   r7   r   r!   r"   r$   r   r   r#   r%   r&   r(   r)   r*   r7  r+   r8  r,   r-   rP  rg  r/   r0   rO  r.   r1   r2   r:   r3   r4   r5   r  r8   r  r  r'   r6   r9   rI   rI   rI   rJ   <module>   s   


"
 I
a

=
<&
vo
 Q
+*
#
 
 I
P
K
Z
f
l
 D
N<
n
:
W
K

s
i
J
 =  
 QN
X 	L
 4  
 K#
p
q