L ivddlmZddlZddlZddlmZddlZddlZddlm Z ddl m Z ddl m Z ddlmZdd lmZdd lmZmZmZdd lmZmZdd lmZdd lmZddlZddlm Z ddl!m"Z"ddl#m$Z$m%Z%m&Z&m'Z'm(Z(ddl)m*Z*m+Z+m,Z,ddl-m.Z.ddl/m/Z/ddl0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6ddl7m8Z8ddl9m:cm;cmZ<ddl=m:cm>Z?gdZ@ddddZAddddddddZBdZCdZDdYdZEdZFdZdZGd[d ZHd!ZId\d#ZJd\d$ZKd%ZLd]d&ZMd'ZNd(ZOd)ZPd]d*ZQd^d+ZRd,ZSd-ZTd.ZUd/ZVd_d0ZWd`d1ZXdZd2ZYd3ZZdYd4Z[dad5Z\dbd6Z]dbd7Z^dcd8Z_ddd:Z`dYd;Zad<Zbded=ZcdYd>Zddfdd"d?d9d@ dgdAZedBZfdhdCZgdidDZhd\dEZidFZjdidGZkdidHZldIZmdidJZndjdKZo dkdLZpdMZqdNZr dl dmdOZsdPZtdQZudddRZv dndSZwdTZxdUZydddVZzdodWZ{dpdXZ|y)q) annotationsN)prod)Literal) ArrayLike)cKDTree) _sigtools)dlti)upfirdn _output_len_upfirdn_modes)linalgfft)ndimage)_init_nd_shape_and_axes)lambertw) get_window) axis_slice axis_reverseodd_exteven_ext const_ext)cheby1 _validate_soszpk2sos)firwin)_sosfilt)array_namespaceis_torchis_numpyxp_copyxp_sizexp_default_dtype)is_array_api_obj)! correlatecorrelation_lags correlate2dconvolve convolve2d fftconvolve oaconvolve order_filtermedfilt medfilt2dwienerlfilterlfilticsosfilt deconvolvehilberthilbert2envelope unique_rootsinvresinvreszresidueresiduezresample resample_polydetrend lfilter_zi sosfilt_zi sosfiltfiltchoose_conv_methodfiltfiltdecimatevectorstrength)validsamefull)fillpadwrapcircularsymm symmetricreflectcP t|S#t$r}td|d}~wwxYw)N5Acceptable mode flags are 'valid', 'same', or 'full'.) _modedictKeyError ValueError)modees _/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/signal/_signaltools.py _valfrommoderZ6s67 7/056 77s % %cV t|dzS#t$r}td|d}~wwxYw)NrFzZAcceptable boundary flags are 'fill', 'circular' (or 'wrap'), and 'symmetric' (or 'symm').) _boundarydictrUrV)boundaryrXs rY_bvalfromboundaryr^>sBMX&!++ MEFKL MMs  ( #(c|dk7rysy|tt}tfd|D}tfd|D}|s |s td| 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. rGFc34K|]}||k\ywN.0ishape1shape2s rY z&_inputs_swap_needed..^ 3fQi6!9$ 3c34K|]}||k\ywrarbrcs rYrhz&_inputs_swap_needed.._rirjzOFor 'valid' mode, one must be at least as large as the other in every dimension)rangelenallrV)rWrfrgaxesok1ok2s `` rY_inputs_swap_neededrrFsk w  |S[! 3d 3 3C 3d 3 3C 3DE E7Nctj|j}tj|tjs|tj tj tjtjtjtjfvs&d|d|d}tj|tdyyy)z/Warn if arr.dtype is object or longdouble. dtype=z is not supported by z and will raise an error in SciPy 1.17.0. Supported dtypes are: boolean, integer, `np.float16`,`np.float32`, `np.float64`, `np.complex64`, `np.complex128`.category stacklevelN)npasarraydtype issubdtypeintegerbool_float16float32float64 complex64 complex128warningswarnDeprecationWarning)arrnamedtmsgs rY_reject_objectsrhs C  B MM"bjj )bhh BJJ llBMM33RD-dV4K L  c$61E3 *rsc> t||}t|rt |dt |d|j |}|j |}|j |j cxk(rdk(r7nn4|j|jdr|j|n|}||zS|j |j k7r td t|}|dvrt|t||||S|dk(r\t||||rRt!j |}t!j |} t!j"|| |} |j | S|d k(xrt%|t%|kDxs!t'||j(|j(} | r||}}t!j |}t!j |} |d k(rqt+|j(|j(D cgc] \} } | | z d z}} } t!j,||j} t/j0|| | |}nt+|j(|j(D cgc] \} } | | zd z }} } t!j2||j}t5d |j(D}|j7||<|d k(r!t!j,||j} n/|d k(r*t!j,|j(|j} t/j0||  |}|j |}| r t||}|Std#t$r t}YdwxYw#t$r}td|d}~wwxYwcc} } wcc} } w)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] = \sum_{l=0}^{N-1} x_l \, y_{l-k}^{*} for :math:`k = -(M-1), \dots, (N-1)`, where :math:`N` is the length of ``x``, :math:`M` is the length of ``y``, and :math:`y_m = 0` when :math:`m` is outside the valid range :math:`[0, M-1]`. The size of :math:`z` is :math:`N + M - 1` and :math:`y^*` denotes the complex conjugate of :math:`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 ``mode='same'`` 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%rcomplex floating/in1 and in2 should have the same dimensionalityrSN)rautodirectrIrGrc34K|]}td|yw)rN)slice)rdres rYrhzcorrelate..>s6quQ{6srH7Acceptable method flags are 'auto', 'direct', or 'fft'.)r TypeError np_compatr rr{ndimisdtyper|conjrVrTrUr(_reverse_and_conj _np_conv_okrzr%r"rrshapezipemptyr _correlateNDzerostuplecopy)in1in2rWmethodxpin2_conjvalrXa_in1a_in2outswapped_inputsrejpsz in1zpaddedscs rYr%r%xs*J S# & |[)[) **S/C **S/C xx388 q zz#))-?@GGCL X~ SXX JKK7o  .sB7vFF 8  sCr *JJsOEJJsOE,,ueT2C::c? "  6>L ws|0KJ-dCIIsyyI  CC 3 3 7?(+CIIsyy(AB1!a%!)BBB((2u{{+C&&ueS#>A),CIIsyy(AB1!a%!)BBB"ekk2J6CII66B"ZZ\JrNv~hhr5;;/hhsyy%++6&&z5#sCA JJqM !!R(A01 1e  , 7/056 77>C Cs5 M  M62N#N M32M36 N? N  Nc|dk(rtj| dz|}|S|dk(rStj| dz|}|jdz}|dz}|dzdk(r |||z ||z}|S|||z ||zdz}|S|dk(r<||z }|dk\rtj|dz}|Stj|d}|Std|d) 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)] rIrrHrFrrGzMode z is invalid)rzarangesizerV)in1_lenin2_lenrWlagsmid lag_bounds rYr&r&Us~ v~yy'Aw/< K; yy'Aw/ii1nqL Q;! YY8D" KYY(9:D K g% >99Y]+D K99Y*D K5k233rsc tj|}tj|j}||z dz}||z}t t |Dcgc]}t ||||}}|t|Scc}w)NrF)rzr{arrayrrlrmrr)rnewshape currshapestartindendindkmyslices rY _centeredrs{zz(#H#IH$*H  F6;CK6HIuXa[&),IGI uW~ JsBFc |j|j du}t|d\}|sts tdDcgc]}|dk7s |dk7s|c}|rj t  fdt |jDstdd t| r||}}||fScc}w) aHandle 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)rroz#when provided, axes cannot be emptyrc3dK|]'}|vr!||k(xs|dk(xs|dk()ywrNrb)rdaros1s2s rYrhz'_init_freq_conv_axes..sH:1D=!u1~9A!9r!uz9:s-0z%incompatible shapes for in1 and in2: z and ro) rrrmrVsortrnrlrrr) rrrWro sorted_axesnoaxes_rrrs ` @@rY_init_freq_conv_axesrs@ B B T\F%cDAGAt #d)>?? 9!r!uzbeqjA 9D :chh: :DbT+, ,4Rd3S T> :s CC$Cct|s||zS|j|jdxs|j|jd}|r(|Dcgc]}tj||| }}n|}|s!tj tj } } n tjtj} } |j|jdr|j||j}|j|jdr|j||j}| |||} | |||} | | | z||} |r't|Dcgc] }t|c}}| |} | Scc}wcc}w)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`. rintegralr) rmrr|sp_fft next_fast_lenrfftnirfftnfftnifftnastyperrr)rrrror calc_fast_lencomplex_resultrfshaperifftsp1sp2retszfslices rY_freq_domain_convrs[> t9Syjj,>?@jj,>?IMNCDF q~+= >NN LL&--TKKT zz#))Z(iiRZZ( zz#))Z(iiRZZ( c6 %C c6 %C sSy&t ,CE2bb 23&k J1N*3s !E9E>c8|dk(r t||S|dk(rtt|||S|dk(rXt|jDcgc]#}||vr|j|n ||||z dz%}}tt|||St dcc}w)aCalculate 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`. rIrrHrGrz4acceptable mode flags are 'valid', 'same', or 'full')r!rrlrrrV)rrrrWrorr shape_valids rY_apply_conv_moderAs2 v~sr"" yb)b11  %chh1()}syy|"Q%"Q%-!:KK1 1yk2r::./ / 1s (Bczt||}|j|}|j|}|j|jcxk(r dk(r||zS|j|jk7r tdt |dk(st |dk(r|jgSt ||||d\}}}|j }|j }t|jDcgc]'}||vrt||||fn ||||zdz )}}t|||||d} t| |||||Scc}w) 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() rrFrrTrr) rr{rrVr"rrrlmaxrr) rrrWrorrrrerrs rYr*r*gsC| c "B **S/C **S/C xx388 q Sy! SXX JKK  gcla/zz"~)#sD$6;=NCd B BCHHo '%&TMS"Q%A r!ur!u}q7H H 'E ' BS$T JC CRt ;;  's(,D8cr||zdz d||f}||k(s |dk(s|dk(r|S||kDr||}}d}nd}||dz k\r|S|dz }| tddtjz|zz djz}t j tj |}||k\r|S|s ||z dz}|}n |}||z dz}||||fS)a;Calculate the optimal FFT lengths for overlap-add convolution. The calculation is done for a single dimension. Parameters ---------- s1 : int Size of the dimension for the first array. s2 : int Size of the dimension for the second array. Returns ------- block_size : int The size of the FFT blocks. overlap : int The amount of overlap between two blocks. in1_step : int The size of each step for the first array. in2_step : int The size of each step for the first array. rNTFrF)r)rmathrXrealrrceil) rrfallbackswappedoverlapopt_size block_sizein1_stepin2_steps rY _calc_oa_lensrs22ar2&H Rx27bAg BwRB RTzldGxQtvvXg%5!6"=BBBH%%dii&9:JR b=?b=? w( 22rsctt|j}||||c||<||<|j||S)z np.swapaxes)listrlr permute_dims)xax1ax2rshps rY _swapaxesrNsA uQVV} CS3s8CHc#h ??1c ""rsc  |j|}t|dz}dgt|z|gz}g}t||d|}t |D]4} || } || dz} |j t|| | df|d|6|S)zDA simplified version of np.split, with `indices` being an list. rrr.)rrmrrrlappend) rindices_or_sectionsaxisrNtotal Nsections div_pointssub_aryssaryrestends rY_splitr WsWWT]F'(1,It/00F8;JH QaB 'D 9 F ]Q $r#vs{"3T1DEF Orsc $%t||}|j|}|j|}|j|jcxk(r dk(r||zS|j|jk7r td|jdk(s|jdk(r|jgS|j |j k(rt |||St|||d\}}|j $|j %s||z}t|$%||St|jDcgc]}|vrdn $|%|zdz }}$%fdt|jD}t|\} } } } | $k(r| %k(rt |||Sg} g}g}g}t|jD]}|vr |d gz }|d gz }$|| |kDrItj$|dz| |z }| || |z |z||kr|dz }|| |z$|z }nd}d}%|| |kDrItj%|dz| |z }| || |z |z||kr|dz }|| |z%|z }nd}d}| |gz } ||gz }|d|fgz }|d|fgz }td |Dstj||d d| }td |Dstj||d d| }t!Dcgc] \}}||z }}}|Dcgc]}|dz }}t#| }t#| }t!|D]/\}}|j%|| ||j%|||1|j'|t)|}|j'|t)|}Dcgc]}| | }}t+|||||d}t||D]_\}}}| |}|t-|| g||\}}t-|dg||d}t-||g||d} t-| dg||d} | |z } at|jDcgc];}||vr5||vr|j |n!|j ||j |dz z=}!}|j'||!}t)|D"cgc] }"t/|"c}"}#||#}t|$%||Scc}wcc}}wcc}wcc}wcc}wcc}"w)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() rr)rWroTrNrc3bK|]&}|vr dd||fnt||(ywrN)r)rdrerorrs rYrhzoaconvolve..sIK5601}b"beRU+"2a5"Q%01Ks,/rrc3&K|] }|dk( ywrNrbrdcurpads rYrhzoaconvolve.. 8Fv8constant)rWconstant_valuesrc3&K|] }|dk( ywrrbrs rYrhzoaconvolve.. rrFrrr)rr{rrVrrr*rrrlrrrrnxpxrL enumeraterinsertreshaperrr r)&rrrWrorrre shape_final optimal_sizesroverlapsrrnsteps1nsteps2 pad_size1 pad_size2 curnstep1curpad1 curnstep2curpad2iax split_axesfft_axes reshape_size1 reshape_size2 fft_shapeaxax_fftax_splitroverpart ret_overpart shape_retislice slice_finalrrs& ` @@rYr+r+ks` c "B **S/C **S/C xx388 q Sy! SXX JKK Q#((a-zz"~ cii 3$T::)#sD$6: X(RD(r:1=cG9fqA   ! /BQj-@"#(!211cii!n,-BIB **S) $C[A6vABK k C CRtR 88M?z7,."B Bs%,S4S S % S% AS*'S/c|t|}t|syt|tjur|j j |vS|D]}|j j |vsyy)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. TF)rr typerzndarrayr|kind)arrayskindsrarray_s rY_numeric_arraysr<=sk z f % B< F|rzz!||  E)) <<  E ) rscx|dk(r%t||Dcgc] \}}||zdz }}}nI|dk(r.t||Dcgc]\}}t||z dz}}}n|dk(r|}ntd|||}}t|dk(rZ|d|d}}|dk(r||z}n|dk(r||k\r ||z dz|zn ||z dz|z}n|dk(r||kr||zn||z|dz|dzdzzz }n||dk(r+t t |t |t |z}nL|dk(r+t t |t |t |z}n|dk(rt |t |z}t||Dcgc] \}}||zdz } }}t | } d| zt j| z} | fScc}}wcc}}wcc}}w) 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``). rIrrGrHz?Acceptable mode flags are 'valid', 'same', or 'full', not mode=rrFrv)rabsrVrmmin_prodrzlog) x_shapeh_shaperWnr out_shaperr direct_opsfull_out_shapeNfft_opss rY _conv_opsrJWs v~+.w+@A41aQUQYA A 03GW0EF1SQZ!^F F  99=@A AgB 7|qA1B 6>bJ W_/1Rx"r'A++b2gkR=OJ V^%'"W"r'r'R1W"q&Q$??  6>U2Yb 2U95EEJ W_U2Yb 2U95EEJ V^rU2Y.J,/,ABDAqa!eaiBNB nA!ebffQiG J =BF2CsF*F0+F6c.t|j|j|\}}|jdk(rdnd}|jdk(r*dd|fdd|f|j|jkrdd |fnd d nd d |fdd|fdd|fd }||\}}} ||z||z| zkS)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. rgMbPg-C6g^]B> >g "]=g{$R>gen=gr0 < ,>gg=)gd[֠+>g@jHI>gh㈵)rGrIrHg.w'>gvlV>gG[*!>gʑQ>gVN+!>g4RP>)rJrrr) rhrWrIrFoffset constantsO_fftO_directO_offsets rY_fftconv_fasterrRs2$AGGQWWd;GZffkUuF 1 $]F;!=&9vv"=&95 !*f5V4V4 !*$E8X 7?X 2X= ==rsct|s!tdddf|jz}||}n|j|}|j |j dr|j |S|S)zO Reverse array `x` in all dimensions and perform the complex conjugate Nrr)rrrfliprr|r)rrreversex_revs rYrrse B<tR(*QVV3'   zz!''-.wwu~ rsc|j|jcxk(rdk(r%ny|dvry|dk(rt|t|k\Syy)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)rIrGTrHFN)rr")volumekernelrWrs rYrrsP{{fkk&Q&  $ $ V^6?gfo5 5rsctj||}d}tddD]}d|z}|j|}|dk\sn|dkDr|}n"dz}|j||}t |}|z } | 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)timeitTimerrlrepeatr?) stmtsetupr^timerrpnumberbestrsecs rY _timeit_fastrgs LLu %E A 1b\Q LL  >    1u"  LL (1v -C Jrsc B t||}t|rt |dt |d|j | |j | |r0i}dD] t  fd| <|d|dkrdnd}||fSt fDcgc]}t|gd|c}rt|j|j t|j|j z}|ttt t z}|dtjd j zd z kDryt gd |ryt g| rt# ryy#t$r t}YwxYwcc}w) 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`. rB)rrc"tS)N)rWr)r()rYrrWrXsrYz$choose_conv_method..os&&.262Crsrrui)r:rrFfloatrbr)rrrr rr{rganyr<intrr>r?r"rzfinfonmantrR) rrrWmeasurertimes chosen_methodr max_valuerYrrXs ` @@@rYrBrBsX S# & |1212 ZZ_F ZZ_F' DF(*CDE&M D"'uh!?X e##  ff=M NOQCt 3 NOrvvf~./#bffRVVF^6L2MM SWV_gfo>?? q"((7+111A5 5'sr:'B/ 664 0 I  . Os FFFFc` t||}t|rt |dt |d|j |}|j |}|j |j cxk(r dk(r||zS|j |j k7r tdt||j|jr||}}|dk(rt|||}|dk(rt|||}|j||}|j|dr|j|}|j|j!|dds$|j#|j!|ddrt%j&d t(d |j+||S|d k(rxt-||||rRt/j |} t/j |} t/j0| | |}|j |St3|t5|||d Std #t$r t}YwxYw)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%rz5volume and kernel should have the same dimensionalityrrWrrrzuUse of fft convolution on input with NAN or inf results in NAN or inf output. Consider using method='direct' instead.rFrwrr)rrrr rr{rrVrrrrBr* result_typerroundisnanrisinfrrRuntimeWarningrrrzr(r%r) rrrWrrrXrYrrya_volumea_kernels rYr(r(sD S# & |[)[) ZZ_F ZZ_F {{fkk&Q&'  #*+ +4v||< #FF> &&t4nnVV4 ::k: .((3-C 88BJJsE*1- ."((2::c5;QRS;T2U MM6$2a A yyk** 8  vvtR 0zz&)Hzz&)H++h$7C::c? "!262!>hOO01 1a  s HH-,H-ct||}|j|}|jD]}|dzdk7s td|j|}|j |j ds=|j |j |jfvstd|j dtj|||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]]) rFrzHEach dimension of domain argument should have an odd number of elements.rruz! is not supported by order_filterr) footprintrW) rr{rrVrr|rrr rank_filter)rdomainrankrdimsizeresults rYr,r, sl F #B ZZ F<<G aKA FG GG 1 A 177J'177rzz2::6N+N6!''*KLMM  DF LF Mrsct|}|j|}|jdk(rtj|d|}|j |j ds=|j |j|jfvstd|j d|dg|jz}|j|}|jdk(r|j||j}t|jD]}||d zdk7std td t||jDrtj d d t#j$|}t'j(||d z|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. rrrrrruz is not supported by medfiltrvrbrF*Each element of kernel_size should be odd.c3,K|] \}}||kDywrarb)rdrss rYrhzmedfilt..s >> 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() rvrbrHrFrxrrr) rr{rrrrr%onesrlmeanrwhere) immysizenoiser mysize_arrrlMeanlsizelVarresrs rYr/r/s"b  B BB ~rwwF#J2BGG# 99V D b"''&/6 2E $KE EME bAgrwwv 7% ?%1* LD } 4/a8 :CA C5LC ((4%< ,C Jrsct||}tj|}tj|}|j|jcxk(rdk(st dt dt ||j |j r||}}t|}t|}tj||d|||}|j|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() rFz)convolve2d inputs must both be 2-D arraysr) rrzr{rrVrrrrZr^r _convolve2d) rrrWr] fillvaluerrbvalrs rYr)r)sV c "B **S/C **S/C 88sxx $1 $DEE %DEE4CII6S t C X &D   S!S$ BC ::c?rsct||}tj|}tj|}|j|jcxk(rdk(st dt dt ||j |j }|r||}}t|}t|}tj||jd|||} |r | ddddddf} |j| S)a Cross-correlate two 2-dimensional arrays. Cross correlate `in1` and `in2` with output size determined by `mode`, and boundary conditions determined by `boundary` and `fillvalue`. Parameters ---------- in1 : array_like First input. in2 : array_like Second input. Should have the same number of dimensions as `in1`. mode : str {'full', 'valid', 'same'}, optional A string indicating the size of the output: ``full`` The output is the full discrete linear cross-correlation of the inputs. (Default) ``valid`` The output consists only of those elements that do not rely on the zero-padding. In 'valid' mode, either `in1` or `in2` must be at least as large as the other in every dimension. ``same`` The output is the same size as `in1`, centered with respect to the 'full' output. boundary : str {'fill', 'wrap', 'symm'}, optional A flag indicating how to handle boundaries: ``fill`` pad input arrays with fillvalue. (default) ``wrap`` circular boundary conditions. ``symm`` symmetrical boundary conditions. fillvalue : scalar, optional Value to fill pad input arrays with. Default is 0. Returns ------- correlate2d : ndarray A 2-dimensional array containing a subset of the discrete linear cross-correlation of `in1` with `in2`. Notes ----- When using "same" mode with even-length inputs, the outputs of `correlate` and `correlate2d` differ: There is a 1-index offset between them. Examples -------- Use 2D cross-correlation to find the location of a template in a noisy image: >>> import numpy as np >>> from scipy import signal, datasets, ndimage >>> rng = np.random.default_rng() >>> face = datasets.face(gray=True) - datasets.face(gray=True).mean() >>> face = ndimage.zoom(face[30:500, 400:950], 0.5) # extract the face >>> template = np.copy(face[135:165, 140:175]) # right eye >>> template -= template.mean() >>> face = face + rng.standard_normal(face.shape) * 50 # add noise >>> corr = signal.correlate2d(face, template, boundary='symm', mode='same') >>> y, x = np.unravel_index(np.argmax(corr), corr.shape) # find the match >>> import matplotlib.pyplot as plt >>> fig, (ax_orig, ax_template, ax_corr) = plt.subplots(3, 1, ... figsize=(6, 15)) >>> ax_orig.imshow(face, cmap='gray') >>> ax_orig.set_title('Original') >>> ax_orig.set_axis_off() >>> ax_template.imshow(template, cmap='gray') >>> ax_template.set_title('Template') >>> ax_template.set_axis_off() >>> ax_corr.imshow(corr, cmap='gray') >>> ax_corr.set_title('Cross-correlation') >>> ax_corr.set_axis_off() >>> ax_orig.plot(x, y, 'ro') >>> fig.show() rFz*correlate2d inputs must both be 2-D arraysrNr) rrzr{rrVrrrrZr^r rr) rrrWr]rrrrrrs rYr'r'\sd c "B **S/C **S/C 88sxx $1 $EFF %EFF(syy#))DNS t C X &D   SXXZCy IC$B$"*o ::c?rsc$t|}tj|}|jjtj tj tjfvr|jt||S|dgdz}tj|}|jdk(r$tj|jd}|D]}|dzdk7s tdtj||}|j|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 rvrFrbrr)rrzr{r|r6ubyterrr-rr^itemrVr _medfilt2d)inputrrimager result_nps rYr.r.sp  B JJu E {{"**bjjAAzz'%566cAg **[)KBii 0 0 2A6 K 1H?IJ JK$$UK8I ::i  rsrc6 t|||}t|r$t |dt |dt dt j t j |}t j|}|t j|}t|dk(rwt jt j|}jdk7r|jdk7r tdt|}||g}|t j|}|j|jk7r tdt|j}jddz ||<t|}|j|k7r|jdgz}|dkr||jz }t|jD]} | |k(r(|j| || k(r|j | || <0| |k7r(|j| || k(r|j | || <]| |k7r|j| dk(rd|| <ztd|d|jdt j"j$j'|||}|j)|t j*|} | j,d vrt/d | d t j0| t j|| }|dzt j|| }t j2fd ||} | jt5dgz} |1t5|j|| |<| t| xx|z cc<t5| j|tz dz| |<| t| } ||j| St5| j|tz dzd| |<| t| }|j| |j|fS|)t7j8|||}|j|St7j8||||\} }|j| |j|fS#t$r t}YwxYw)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() r0Nrz+object of too small depth for desired arrayrz"Unexpected shape for zi: expected z, found .fdgFDGO input type '' not supportedr|c0tj|Sra)rzr()yrms rYrjzlfilter..sQ1Brs)rrrr rrz atleast_1dr{rmrrV _validate_xrrrrlstrideslib stride_tricks as_stridedrrycharNotImplementedErrorrapply_along_axisrr _linear_filter)rmrrrzirinputsexpected_shaperrr|out_fullindrzfrs` rYr0r02sx Q1b ) |9%9%9% aA aA 1 A ~ JJrNr 1v{ JJqM JJqM 66Q;166Q;JK K NQ >BBww!&&  !NOO!!'']N#$771:>N4 ">2Nxx>)''TF*!8BGGODrww QADyRXXa[N14E%E%'ZZ] drxx{nQ6G'G%'ZZ] drxx{a'7%& ()M,:+;8BHH:Q*PQQ QVV))44R5<> MM" ' ::Y &% UG?&KL L HHQe $ JJq & QqT  JJq &&&'BD!LmmuT{m+ >bhhtn-CI U3Z B & (...Q7!;<D uSz" :::c? "hnnT2SV;a?FCI%*%B::c?BJJrN2 2 :,,Q1d;F::f% %..q!QbAGC::c?BJJrN2 2g  sRRRc  t||||}t|r2t |dt |dt |d| t |dt j |j|d|}t j |j|d|}|jdkDr td|jdkDr td|jddz }|jddz }t||}|j|}|dkr td|E|j|||}|j|d r |j}|j|| }n|j|}|j||||}|j|d r |j}|j!||}t#|} | |kr%|j%||j|| z f}|j!||}|j|| } t#|} | |kr%|j%||j|| z f}t'|D]'} |j)|| dzd|d|| z zd | | <)t'|D]/} | | xx|j)|| dzd|d|| z zd zcc<1|dd k7r|dd k(r td| |dz} | S#t$r t}YwxYw)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 r1Nrrz$Filter coefficients `a` must be 1-D.z$Filter coefficients `b` must be 1-D.rz+There must be at least one `a` coefficient.)boolrrr?z.First `a` filter coefficient must be non-zero.)rrrr rrrr{rrVrrryrrrrr"concatrlsum) rmrrrrrHMKryLrms rYr1r1 sP Q1a (|9%9%9% = Ay ) rzz!}14A rzz!}14Avvz?@@vvz?@@  QA  QA Aq A 1 A1uFGGynnQ1- ::k#7 8**K HHQkH * JJqMnnQ1a0 ::k#7 8**K IIa % AJ q5 1bhhq1uo./A ![!A !; 'B A1u IIq"((1q5/* + 1X6qQy1Va!e9,15161X7 1!a%& Afq1uI-A667 trz Q42:MN N ad  Iw  sK""K54K5ct||}tj|j|d|}tj|j|d|}|jdkDr t d|jdkDr t d|j d}|j d}||kDrg}|}||fS|j||z dz|j} d| d<t||| }|t||dz }||fS) aDeconvolves ``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.]) rrzsignal must be 1-D.zdivisor must be 1-D.rrrIrw) rrrr{rrVrrrr0r() signaldivisorrnumdenrHDquotremrs rYr3r3n sR  )B ..F+! ;C ..G,1 >> import numpy as np >>> import matplotlib.pyplot as plt >>> from scipy.signal import hilbert, chirp ... >>> duration, fs = 1, 400 # 1 s signal with sampling frequency of 400 Hz >>> t = np.arange(int(fs*duration)) / fs # timestamps of samples >>> signal = chirp(t, 20.0, t[-1], 100.0) >>> signal *= (1.0 + 0.5 * np.sin(2.0*np.pi*3.0*t) ) The amplitude envelope is given by the magnitude of the analytic signal. The instantaneous frequency can be obtained by differentiating the instantaneous phase in respect to time. The instantaneous phase corresponds to the phase angle of the analytic signal. >>> analytic_signal = hilbert(signal) >>> amplitude_envelope = np.abs(analytic_signal) >>> instantaneous_phase = np.unwrap(np.angle(analytic_signal)) >>> instantaneous_frequency = np.diff(instantaneous_phase) / (2.0*np.pi) * fs ... >>> fig, (ax0, ax1) = plt.subplots(nrows=2, sharex='all', tight_layout=True) >>> ax0.set_title("Amplitude-modulated Chirp Signal") >>> ax0.set_ylabel("Amplitude") >>> ax0.plot(t, signal, label='Signal') >>> ax0.plot(t, amplitude_envelope, label='Envelope') >>> ax0.legend() >>> ax1.set(xlabel="Time in seconds", ylabel="Phase in rad", ylim=(0, 120)) >>> ax1.plot(t[1:], instantaneous_frequency, 'C2-', label='Instantaneous Phase') >>> ax1.legend() >>> plt.show() rx must be real.NrN must be positive.rrrFr)rr{rr|rVrrrrrnewaxisrrr)rrHrrXfrLrs rYr4r4 s'z  B 1 A zz!''-.*++y GGDMAv.// Aqt $B "((#A1uz!qay!AF !!QUqLvvzzzlQVV#$KD eCjM BF&A Hrsct|}tj|j|d|}|jdkDr t d|j |jdr t d| |j}nat|tr|dkr t d||f}n`__ .. [3] T.G. Kincaid, "The complex representation of signals.", TIS R67# MH5, General Electric Co. (1966). `PDF `__ .. [4] "Envelope (mathematics)", Wikipedia, https://en.wikipedia.org/wiki/Envelope_(mathematics) .. [5] Yang, Yanli. "A signal theoretic approach for envelope analysis of real-valued signals." IEEE Access 5 (2017): 5623-5630. `PDF `__ See Also -------- hilbert: Compute analytic signal by means of Hilbert transform. Examples -------- The following plot illustrates the envelope of a signal with variable frequency and a low-frequency drift. To separate the drift from the envelope, a 4 Hz highpass filter is used. The low-pass residuum of the input bandpass filter is utilized to determine an asymmetric upper and lower bound to enclose the signal. Due to the smoothness of the resulting envelope, it is down-sampled from 500 to 40 samples. Note that the instantaneous amplitude ``a_x`` and the computed envelope ``x_env`` are not perfectly identical. This is due to the signal not being perfectly periodic as well as the existence of some spectral overlapping of ``x_carrier`` and ``x_drift``. Hence, they cannot be completely separated by a bandpass filter. >>> import matplotlib.pyplot as plt >>> import numpy as np >>> from scipy.signal.windows import gaussian >>> from scipy.signal import envelope ... >>> n, n_out = 500, 40 # number of signal samples and envelope samples >>> T = 2 / n # sampling interval for 2 s duration >>> t = np.arange(n) * T # time stamps >>> a_x = gaussian(len(t), 0.4/T) # instantaneous amplitude >>> phi_x = 30*np.pi*t + 35*np.cos(2*np.pi*0.25*t) # instantaneous phase >>> x_carrier = a_x * np.cos(phi_x) >>> x_drift = 0.3 * gaussian(len(t), 0.4/T) # drift >>> x = x_carrier + x_drift ... >>> bp_in = (int(4 * (n*T)), None) # 4 Hz highpass input filter >>> x_env, x_res = envelope(x, bp_in, n_out=n_out) >>> t_out = np.arange(n_out) * (n / n_out) * T ... >>> fg0, ax0 = plt.subplots(1, 1, tight_layout=True) >>> ax0.set_title(r"$4\,$Hz Highpass Envelope of Drifting Signal") >>> ax0.set(xlabel="Time in seconds", xlim=(0, n*T), ylabel="Amplitude") >>> ax0.plot(t, x, 'C0-', alpha=0.5, label="Signal") >>> ax0.plot(t, x_drift, 'C2--', alpha=0.25, label="Drift") >>> ax0.plot(t_out, x_res+x_env, 'C1.-', alpha=0.5, label="Envelope") >>> ax0.plot(t_out, x_res-x_env, 'C1.-', alpha=0.5, label=None) >>> ax0.grid(True) >>> ax0.legend() >>> plt.show() The second example provides a geometric envelope interpretation of complex-valued signals: The following two plots show the complex-valued signal as a blue 3d-trajectory and the envelope as an orange round tube with varying diameter, i.e., as :math:`|a(t)| \exp(j\rho(t))`, with :math:`\rho(t)\in[-\pi,\pi]`. Also, the projection into the 2d real and imaginary coordinate planes of trajectory and tube is depicted. Every point of the complex-valued signal touches the tube's surface. The left plot shows an analytic signal, i.e, the phase difference between imaginary and real part is always 90 degrees, resulting in a spiraling trajectory. It can be seen that in this case the real part has also the expected envelope, i.e., representing the absolute value of the instantaneous amplitude. The right plot shows the real part of that analytic signal being interpreted as a complex-vauled signal, i.e., having zero imaginary part. There the resulting envelope is not as smooth as in the analytic case and the instantaneous amplitude in the real plane is not recovered. If ``z_re`` had been passed as a real-valued signal, i.e., as ``z_re = z.real`` instead of ``z_re = z.real + 0j``, the result would have been identical to the left plot. The reason for this is that real-valued signals are interpreted as being the real part of a complex-valued analytic signal. >>> import matplotlib.pyplot as plt >>> import numpy as np >>> from scipy.signal.windows import gaussian >>> from scipy.signal import envelope ... >>> n, T = 1000, 1/1000 # number of samples and sampling interval >>> t = np.arange(n) * T # time stamps for 1 s duration >>> f_c = 3 # Carrier frequency for signal >>> z = gaussian(len(t), 0.3/T) * np.exp(2j*np.pi*f_c*t) # analytic signal >>> z_re = z.real + 0j # complex signal with zero imaginary part ... >>> e_a, e_r = (envelope(z_, (None, None), residual=None) for z_ in (z, z_re)) ... >>> # Generate grids to visualize envelopes as 2d and 3d surfaces: >>> E2d_t, E2_amp = np.meshgrid(t, [-1, 1]) >>> E2d_1 = np.ones_like(E2_amp) >>> E3d_t, E3d_phi = np.meshgrid(t, np.linspace(-np.pi, np.pi, 300)) >>> ma = 1.8 # maximum axis values in real and imaginary direction ... >>> fg0 = plt.figure(figsize=(6.2, 4.)) >>> ax00 = fg0.add_subplot(1, 2, 1, projection='3d') >>> ax01 = fg0.add_subplot(1, 2, 2, projection='3d', sharex=ax00, ... sharey=ax00, sharez=ax00) >>> ax00.set_title("Analytic Signal") >>> ax00.set(xlim=(0, 1), ylim=(-ma, ma), zlim=(-ma, ma)) >>> ax01.set_title("Real-valued Signal") >>> for z_, e_, ax_ in zip((z, z.real), (e_a, e_r), (ax00, ax01)): ... ax_.set(xlabel="Time $t$", ylabel="Real Amp. $x(t)$", ... zlabel="Imag. Amp. $y(t)$") ... ax_.plot(t, z_.real, 'C0-', zs=-ma, zdir='z', alpha=0.5, label="Real") ... ax_.plot_surface(E2d_t, e_*E2_amp, -ma*E2d_1, color='C1', alpha=0.25) ... ax_.plot(t, z_.imag, 'C0-', zs=+ma, zdir='y', alpha=0.5, label="Imag.") ... ax_.plot_surface(E2d_t, ma*E2d_1, e_*E2_amp, color='C1', alpha=0.25) ... ax_.plot(t, z_.real, z_.imag, 'C0-', label="Signal") ... ax_.plot_surface(E3d_t, e_*np.cos(E3d_phi), e_*np.sin(E3d_phi), ... color='C1', alpha=0.5, shade=True, label="Envelope") ... ax_.view_init(elev=22.7, azim=-114.3) >>> fg0.subplots_adjust(left=0.08, right=0.97, wspace=0.15) >>> plt.show() zInvalid parameter axis=z for z.shape=!rz"z.shape[axis] not > 0 for z.shape=z, axis=rFc3HK|]}t|txs|duywra)rro)rdb_s rYrhzenvelope..@ s#!V":b##6#D"*#D!Vs "zbp_in=z2 isn't a 2-tuple of type (int | None, int | None)!Nzn_out=z# is not a positive integer or None!)rrnNz residual=z! not in ['lowpass', 'all', None]!rz9`-n//2 <= bp_in[0] < bp_in[1] <= (n+1)//2` does not hold zfor n=z.shape[axis]=z and bp_in=rr.r)rDrrrfreq)rr?r)rrrVrrmrnrrorstartstopmoveaxisrr|rrrfft zeros_likerfftshiftr>rimagr<r?irfftstack)rbp_inrrrrrrDfakbpZrz_bbbp_shiftz_envz_resrs rYr6r6a st  B VVGt $aff $3dWN!''1EFF GGDMA >aggZx$JKK 5zQc!VPU!VVFE8#UVWW s #E emFE8#FGHH//IH;&GHII  AAEE !)C 58/uQxq!tW 8/uQxacAX ?B BERXX 3 3AaC!8 3T0!''$-!1uha@AB B AtR A zz!''-. JJqM [[37 $ * * MM!2M &"KKN#y1qy. 88a< c2gJ!OJ WWq[ c1RWW9n  "  HH #BGG #{{1S"W:/#5AqD"''AqD.9{{6??126sH}EORUU 'BFF4LRWWT]a-?"''$-STBT-TE KKr4 (E HH #BGG ##r' .2+#xx-!CN+9 77Q;)*Ac277AaCA:%% &8< 5Ac2889n qaQ1 n!45 zz!''-.E6: A:Au -12a7 c1a4iLA 3Lfll1.. 88UBKKr4898 BBrsctj|}tjt|}tj||d|fS)aSort 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)rzr{argsortr>take)rbindxs rY _cmplx_sortr} s;2 1 A ::c!f D 771dA  $$rsc8|dvrtj}n5|dvrtj}n |dvrtj}n t dtj |}tj t|df}tj||dddf<tj||dddf<t|}g}g}tjt|t }tt|D]k} || r |j|| |} | D cgc] } || r |  } } |j||| |jt| d || <mtj |tj |fScc} w) ahDetermine 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]) rmaximumr?minimumavgrJ`rtype` must be one of {'max', 'maximum', 'min', 'minimum', 'avg', 'mean'}rFNrrrT)rzrr?rrVr{rrmrrrrrrlquery_ball_pointr) rbtolrtypereducepointstreep_uniquep_multiplicityusedregrouprs rYr7r7 sih "" $ $ / !OP P 1 A XXs1vqk "F771:F1a4L771:F1a4L 6?DHN 88CF$ 'D 3q6]  7 %%fQi5!1qa11qx()c%j)U   ::h N!; ;;2s ! F,Fctj|}tj|}tjtj|d}t|||\}}t ||d\}}t |dk(rd} ntj ||} t||D]\} } tj| | | z} | |fS)aCompute 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 fTinclude_powersr rzr trim_zeros _group_poles_compute_factorsrmpolymulrpolyadd rerbrrr unique_poles multiplicityfactors denominator numeratorr:factors rYr8r8 sp aA aA bmmA&,A!-ae!<L,+L,;?AG[ 1v{ JJq+. q'?<JJy'F*:; < k !!rsctjdg}|g}t|ddd|dddD]T\}}tjd| g}t|D]}tj||}|j |V|ddd}g} tjdg}t|||D]\}}} tjd| g}g} t|D]D} | dk(s|r%| j tj|| tj||}F| j t| | |fS)z>Compute the total polynomial divided by factors for each root.rrrN)rzrrrlrrextendreversed) rootsrrcurrentsuffixespolemultmonomialrrsuffixblockres rYrr= sGhhsmGyH%1R.,r!Bw*?@! d88QJ't 4Ajj(3G 4 ! "~HGhhsmG!%x@(dF88QJ't 4AAv RZZ89jj(3G 4 x'( G rsct||\}}|j|j}g}t|||D]\}}}|dk(r=|j t j ||t j ||z J|j} t jd| g} t j|| \}} g} t|D]P}t j| | \} } | d| dz }t j| ||z} | j |R|jt| t j|S)Nrr)rrr|rrrzpolyvalrrpolydivrlpolysubr!r"r{)polesrrdenominator_factorsrresiduesr&r'rnumerr(dr*rDres rY_compute_residuesr4V s7-e\B  -IH!%"57-dF 19 OOBJJy$7JJvt45 6NN$ExxTE +H 684IFAE4[ ::eX6qaD1Q4K 5!f*5 Q  OOHUO ,#-& ::h rsctj|}tj|}tj|jtjs.tj|jtjr+|j t }|j t }n*|j t}|j t}tjtj|d}tjtj|d}|jdk(r tdtj|}|jdk(rAtj|jt|dtj gfSt#|t#|krtj$d}ntj&||\}}t)|||\}}t|\}}||}t+|||} d} t-||D]\} } | || | | z| | z } | |dz ||fS)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. rrDenominator `a` is zero.rr)rzr{r}r|complexfloatingrcomplexrlrrrrVr#rrrrrmrr-r7r4r) rmrrrr/rrrorderr1indexr&r's rYr:r:q sX 1 A 1 A aggr112}}QWWb&8&89 HHW  HHW  HHUO HHUO bmmA&,A bmmA&,Avv{344 HHQKEvv{xx $k%&8&;RXXb\II 1vA HHQKzz!Q1!-eE!JL,%l3L%&L |Q?H E, 5 d$(eEDL!   ad?E1 $$rsctj|}tj|}tj|jtjs.tj|jtjr+|j t }|j t }n*|j t}|j t}tjtj|d}tjtj|d}|jdk(r td|ddk(r tdtj|}|jdk(rAtj|jt|dtj gfS|ddd}|ddd}t#|t#|krtj$d}ntj&||\}}t)|||\}} t|\}} | | } t+d|z | |} d} tj$t#| t, } t/|| D]0\}}||| | |zdtj0|z| | | |z| |z } 2| | | z|dz z} | ||dddfS) aCompute 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 rmrr6z6First coefficient of determinant `a` must be non-zero.Nrr7rr)rzr{r}r|r8rr9rlrrrrVr#rrrrrmrr-r7r4rorr)rmrrrr/b_reva_revk_revrrr:r1r;powersr&r's rYr;r; sUp 1 A 1 A aggr112}}QWWb&8&89 HHW  HHW  HHUO HHUO bmmA&,A bmmA&,Avv{344 1%& & HHQKEvv{xx $k%&8&;RXXb\II ddGE ddGE 5zCJ zz%/ u!-eE!JL,%l3L%&L \!1<GH E XXc(m3 /F, 5 d$(eEDL!%&4%8uUT\"    %F"U1X--H UE$B$K ''rscV|dvrtj}n5|dvrtj}n |dvrtj}n t dg}g}|d}|g}t dt |D]a}t|||z |kr|j|)|j|||jt |||}|g}c|j|||jt |tj|tj|fS)Nrrrrrr) rzrr?rrVrlrmr>rr{) r/rrruniquerr&r*res rYrrM s "" $ $ / !OP PFL 8D FE 1c%j ! uQx$ 3 & LL  MM&- (   E +8DFE MM&- E # ::f rzz,7 77rsc tj|}tj|}tjtj|d}t|||\}}t ||d\}}t |dk(rd} n"tj |ddd|ddd} t||D]$\} } tj| | | dddz} &| ddd|fS)aCompute 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 rmTrrNrrrs rYr9r9l sn aA aA bmmA&,A!-ae!<L,+L,;?AG[ 1v{ JJq2w DbD(9: q'?BJJy'F4R4L*@A B TrT?K ''rsc r|dvrtd|dt||}|j|}|jdkDr|j ||d}|j d}||z }t ||} | dzdz} |d} nt|r|tj|} nt|drC|j |fk7rtd |j d |d d z|j|d } n>> import numpy as np >>> import matplotlib.pyplot as plt >>> from scipy.signal import resample ... >>> n0, n1 = 20, 100 # number of samples >>> t0 = np.linspace(0, 10, n0, endpoint=False) # input time stamps >>> x0 = np.cos(-t0**2/6) # input signal ... >>> x1 = resample(x0, n1) # resampled signal >>> t1 = np.linspace(0, 10, n1, endpoint=False) # timestamps of x1 ... >>> fig0, ax0 = plt.subplots(1, 1, tight_layout=True) >>> ax0.set_title(f"Resampling $x(t)$ from {n0} samples to {n1} samples") >>> ax0.set(xlabel="Time $t$", ylabel="Amplitude $x(t)$") >>> ax0.plot(t1, x1, '.-', alpha=.5, label=f"Resampled") >>> ax0.plot(t0, x0, 'o-', alpha=.5, label="Original") >>> ax0.plot(10, x0[0], 'rs', alpha=.5, label="Next Cycle") >>> ax0.legend(loc='best') >>> ax0.grid(True) >>> plt.show() The following example compares this function with a naive `~scipy.fft.rfft` / `~scipy.fft.irfft` combination: An input signal with a sampling interval of one second is upsampled by a factor of eight. The first figure depicts an odd number of input samples whereas the second figure an even number. The upper subplots show the signals over time: The input samples are marked by large green dots, the upsampled signals by a continuous and a dashed line. The lower subplots show the magnitude spectrum: The FFT values of the input are depicted by large green dots, which lie in the frequency interval [-0.5, 0.5] Hz, whereas the frequency interval of the upsampled signal is [-4, 4] Hz. The continuous green line depicts the upsampled spectrum without antialiasing filter, which is a periodic continuation of the input spectrum. The blue x's and orange dots depict the FFT values of the signal created by the naive approach as well as this function's result. >>> import matplotlib.pyplot as plt >>> import numpy as np >>> from scipy.fft import fftshift, fftfreq, fft, rfft, irfft >>> from scipy.signal import resample, resample_poly ... >>> fac, T0, T1 = 8, 1, 1/8 # upsampling factor and sampling intervals >>> for n0 in (15, 16): # number of samples of input signal ... n1 = fac * n0 # number of samples of upsampled signal ... t0, t1 = T0 * np.arange(n0), T1 * np.arange(n1) # time stamps ... x0 = np.zeros(n0) # input signal has two non-zero sample values ... x0[n0//2], x0[n0//2+1] = n0 // 2, -(n0 // 2) ... ... x1n = irfft(rfft(x0), n=n1) * n1 / n0 # naive resampling ... x1r = resample(x0, n1) # resample signal ... ... # Determine magnitude spectrum: ... x0_up = np.zeros_like(x1r) # upsampling without antialiasing filter ... x0_up[::n1 // n0] = x0 ... X0, X0_up = (fftshift(fft(x_)) / n0 for x_ in (x0, x0_up)) ... XX1 = (fftshift(fft(x_)) / n1 for x_ in (x1n, x1r)) ... f0, f1 = fftshift(fftfreq(n0, T0)), fftshift(fftfreq(n1, T1)) # frequencies ... df = f0[1] - f0[0] # frequency resolution ... ... fig, (ax0, ax1) = plt.subplots(2, 1, layout='constrained', figsize=(5, 4)) ... ax0.set_title(rf"Upsampling ${fac}\times$ from {n0} to {n1} samples") ... ax0.set(xlabel="Time $t$ in seconds", ylabel="Amplitude $x(t)$", ... xlim=(0, n1*T1)) ... ax0.step(t0, x0, 'C2o-', where='post', alpha=.3, linewidth=2, ... label="$x_0(t)$ / $X_0(f)$") ... for x_, l_ in zip((x1n, x1r), ('C0--', 'C1-')): ... ax0.plot(t1, x_, l_, alpha=.5, label=None) ... ax0.grid() ... ax1.set(xlabel=rf"Frequency $f$ in hertz ($\Delta f = {df*1e3:.1f}\,$mHz)", ... ylabel="Magnitude $|X(f)|$", xlim=(-0.7, 0.7)) ... ax1.axvspan(0.5/T0, f1[-1], color='gray', alpha=.2) ... ax1.axvspan(f1[0], -0.5/T0, color='gray', alpha=.2) ... ax1.plot(f1, abs(X0_up), 'C2-', f0, abs(X0), 'C2o', alpha=.3, linewidth=2) ... for X_, n_, l_ in zip(XX1, ("naive", "resample"), ('C0x--', 'C1.-')): ... ax1.plot(f1, abs(X_), l_, alpha=.5, label=n_) ... ax1.grid() ... fig.legend(loc='outside lower center', ncols=4) >>> plt.show() The first figure shows that upsampling an odd number of samples produces identical results. The second figure illustrates that the signal produced with the naive approach (dashed blue line) from an even number of samples does not touch all original samples. This deviation is due to `resample` correctly treating unpaired frequency bins. I.e., the input `x1` has a bin pair ±0.5 Hz, whereas the output has only one unpaired bin at -0.5 Hz, which demands rescaling of that bin pair. Generally, special treatment is required if ``n_x != num`` and ``min(n_x, num)`` is even. If the bin values at `±m` are zero, obviously, no special treatment is needed. Consult the source code of `resample` for details. The final example shows how to utilize `resample_poly` to speed up the down-sampling: The input signal a non-zero value at :math:`t=0` and is downsampled from 19937 to 128 samples. Since 19937 is prime, the FFT is expected to be slow. To speed matters up, `resample_poly` is used to downsample first by a factor of ``n0 // n1 = 155`` and then pass the result to `resample`. Two parameterization of `resample_poly` are used: Passing ``padtype='wrap'`` treats the input as being periodic wheras the default parametrization performs zero-padding. The upper subplot shows the resulting signals over time whereas the lower subplot depicts the resulting one-sided magnitude spectra. >>> import matplotlib.pyplot as plt >>> import numpy as np >>> from scipy.fft import rfftfreq, rfft >>> from scipy.signal import resample, resample_poly ... >>> n0 = 19937 # number of input samples - prime >>> n1 = 128 # number of output samples - fast FFT length >>> T0, T1 = 1/n0, 1/n1 # sampling intervals >>> t0, t1 = np.arange(n0)*T0, np.arange(n1)*T1 # time stamps ... >>> x0 = np.zeros(n0) # Input has one non-zero sample >>> x0[0] = n0 >>> >>> x1r = resample(x0, n1) # slow due to n0 being prime >>> # This is faster: >>> x1p = resample(resample_poly(x0, 1, n0 // n1, padtype='wrap'), n1) # periodic >>> x2p = resample(resample_poly(x0, 1, n0 // n1), n1) # with zero-padding ... >>> X0 = rfft(x0) / n0 >>> X1r, X1p, X2p = rfft(x1r) / n1, rfft(x1p) / n1, rfft(x2p) / n1 >>> f0, f1 = rfftfreq(n0, T0), rfftfreq(n1, T1) ... >>> fig, (ax0, ax1) = plt.subplots(2, 1, layout='constrained', figsize=(5, 4)) >>> ax0.set_title(f"Dowsampled Impulse response (from {n0} to {n1} samples)") >>> ax0.set(xlabel="Time $t$ in seconds", ylabel="Amplitude $x(t)$", xlim=(-T1, 1)) >>> for x_ in (x1r, x1p, x2p): ... ax0.plot(t1, x_, alpha=.5) >>> ax0.grid() >>> ax1.set(xlabel=rf"Frequency $f$ in hertz ($\Delta f = {f1[1]}\,$Hz)", ... ylabel="Magnitude $|X(f)|$", xlim=(0, 0.55/T1)) >>> ax1.axvspan(0.5/T1, f0[-1], color='gray', alpha=.2) >>> ax1.plot(f1, abs(X1r), 'C0.-', alpha=.5, label="resample") >>> ax1.plot(f1, abs(X1p), 'C1.-', alpha=.5, label="resample_poly(padtype='wrap')") >>> ax1.plot(f1, abs(X2p), 'C2x-', alpha=.5, label="resample_poly") >>> ax1.grid() >>> fig.legend(loc='outside lower center', ncols=2) >>> plt.show() The plots show that the results of the "pure" `resample` and the usage of the default parameters of `resample_poly` agree well. The periodic padding of `resample_poly` (``padtype='wrap'``) on the other hand produces significant deviations. This is caused by the disconiuity at the beginning of the signal, for which the default filter of `resample_poly` is not suited well. This example illustrates that for some use cases, adpating the `resample_poly` parameters may be beneficial. `resample` has a big advantage in this regard: It uses the ideal antialiasing filter with the maximum bandwidth by default. Note that the doubled spectral magnitude at the Nyqist frequency of 64 Hz is due the even number of ``n1=128`` output samples, which requires a special treatment as discussed in the previous example. )timerzParameter domain=z not in ('time', 'freq')!rrrFNrz window.shape=z != (z,), i.e., window length z)is not equal to number of frequency bins!TrrrEr.rr)rD overwrite_xr)rVrr{rrrr?callablerfftfreqhasattrrrrr#rr|rrTrrrrr)rrtrwindowrrn_xs_facrm2WXn_Xx_rYs rYr<r< sz^%%-fY.GHII A B 1 Avvz KK4 $ ''"+C #IE C A a!B ~  &  6>>#& '  ! <#v-FJJqM1 =AA HHQWWSb\SF*!''H :SbSk#ss( 6c2a45jMAc2a45jM q5A:Sy#r1u* 3A:. s#q!t) ! #$S!Q$Y<#s1a4x- kk!e)s= xx!|kk#r4(}AaDAaD1Q4K50299S>AAAA Jrsct|j|}|t|k7r td|t|k7r tdt|}t|}|dks|dkr td||dk7r td|t j ||}||z}||z}||cxk(rdk(rnnj|d S|j |}||z} | |zt| |zz} t|ts t|rAj|d }|jdkDr td t|dz d z} |} nt||} d | z } d | z} j|jdr2t!d | zdz| |} j| |j} n%t!d | zdz| |} j| } | |z} || |zz }d}| |z|z}t#| j d|z|z|||| |zkr-|dz }t#| j d|z|z|||| |zkr-j%j'|| j| j'|| jf} || z}fd}j(|j*jd}ddd}||vr||||d}n<|t,vrd|i}|dk(r+|d}||d<n!tddj/t,z||vr|z }t1| |||fd|i|}t3dg|jz}t3||||<|t5|}||vr|z }|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() zup must be an integerzdown must be an integerrzup and down must be >= 1Nrz#cval has no effect when padtype is TrFzwindow must be 1-DrFrr[)z real floatingrrLrrczjtjtj|g|i|Sra)r{rzmedian)rargskwdsrs rY_medianzresample_poly.._medians-zz"))BJJqMADADABBrs)rrXrr)rWcval)rkeepdimsrWr\z8padtype must be one of: maximum, mean, median, minimum, z, r)rr{rorVrgcdrrrrr$rr"rrr|rr rrrr?r joinr rr)rupdownrrLpadtyper\g_n_inrhalf_lenrLmax_ratef_c n_pre_pad n_post_pad n_pre_removen_pre_remove_endr[funcsupfirdn_kwargsbackground_valuesrkeepy_keeprs @rYr=r=sx  B 1 A SW}011 s4y233 RB t9D Av344 Gz1>HH "d B2IBRKD TQzz!$z'' 774=D 2IE TMD. .E&$#3F#;F. ;;?12 2FOa'A- r4=8m= ::aggD Eq8|a'Vrt) eventsperiodr scalarperiodevents_vectors vectormeanstrengthphases rYrErEsX^  (B ZZ F ZZ F zz&,, +62::. {{QDEE {{QDEE{{?L ^^Fr 2F ^^Fr 2F vvfk344ii -GffR255688+g567Gq)Jvvj!H :r "EA;a U?rsc 0|dvr tdt|tr t|}n t||}t j |}|j j}|dvrd}|dvr,|t j||dz }|j |S|j}||} t j |}t jt jt jt jd|| }t j|| kDr td t|} |dkr|| z}t j ||d} | j} | j#| d } |s| j%} | j jdvr| j'|} t)t|d z D]} || d z|| z }t j*|d f|}t j,d |d z| |z |dddf<t/|| || d z}t1j2|| |\}}}}| |||zz | |<| j#| } t j | d|}|j |S)a Remove linear or constant trend along axis from data. Parameters ---------- data : array_like The input data. axis : int, optional The axis along which to detrend the data. By default this is the last axis (-1). type : {'linear', 'constant'}, optional The type of detrending. If ``type == 'linear'`` (default), the result of a linear least-squares fit to `data` is subtracted from `data`. If ``type == 'constant'``, only the mean of `data` is subtracted. bp : array_like of ints, optional A sequence of break points. If given, an individual linear fit is performed for each part of `data` between two break points. Break points are specified as indices into `data`. This parameter only has an effect when ``type == 'linear'``. overwrite_data : bool, optional If True, perform in place detrending and avoid a copy. Default is False Returns ------- ret : ndarray The detrended input data. Notes ----- Detrending can be interpreted as subtracting a least squares fit polynomial: Setting the parameter `type` to 'constant' corresponds to fitting a zeroth degree polynomial, 'linear' to a first degree polynomial. Consult the example below. See Also -------- numpy.polynomial.polynomial.Polynomial.fit: Create least squares fit polynomial. Examples -------- The following example detrends the function :math:`x(t) = \sin(\pi t) + 1/4`: >>> import matplotlib.pyplot as plt >>> import numpy as np >>> from scipy.signal import detrend ... >>> t = np.linspace(-0.5, 0.5, 21) >>> x = np.sin(np.pi*t) + 1/4 ... >>> x_d_const = detrend(x, type='constant') >>> x_d_linear = detrend(x, type='linear') ... >>> fig1, ax1 = plt.subplots() >>> ax1.set_title(r"Detrending $x(t)=\sin(\pi t) + 1/4$") >>> ax1.set(xlabel="t", ylabel="$x(t)$", xlim=(t[0], t[-1])) >>> ax1.axhline(y=0, color='black', linewidth=.5) >>> ax1.axvline(x=0, color='black', linewidth=.5) >>> ax1.plot(t, x, 'C0.-', label="No detrending") >>> ax1.plot(t, x_d_const, 'C1x-', label="type='constant'") >>> ax1.plot(t, x_d_linear, 'C2+-', label="type='linear'") >>> ax1.legend() >>> plt.show() Alternatively, NumPy's `~numpy.polynomial.polynomial.Polynomial` can be used for detrending as well: >>> pp0 = np.polynomial.Polynomial.fit(t, x, deg=0) # fit degree 0 polynomial >>> np.allclose(x_d_const, x - pp0(t)) # compare with constant detrend True >>> pp1 = np.polynomial.Polynomial.fit(t, x, deg=1) # fit degree 1 polynomial >>> np.allclose(x_d_linear, x - pp1(t)) # compare with linear detrend True Note that `~numpy.polynomial.polynomial.Polynomial` also allows fitting higher degree polynomials. Consult its documentation on how to extract the polynomial coefficients. )linearlrcz*Trend type must be 'linear' or 'constant'.dfDFr3)rrT)r]rz>Breakpoints must be less than length of data along given axis.rrrFrN)rVrrorrzr{r|rrrrrB concatenaterrnrmrrrrrlrrrrlstsq)datarr6roverwrite_datarr|rdshaperHrnknewdata newdata_shaperNptsAslcoefresidsrrs rYr>r>sY` 33EFF"c D !r D" %r ::d D JJOOE F   RWWT4$77zz# 4L ZZ^ WWRYYr~~bmmAr1.EFG H 66"q&>9: : &k !8#:D++dD!, //!R(llnG ==  V +nnU+Gs2w{# 1Aa!e9r!u$Dq 5)Aii4!859D@AadGr!ubQi(B$*LLGBK$@ !D&$!"+D0GBK  1//-0kk'1d+zz#rsct||}tj|j|d|}|jdk7r t dtj|j|d|}|jdk7r t d|j ddkDr(|ddk(r |dd}|j ddkDr |ddk(r t|dkr t d|dd k7r||dz }||dz }t|j d|j d}|j d|kr?|j||j||j dz |j f}nP|j d|kr>|j||j||j dz |j f}|j||}tj|dz tj |j"z }|j|| }|dd|dd|dzz }|jj%||}|S) ab 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. rrzNumerator b must be 1-D.zDenominator a must be 1-D.rrNz3There must be at least one nonzero `a` coefficient.rr)rrrr{rrVrr"rrrr|ryrzeyer companionrxsolve)rmrrrDrIminusABrs rYr?r?sd A B rzz!}14Avv{344 rzz!}14Avv{566 ''!*q.QqTS[ abE ''!*q.QqTS[qzA~NOOts{ !H !H AGGAJ #A wwqzA~ IIq"((1qwwqz>(AB C a IIq"((1qwwqz>(AB C 1 BffQUmf..q1333Gjjj+G !"!"! A ! $B Irsct|}|j|}|jdk7s|jddk7r t d|j |j dr|j||j}|jd}|j|df|j }d}t|D]N}||d d f}||d d f}|t||z||d f<||j||j|z z}P|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() rFrz!sos must be shape (n_sections, 6))rrrrrNrv.) rr{rrrVrr|rrrrlr?r)sosr n_sectionsrscalesectionrmrs rYr@r@*s l  B **S/C xx1} ! )<== zz#))12iiRZZ(1J :q/ 3B E$' !    :a#337C< RVVAY&&' Irsc tj|}tj|}tt|t|dz }|dk(r>|d|dz dz}||z}|tjgtjgfS|dk7s||j dz k7r$tj |||j dz }|jd}||d|zkr|} n|} tj| |f} tj|} d| d<t||tj| | d| dddf<td|D]} | d| df| | d| f<| ddd} t||| dddd}|ddd}| |k(rtj|| z | |z f}n9tjd| zd|zf}|| z |d| d|f<| |z || d|df<t|||}t|||ddddfddddf}t|||ddddfddddf}t|||}||z }| |k(r|}n,|dd| f}|d| df}tj||fd}|j dk(rtj||d}n{|jd|jdj }tj||dj }|j|jdd|jdfz}| |k(rtj|| f}n3tjd| zd|zf}||d| d|f<| || d|df<|j#|j }|}| |k(r||z }n2|dd| fxx|dd| fz cc<|d| dfxx|d| dfz cc<|dd|f}|d| df} |dk7s||j dz k7rltj |||j dz }tj | ||j dz } tj |||j dz }||| fS) a9Forward-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. rrrFrN)rr.)rzrrrmrrswapaxesrrr0rlhstackrrrrrxdot)!rmrrrirlenr:rrrDrObsrrObsrSSrry_fy_fby_by_bf delta_y_bf_fbdeltastart_mend_mic_optdelta2dic_opt0rPwicy_optx0x1s! rY_filtfilt_gustrxsb aA aA AA ! #E z1!q  AI"((2, ,, rzTQVVaZ' KK4! ,  A }QuW   ((Au: C %B BqE1bhhqkb1!4C1I 1e_!1"a[ABE ! tt9D 1c$B$ia(A 4R4B Av IIrCx* + HHac1U7^ $S"1"fuf* q!"ef* !Q C 1aS$B$Y (dd 3D !Q#tt) %c4R4i 0C 1a D4KMAvRaR(cA23h'/b9  zzQa'*--EKKO466,,q'*1-//Sb!1QWWR[N!BC Av IIr4j ! HHac1U7^ $"1"fuf* !"ef*  **QSS/C EAv   c2A2g#c2A2g,& cA23h3sQBCx=( VeV B eVW B rzTQVVaZ' [[T166A: . [[T166A: . E4!4 "b=rsc .t|||}tj|}tj|}tj|}|dvr t d|dk(r%t |||||\} } } |j| St ||||tt|t|\} } t||}dg|jz}|j||<tj||}t| d|}t||| |||z\} }t| d | }t||t| | |||z\} }t| | } | d kDr+t| | | | } t!|r| j#} |j| 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 )rLgustzmethod must be 'pad' or 'gust'.r)rrntapsrrrrrrrrrrrrr)rrzrr{rVr _validate_padrrmr?rrrrr0rrr)rmrrrrbpadlenrrrrz1z2edgeextrzi_shaperry0s rYrCrC+s| Aq !B aA aA 1 A _$:;; "1aUC 2rzz!}gvq$$'AA$79ID# Aq B sQVV|HWWHTN B !B Cad +BaCdrBw7GQ ARd +BaL6Tb2gNGQ QT"A ax qD5t < B<A ::a=rsc |dvrtd|d|d}||dz}n|}|j||krtd|d|E|dkDr@|dk(rt||| }||fS|d k(rt||| }||fSt ||| }||fS|}||fS) z'Helper to validate padding for filtfilt)evenoddrNzUnknown value 'zG' given to padtype. padtype must be 'even', 'odd', 'constant', or None.rrvzGThe length of the input vector x must be greater than padlen, which is rrrr)rVrrrr)rbrrrrrrs rYrrs77?7)4OOP P ~qy wwt}vQ   tax f 1d.C 9  !T-C 9At$/C 9 9rscdtj|}|jdk(r td|S)Nrzx must be at least 1-D)rzr{rrV)rs rYrrs+ 1 Avv{122 Hrsc  t|||}t|r&t |dt |d| t |dt |}t |\}}t|j}d||<t|g|z}||g}|$|jtj|tj|}|jdvrtd|d|ntj||}t!|t|}|j|k7r/t#d|d |jd |d |d |jd d} ntj$||}d} ||j&z}tj(||d}tj(|d|dzfd}|j|j} } tj*|d|jdf}tj,||d}tj.tj*|d|df}|j1|d}t3|||| |_tj(|d|}| rG| |_tj(|dd|dzf}|j||j|f} | S|j|} | S#t$r t}YwxYw)a Filter data along one dimension using cascaded second-order sections. Filter a data sequence, `x`, using a digital IIR filter defined by `sos`. Parameters ---------- sos : array_like Array of second-order filter coefficients, must have shape ``(n_sections, 6)``. Each row corresponds to a second-order section, with the first three columns providing the numerator coefficients and the last three providing the denominator coefficients. x : array_like An N-dimensional input array. axis : int, optional The axis of the input data array along which to apply the linear filter. The filter is applied to each subarray along this axis. Default is -1. zi : array_like, optional Initial conditions for the cascaded filter delays. It is a (at least 2D) vector of shape ``(n_sections, ..., 2, ...)``, where ``..., 2, ...`` denotes the shape of `x`, but with ``x.shape[axis]`` replaced by 2. If `zi` is None or is not given then initial rest (i.e. all zeros) is assumed. Note that these initial conditions are *not* the same as the initial conditions given by `lfiltic` or `lfilter_zi`. Returns ------- y : ndarray The output of the digital filter. zf : ndarray, optional If `zi` is None, this is not returned, otherwise, `zf` holds the final filter delay values. See Also -------- zpk2sos, sos2zpk, sosfilt_zi, sosfiltfilt, freqz_sos Notes ----- The filter function is implemented as a series of second-order filters with direct-form II transposed structure. It is designed to minimize numerical precision errors for high-order filters. .. versionadded:: 0.16.0 Examples -------- Plot a 13th-order filter's impulse response using both `lfilter` and `sosfilt`, showing the instability that results from trying to do a 13th-order filter in a single stage (the numerical error pushes some poles outside of the unit circle): >>> import matplotlib.pyplot as plt >>> from scipy import signal >>> b, a = signal.ellip(13, 0.009, 80, 0.05, output='ba') >>> sos = signal.ellip(13, 0.009, 80, 0.05, output='sos') >>> x = signal.unit_impulse(700) >>> y_tf = signal.lfilter(b, a, x) >>> y_sos = signal.sosfilt(sos, x) >>> plt.plot(y_tf, 'r', label='TF') >>> plt.plot(y_sos, 'k', label='SOS') >>> plt.legend(loc='best') >>> plt.show() r2rFrrrrrzInvalid zi shape. With axis=z, an input with shape z, and an sos array with z sections, zi must have shape z, got rTFrrr)rC)r:rF)rrrr rrrrrrrrzr{ryrrr!rVrrrrrascontiguousarrayrr) rrrrrr x_zi_shaperr| return_zirBrrs rYr2r2$sL S!R ( |Y'9% > B *AA#C(OCaggJJt |j01J1XF ~ bjjn% NNF #E zz"!L"GHH ~ ZZ% ( ROB/ 0 88z !.th7''(wwk2))3 5#fRXXL;   XXj . !&&=D AtR A R!TAX 1BXG 1r1772;'(A E%A  bjjb*a-@A BB **U* 'C S!RAG Ar4 A [[X4!8} 5zz!}bjjn- Jjjm Jq  s KKKc^t||}t|\}}t|}d|zdz}|t|dddfdk(j |dddfdk(j z}t |||||\}} t |} dg|jz} d| |<|g| z| _t| d|} t|| || | z\} }t| d | }t|t| | || |z\} }t| | } |dkDrt| || | } |j| 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, freqz_sos Notes ----- .. versionadded:: 0.18.0 Examples -------- >>> import numpy as np >>> from scipy.signal import sosfiltfilt, butter >>> import matplotlib.pyplot as plt >>> rng = np.random.default_rng() Create an interesting signal to filter. >>> n = 201 >>> t = np.linspace(0, 1, n) >>> x = 1 + (t < 0.5) - 0.25*t**2 + 0.05*rng.standard_normal(n) Create a lowpass Butterworth filter, and use it to filter `x`. >>> sos = butter(4, 0.125, output='sos') >>> y = sosfiltfilt(sos, x) For comparison, apply an 8th order filter using `sosfilt`. The filter is initialized using the mean of the first four values of `x`. >>> from scipy.signal import sosfilt, sosfilt_zi >>> sos8 = butter(8, 0.125, output='sos') >>> zi = x[:4].mean() * sosfilt_zi(sos8) >>> y2, zo = sosfilt(sos8, x, zi=zi) Plot the results. Note that the phase of `y` matches the input, while `y2` has a significant phase delay. >>> plt.plot(t, x, alpha=0.5, label='x(t)') >>> plt.plot(t, y, label='y(t)') >>> plt.plot(t, y2, label='y2(t)') >>> plt.legend(framealpha=1, shadow=True) >>> plt.grid(alpha=0.25) >>> plt.xlabel('t') >>> plt.show() rFrNrrrrrrrr) rrrr?rrr@rrrr2rr{)rrrrbrrrrrrrrx_0rry_0s rYrArAsCr a B#C(OCAA  NQ E S#ad)q.%%'#ad)q.)=)=)? @@Egvq$$)+ID# CBsQVV|HHTN|h&BH Sqt ,Cc3Tb3h7GQ Qbt ,Cc<5DR#XNGQQT"A ax qD5t < ::a=rsctj|}tj|}|tj|}|j}tj |tj r|jtjk(rtj}|dk(rR| d|z}d|z}t|dzd|z dd} }tj|| }tj| | } n|d k(r1d } |d }t|d d|z d} tj| | } nRt|tr6|j} | jj ddk(r+|j#} | j$| j&} }d}nt)tj*| jsGt)tj*| jstj*| j,r+d} |j#} | j$| j&} }nPd } t/| j0| j| j,} tj| | } n t3dt5dg|j6z} |dk(rg z }|rt9|d|||}n|j ||zt;|j ||zz}t=||d||}t5d|d| |<nS|r! rt? ||}n0tA ||}n  rtC ||}ntE ||}t5dd|| |<|tG| S)a3 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 input signal made up of equidistant samples. If `x` is a multidimensional array, the parameter `axis` specifies the time axis. q : int The downsampling factor, which is a postive integer. 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 ----- For non-integer downsampling factors, `~scipy.signal.resample` can be used. Consult the `scipy.interpolate` module for methods of resampling signals with non-constant sampling intervals. 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() Nfirr[rFrrhammingrVriirTg?g?r)outputrFz invalid ftype)rrL)r`rarr)$rzr{operatorr;r|r}inexactr6rrrrrr _as_zpkr/r_as_tfrrrn iscomplexgainrrrVrrr=rr rArCr2r0r)rqrDftyper zero_phaseryrermr iir_use_sosrsystemrrrs rYrDrDst 1 AqA} NN1 ''K ==bjj 1   bjj (jj  ~ 9AvHH Aac26)4b1 JJq , JJq , % 9AQcAge4jjK0 E4  <<  a A %\\^F::vzzqAE",,v||,-R\\&,,/0fkk*K\\^F::vzzqAK&,, fkkBC**S 4C)) + B ~ E aAD;AGGDMQ&aggdma.?)@@E16AT5$/BtH QT2Q140C.Aq!$/tQ'4 U2Y<rsra)rIr)rI)F)rIN)buifcN)passrrv)rIF)NN)rIrKr)rvr )Nr)r) rztuple[int | None, int | None]rz int | NonerrrzLiteral['lowpass', 'all', None]rro)MbP?r?)rr)NrNrE)r)kaiserg@rN)rrrF) r np.ndarrayrror6zLiteral['linear', 'constant']rzArrayLike | intrrreturnr)rrNrLN)rrN)NrrT)} __future__rrrrr@r\rtypingr numpy._typingr scipy.spatialrr _ltisysr _upfirdnr r r scipyrrrrscipy.fft._helperrnumpyrz scipy.specialrwindowsr _arraytoolsrrrrr_filter_designrrr_fir_filter_designrrscipy._lib._array_apirrr r!r"r#scipy._lib.array_api_compatr$!scipy._lib.array_api_compat.numpy_libarray_api_compatrscipy._lib.array_api_extraarray_api_extrar__all__rTr\rZr^rrrr%r&rrrrr*rrr r+r<rJrRrrrgrBr(r,r-r/r)r'r.r0r1r3r4r5r6rr7r8rr4r:r;rr9r<r=rtrEr>r?r@rrCrrr2rArDrbrsrYrs#  #!::'5"OO::&955(( 5A . 1aQA/ 7MD F Z1z`F:z?D#/LuT&" FRjU1pDNEPL^[|dNl!^Q3heP;|v r9 xYC!%u9BYCYC04YC6YCYCx%G(TgT />+/Xv Qh+-2: