Help us shape the future of Go! Take the 2026 Go Developer Survey

signal

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 20, 2026 License: BSD-3-Clause Imports: 11 Imported by: 0

README

go-dsp/signal

Signal processing in pure Go (CGO_ENABLED=0): filter design and filtering, spectral estimation, resampling and peak finding, with the semantics of SciPy's scipy.signal and, where it differs, a note on MATLAB's.

import "github.com/go-dsp/signal"

z, _ := signal.Butter(8, []float64{0.2}, signal.Lowpass, nil) // zeros, poles, gain
sos, _ := z.SOS(false)                                        // second-order sections
y, _ := signal.SOSFiltFilt(sos, x, nil)                       // zero-phase filtering
f, p, _ := signal.Welch(x, &signal.SpectralOptions{Fs: 1000, Nperseg: 1024})

The module is github.com/go-dsp/signal, BSD-3-Clause. It depends on go-fft/fft (transforms and the classic windows), go-numerics/special (complete elliptic integrals, I0) and go-simd/floats (the assembly dot product used by the FIR kernels).

remez.go's exchange follows the Parks–McClellan program of J. H. McClellan, T. W. Parks and L. R. Rabiner (IEEE Trans. Audio Electroacoust., 1973) as SciPy's _sigtoolsmodule.cc carries it in E. Kvaleberg's C translation (SciPy License, BSD-3-Clause; Copyright 2005 Travis Oliphant and the SciPy developers); its control flow and label numbers are kept so the two read side by side.

Conventions

  • Signals and coefficients are []float64; filters have real coefficients and signals are real and one-dimensional (no axis argument: loop over the channels of a matrix).
  • A filter is a ZPK (zeros, poles, gain), a transfer function (b, a) or an SOS (second-order sections). Use SOS above order 8: the transfer function form loses accuracy fast (see docs/verification.md).
  • Functions that can fail return an error; nothing panics on bad arguments (the fuzz targets enforce it), and sizes are bounded (2^28 elements) so absurd arguments fail instead of exhausting memory.
  • Option structs have useful zero values: nil means SciPy's defaults. Where SciPy's default differs between functions (detrend, scaling) the zero value is "the default of this function".

What is provided

area functions SciPy MATLAB
representations ZPK, SOS, Normalize, TF2ZPK, ZPK2TF, ZPK2SOS, TF2SOS, SOS2TF, SOS2ZPK, Roots normalize, tf2zpk, zpk2tf, zpk2sos, tf2sos, sos2tf, sos2zpk, numpy.roots tf2zp, zp2tf, zp2sos, tf2sos, sos2tf, sos2zp, roots
responses Freqz, SOSFreqz, FreqzZPK, GroupDelay, Freqs, FreqsZPK freqz, sosfreqz, freqz_zpk, group_delay, freqs, freqs_zpk freqz, grpdelay, freqs
analog prototypes ButtAP, Cheb1AP, Cheb2AP, EllipAP (own Jacobi Ellipj), BesselAP buttap, cheb1ap, cheb2ap, ellipap, besselap buttap, cheb1ap, cheb2ap, ellipap, besselap
band transforms LP2LP, LP2HP, LP2BP, LP2BS and the ...ZPK forms, Bilinear, BilinearZPK lp2lp ... lp2bs, bilinear lp2lp, lp2hp, lp2bp, lp2bs, bilinear
IIR design IIRFilter, Butter, Cheby1, Cheby2, Ellip, BesselFilter, IIRDesign, IIRNotch, IIRPeak iirfilter, butter, cheby1, cheby2, ellip, bessel, iirdesign, iirnotch, iirpeak butter, cheby1, cheby2, ellip, besself, designfilt, iirnotch, iirpeak
order selection ButtOrd, Cheb1Ord, Cheb2Ord, EllipOrd buttord, cheb1ord, cheb2ord, ellipord buttord, cheb1ord, cheb2ord, ellipord
FIR design Firwin, Firwin2, Remez (Parks–McClellan), Firls, KaiserOrd, KaiserBeta, KaiserAtten firwin, firwin2, remez, firls, kaiserord fir1, fir2, firpm, firls, kaiserord
windows Hann, Hamming, Blackman, BlackmanHarris, Bartlett, Boxcar, Triang, Parzen, Bohman, Nuttall, Flattop, Cosine, Barthann, Kaiser, Tukey, Gaussian, GeneralGaussian, GeneralHamming, GeneralCosine, Exponential, Chebwin, DPSS (Slepian, with concentration ratios), GetWindow windows.*, get_window hann, hamming, blackman, kaiser, tukeywin, gausswin, chebwin, dpss, ...
filtering LFilter, LFilterZI, LFilterIC, FiltFilt (odd/even/constant padding and Gustafsson), SOSFilt, SOSFiltZI, SOSFiltFilt lfilter, lfilter_zi, lfiltic, filtfilt, sosfilt, sosfilt_zi, sosfiltfilt filter, filtfilt
convolution Convolve, Correlate, CorrelationLags, FFTConvolve, OAConvolve, ChooseConvMethod, Deconvolve convolve, correlate, correlation_lags, fftconvolve, oaconvolve, choose_conv_method, deconvolve conv, xcorr, fftfilt, deconv
spectral Periodogram, Welch, CSD, Coherence, Spectrogram, STFT, ISTFT, CheckCOLA, CheckNOLA, Lombscargle periodogram, welch, csd, coherence, spectrogram, stft, istft, check_COLA, check_NOLA, lombscargle periodogram, pwelch, cpsd, mscohere, spectrogram, stft, istft, plomb
resampling Resample (FFT), ResamplePoly (polyphase), Decimate, Upfirdn resample, resample_poly, decimate, upfirdn resample, decimate, upfirdn
analytic signal, trend Hilbert, Detrend hilbert, detrend hilbert, detrend
peaks FindPeaks (height, threshold, distance, prominence, width, plateau), PeakProminences, PeakWidths find_peaks, peak_prominences, peak_widths findpeaks, peakwidths, peakprom

Differences worth knowing:

  • STFT/ISTFT follow SciPy's legacy stft/istft (the ShortTimeFFT class is not provided).
  • SciPy emits warnings where Go returns values: a singular group delay is set to zero silently; Remez returns the best filter together with ErrNotConverged (SciPy raises; a degenerate design whose taps would not be finite returns nil).
  • EllipAP returns an error (SciPy returns NaN poles) when the stopband attenuation is below the passband ripple.
  • Bessel prototypes use exact integer polynomial coefficients refined in 320-bit arithmetic (double precision loses the zeros above order 8) and are limited to order 150, where the delay gain overflows float64.
  • The PadModeReflect, PadModeAntireflect, PadModeSmooth and PadModeLine extensions of a one-sample signal are undefined in SciPy; here they repeat the sample.

Not provided: N-dimensional and axis variants, complex-coefficient filters, dlti/lti classes, ShortTimeFFT, savgol_filter, czt, continuous wavelets and find_peaks_cwt (wavelets are planned in this organisation).

Verification

SciPy 1.18.1 with NumPy 2.5.4 is the oracle, driven from Go (oracle_test.go: one persistent Python process, base64 float64/complex128 over JSON lines, so no decimal round trip loses a bit). Every comparison is recorded in testdata/oracle and replayed from there, so go test needs no Python and the same recorded SciPy output is checked on every architecture CI runs. GOWORK=off go test -update ./... re-records it and rewrites docs/accuracy.md, the table of maximum ULP errors, normwise relative errors and exact-equality counts for 225 groups of values; docs/verification.md explains the measures and the few places where SciPy itself is the less accurate side (ill-conditioned elliptic and Bessel designs, high-order transfer functions).

  • 100% statement coverage with -race, including the error paths.
  • gofmt, go vet, govulncheck; amd64, arm64, 386 (and under qemu riscv64, loong64, ppc64le, s390x, arm) and every GOOS/GOARCH pair compiling the tests.
  • Fuzz targets for the design constructors, the spectral estimators, the convolutions and the peak finder.

Performance

docs/perf.md: one core against SciPy on the same host, in interleaved rounds, with the load average checked (-perf -perfcase <regexp> measures a subset without rewriting the table). The FIR kernels call the SIMD dot product of go-simd/floats; the recursions are serial by nature, so SOSFilt runs four (or two) sections sample-major to overlap their dependency chains and the FIR form of LFilter is a direct chain eight outputs wide, both bit-identical to the one-section, one-output form. Remez runs the McClellan–Parks–Rabiner exchange (its search walks the error curve from each extremum instead of evaluating the whole grid every iteration), PeakProminences finds every base in two monotonic-stack passes (O(n), where the per-peak scan SciPy uses is O(n·peaks)), and Spectrogram computes its PSD through one reused spectrum buffer.

Layout

file contents
convert.go, poly.go representations, conversions, polynomial roots
freq.go frequency responses, group delay
analog.go, transform.go, iir.go prototypes, band transforms, IIR design and order selection
fir.go, remez.go, windows.go, linalg.go FIR design, Parks–McClellan, windows and DPSS, small solvers
filter.go, convolve.go filtering, convolution
spectral.go, resample.go spectral estimation, resampling, peaks
*_test.go, testdata/oracle tests, SciPy oracle harness and recorded responses

Documentation

Overview

Package signal is signal processing in pure Go: filter design and filtering, spectral estimation and resampling, with SciPy's semantics (scipy.signal) and, where they differ, a note on MATLAB's.

All vectors are []float64 and filters have real coefficients. Filters travel as transfer-function coefficients (TF), zeros-poles-gain (ZPK) or second-order sections (SOS); prefer SOS above order 8, where the transfer function form loses accuracy.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrNotConverged = errors.New("signal: the Remez exchange did not converge; try a wider transition band")

ErrNotConverged is returned by Remez, with the best filter found, when the exchange does not converge within MaxIter iterations or its deviation stops growing (SciPy raises "Failure to converge" there). For a degenerate design whose filter would not be finite, the filter returned is nil.

Functions

func Barthann

func Barthann(n int, sym bool) []float64

Barthann is the modified Bartlett–Hann window.

func Bartlett

func Bartlett(n int, sym bool) []float64

Bartlett is the triangular window with zero end points.

func Bilinear

func Bilinear(b, a []float64, fs float64) ([]float64, []float64, error)

Bilinear maps an analog transfer function b/a (in s) to a digital one (in z) by the bilinear transform at sampling frequency fs (scipy.signal.bilinear).

func Blackman

func Blackman(n int, sym bool) []float64

Blackman is the Blackman window.

func BlackmanHarris

func BlackmanHarris(n int, sym bool) []float64

BlackmanHarris is the 4-term Blackman–Harris window.

func Bohman

func Bohman(n int, sym bool) []float64

Bohman is the Bohman window.

func Boxcar

func Boxcar(n int, sym bool) []float64

Boxcar is the rectangular window.

func ButtOrd

func ButtOrd(wp, ws []float64, gpass, gstop float64, analog bool, fs float64) (int, []float64, error)

ButtOrd returns the minimum order and the natural (-3 dB) frequencies of a Butterworth filter meeting the passband (wp, gpass dB) and stopband (ws, gstop dB) specification (scipy.signal.buttord). wp and ws hold one frequency (lowpass/highpass) or two (bandpass/bandstop); with fs == 0 they are normalised to the Nyquist frequency.

func CSD

func CSD(x, y []float64, o *SpectralOptions) (f []float64, p []complex128, err error)

CSD estimates the cross power spectral density of x and y by Welch's method (scipy.signal.csd; MATLAB cpsd). The shorter signal is zero padded.

func Cheb1Ord

func Cheb1Ord(wp, ws []float64, gpass, gstop float64, analog bool, fs float64) (int, []float64, error)

Cheb1Ord returns the minimum order and the passband edge frequencies of a Chebyshev type I filter (scipy.signal.cheb1ord).

func Cheb2Ord

func Cheb2Ord(wp, ws []float64, gpass, gstop float64, analog bool, fs float64) (int, []float64, error)

Cheb2Ord returns the minimum order and the stopband-start frequencies of a Chebyshev type II filter (scipy.signal.cheb2ord).

func CheckCOLA

func CheckCOLA(win []float64, nperseg, noverlap int, tol float64) (bool, error)

CheckCOLA reports whether the window and overlap satisfy the constant overlap-add condition, so that STFT with those parameters is invertible and the overlapped windows sum to a constant (scipy.signal.check_COLA).

func CheckNOLA

func CheckNOLA(win []float64, nperseg, noverlap int, tol float64) (bool, error)

CheckNOLA reports whether the window and overlap satisfy the nonzero overlap-add condition: the squared windows sum to a nonzero value everywhere, the minimum requirement for ISTFT (scipy.signal.check_NOLA).

func Coherence

func Coherence(x, y []float64, o *SpectralOptions) (f, c []float64, err error)

Coherence estimates the magnitude-squared coherence of x and y, |Pxy|^2/(Pxx Pyy) (scipy.signal.coherence; MATLAB mscohere).

func Convolve

func Convolve(a, b []float64, mode ConvMode, method ConvMethod) ([]float64, error)

Convolve convolves a and b (scipy.signal.convolve; MATLAB conv).

Example
package main

import (
	"fmt"

	"github.com/go-dsp/signal"
)

func main() {
	y, _ := signal.Convolve([]float64{1, 2, 3}, []float64{0, 1, 0.5}, signal.ConvFull, signal.ConvAuto)
	fmt.Println(y)
}
Output:
[0 1 2.5 4 1.5]

func Correlate

func Correlate(a, b []float64, mode ConvMode, method ConvMethod) ([]float64, error)

Correlate cross-correlates a and b: out[k] = sum_n a[n+k] b[n] (scipy.signal.correlate; MATLAB xcorr up to its lag convention).

func CorrelationLags

func CorrelationLags(n1, n2 int, mode ConvMode) ([]int, error)

CorrelationLags returns the lag of each output of Correlate for inputs of the given lengths (scipy.signal.correlation_lags).

func Cosine

func Cosine(n int, sym bool) []float64

Cosine is the half-cosine (sine) window.

func DPSS

func DPSS(m int, nw float64, kmax int, sym bool, norm DPSSNorm) (windows [][]float64, ratios []float64, err error)

DPSS returns the first kmax discrete prolate spheroidal (Slepian) sequences of length m and time-half-bandwidth product nw, the multitaper windows of Thomson, computed from the symmetric tridiagonal eigenproblem of Percival and Walden. ratios holds the spectral concentration ratios.

func Decimate

func Decimate(x []float64, q int, o *DecimateOptions) ([]float64, error)

Decimate downsamples x by the integer factor q after low-pass filtering to prevent aliasing (scipy.signal.decimate; MATLAB decimate).

func Deconvolve

func Deconvolve(signal, divisor []float64) (quot, rem []float64, err error)

Deconvolve divides the polynomial signal by divisor, returning the quotient and remainder (scipy.signal.deconvolve): signal = conv(divisor, quot) + rem.

func Detrend

func Detrend(x []float64, t DetrendType, bp []int) ([]float64, error)

Detrend removes a constant or piecewise-linear trend from x, with breakpoints bp between the linear pieces (scipy.signal.detrend).

func EllipOrd

func EllipOrd(wp, ws []float64, gpass, gstop float64, analog bool, fs float64) (int, []float64, error)

EllipOrd returns the minimum order and the passband edge frequencies of an elliptic filter (scipy.signal.ellipord).

func Ellipj

func Ellipj(u, m float64) (sn, cn, dn float64)

Ellipj evaluates the Jacobi elliptic functions sn, cn and dn of argument u and parameter m = k^2 in [0, 1] (the algorithm of Cephes' ellpj, via the arithmetic-geometric mean; NaN outside the domain).

func FFTConvolve

func FFTConvolve(a, b []float64, mode ConvMode) ([]float64, error)

FFTConvolve convolves a and b using the FFT (scipy.signal.fftconvolve).

func FiltFilt

func FiltFilt(b, a, x []float64, o *FiltFiltOptions) ([]float64, error)

FiltFilt applies the filter b/a forward and backward, giving zero phase distortion and squared magnitude response (scipy.signal.filtfilt; MATLAB filtfilt). The signal is extended at both ends to reduce transients.

func Firls

func Firls(numtaps int, bands, desired, weight []float64, fs float64) ([]float64, error)

Firls designs a linear-phase FIR filter by least squares (scipy.signal.firls; MATLAB firls). numtaps must be odd. bands holds pairs of band edges (increasing, between 0 and fs/2), desired the gain at each edge, and weight (optional, one per band) the relative weight of each band. fs defaults to 2.

func Firwin

func Firwin(numtaps int, cutoff []float64, o *FirwinOptions) ([]float64, error)

Firwin designs a linear-phase FIR filter with the window method (scipy.signal.firwin; MATLAB fir1). cutoff holds one or more strictly increasing frequencies between 0 and Fs/2.

Example
package main

import (
	"fmt"

	"github.com/go-dsp/signal"
)

func main() {
	h, _ := signal.Firwin(21, []float64{0.3}, nil)
	var sum float64
	for _, v := range h {
		sum += v
	}
	fmt.Printf("%d taps, DC gain %.6f\n", len(h), sum)
}
Output:
21 taps, DC gain 1.000000

func Firwin2

func Firwin2(numtaps int, freq, gain []float64, o *Firwin2Options) ([]float64, error)

Firwin2 designs an FIR filter by frequency sampling: freq and gain describe a piecewise-linear desired response from 0 to Fs/2 (scipy.signal.firwin2; MATLAB fir2).

func Flattop

func Flattop(n int, sym bool) []float64

Flattop is the flat top window.

func Freqs

func Freqs(b, a []float64, o *FreqOptions) (w []float64, h []complex128, err error)

Freqs returns the frequency response H(jw) = B(jw)/A(jw) of the analog filter b/a (scipy.signal.freqs); o.W is in rad/s and o.N defaults to 200 logarithmically spaced points chosen from the poles and zeros.

func FreqsZPK

func FreqsZPK(s ZPK, o *FreqOptions) (w []float64, h []complex128, err error)

FreqsZPK is Freqs for a filter given as zeros, poles and gain.

func Freqz

func Freqz(b, a []float64, o *FreqOptions) (w []float64, h []complex128, err error)

Freqz returns the frequency response H(e^jw) = B(e^-jw)/A(e^-jw) of the digital filter b/a at the frequencies w (in the units of o.Fs), like scipy.signal.freqz (MATLAB freqz).

func FreqzZPK

func FreqzZPK(s ZPK, o *FreqOptions) (w []float64, h []complex128, err error)

FreqzZPK is Freqz for a filter given as zeros, poles and gain.

func GetWindow

func GetWindow(name string, n int, fftbins bool, params ...float64) ([]float64, error)

GetWindow returns the named window (scipy.signal.get_window): the name is one of boxcar, triang, bartlett, hann, hamming, blackman, blackmanharris, nuttall, flattop, cosine, bohman, parzen, barthann, kaiser(beta), gaussian(std), general_gaussian(p, sig), general_hamming(alpha), general_cosine(a...), tukey(alpha), exponential(tau), chebwin(at) and dpss(NW), with the parameters in params. fftbins selects the periodic (true) form; a "_symmetric" or "_periodic" suffix overrides it.

func GroupDelay

func GroupDelay(b, a []float64, o *FreqOptions) (w, gd []float64, err error)

GroupDelay returns the group delay, in samples, of the digital filter b/a (scipy.signal.group_delay). Where the delay is singular it is set to zero.

func Hamming

func Hamming(n int, sym bool) []float64

Hamming is the Hamming window.

func Hann

func Hann(n int, sym bool) []float64

Hann is the Hann window (go-fft's, extended to the periodic form).

func Hilbert

func Hilbert(x []float64, n int) ([]complex128, error)

Hilbert returns the analytic signal x + i*H(x), computed in the frequency domain (scipy.signal.hilbert; MATLAB hilbert). n is the FFT length (0 means len(x)).

func IIRNotch

func IIRNotch(w0, q, fs float64) (b, a []float64, err error)

IIRNotch designs a second-order notch (band-reject) filter at frequency w0 with quality factor q (scipy.signal.iirnotch; MATLAB iirnotch). fs == 0 means 2, so that w0 is relative to the Nyquist frequency.

func IIRPeak

func IIRPeak(w0, q, fs float64) (b, a []float64, err error)

IIRPeak designs a second-order peaking (band-pass) filter (scipy.signal.iirpeak; MATLAB iirpeak).

func ISTFT

func ISTFT(z [][]complex128, o *ISTFTOptions) (t, x []float64, err error)

ISTFT inverts STFT by weighted overlap-add (scipy.signal.istft).

func KaiserAtten

func KaiserAtten(numtaps int, width float64) float64

KaiserAtten returns the attenuation in dB of a Kaiser-window FIR filter with numtaps taps and a transition width relative to Nyquist (scipy.signal.kaiser_atten).

func KaiserBeta

func KaiserBeta(a float64) float64

KaiserBeta returns the Kaiser window shape parameter for a given stopband attenuation a in dB (scipy.signal.kaiser_beta).

func KaiserOrd

func KaiserOrd(ripple, width float64) (numtaps int, beta float64, err error)

KaiserOrd returns the number of taps and the Kaiser beta needed for a ripple (attenuation) of the given dB and a transition width relative to Nyquist (scipy.signal.kaiserord).

func LFilter

func LFilter(b, a, x, zi []float64) (y, zf []float64, err error)

LFilter filters x with the IIR or FIR filter b/a using the direct form II transposed structure (scipy.signal.lfilter; MATLAB filter). zi, if not nil, holds the initial state (length max(len(a), len(b))-1), and the final state zf is returned so that long signals can be filtered in pieces.

func LFilterIC

func LFilterIC(b, a, y, x []float64) ([]float64, error)

LFilterIC constructs the initial state of lfilter for given past outputs y and inputs x (most recent first), scipy.signal.lfiltic. x may be nil (zero input history).

func LFilterZI

func LFilterZI(b, a []float64) ([]float64, error)

LFilterZI returns the initial state of the filter b/a for a step input of unit amplitude: the state in which a constant input of 1 gives a constant output (scipy.signal.lfilter_zi).

func LP2BP

func LP2BP(b, a []float64, wo, bw float64) ([]float64, []float64, error)

LP2BP transforms a lowpass prototype b/a to a bandpass centred on wo with bandwidth bw (scipy.signal.lp2bp).

func LP2BS

func LP2BS(b, a []float64, wo, bw float64) ([]float64, []float64, error)

LP2BS transforms a lowpass prototype b/a to a bandstop centred on wo with bandwidth bw (scipy.signal.lp2bs).

func LP2HP

func LP2HP(b, a []float64, wo float64) ([]float64, []float64, error)

LP2HP transforms a lowpass prototype b/a to a highpass with cutoff wo (scipy.signal.lp2hp).

func LP2LP

func LP2LP(b, a []float64, wo float64) ([]float64, []float64, error)

LP2LP transforms a lowpass prototype b/a to a lowpass with cutoff wo (scipy.signal.lp2lp).

func Lombscargle

func Lombscargle(x, y, freqs []float64, o *LombOptions) ([]float64, error)

Lombscargle computes the Lomb–Scargle periodogram of the unevenly sampled y(x) at the angular frequencies freqs (scipy.signal.lombscargle).

func LombscargleAmplitude

func LombscargleAmplitude(x, y, freqs []float64, o *LombOptions) ([]complex128, error)

LombscargleAmplitude is Lombscargle returning the complex best-fit amplitude and phase a + ib, rotated by the phase offset (normalize='amplitude').

func Normalize

func Normalize(b, a []float64) ([]float64, []float64, error)

Normalize scales the transfer function b/a so that a[0] == 1, trims the leading zeros of a and the leading numerator coefficients that are all below 1e-14 (keeping at least one), like scipy.signal.normalize.

func Nuttall

func Nuttall(n int, sym bool) []float64

Nuttall is the minimum 4-term Blackman–Harris window of Nuttall.

func OAConvolve

func OAConvolve(a, b []float64, mode ConvMode) ([]float64, error)

OAConvolve convolves a and b by the overlap-add method, which is faster than FFTConvolve when one input is much longer than the other (scipy.signal.oaconvolve).

func Overlap

func Overlap(n int) *int

Overlap returns a pointer to n, for SpectralOptions.Noverlap.

func Parzen

func Parzen(n int, sym bool) []float64

Parzen is the Parzen (de la Vallée Poussin) window.

func PeakProminences

func PeakProminences(x []float64, peaks []int, wlen float64) (prom []float64, left, right []int, err error)

PeakProminences calculates the prominence of each peak: its height above the higher of the two lowest contours towards the next higher peaks (scipy.signal.peak_prominences). wlen <= 1 means the whole signal.

func PeakWidths

func PeakWidths(x []float64, peaks []int, relHeight float64, prom []float64, left, right []int) (widths, heights, leftIP, rightIP []float64, err error)

PeakWidths calculates the width of each peak at relHeight times its prominence below the peak (scipy.signal.peak_widths). The prominence data are those of PeakProminences.

func Periodogram

func Periodogram(x []float64, o *SpectralOptions) (f, p []float64, err error)

Periodogram estimates the power spectral density of x from one windowed FFT (scipy.signal.periodogram; MATLAB periodogram). The default window is rectangular.

func Remez

func Remez(numtaps int, bands, desired []float64, o *RemezOptions) ([]float64, error)

Remez designs an optimal equiripple FIR filter with the Parks–McClellan exchange algorithm (scipy.signal.remez; MATLAB firpm). bands holds pairs of band edges between 0 and Fs/2, desired the gain in each band.

func Resample

func Resample(x []float64, num int, o *ResampleOptions) ([]float64, error)

Resample resamples x to num samples using the FFT, assuming x is periodic (scipy.signal.resample). It is best for periodic signals; use ResamplePoly otherwise.

func ResamplePoly

func ResamplePoly(x []float64, up, down int, o *ResamplePolyOptions) ([]float64, error)

ResamplePoly resamples x by the rational factor up/down with a polyphase FIR filter (scipy.signal.resample_poly; MATLAB resample). The filter is linear phase and the output is aligned with the input.

Example
package main

import (
	"fmt"

	"github.com/go-dsp/signal"
)

func main() {
	x := make([]float64, 100)
	for i := range x {
		x[i] = float64(i)
	}
	y, _ := signal.ResamplePoly(x, 3, 2, nil)
	fmt.Println(len(y))
}
Output:
150

func Roots

func Roots(p []float64) ([]complex128, error)

Roots returns the roots of the polynomial p[0]*x^n + ... + p[n], like numpy.roots: the eigenvalues of the companion matrix (balanced, reduced by the shifted QR algorithm). Leading zeros are dropped and trailing zeros give exact zero roots. Roots of a real polynomial come in conjugate pairs.

The order of the returned roots is unspecified.

func SOS2TF

func SOS2TF(sos SOS) (b, a []float64)

SOS2TF converts second-order sections to a transfer function.

func SOSFilt

func SOSFilt(sos SOS, x []float64, zi [][2]float64) (y []float64, zf [][2]float64, err error)

SOSFilt filters x with a cascade of second-order sections (scipy.signal.sosfilt). zi, if not nil, holds the initial state of each section (len(sos) rows of two values); the final state is returned.

func SOSFiltFilt

func SOSFiltFilt(sos SOS, x []float64, o *FiltFiltOptions) ([]float64, error)

SOSFiltFilt is the zero-phase forward-backward filter for second-order sections (scipy.signal.sosfiltfilt).

func SOSFiltZI

func SOSFiltZI(sos SOS) ([][2]float64, error)

SOSFiltZI returns the initial state of each section for a unit step input (scipy.signal.sosfilt_zi).

func SOSFreqz

func SOSFreqz(sos SOS, o *FreqOptions) (w []float64, h []complex128, err error)

SOSFreqz returns the frequency response of a cascade of sections (scipy.signal.sosfreqz).

func STFT

func STFT(x []float64, o *STFTOptions) (f, t []float64, z [][]complex128, err error)

STFT computes the short-time Fourier transform of x (scipy.signal.stft; legacy API): Z[f][t] with the default Hann window of 256 samples, 50% overlap, zero boundary extension and padding, scaled as a spectrum.

func Spectrogram

func Spectrogram(x []float64, o *SpectralOptions, mode SpectrogramMode) (f, t []float64, s [][]float64, err error)

Spectrogram computes a spectrogram of x from consecutive Fourier transforms (scipy.signal.spectrogram; MATLAB spectrogram): S[f][t], with the default Tukey window (alpha 0.25) and Nperseg/8 overlap.

func Triang

func Triang(n int, sym bool) []float64

Triang is the triangular window with nonzero end points.

func Upfirdn

func Upfirdn(h, x []float64, up, down int, mode PadMode, cval float64) ([]float64, error)

Upfirdn upsamples x by up (inserting zeros), filters with h, and downsamples by down, computing only the samples that are kept (scipy.signal.upfirdn). mode and cval define the signal beyond its ends.

func Welch

func Welch(x []float64, o *SpectralOptions) (f, p []float64, err error)

Welch estimates the power spectral density of x by Welch's method of averaged, windowed, overlapping periodograms (scipy.signal.welch; MATLAB pwelch).

Example
package main

import (
	"fmt"
	"math"

	"github.com/go-dsp/signal"
)

func main() {
	x := make([]float64, 4096)
	for i := range x {
		x[i] = math.Sin(2 * math.Pi * 100 * float64(i) / 1000) // 100 Hz at fs = 1000 Hz
	}
	f, p, _ := signal.Welch(x, &signal.SpectralOptions{Fs: 1000, Nperseg: 500})
	best := 0
	for i := range p {
		if p[i] > p[best] {
			best = i
		}
	}
	fmt.Printf("peak at %.0f Hz\n", f[best])
}
Output:
peak at 100 Hz

func ZPK2TF

func ZPK2TF(s ZPK) (b, a []float64, err error)

ZPK2TF converts zeros, poles and gain to a transfer function. Complex roots must come in conjugate pairs.

Types

type Average

type Average int

Average selects how Welch-type estimators combine segments.

const (
	// AverageMean takes the mean (Welch's method).
	AverageMean Average = iota
	// AverageMedian takes the median, corrected for bias (robust to outliers).
	AverageMedian
)

type BandType

type BandType int

BandType is the band layout of a filter.

const (
	Lowpass BandType = iota
	Highpass
	Bandpass
	Bandstop
)

type BesselNorm

type BesselNorm int

BesselNorm selects the frequency normalisation of the Bessel prototype.

const (
	// BesselPhase (the default) matches the phase to half of the asymptotic
	// shift at 1 rad/s; the asymptotes are those of a Butterworth filter.
	BesselPhase BesselNorm = iota
	// BesselDelay normalises the low-frequency group delay to 1 s.
	BesselDelay
	// BesselMag puts the -3 dB magnitude point at 1 rad/s.
	BesselMag
)

type ConvMethod

type ConvMethod int

ConvMethod selects the algorithm of Convolve and Correlate.

const (
	// ConvAuto picks the faster of direct and FFT (scipy's choose_conv_method).
	ConvAuto ConvMethod = iota
	// ConvDirect sums the products directly.
	ConvDirect
	// ConvFFT uses the FFT.
	ConvFFT
)

func ChooseConvMethod

func ChooseConvMethod(n1, n2 int, mode ConvMode) ConvMethod

ChooseConvMethod returns the faster method for convolving inputs of length n1 and n2, by SciPy's fitted cost model (scipy.signal.choose_conv_method without measuring).

type ConvMode

type ConvMode int

ConvMode selects which part of the full convolution is returned.

const (
	// ConvFull returns the complete discrete convolution, len(a)+len(b)-1 samples.
	ConvFull ConvMode = iota
	// ConvSame returns the central part, the size of the first input.
	ConvSame
	// ConvValid returns only the samples computed without zero padding.
	ConvValid
)

type DPSSNorm

type DPSSNorm int

DPSSNorm selects the normalisation of discrete prolate spheroidal sequences.

const (
	// DPSSApproximate (the default for a single window) scales the peak to 1
	// and corrects for even lengths by an analytic approximation.
	DPSSApproximate DPSSNorm = iota
	// DPSSSubsample scales to 1 at the interpolated centre of even lengths.
	DPSSSubsample
	// DPSSNorm2 normalises to unit energy (the default for several windows).
	DPSSNorm2
)

type DecimateOptions

type DecimateOptions struct {
	// N is the filter order (default 8 for IIR, 20*q for FIR, where it is the
	// number of taps minus one).
	N int
	// FIR uses a Hamming-window FIR filter instead of a Chebyshev type I IIR.
	FIR bool
	// NoZeroPhase filters once instead of forward and backward.
	NoZeroPhase bool
}

DecimateOptions are the optional parameters of Decimate.

type DetrendType

type DetrendType int

DetrendType selects what is removed from each segment before analysis.

const (
	// DetrendDefault is the default of the function it is passed to:
	// constant for Welch, CSD, Periodogram and Spectrogram, none for STFT.
	DetrendDefault DetrendType = iota
	// DetrendConstant removes the mean.
	DetrendConstant
	// DetrendLinear removes the least-squares line.
	DetrendLinear
	// DetrendNone leaves the data alone.
	DetrendNone
)

type FiltFiltOptions

type FiltFiltOptions struct {
	PadType PadType
	// PadLen is the number of samples to extend at each end; zero means the
	// default of 3*max(len(a), len(b)). Use PadNone for no padding.
	PadLen int
	Method FiltMethod
	// IRLen is the impulse response length used by FiltGust (0: the whole
	// signal).
	IRLen int
}

FiltFiltOptions are the optional parameters of FiltFilt.

type FiltMethod

type FiltMethod int

FiltMethod selects the way FiltFilt handles the ends of the signal.

const (
	// FiltPad pads the signal (default).
	FiltPad FiltMethod = iota
	// FiltGust uses Gustafsson's method, choosing initial conditions that
	// make the forward-backward and backward-forward results agree.
	FiltGust
)

type FilterType

type FilterType int

FilterType is the family of an IIR design.

const (
	Butterworth FilterType = iota
	Chebyshev1
	Chebyshev2
	Elliptic
	Bessel
)

type FindPeaksOptions

type FindPeaksOptions struct {
	// Height is the required peak height.
	Height *Interval
	// Threshold is the required vertical distance to the neighbouring samples.
	Threshold *Interval
	// Distance is the required minimal horizontal distance (in samples, >= 1)
	// between neighbouring peaks; the smaller peaks are removed first.
	Distance float64
	// Prominence is the required prominence of the peaks.
	Prominence *Interval
	// Width is the required width at RelHeight.
	Width *Interval
	// Wlen limits the window (in samples, > 1) in which prominence is evaluated.
	Wlen float64
	// RelHeight is the fraction of the prominence at which widths are measured
	// (default 0.5; widths at 0 are not available, use a tiny value).
	RelHeight float64
	// PlateauSize is the required size of a flat peak.
	PlateauSize *Interval
}

FindPeaksOptions are the optional conditions of FindPeaks; a nil condition is not applied.

type FirPass

type FirPass int

FirPass selects the passband layout of Firwin, like the pass_zero argument of scipy.signal.firwin.

const (
	// FirPassZeroTrue: the response at DC is passed (pass_zero=True).
	FirPassZeroTrue FirPass = iota
	// FirPassZeroFalse: the response at DC is blocked (pass_zero=False).
	FirPassZeroFalse
	// FirLowpass: a single cutoff, DC passed.
	FirLowpass
	// FirHighpass: a single cutoff, DC blocked.
	FirHighpass
	// FirBandpass: at least two cutoffs, DC blocked.
	FirBandpass
	// FirBandstop: at least two cutoffs, DC passed.
	FirBandstop
)

type Firwin2Options

type Firwin2Options struct {
	// Nfreqs is the size of the interpolation grid (default 1 + 2^ceil(log2(numtaps))).
	Nfreqs int
	// Window defaults to Hamming; NoWindow disables windowing.
	Window   Window
	NoWindow bool
	// Antisymmetric designs a type III/IV filter (Hilbert transformers,
	// differentiators).
	Antisymmetric bool
	// Fs is the sampling frequency (default 2).
	Fs float64
}

Firwin2Options are the optional parameters of Firwin2.

type FirwinOptions

type FirwinOptions struct {
	// Width, if positive, is the approximate transition width in the units of
	// Fs; it selects a Kaiser window and overrides Window.
	Width float64
	// Window defaults to Hamming.
	Window Window
	// PassZero selects how the cutoffs are read (default FirPassZeroTrue).
	PassZero FirPass
	// NoScale disables scaling the passband gain to exactly 1.
	NoScale bool
	// Fs is the sampling frequency (default 2: cutoffs relative to Nyquist=1).
	Fs float64
}

FirwinOptions are the optional parameters of Firwin.

type FreqOptions

type FreqOptions struct {
	// N is the number of frequencies when W is nil (default 512 for digital
	// responses, 200 for analog ones).
	N int
	// W lists the frequencies to evaluate, in the units of Fs (rad/s for
	// analog responses, where Fs does not apply).
	W []float64
	// Whole evaluates around the whole unit circle, [0, 2π), instead of
	// the upper half [0, π).
	Whole bool
	// Fs is the sampling frequency; zero means 2π, so that frequencies are
	// in rad/sample.
	Fs float64
	// IncludeNyquist includes the Nyquist frequency when Whole is false
	// and N points are generated.
	IncludeNyquist bool
}

FreqOptions selects the frequencies of a response. The zero value means the defaults of scipy.signal.freqz: 512 points on [0, π) in rad/sample.

type IIROptions

type IIROptions struct {
	// Rp is the maximum passband ripple in dB (Chebyshev I, elliptic).
	Rp float64
	// Rs is the minimum stopband attenuation in dB (Chebyshev II, elliptic).
	Rs float64
	// Analog designs an analog filter, with Wn in rad/s.
	Analog bool
	// Fs is the sampling frequency of a digital design: Wn is then in the
	// same units. Zero means Wn is normalised to the Nyquist frequency (1).
	Fs float64
	// Bessel selects the Bessel normalisation (default BesselPhase).
	Bessel BesselNorm
}

IIROptions holds the optional parameters of an IIR design.

type ISTFTOptions

type ISTFTOptions struct {
	SpectralOptions
	// TwoSidedInput says z holds the full spectrum rather than 0..Fs/2.
	TwoSidedInput bool
	// NoBoundary says the forward transform used no boundary extension.
	NoBoundary bool
}

ISTFTOptions are the parameters of ISTFT.

type Interval

type Interval struct {
	Min, Max       float64
	HasMin, HasMax bool
}

Interval is an optional lower and upper bound of a peak property.

func AtLeast

func AtLeast(v float64) *Interval

AtLeast is the interval [v, inf).

func AtMost

func AtMost(v float64) *Interval

AtMost is the interval (-inf, v].

func Between

func Between(lo, hi float64) *Interval

Between is the interval [lo, hi].

type LombOptions

type LombOptions struct {
	// Weights are non-negative sample weights (default uniform).
	Weights []float64
	// Normalize scales the periodogram by the signal variance (range [0, 1]).
	Normalize bool
	// FloatingMean fits a constant offset together with the sinusoid.
	FloatingMean bool
}

LombOptions are the optional parameters of Lombscargle.

type PadMode

type PadMode string

PadMode is the signal extension used by Upfirdn and ResamplePoly beyond the ends of the input.

const (
	PadModeConstant      PadMode = "constant"
	PadModeEdge          PadMode = "edge"
	PadModeWrap          PadMode = "wrap"
	PadModeSymmetric     PadMode = "symmetric"
	PadModeReflect       PadMode = "reflect"
	PadModeAntisymmetric PadMode = "antisymmetric"
	PadModeAntireflect   PadMode = "antireflect"
	// PadModeSmooth extends by the slope of the last two points at each end.
	PadModeSmooth PadMode = "smooth"
	// PadModeLine extends by the line through the first and last points.
	PadModeLine PadMode = "line"
)

Extension modes; the first group are those of numpy.pad.

type PadType

type PadType int

PadType is the signal extension used by FiltFilt.

const (
	// PadOdd extends by odd (point) reflection about the end points (default).
	PadOdd PadType = iota
	// PadEven extends by even reflection.
	PadEven
	// PadConstant extends with the end values.
	PadConstant
	// PadNone does not extend the signal.
	PadNone
)

type Pairing

type Pairing int

Pairing selects how ZPK2SOS pairs poles with zeros.

const (
	// PairNearest (the default for digital filters) pairs each pole nearest
	// the unit circle with the closest zero and pads to an even order.
	PairNearest Pairing = iota
	// PairKeepOdd keeps the odd section last, like PairNearest but without
	// padding the pole and zero counts to an even number.
	PairKeepOdd
	// PairMinimal gives sections of the lowest necessary order; it is the
	// only valid choice for analog filters.
	PairMinimal
)

type PeakProperties

type PeakProperties struct {
	PlateauSizes, LeftEdges, RightEdges []int
	PeakHeights                         []float64
	LeftThresholds, RightThresholds     []float64
	Prominences                         []float64
	LeftBases, RightBases               []int
	Widths, WidthHeights                []float64
	LeftIPs, RightIPs                   []float64
}

PeakProperties holds the properties computed for the peaks found; a slice is nil when the condition that computes it was not requested.

func FindPeaks

func FindPeaks(x []float64, o *FindPeaksOptions) (peaks []int, props PeakProperties, err error)

FindPeaks finds the local maxima of x satisfying the conditions of o (scipy.signal.find_peaks; MATLAB findpeaks). A flat peak is reported at its middle sample. Conditions apply in the order plateau size, height, threshold, distance, prominence, width.

Example
package main

import (
	"fmt"

	"github.com/go-dsp/signal"
)

func main() {
	peaks, props, _ := signal.FindPeaks([]float64{0, 1, 0, 2, 0, 1.5, 0}, &signal.FindPeaksOptions{Height: signal.AtLeast(1.2)})
	fmt.Println(peaks, props.PeakHeights)
}
Output:
[3 5] [2 1.5]

type RemezOptions

type RemezOptions struct {
	// Weight has one relative weight per band (default all 1).
	Weight []float64
	// Type defaults to RemezBandpass.
	Type RemezType
	// MaxIter defaults to 25.
	MaxIter int
	// GridDensity defaults to 16.
	GridDensity int
	// Fs is the sampling frequency (default 1).
	Fs float64
}

RemezOptions are the optional parameters of Remez.

type RemezType

type RemezType int

RemezType is the kind of filter Remez designs.

const (
	// RemezBandpass is a symmetric multiband filter.
	RemezBandpass RemezType = iota
	// RemezDifferentiator has a gain proportional to frequency, with the
	// error weighted by 1/f.
	RemezDifferentiator
	// RemezHilbert is an antisymmetric filter.
	RemezHilbert
)

type ResampleOptions

type ResampleOptions struct {
	// Window, if not nil, weights the spectrum (a frequency-domain window,
	// generated for len(x) points and centred on DC like SciPy's).
	Window Window
	// WindowFreq, if not nil, is the spectral weighting in FFT order.
	WindowFreq []float64
}

ResampleOptions are the optional parameters of Resample.

type ResamplePolyOptions

type ResamplePolyOptions struct {
	// Window designs the anti-aliasing filter (default Kaiser with beta 5).
	Window Window
	// Taps, if not nil, is the FIR filter to use instead.
	Taps []float64
	// PadType is how the signal is extended: "mean", "median", "minimum" or
	// "maximum" (the signal minus that value is filtered, then it is added
	// back), or one of the PadMode values (default PadModeConstant).
	PadType string
	// Cval is the value for PadModeConstant.
	Cval float64
}

ResamplePolyOptions are the optional parameters of ResamplePoly.

type SOS

type SOS [][6]float64

SOS is a cascade of second-order sections, each [b0 b1 b2 a0 a1 a2]; the digital form is b0 + b1 z^-1 + b2 z^-2 over a0 + a1 z^-1 + a2 z^-2 with a0 == 1. The gain is carried by the first section.

func TF2SOS

func TF2SOS(b, a []float64, pairing Pairing, analog bool) (SOS, error)

TF2SOS converts a transfer function to second-order sections.

func ZPK2SOS

func ZPK2SOS(s ZPK, pairing Pairing, analog bool) (_ SOS, err error)

ZPK2SOS converts zeros, poles and gain to second-order sections, ordering them so that the poles nearest the unit circle (the imaginary axis if analog) come last, as scipy.signal.zpk2sos does.

type STFTOptions

type STFTOptions struct {
	SpectralOptions
	// Boundary extends the signal at both ends so that the first window is
	// centred on the first sample: "zeros" (the default when empty and
	// NoBoundary is false), "even", "odd" or "constant".
	Boundary string
	// NoBoundary disables the extension.
	NoBoundary bool
	// NoPad disables zero padding to a whole number of segments.
	NoPad bool
}

STFTOptions are the parameters of STFT beyond SpectralOptions.

type Scaling

type Scaling int

Scaling selects the units of a spectrum.

const (
	// ScaleDefault is the default of the function it is passed to: density for
	// Welch, CSD, Periodogram and Spectrogram, spectrum for STFT and ISTFT.
	ScaleDefault Scaling = iota
	// ScaleDensity gives a power spectral density (units^2/Hz).
	ScaleDensity
	// ScaleSpectrum gives a power spectrum (units^2).
	ScaleSpectrum
)

type SpectralOptions

type SpectralOptions struct {
	// Fs is the sampling frequency (default 1).
	Fs float64
	// Window generates the window (periodic form) of Nperseg samples;
	// WindowTaps, if not nil, is used instead and sets Nperseg.
	Window     Window
	WindowTaps []float64
	// Nperseg is the length of each segment (default 256, or the signal
	// length if shorter).
	Nperseg int
	// Noverlap is the number of overlapping samples (default depends on the
	// estimator: Nperseg/2 for Welch, Nperseg/8 for Spectrogram).
	Noverlap *int
	// Nfft is the FFT length, at least Nperseg (default Nperseg).
	Nfft int
	// Detrend is applied to each segment.
	Detrend DetrendType
	// Scaling is the density (default) or spectrum.
	Scaling Scaling
	// TwoSided returns both halves of the spectrum instead of 0..Fs/2.
	TwoSided bool
	// Average is used by Welch, CSD and Coherence.
	Average Average
}

SpectralOptions are the optional parameters of the spectral estimators. The zero value is SciPy's defaults for the function it is passed to.

type SpectrogramMode

type SpectrogramMode int

SpectrogramMode selects what Spectrogram returns.

const (
	// SpecPSD is the power spectral density or spectrum of each segment.
	SpecPSD SpectrogramMode = iota
	// SpecMagnitude is the magnitude of the STFT.
	SpecMagnitude
	// SpecAngle is the angle of the STFT in radians.
	SpecAngle
	// SpecPhase is the unwrapped angle along time.
	SpecPhase
)

type Window

type Window func(n int, sym bool) []float64

Window generates an n-point window: symmetric when sym is true (for filter design), periodic otherwise (for spectral analysis, the DFT-even form of get_window's default). A window that cannot be generated for the given parameters returns nil.

func Chebwin

func Chebwin(at float64) Window

Chebwin is the Dolph–Chebyshev window with at dB of sidelobe attenuation.

func Exponential

func Exponential(center, tau float64) Window

Exponential is the Poisson window exp(-|n - center|/tau). A NaN center means the middle of the window; as in SciPy an explicit center is only allowed for a periodic window (sym false), otherwise nil is returned.

func Gaussian

func Gaussian(std float64) Window

Gaussian is the Gaussian window with standard deviation std (in samples).

func GeneralCosine

func GeneralCosine(a []float64) Window

GeneralCosine is the sum of cosines sum_k a[k] cos(k*x), x in [-π, π] (scipy.signal.windows.general_cosine).

func GeneralGaussian

func GeneralGaussian(p, sig float64) Window

GeneralGaussian is exp(-0.5 |n/sig|^(2p)); p = 1 is Gaussian.

func GeneralHamming

func GeneralHamming(alpha float64) Window

GeneralHamming is alpha - (1-alpha) cos(2πn/(M-1)); alpha 0.54 is Hamming and 0.5 Hann.

func Kaiser

func Kaiser(beta float64) Window

Kaiser is the Kaiser window with shape parameter beta.

func Tukey

func Tukey(alpha float64) Window

Tukey is the tapered cosine window; alpha is the fraction of the window inside the cosine tapered regions (0 is rectangular, 1 is Hann).

type ZPK

type ZPK struct {
	Z, P []complex128
	K    float64
}

ZPK is a filter as zeros, poles and gain. Roots of a real filter are real or come in conjugate pairs. In the digital case the transfer function is H(z) = K * prod(z - Z[i]) / prod(z - P[i]); in the analog case the same with s.

func BesselAP

func BesselAP(n int, norm BesselNorm) (ZPK, error)

BesselAP returns the analog Bessel (Thomson) lowpass prototype of order n (scipy.signal.besselap).

func BesselFilter

func BesselFilter(n int, wn []float64, bt BandType, norm BesselNorm, o *IIROptions) (ZPK, error)

BesselFilter designs a Bessel/Thomson filter with the given normalisation.

func BilinearZPK

func BilinearZPK(s ZPK, fs float64) (ZPK, error)

BilinearZPK maps an analog filter to a digital one with the bilinear transform at sampling frequency fs (scipy.signal.bilinear_zpk). Zeros at infinity go to the Nyquist frequency.

func ButtAP

func ButtAP(n int) (ZPK, error)

ButtAP returns the zeros, poles and gain of the analog Butterworth lowpass prototype of order n, with cutoff 1 rad/s (scipy.signal.buttap).

func Butter

func Butter(n int, wn []float64, bt BandType, o *IIROptions) (ZPK, error)

Butter designs a Butterworth filter (scipy.signal.butter).

Example
package main

import (
	"fmt"

	"github.com/go-dsp/signal"
)

func main() {
	z, _ := signal.Butter(2, []float64{0.2}, signal.Lowpass, nil)
	b, a, _ := z.TF()
	fmt.Printf("b = %.6f\na = %.6f\n", b, a)
}
Output:
b = [0.067455 0.134911 0.067455]
a = [1.000000 -1.142981 0.412802]

func Cheb1AP

func Cheb1AP(n int, rp float64) (ZPK, error)

Cheb1AP returns the analog Chebyshev type I lowpass prototype of order n with rp dB of passband ripple, passband edge 1 rad/s (scipy.signal.cheb1ap).

func Cheb2AP

func Cheb2AP(n int, rs float64) (ZPK, error)

Cheb2AP returns the analog Chebyshev type II lowpass prototype of order n with rs dB of stopband attenuation, stopband edge 1 rad/s (scipy.signal.cheb2ap).

func Cheby1

func Cheby1(n int, rp float64, wn []float64, bt BandType, o *IIROptions) (ZPK, error)

Cheby1 designs a Chebyshev type I filter with rp dB of passband ripple.

func Cheby2

func Cheby2(n int, rs float64, wn []float64, bt BandType, o *IIROptions) (ZPK, error)

Cheby2 designs a Chebyshev type II filter with rs dB of stopband attenuation.

func Ellip

func Ellip(n int, rp, rs float64, wn []float64, bt BandType, o *IIROptions) (ZPK, error)

Ellip designs an elliptic (Cauer) filter.

func EllipAP

func EllipAP(n int, rp, rs float64) (ZPK, error)

EllipAP returns the analog elliptic (Cauer) lowpass prototype of order n with rp dB of passband ripple and rs dB of stopband attenuation, passband edge 1 rad/s (scipy.signal.ellipap).

func IIRDesign

func IIRDesign(wp, ws []float64, gpass, gstop float64, ft FilterType, o *IIROptions) (ZPK, error)

IIRDesign designs the lowest-order filter of the given family meeting a passband/stopband specification (scipy.signal.iirdesign): wp and ws are the passband and stopband edges (one or two each), gpass the maximum passband loss and gstop the minimum stopband attenuation in dB. Bessel has no order selection.

func IIRFilter

func IIRFilter(n int, wn []float64, bt BandType, ft FilterType, o *IIROptions) (ZPK, error)

IIRFilter designs an order-n IIR filter of the given family and band layout (scipy.signal.iirfilter). wn holds one critical frequency for a lowpass or highpass filter and two for a bandpass or bandstop filter; for Chebyshev I the frequency is the edge of the ripple band, for Chebyshev II the start of the stopband. The result is zeros, poles and gain; use TF or SOS to convert (prefer SOS above order 8).

func LP2BPZPK

func LP2BPZPK(s ZPK, wo, bw float64) (ZPK, error)

LP2BPZPK transforms a lowpass prototype to a bandpass filter centred on wo with bandwidth bw (scipy.signal.lp2bp_zpk).

func LP2BSZPK

func LP2BSZPK(s ZPK, wo, bw float64) (ZPK, error)

LP2BSZPK transforms a lowpass prototype to a bandstop filter centred on wo with bandwidth bw (scipy.signal.lp2bs_zpk).

func LP2HPZPK

func LP2HPZPK(s ZPK, wo float64) (ZPK, error)

LP2HPZPK transforms a lowpass prototype to a highpass filter with cutoff wo (scipy.signal.lp2hp_zpk).

func LP2LPZPK

func LP2LPZPK(s ZPK, wo float64) (ZPK, error)

LP2LPZPK transforms a lowpass prototype to a lowpass filter with cutoff wo (scipy.signal.lp2lp_zpk).

func SOS2ZPK

func SOS2ZPK(sos SOS) (ZPK, error)

SOS2ZPK converts second-order sections to zeros, poles and gain.

func TF2ZPK

func TF2ZPK(b, a []float64) (ZPK, error)

TF2ZPK converts a transfer function b/a to zeros, poles and gain.

func (ZPK) SOS

func (z ZPK) SOS(analog bool) (SOS, error)

SOS returns the filter as second-order sections with SciPy's default pairing: nearest for digital filters, minimal for analog ones.

func (ZPK) TF

func (z ZPK) TF() (b, a []float64, err error)

TF returns the transfer-function coefficients of the filter.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL