dsp

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 12 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package dsp is offline signal processing for engineers: filter design, filtering, frequency response, conditioning, smoothing, peaks, alignment, spectral analysis and reductions. It works on whole signals as []float64, uses only the standard library, and is checked against SciPy and MATLAB, which the tables in docs/accuracy.md measure.

f, err := dsp.Butter(4, dsp.Lowpass(0.2))
sos, err := f.SOS()
y, err := dsp.SOSFiltFilt(sos, x)

Filter design

Each design returns a ZPK, whose SOS method gives second-order sections and BA method (b, a). A Band is Lowpass, Highpass, Bandpass or Bandstop, with edges as fractions of Nyquist.

tukey                SciPy                MATLAB
Butter               butter               butter
Cheby1               cheby1               cheby1
Cheby2               cheby2               cheby2
Ellip                ellip                ellip
Bessel               bessel               besself, then bilinear
ButterOrd            buttord              buttord
Cheby1Ord            cheb1ord             cheb1ord
Cheby2Ord            cheb2ord             cheb2ord
EllipOrd             ellipord             ellipord
IIRNotch             iirnotch             iirnotch, DSP System Toolbox
IIRPeak              iirpeak              iirpeak, DSP System Toolbox
FIRWin               firwin               fir1
ZPK.BA               zpk2tf               zp2tf
ZPK.SOS              zpk2sos              zp2sos

Filtering and response

tukey                SciPy                MATLAB
Filter               lfilter              filter
FilterState          lfilter with zi      filter with zi
FilterZi             lfilter_zi
SOSFilter            sosfilt              sosfilt
SOSFilterState       sosfilt with zi
SOSFilterZi          sosfilt_zi
FiltFilt             filtfilt             filtfilt
SOSFiltFilt          sosfiltfilt          filtfilt(sos, g, x)
Freqz                freqz                freqz
SOSFreqz             freqz_sos            freqz(sos, n)
GroupDelay           group_delay          grpdelay
SOSGroupDelay                             grpdelay(sos, n)

ConvertFrequency, and shortcuts such as HzToNyquist and RadPerSampleToHz, convert between Hz, rad/sample, cycles/sample and fractions of Nyquist.

Signals

tukey                SciPy                         MATLAB
Detrend              detrend                       detrend
Interp1              interp1d(bounds_error=False)  interp1
FillMissing                                        fillmissing
Convolve             convolve                      conv
Correlate            correlate, correlation_lags   xcorr
MedFilt              medfilt                       medfilt1
SavGolFilter         savgol_filter                 sgolayfilt
FindPeaks            find_peaks                    findpeaks
PeakProminences      peak_prominences              findpeaks fourth output
PeakWidths           peak_widths                   findpeaks third output
Hilbert              hilbert                       hilbert
Envelope             envelope                      envelope
FindSignal                                         findsignal

Spectral analysis

Each takes the window as a slice, from tukey/window or anywhere, and its length is the segment length.

tukey                SciPy                MATLAB
STFT                 stft                 spectrogram S
Spectrogram          spectrogram          spectrogram P
Welch                welch                pwelch
Periodogram          periodogram          periodogram

Reductions and calculus

tukey                NumPy and SciPy               MATLAB
Sum                  numpy.sum                     sum
Mean                 numpy.mean                    mean
RMS                                                rms
Percentile           numpy.percentile              prctile, with PercentileHazen
Diff                 numpy.diff                    diff
Grad                 numpy.gradient                gradient
CumSum               numpy.cumsum                  cumsum
Trapz                trapezoid                     trapz
CumTrapz             cumulative_trapezoid          cumtrapz

Conventions

Every function is offline and stateless: the whole signal goes in as a slice, and a new slice comes back. Inputs are never modified, and nothing is shared between calls, so all functions are safe for concurrent use. To filter in blocks, FilterState and SOSFilterState take a starting state and return the final one, to pass to the next block. An empty result is an empty slice, never nil.

Invalid input returns an error wrapping one of the Err sentinels, so check for one with errors.Is. Filtering functions don't check that a filter is stable, and assume it is, same as SciPy and MATLAB.

Where tukey differs

Where SciPy and MATLAB differ, tukey follows SciPy, and MATLAB's behaviour is an option. Where neither suits general use, tukey chooses its own default and says why.

Frequencies:

  • band edges, w0 and cutoffs are fractions of Nyquist, same as SciPy and MATLAB, and HzToNyquist converts from Hz
  • Freqz and GroupDelay return w in rad/sample, and w first, where MATLAB returns the response first
  • the spectral functions work in Hz, given fs

Filter design and filtering:

  • (b, a) loses digits as the order rises or the band narrows, so use SOS, SOSFilter and SOSFiltFilt above order 4 or so
  • Bessel's band edge is the -3 dB point by default, same as Butter's, where SciPy's default is BesselNormPhase
  • the order selections meet the passband edge, same as SciPy, and MatchStopband meets the stopband's, same as MATLAB's buttord and cheb2ord
  • IIRNotch and IIRPeak take the quality factor q, where MATLAB takes the bandwidth w0/q
  • FIRWin takes the window itself, whose length is the number of taps, where fir1 takes the order, one less
  • FiltFilt pads by SciPy's length, and MATLABPadLen uses MATLAB's
  • SOSFiltFilt filters the whole cascade forward then backward, same as SciPy, and BySection filters each section in turn, same as MATLAB

Signals:

  • indices are 0-based, in FindPeaks, PeakProminences, PeakWidths and FindSignal
  • ConvolveSame starts one output earlier than MATLAB's conv 'same' for an even len(v), and ConvolveValid with v longer than a isn't empty
  • Correlate gives only the lags where a and v overlap, where xcorr pads the shorter with zeros
  • MedFilt truncates its window at the ends by default, where SciPy and MATLAB pad with zeros, MedFiltZeroPad
  • FindPeaks follows SciPy's rules, and MATLABPeaks MATLAB's, whose MinPeakDistance d is MinPeakDistance(d+1)
  • FindSignal's distance is exact, where MATLAB's rounds, and SearchFast rounds the same way as MATLAB

Spectral analysis:

  • there's no default window or segment length, as together they set the trade-off between time and frequency resolution
  • there's no detrending by default, where SciPy's welch, spectrogram and periodogram subtract each segment's mean, so pass SegmentDetrend(DetrendConstant()) to match
  • TimeFrequency's Values are [segment][frequency], the transpose of SciPy's and MATLAB's
  • STFT isn't divided by the window's sum, where SciPy's stft is
  • TwoSided frequencies run from 0 up then negative, same as fft.Freq, where MATLAB's run up to fs

Reductions:

  • sums are compensated, so a long signal, or small values among large ones, keeps its low bits, e.g. 1e8, 20,000 values of 0.001 and -1e8 sum to 20, where MATLAB's sum gives 20.00001
  • Mean and RMS of an empty signal return ErrSignalTooShort, where MATLAB's mean and rms give NaN
  • Percentile is linear by default, same as NumPy, and PercentileHazen is MATLAB's prctile, but any NaN gives NaN, where prctile ignores it, so use FillMissing first

NaN and infinity

A NaN or infinite sample affects only the outputs it contributes to, as plain arithmetic would. A sample is part of the signal, so it's never an error. What it contributes to depends on the function:

  • a running sum, a filter with feedback, or FiltFilt's backward pass carries it on
  • a transform, such as Hilbert, Envelope's analytic method or ConvolveFFT, mixes every sample into every output
  • Detrend and Envelope's RMS method use the whole signal's trend or mean

A sample and a filter coefficient of exactly 0 contribute nothing, so a zero coefficient never turns a NaN or infinite sample into NaN. Interpolating next to an infinite value gives that infinity, its limit. Each function's doc says where it differs, e.g. Percentile, where any NaN gives NaN.

A NaN or infinite parameter, coefficient, state or window tap returns an error, unless the function's doc gives it a meaning, e.g. MinPeakHeight(math.Inf(-1)) is no limit.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidLength is a length or count that's wrong in itself,
	// or lengths that should match and don't
	ErrInvalidLength = errors.New("dsp: invalid length")
	// ErrSignalTooShort is an input with too few samples for what's asked, including none
	ErrSignalTooShort = errors.New("dsp: signal too short")
	// ErrInvalidParameter is a value outside its domain
	ErrInvalidParameter = errors.New("dsp: invalid parameter")
	// ErrInvalidOption is an option or enum value that's unknown or doesn't apply
	ErrInvalidOption = errors.New("dsp: invalid option")

	// ErrInvalidBand is a Band that's zero, or whose edges aren't in (0, 1) and in order
	ErrInvalidBand = errors.New("dsp: invalid band")
	// ErrInvalidOrder is a filter order below 1
	ErrInvalidOrder = errors.New("dsp: invalid filter order")
	// ErrInvalidCoefficients is an empty b or a, or an a[0] of 0
	ErrInvalidCoefficients = errors.New("dsp: invalid filter coefficients")
	// ErrInvalidZPK is complex zeros or poles that aren't in conjugate pairs
	ErrInvalidZPK = errors.New("dsp: invalid zeros, poles and gain")
	// ErrInvalidSOS is no sections, or a section whose a0 isn't 1
	ErrInvalidSOS = errors.New("dsp: invalid second-order sections")
	// ErrInvalidState is a filter state of the wrong size
	ErrInvalidState = errors.New("dsp: invalid filter state")
	// ErrNoSteadyState is a filter with a pole at z = 1, which has no steady state
	ErrNoSteadyState = errors.New("dsp: filter has no steady state")
	// ErrInvalidSamplePoints is sample points that aren't strictly increasing
	ErrInvalidSamplePoints = errors.New("dsp: invalid sample points")
)

Errors returned for invalid input. Each is wrapped with the detail of what was wrong, so check for one with errors.Is, e.g. errors.Is(err, dsp.ErrSignalTooShort). The first four mean the same in every tukey package.

Functions

func ConvertFrequency added in v1.0.0

func ConvertFrequency[T float64 | []float64](f T, from, to FrequencyUnit, fs float64) (g T, err error)

ConvertFrequency returns f, a frequency or a slice of them in the unit from, in the unit to. fs is the sample rate in Hz, used only when either unit is UnitHz. A slice gives a new slice, and a single value a single value:

wn, err := dsp.ConvertFrequency(50.0, dsp.UnitHz, dsp.UnitNyquist, 1000) // 0.1
f, err := dsp.ConvertFrequency(w, dsp.UnitRadPerSample, dsp.UnitHz, fs)

A single value must be a float64, so write 50.0 rather than 50. Between UnitHz, UnitNyquist and UnitCyclesPerSample the result is correctly rounded. To or from UnitRadPerSample it's within an ULP or two, as π isn't exact.

Units:

  • f is in the unit from, and g in the unit to
  • fs is in Hz

Returns: ErrInvalidParameter for a unit that isn't one of the four, or an fs that isn't positive and finite when either unit is UnitHz.

Equivalent to:

  • scipy.signal.freqz(b, a, fs=fs), which returns w in Hz
  • MATLAB freqz(b, a, n, fs), which returns w in Hz

func Convolve added in v0.10.0

func Convolve(a, v []float64, opts ...ConvolveOption) (c []float64, err error)

Convolve returns the convolution of a and v, c[k] = Σ a[i]·v[k-i]: by default the full result, len(a) + len(v) - 1 outputs, or the part ConvolveSame or ConvolveValid selects. It sums directly or by FFT, whichever is faster, unless ConvolveDirect or ConvolveFFT says. Filtering a signal by an FIR filter h, keeping x's length, is:

y, err := dsp.Convolve(x, h, dsp.ConvolveSame())

Units: c is in a's unit times v's

Returns: ErrSignalTooShort for an empty a or v.

Equivalent to:

  • scipy.signal.convolve(a, v, mode), and numpy.convolve(a, v, mode)
  • MATLAB conv(a, v, shape), except that its 'same' starts one output later for an even len(v), and its 'valid' is empty when v is longer than a
Example
package main

import (
	"fmt"
	"log"
	"math"

	"github.com/cxd309/tukey/dsp"
	"github.com/cxd309/tukey/waveform"
	"github.com/cxd309/tukey/window"
)

func main() {
	// a 101-tap lowpass at a fifth of Nyquist, by the window method
	w, err := window.Hamming(101)
	if err != nil {
		log.Fatal(err)
	}
	h, err := dsp.FIRWin(w, dsp.Lowpass(0.2))
	if err != nil {
		log.Fatal(err)
	}

	// filter a slow sine with a fast one on top, keeping x's length,
	// at 0.01 and 0.3 cycles per sample, so the times are the sample indices
	t, err := waveform.Timebase(1000, 1)
	if err != nil {
		log.Fatal(err)
	}
	slow, err := waveform.Tone(t, 0.01, waveform.Phase(-90))
	if err != nil {
		log.Fatal(err)
	}
	fast, err := waveform.Tone(t, 0.3, waveform.Phase(-90))
	if err != nil {
		log.Fatal(err)
	}
	x := make([]float64, len(t))
	for i := range x {
		x[i] = slow[i] + fast[i]
	}
	y, err := dsp.Convolve(x, h, dsp.ConvolveSame())
	if err != nil {
		log.Fatal(err)
	}

	// away from the ends, only the slow tone is left, less the passband's ripple
	worst := 0.0
	for i := 100; i < 900; i++ {
		worst = math.Max(worst, math.Abs(y[i]-slow[i]))
	}
	fmt.Printf("y matches the slow tone to within %.0e\n", worst)
}
Output:
y matches the slow tone to within 3e-03

func CumSum added in v0.9.0

func CumSum(x []float64) (s []float64)

CumSum returns the running total of x, s[i] = x[0] + ... + x[i], the same length as x. It's summed with compensation, so its error doesn't grow with the signal's length, as a plain running sum's does.

s := dsp.CumSum([]float64{1, 2, 3}) // [1 3 6]

Units: same as x

Equivalent to:

  • numpy.cumsum(x), which sums plainly
  • MATLAB cumsum(x), which sums plainly

func CumTrapz added in v0.9.0

func CumTrapz(y []float64, dx float64) (integral []float64, err error)

CumTrapz returns the running trapezoidal integral of y, sampled every dx: the integral up to each sample, starting at 0, the same length as y, so it lines up with y and its time axis. It's summed with compensation, same as Trapz.

velocity, err := dsp.CumTrapz(acceleration, 1/fs)

Units:

  • dx is the time between samples, e.g. 1/fs in seconds
  • integral is in y's unit times dx's

Returns: ErrInvalidParameter for a dx that isn't positive and finite.

Equivalent to:

  • scipy.integrate.cumulative_trapezoid(y, dx=dx, initial=0)
  • MATLAB cumtrapz(dx, y)

func Detrend added in v0.5.0

func Detrend(x []float64, mode DetrendMode) (y []float64)

Detrend returns x with its trend removed: the least-squares line for DetrendLinear, or the mean for DetrendConstant. An empty x gives an empty result, and a single sample gives [0].

y := dsp.Detrend(x, dsp.DetrendLinear())

Units: same as x

Equivalent to:

  • scipy.signal.detrend(x, type='linear'), or type='constant'
  • MATLAB detrend(x), or detrend(x, 0)

func Diff added in v0.9.0

func Diff(x []float64) (d []float64)

Diff returns the difference between each sample and the next, d[i] = x[i+1] - x[i], one shorter than x. Fewer than 2 samples have no differences, so give an empty slice. A higher order is Diff applied again, e.g. Diff(Diff(x)).

d := dsp.Diff([]float64{1, 4, 9}) // [3 5]

Units: same as x, per sample

Equivalent to:

  • numpy.diff(x)
  • MATLAB diff(x)

func Envelope added in v0.6.0

func Envelope(x []float64, method EnvelopeMethod) (upper, lower []float64, err error)

Envelope returns the upper and lower envelopes of x: its mean plus and minus the envelope of x less its mean, measured by method. An empty x gives empty envelopes.

upper, lower, err := dsp.Envelope(x, dsp.EnvelopeAnalytic())

Units: same as x

Returns: ErrInvalidParameter for an EnvelopeRMS window below 1.

Equivalent to:

  • scipy.signal.envelope, which drops the Nyquist bin from the analytic envelope, and has no RMS method
  • MATLAB [upper, lower] = envelope(x), or envelope(x, n, 'rms')
Example
package main

import (
	"fmt"
	"log"

	"github.com/cxd309/tukey/dsp"
	"github.com/cxd309/tukey/waveform"
)

func main() {
	// a 50 Hz tone whose amplitude swings between 0.5 and 1.5 twice a second, sampled at 1 kHz for 1 s
	const fs = 1000.0
	t, err := waveform.Timebase(1000, fs)
	if err != nil {
		log.Fatal(err)
	}
	carrier, err := waveform.Tone(t, 50)
	if err != nil {
		log.Fatal(err)
	}
	swing, err := waveform.Tone(t, 2)
	if err != nil {
		log.Fatal(err)
	}
	x := make([]float64, len(t))
	for i := range x {
		x[i] = (1 + 0.5*swing[i]) * carrier[i]
	}

	upper, _, err := dsp.Envelope(x, dsp.EnvelopeAnalytic())
	if err != nil {
		log.Fatal(err)
	}
	for _, i := range []int{0, 125, 250} {
		fmt.Printf("t = %.3f s: %.2f\n", t[i], upper[i])
	}
}
Output:
t = 0.000 s: 1.50
t = 0.125 s: 1.00
t = 0.250 s: 0.50

func FIRWin added in v0.10.0

func FIRWin(window []float64, band Band, opts ...FIROption) (h []float64, err error)

FIRWin designs a linear-phase FIR filter for band by the window method, and returns its taps: the ideal response's impulse response, truncated to the window's length and multiplied by it. The window's shape sets the transition width and stopband attenuation, and its length, the number of taps, sets the sharpness. The taps are scaled so the response is exactly 1 at DC if the band passes it, at Nyquist for a highpass, and otherwise at the passband's centre, unless FIRNoScale. Any window is accepted, but only a symmetric one gives exactly linear phase, so build it with window's default symmetric form, not Periodic. The filter's delay is (len(window) - 1)/2 samples.

w, err := window.Hamming(101)
h, err := dsp.FIRWin(w, dsp.Lowpass(0.2))
y, err := dsp.Convolve(x, h, dsp.ConvolveSame())

Units:

  • window and h are dimensionless
  • band's edges are fractions of Nyquist

Returns:

  • ErrInvalidLength for an empty window, or an even length for a Highpass or Bandstop, as an even-length filter can't pass Nyquist.
  • ErrInvalidBand for the zero Band, an edge outside (0, 1), or a low edge not below the high.
  • ErrInvalidParameter for a NaN or infinite window tap.

Equivalent to:

  • scipy.signal.firwin(len(window), wn, window=name, pass_zero=btype), whose window is given by name
  • MATLAB fir1(len(window) - 1, wn, ftype, window)

func FillMissing added in v0.5.0

func FillMissing(x []float64, fill Fill) (y []float64)

FillMissing returns x with each NaN replaced as fill says. With FillLinear, fewer than two known samples leave x unchanged, as there's no line to draw.

y := dsp.FillMissing([]float64{1, math.NaN(), 3}, dsp.FillLinear()) // [1 2 3]

Units: same as x

Equivalent to:

  • SciPy has none
  • MATLAB fillmissing(x, 'linear'), or fillmissing(x, 'constant', value)

func FiltFilt

func FiltFilt(b, a, x []float64, opts ...FiltOption) (y []float64, err error)

FiltFilt applies the filter b/a to x twice, forward then backward, for zero phase: features stay where they are in the signal, and the magnitude response is squared, so a -3 dB edge becomes -6 dB. x is extended past each end, by PaddingOdd and SciPy's padding length 3·max(len(a), len(b)) unless the options say otherwise, and each pass starts from the filter's steady state scaled to its first sample, so neither end shows a startup transient. The filter must be stable, which isn't checked, same as SciPy and MATLAB.

f, err := dsp.Butter(2, dsp.Lowpass(0.3))
b, a, err := f.BA()
y, err := dsp.FiltFilt(b, a, x)

Units:

  • b and a are dimensionless
  • y is in x's unit

Returns:

  • ErrInvalidCoefficients for an empty b or a, an a[0] of 0, or a NaN or infinite coefficient.
  • ErrInvalidParameter for a negative PadLen.
  • ErrSignalTooShort for an x no longer than the padding length.
  • ErrNoSteadyState for a filter with a pole at DC, where Σ a = 0.

Equivalent to:

  • scipy.signal.filtfilt(b, a, x)
  • MATLAB filtfilt(b, a, x), with MATLABPadLen
Example
package main

import (
	"fmt"
	"log"
	"slices"

	"github.com/cxd309/tukey/dsp"
)

func main() {
	// a narrow pulse at sample 50
	x := make([]float64, 100)
	x[50] = 1

	f, err := dsp.Butter(2, dsp.Lowpass(0.1))
	if err != nil {
		log.Fatal(err)
	}
	b, a, err := f.BA()
	if err != nil {
		log.Fatal(err)
	}
	causal, err := dsp.Filter(b, a, x)
	if err != nil {
		log.Fatal(err)
	}
	zeroPhase, err := dsp.FiltFilt(b, a, x)
	if err != nil {
		log.Fatal(err)
	}

	// Filter delays the pulse, and FiltFilt smooths it but leaves it where it was
	fmt.Println("Filter peak at sample", peak(causal))
	fmt.Println("FiltFilt peak at sample", peak(zeroPhase))
}

// peak is the index of v's largest value.
func peak(v []float64) (index int) {
	index = slices.Index(v, slices.Max(v))
	return
}
Output:
Filter peak at sample 54
FiltFilt peak at sample 50

func Filter

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

Filter applies the filter b/a to x causally, in one direction, starting from rest:

a[0]·y[n] = Σ b[k]·x[n-k] - Σ a[k]·y[n-k], the second sum from k = 1

The output is delayed by the filter's phase, and FiltFilt gives zero phase instead. The filter must be stable, with every pole inside the unit circle. That isn't checked, same as SciPy and MATLAB, and an unstable filter's output grows without bound. As the order rises or the band narrows, b and a lose digits, and SOSFilter keeps them.

y, err := dsp.Filter([]float64{1, 1}, []float64{2}, x) // the mean of each sample and the one before

Units:

  • b and a are dimensionless
  • y is in x's unit

Returns: ErrInvalidCoefficients for an empty b or a, an a[0] of 0, or a NaN or infinite coefficient.

Equivalent to:

  • scipy.signal.lfilter(b, a, x)
  • MATLAB filter(b, a, x)

func FilterState added in v0.2.0

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

FilterState applies the filter b/a to x causally, starting from the state zi, and returns the final state zf too. Passing each block's zf as the next block's zi filters a long signal in blocks, exactly as filtering it in one go would. zi has max(len(a), len(b)) - 1 values, all 0 for rest, or FilterZi's scaled by the first sample to start without a transient.

zi := make([]float64, max(len(a), len(b))-1)
for _, block := range blocks {
	y, zi, err = dsp.FilterState(b, a, block, zi)
}

Units:

  • b and a are dimensionless
  • zi, zf and y are in x's unit

Returns:

  • ErrInvalidCoefficients for an empty b or a, an a[0] of 0, or a NaN or infinite coefficient.
  • ErrInvalidState for a zi of the wrong length, or one that isn't finite.

Equivalent to:

  • scipy.signal.lfilter(b, a, x, zi=zi)
  • MATLAB [y, zf] = filter(b, a, x, zi)

func FilterZi added in v0.2.0

func FilterZi(b, a []float64) (zi []float64, err error)

FilterZi returns the state the filter b/a settles into after a long unit step. Scaled by a signal's first sample, it starts FilterState without a startup transient:

zi, err := dsp.FilterZi(b, a)
for i := range zi {
	zi[i] *= x[0]
}
y, _, err := dsp.FilterState(b, a, x, zi)

Units: b, a and zi are dimensionless, zi per unit of step

Returns:

  • ErrInvalidCoefficients for an empty b or a, an a[0] of 0, or a NaN or infinite coefficient.
  • ErrNoSteadyState for a filter with a pole at DC, where Σ a = 0.

Equivalent to:

  • scipy.signal.lfilter_zi(b, a)
  • MATLAB has none, as filtfilt computes it internally

func Freqz added in v0.2.0

func Freqz(b, a []float64, n int) (w []float64, h []complex128, err error)

Freqz returns the frequency response of the filter b/a at n frequencies w, evenly spaced from 0 up to, but not including, Nyquist. h[k] is the complex gain at w[k], so |h[k]| is the magnitude, and its angle the phase. n = 0 gives empty slices, same as SciPy, where MATLAB's freqz errors.

w, h, err := dsp.Freqz(b, a, 512)
f, err := dsp.RadPerSampleToHz(w, fs)

Units:

  • b and a are dimensionless
  • w is in rad/sample, where π is Nyquist, and RadPerSampleToHz or RadPerSampleToNyquist converts it
  • h is dimensionless, a gain

Returns:

  • ErrInvalidCoefficients for an empty b or a, an a[0] of 0, or a NaN or infinite coefficient.
  • ErrInvalidLength for a negative n.

Equivalent to:

  • scipy.signal.freqz(b, a, worN=n)
  • MATLAB [h, w] = freqz(b, a, n), which returns h first

func Grad added in v0.9.0

func Grad(x []float64, dx float64) (g []float64, err error)

Grad returns the derivative of x, sampled every dx, estimated at each sample: central differences inside, (x[i+1] - x[i-1])/(2·dx), and one-sided differences at the ends. Where Diff gives the slope between samples, Grad gives it at each one, the same length as x.

v, err := dsp.Grad(position, 1/fs) // velocity, for position sampled at fs Hz

Units:

  • dx is the time between samples, e.g. 1/fs in seconds
  • g is in x's unit per unit of dx

Returns:

  • ErrSignalTooShort for fewer than 2 samples.
  • ErrInvalidParameter for a dx that isn't positive and finite.

Equivalent to:

  • numpy.gradient(x, dx)
  • MATLAB gradient(x, dx)

func GroupDelay added in v0.10.0

func GroupDelay(b, a []float64, n int) (w, delay []float64, err error)

GroupDelay returns the group delay of the filter b/a at n frequencies w, evenly spaced from 0 up to, but not including, Nyquist, same as Freqz's: how long each frequency's envelope is delayed by, -dφ/dω. It's computed from the coefficients exactly, to rounding, not by differentiating the phase. A symmetric or antisymmetric b or a, such as a linear-phase FIR or a Butterworth numerator, contributes exactly half its order. Where b or a is ill-conditioned, its roots crowded against the unit circle, the point is evaluated in big.Float. At a zero on the unit circle, where the phase jumps by π, the delay is its limit from either side. A high-order filter's (b, a) is ill-conditioned, and SOSGroupDelay on its sections is faster and gives the same answer.

w, delay, err := dsp.GroupDelay(b, a, 512)

Units:

  • b and a are dimensionless
  • w is in rad/sample, where π is Nyquist, and RadPerSampleToHz or RadPerSampleToNyquist converts it
  • delay is in samples

Returns:

  • ErrInvalidCoefficients for an empty b or a, an a[0] of 0, or a NaN or infinite coefficient.
  • ErrInvalidLength for a negative n.

Equivalent to:

  • scipy.signal.group_delay((b, a), n), which is 0 at a zero on the unit circle, and loses digits near one, 3% off for butter(8, 0.01)
  • MATLAB [delay, w] = grpdelay(b, a, n), which also gives the limit

func Hilbert added in v0.6.0

func Hilbert(x []float64) (analytic []complex128)

Hilbert returns the analytic signal of x, x + i·H(x), where H(x), the Hilbert transform, is x with every frequency's phase shifted by -90°. Its magnitude is x's envelope, and its angle x's instantaneous phase. It works in the frequency domain, doubling the positive frequencies and zeroing the negative ones, so it treats x as one period of a periodic signal. An empty x gives an empty result, and nothing else can fail, so there's no error.

analytic := dsp.Hilbert(x)
phase := cmplx.Phase(analytic[k])

Units: same as x

Equivalent to:

  • scipy.signal.hilbert(x)
  • MATLAB hilbert(x)

func HzToNyquist added in v1.0.0

func HzToNyquist[T float64 | []float64](f T, fs float64) (wn T, err error)

HzToNyquist returns f in Hz as a fraction of Nyquist, f/(fs/2), the unit of a Band's edges. f may be a float64 or a []float64:

wn, err := dsp.HzToNyquist(50.0, 1000) // 0.1
f, err := dsp.Butter(4, dsp.Lowpass(wn))

Returns: ErrInvalidParameter for an fs that isn't positive and finite.

Units:

  • f and fs are in Hz
  • wn is a fraction of Nyquist

Equivalent to:

  • the fs argument of scipy.signal.butter and the other designs
  • MATLAB f/(fs/2)
Example
package main

import (
	"fmt"
	"log"
	"math"
	"math/cmplx"

	"github.com/cxd309/tukey/dsp"
)

func main() {
	// a 4th-order lowpass at 100 Hz, for a signal sampled at 1 kHz
	const fs = 1000.0
	wn, err := dsp.HzToNyquist(100.0, fs)
	if err != nil {
		log.Fatal(err)
	}
	f, err := dsp.Butter(4, dsp.Lowpass(wn))
	if err != nil {
		log.Fatal(err)
	}
	sos, err := f.SOS()
	if err != nil {
		log.Fatal(err)
	}

	// its response, labelled in Hz, is -3 dB at the cutoff
	w, h, err := dsp.SOSFreqz(sos, 500)
	if err != nil {
		log.Fatal(err)
	}
	hz, err := dsp.RadPerSampleToHz(w, fs)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("wn = %g\n", wn)
	fmt.Printf("%.0f Hz: %.2f dB\n", hz[100], 20*math.Log10(cmplx.Abs(h[100])))
}
Output:
wn = 0.2
100 Hz: -3.01 dB

func HzToRadPerSample added in v1.0.0

func HzToRadPerSample[T float64 | []float64](f T, fs float64) (w T, err error)

HzToRadPerSample returns f in Hz in radians per sample, 2π·f/fs. f may be a float64 or a []float64.

Units:

  • f and fs are in Hz
  • w is in rad/sample

Returns: ErrInvalidParameter for an fs that isn't positive and finite.

Equivalent to: MATLAB 2*pi*f/fs, as SciPy has none

func Interp1 added in v0.5.0

func Interp1(x, y, xi []float64) (yi []float64, err error)

Interp1 returns y, sampled at the strictly increasing points x, linearly interpolated at each point of xi. A point of xi outside [x[0], x[len(x)-1]], or a NaN one, gives NaN. Next to an infinite y the line is that infinity, its limit.

yi, err := dsp.Interp1([]float64{0, 1, 2}, []float64{0, 10, 0}, []float64{0.5, 1.5}) // [5 5]

Units:

  • x and xi share a unit
  • yi is in y's unit

Returns:

  • ErrInvalidLength for an x and y of different lengths, or shorter than 2.
  • ErrInvalidSamplePoints for an x that isn't strictly increasing, including one with a NaN.

Equivalent to:

  • scipy.interpolate.interp1d(x, y, bounds_error=False)(xi), where numpy.interp repeats the end values outside x's range instead
  • MATLAB interp1(x, y, xi)

func Mean added in v0.9.0

func Mean(x []float64) (m float64, err error)

Mean returns the arithmetic mean of x, its Sum divided by its length, summed with compensation, same as Sum.

m, err := dsp.Mean(x)

Units: same as x

Returns: ErrSignalTooShort for an empty x, which has no mean.

Equivalent to:

  • numpy.mean(x)
  • MATLAB mean(x), which gives NaN for an empty x

func MedFilt added in v0.10.0

func MedFilt(x []float64, n int, opts ...MedFiltOption) (y []float64, err error)

MedFilt replaces each sample of x with the median of the n samples centred on it, which removes spikes without blurring steps. n must be odd. A window holding a NaN gives NaN, and an infinite sample is outvoted, as any outlier is. A window with an even count, which only MedFiltTruncate gives near the ends, takes the midpoint of its two middle values, rounded once, so y is exact. It keeps the window sorted as it slides, O(n) per sample.

y, err := dsp.MedFilt(x, 5)

Units:

  • n is a number of samples
  • y is in x's unit

Returns: ErrInvalidLength for an n that isn't odd and positive.

Equivalent to:

  • scipy.signal.medfilt(x, n), with MedFiltZeroPad, except at a NaN, where its result depends on how NaN sorts
  • MATLAB medfilt1(x, n, 'truncate'), or medfilt1(x, n) with MedFiltZeroPad

func NyquistToHz added in v1.0.0

func NyquistToHz[T float64 | []float64](wn T, fs float64) (f T, err error)

NyquistToHz returns wn, a fraction of Nyquist, in Hz, wn·fs/2. wn may be a float64 or a []float64.

Units:

  • wn is a fraction of Nyquist
  • fs and f are in Hz

Returns: ErrInvalidParameter for an fs that isn't positive and finite.

Equivalent to: MATLAB wn*fs/2, as SciPy has none

func NyquistToRadPerSample added in v1.0.0

func NyquistToRadPerSample[T float64 | []float64](wn T) (w T)

NyquistToRadPerSample returns wn, a fraction of Nyquist, in radians per sample, wn·π. wn may be a float64 or a []float64, and it can't fail.

Units:

  • wn is a fraction of Nyquist
  • w is in rad/sample

Equivalent to: MATLAB wn*pi, as SciPy has none

func Percentile added in v0.9.0

func Percentile(x []float64, p float64, opts ...PercentileOption) (value float64, err error)

Percentile returns the value below which p percent of x falls, for p from 0 to 100, interpolating between the sorted samples, by PercentileLinear unless PercentileHazen is given. Any NaN in x gives NaN, as a missing sample leaves the percentile unknown. It sorts a copy, so x keeps its order.

median, err := dsp.Percentile(x, 50)

Units:

  • p is a percentage
  • value is in x's unit

Returns:

  • ErrSignalTooShort for an empty x.
  • ErrInvalidParameter for a p outside 0 to 100.

Equivalent to:

  • numpy.percentile(x, p)
  • MATLAB prctile(x, p), with PercentileHazen, except that prctile ignores NaN
Example
package main

import (
	"fmt"
	"log"

	"github.com/cxd309/tukey/dsp"
)

func main() {
	x := []float64{12, 3, 7, 1, 9, 15, 4, 8, 2, 10}

	median, err := dsp.Percentile(x, 50)
	if err != nil {
		log.Fatal(err)
	}
	upper, err := dsp.Percentile(x, 75)
	if err != nil {
		log.Fatal(err)
	}
	// MATLAB's prctile places a percentile differently between the sorted samples
	upperHazen, err := dsp.Percentile(x, 75, dsp.PercentileHazen())
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("median:", median)
	fmt.Println("75th:", upper)
	fmt.Println("75th, same as MATLAB:", upperHazen)
}
Output:
median: 7.5
75th: 9.75
75th, same as MATLAB: 10

func RMS added in v0.5.0

func RMS(x []float64) (rms float64, err error)

RMS returns the root mean square of x, √(mean(x²)), its squares summed with compensation.

rms, err := dsp.RMS(x)

Units: same as x

Returns: ErrSignalTooShort for an empty x, which has no RMS.

Equivalent to:

  • numpy.sqrt(numpy.mean(x**2)), as SciPy has none
  • MATLAB rms(x), which gives NaN for an empty x

func RadPerSampleToHz added in v1.0.0

func RadPerSampleToHz[T float64 | []float64](w T, fs float64) (f T, err error)

RadPerSampleToHz returns w in radians per sample in Hz, w·fs/(2π), e.g. to label Freqz's response in Hz. w may be a float64 or a []float64:

w, h, err := dsp.Freqz(b, a, 512)
f, err := dsp.RadPerSampleToHz(w, fs)

Units:

  • w is in rad/sample
  • fs and f are in Hz

Returns: ErrInvalidParameter for an fs that isn't positive and finite.

Equivalent to:

  • scipy.signal.freqz(b, a, fs=fs)'s w
  • MATLAB freqz(b, a, n, fs)'s w

func RadPerSampleToNyquist added in v1.0.0

func RadPerSampleToNyquist[T float64 | []float64](w T) (wn T)

RadPerSampleToNyquist returns w in radians per sample as a fraction of Nyquist, w/π, e.g. to compare Freqz's response with a Band's edges. w may be a float64 or a []float64, and it can't fail.

Units:

  • w is in rad/sample
  • wn is a fraction of Nyquist

Equivalent to:

  • scipy.signal.freqz(b, a, fs=2)'s w
  • MATLAB w/pi

func SOSFiltFilt added in v0.2.0

func SOSFiltFilt(sos SOS, x []float64, opts ...FiltOption) (y []float64, err error)

SOSFiltFilt applies the filter sos to x twice, forward then backward, for zero phase, staying accurate at high orders and narrow bands. The magnitude response is squared, so a -3 dB edge becomes -6 dB. x is extended past each end, by PaddingOdd and SciPy's padding length 3·ntaps unless the options say otherwise, where ntaps is 2·len(sos) + 1, less 1 for each first-order section, whose b2 and a2 are both 0. Each pass starts from the filter's steady state scaled to its first sample, so neither end shows a startup transient. By default the whole cascade is filtered forward then backward, same as SciPy, and with BySection each section is in turn, same as MATLAB:

y, err := dsp.SOSFiltFilt(sos, x, dsp.BySection(), dsp.MATLABPadLen()) // same as MATLAB filtfilt(sos, 1, x)

Units:

  • sos is dimensionless
  • y is in x's unit

Returns:

  • ErrInvalidSOS for no sections, a section whose a0 isn't 1, or a NaN or infinite coefficient.
  • ErrInvalidParameter for a negative PadLen.
  • ErrSignalTooShort for an x no longer than the padding length.
  • ErrNoSteadyState for a filter with a pole at DC, where Σ a = 0.

Equivalent to:

  • scipy.signal.sosfiltfilt(sos, x)
  • MATLAB filtfilt(sos, g, x), with BySection and MATLABPadLen, and g folded into the first section

func SOSFilter added in v0.2.0

func SOSFilter(sos SOS, x []float64) (y []float64, err error)

SOSFilter applies the filter sos to x causally, section by section, starting from rest. It stays accurate at high orders and narrow bands, where Filter's (b, a) form loses digits. The filter must be stable, which isn't checked, same as SciPy and MATLAB.

f, err := dsp.Butter(8, dsp.Lowpass(0.1))
sos, err := f.SOS()
y, err := dsp.SOSFilter(sos, x)

Units:

  • sos is dimensionless
  • y is in x's unit

Returns: ErrInvalidSOS for no sections, a section whose a0 isn't 1, or a NaN or infinite coefficient.

Equivalent to:

  • scipy.signal.sosfilt(sos, x)
  • MATLAB sosfilt(sos, x)

func SOSFilterState added in v0.2.0

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

SOSFilterState applies the filter sos to x causally, section by section, starting from the state zi, one pair per section, and returns the final state zf too. Passing each block's zf as the next block's zi filters a long signal in blocks, exactly as filtering it in one go would.

zi := make([][2]float64, len(sos))
for _, block := range blocks {
	y, zi, err = dsp.SOSFilterState(sos, block, zi)
}

Units:

  • sos is dimensionless
  • zi, zf and y are in x's unit

Returns:

  • ErrInvalidSOS for no sections, a section whose a0 isn't 1, or a NaN or infinite coefficient.
  • ErrInvalidState for a zi without one pair per section, or one that isn't finite.

Equivalent to:

  • scipy.signal.sosfilt(sos, x, zi=zi)
  • MATLAB has none, as its sosfilt takes no state

func SOSFilterZi added in v0.2.0

func SOSFilterZi(sos SOS) (zi [][2]float64, err error)

SOSFilterZi returns the state each section of sos settles into after a long unit step. Scaled by a signal's first sample, it starts SOSFilterState without a startup transient.

Units: sos and zi are dimensionless, zi per unit of step

Returns:

  • ErrInvalidSOS for no sections, a section whose a0 isn't 1, or a NaN or infinite coefficient.
  • ErrNoSteadyState for a section with a pole at DC.

Equivalent to:

  • scipy.signal.sosfilt_zi(sos)
  • MATLAB has none

func SOSFreqz added in v0.2.0

func SOSFreqz(sos SOS, n int) (w []float64, h []complex128, err error)

SOSFreqz returns the frequency response of the filter sos at n frequencies w, evenly spaced from 0 up to, but not including, Nyquist: the product of each section's response, which stays accurate where a high order's (b, a) doesn't. n = 0 gives empty slices.

w, h, err := dsp.SOSFreqz(sos, 512)

Units:

  • sos is dimensionless
  • w is in rad/sample, where π is Nyquist, and RadPerSampleToHz or RadPerSampleToNyquist converts it
  • h is dimensionless, a gain

Returns:

  • ErrInvalidSOS for no sections, a section whose a0 isn't 1, or a NaN or infinite coefficient.
  • ErrInvalidLength for a negative n.

Equivalent to:

  • scipy.signal.freqz_sos(sos, worN=n), called sosfreqz before SciPy 1.15
  • MATLAB [h, w] = freqz(sos, n), which returns h first

func SOSGroupDelay added in v0.10.0

func SOSGroupDelay(sos SOS, n int) (w, delay []float64, err error)

SOSGroupDelay returns the group delay of the filter sos at n frequencies w, evenly spaced from 0 up to, but not including, Nyquist, same as SOSFreqz's. It's the sum of each section's delay, computed exactly as GroupDelay's, which is better conditioned than the delay of the sections' product.

w, delay, err := dsp.SOSGroupDelay(sos, 512)

Units:

  • sos is dimensionless
  • w is in rad/sample, where π is Nyquist, and RadPerSampleToHz or RadPerSampleToNyquist converts it
  • delay is in samples

Returns:

  • ErrInvalidSOS for no sections, a section whose a0 isn't 1, or a NaN or infinite coefficient.
  • ErrInvalidLength for a negative n.

Equivalent to:

  • scipy.signal.group_delay of the sections' product, as SciPy has no sections form
  • MATLAB [delay, w] = grpdelay(sos, n)

func SavGolFilter added in v0.10.0

func SavGolFilter(x []float64, n, polyOrder int, opts ...SavGolOption) (y []float64, err error)

SavGolFilter smooths x with a Savitzky-Golay filter: each sample is replaced by a polynomial of degree polyOrder, fitted by least squares to the n samples centred on it, and evaluated there. It smooths noise while keeping the height and width of peaks, which a moving average flattens. Within n/2 of the ends, one polynomial is fitted to the first or last n samples and evaluated at each. A window holding a NaN gives NaN.

The fit is in polynomials orthogonal over the window's samples, built by Arnoldi iteration, so it stays accurate for long windows and high degrees, up to n - 1, where the fit passes through every sample. Each output is taken relative to its own sample, so a constant is kept exactly, and a small signal on a large offset keeps its digits.

y, err := dsp.SavGolFilter(x, 21, 3) // noise smoothed, peaks kept

Units:

  • n is a number of samples
  • polyOrder is the polynomial's degree
  • y is in x's unit, or with SavGolDeriv in x's unit per unit of dx to the derivative's order

Returns:

  • ErrInvalidLength for an n that isn't odd and positive.
  • ErrInvalidParameter for a polyOrder outside 0 to n - 1, or a SavGolDeriv with a negative order or a dx that isn't positive and finite.
  • ErrSignalTooShort for an x shorter than n.

Equivalent to:

  • scipy.signal.savgol_filter(x, n, polyOrder), and with SavGolDeriv deriv=order and delta=dx
  • MATLAB sgolayfilt(x, polyOrder, n), without SavGolDeriv

func Sum added in v0.9.0

func Sum(x []float64) (sum float64)

Sum returns the total of x, or 0 for an empty x. It's summed with compensation, so small values beside large ones keep their low bits, and it's closer to the exact total than a plain or pairwise sum: 1e8, then 20,000 values of 0.001, then -1e8, sum to exactly 20, where MATLAB gives 20.00001.

total := dsp.Sum(x)

Units: same as x

Equivalent to:

  • numpy.sum(x), which sums pairwise
  • MATLAB sum(x), which sums plainly

func Trapz added in v0.9.0

func Trapz(y []float64, dx float64) (integral float64, err error)

Trapz returns the trapezoidal integral of y, sampled every dx, over the whole signal, summed with compensation:

dx·(y[0]/2 + y[1] + ... + y[n-2] + y[n-1]/2)

Fewer than 2 samples have no interval to integrate over, so give 0.

distance, err := dsp.Trapz(speed, 1/fs)

Units:

  • dx is the time between samples, e.g. 1/fs in seconds
  • integral is in y's unit times dx's

Returns: ErrInvalidParameter for a dx that isn't positive and finite.

Equivalent to:

  • scipy.integrate.trapezoid(y, dx=dx), and numpy.trapezoid, called trapz before NumPy 2
  • MATLAB trapz(dx, y)

Types

type Band

type Band struct {
	// contains filtered or unexported fields
}

Band is the frequency response a filter design targets: which frequencies it passes, and where its edges are. Build one with Lowpass, Highpass, Bandpass or Bandstop. Its zero value is no band, which every design rejects with ErrInvalidBand.

Its edges are fractions of Nyquist, so they lie in (0, 1). HzToNyquist converts from Hz:

wn, err := dsp.HzToNyquist(100.0, fs)
f, err := dsp.Butter(4, dsp.Lowpass(wn))

func Bandpass

func Bandpass(low, high float64) (band Band)

Bandpass is the band between low and high. A design checks the edges, so Bandpass itself can't fail.

Units: low and high are fractions of Nyquist

Equivalent to:

  • SciPy's btype='bandpass', with Wn = [low, high]
  • MATLAB's 'bandpass', with Wn = [low high]

func Bandstop

func Bandstop(low, high float64) (band Band)

Bandstop is everything but the band between low and high. A design checks the edges, so Bandstop itself can't fail.

Units: low and high are fractions of Nyquist

Equivalent to:

  • SciPy's btype='bandstop', with Wn = [low, high]
  • MATLAB's 'stop', with Wn = [low high]

func ButterOrd added in v0.10.0

func ButterOrd(pass, stop Band, rippleDB, attenuationDB float64, opts ...OrderOption) (order int, wn Band, err error)

ButterOrd returns the lowest order of Butter filter that meets a specification, and the band to design it for: at most rippleDB of loss up to the passband's edges, and at least attenuationDB from the stopband's. pass and stop are the same type of band, with stop's edges in the stopband. The order usually has margin to spare. By default the passband edge is met exactly and the stopband gets the margin, and MatchStopband swaps them. A bandpass's tighter stopband edge is the one met. A bandstop's passband edges are first moved inward until the stopband's edges are equally hard to meet, which gives the lowest order there is.

order, wn, err := dsp.ButterOrd(dsp.Lowpass(0.2), dsp.Lowpass(0.3), 1, 40)
f, err := dsp.Butter(order, wn)

Units:

  • pass's and stop's edges, and wn's, are fractions of Nyquist
  • rippleDB and attenuationDB are in dB, positive
  • order is the prototype's order

Returns:

  • ErrInvalidBand for the zero Band, an edge outside (0, 1), or a low edge not below the high, for pass and stop of different types, for stop's edges not beyond pass's, or for edges too close together to meet.
  • ErrInvalidParameter for a rippleDB or attenuationDB that isn't positive and finite, or an attenuationDB that isn't greater than rippleDB.

Equivalent to:

  • scipy.signal.buttord(wp, ws, rippleDB, attenuationDB), whose bandstop edges come from a numerical minimiser, to about 1e-5
  • MATLAB buttord(wp, ws, rippleDB, attenuationDB), with MatchStopband, and the same minimiser for a bandstop

func Cheby1Ord added in v0.10.0

func Cheby1Ord(pass, stop Band, rippleDB, attenuationDB float64, opts ...OrderOption) (order int, wn Band, err error)

Cheby1Ord returns the lowest order of Cheby1 filter that meets a specification, and the band to design it for: at most rippleDB of loss up to the passband's edges, and at least attenuationDB from the stopband's. pass and stop are the same type of band, with stop's edges in the stopband. By default the passband edge is met exactly and the stopband gets the margin, and MatchStopband swaps them. A bandpass's tighter stopband edge is the one met, and a bandstop's passband edges are first moved inward until its stopband's edges are equally hard to meet.

order, wn, err := dsp.Cheby1Ord(dsp.Lowpass(0.2), dsp.Lowpass(0.3), 1, 40)
f, err := dsp.Cheby1(order, 1, wn)

Units:

  • pass's and stop's edges, and wn's, are fractions of Nyquist
  • rippleDB and attenuationDB are in dB, positive
  • order is the prototype's order

Returns:

  • ErrInvalidBand for the zero Band, an edge outside (0, 1), or a low edge not below the high, for pass and stop of different types, for stop's edges not beyond pass's, or for edges too close together to meet.
  • ErrInvalidParameter for a rippleDB or attenuationDB that isn't positive and finite, or an attenuationDB that isn't greater than rippleDB.

Equivalent to:

  • scipy.signal.cheb1ord(wp, ws, rippleDB, attenuationDB), whose bandstop edges come from a numerical minimiser, to about 1e-5
  • MATLAB cheb1ord(wp, ws, rippleDB, attenuationDB), except for a bandstop, whose order MATLAB selects for the moved passband edges but whose edges it returns unmoved, which can fall short of attenuationDB

func Cheby2Ord added in v0.10.0

func Cheby2Ord(pass, stop Band, rippleDB, attenuationDB float64, opts ...OrderOption) (order int, wn Band, err error)

Cheby2Ord returns the lowest order of Cheby2 filter that meets a specification, and the band to design it for: at most rippleDB of loss up to the passband's edges, and at least attenuationDB from the stopband's. pass and stop are the same type of band, with stop's edges in the stopband. Cheby2's band edges are its stopband's, so by default those returned lie inside the stopband, where -attenuationDB is first reached, and MatchStopband puts them at stop's edges. A bandpass's tighter stopband edge is the one met, and a bandstop's passband edges are first moved inward until its stopband's edges are equally hard to meet.

order, wn, err := dsp.Cheby2Ord(dsp.Lowpass(0.2), dsp.Lowpass(0.3), 1, 40)
f, err := dsp.Cheby2(order, 40, wn)

Units:

  • pass's and stop's edges, and wn's, are fractions of Nyquist
  • rippleDB and attenuationDB are in dB, positive
  • order is the prototype's order

Returns:

  • ErrInvalidBand for the zero Band, an edge outside (0, 1), or a low edge not below the high, for pass and stop of different types, for stop's edges not beyond pass's, or for edges too close together to meet.
  • ErrInvalidParameter for a rippleDB or attenuationDB that isn't positive and finite, or an attenuationDB that isn't greater than rippleDB.

Equivalent to:

  • scipy.signal.cheb2ord(wp, ws, rippleDB, attenuationDB), whose bandstop edges come from a numerical minimiser, to about 1e-5
  • MATLAB cheb2ord(wp, ws, rippleDB, attenuationDB), with MatchStopband, except for a bandpass, where MATLAB meets both stopband edges exactly, and Cheby2Ord only the tighter

func EllipOrd added in v0.10.0

func EllipOrd(pass, stop Band, rippleDB, attenuationDB float64, opts ...OrderOption) (order int, wn Band, err error)

EllipOrd returns the lowest order of Ellip filter that meets a specification, and the band to design it for: at most rippleDB of loss up to the passband's edges, and at least attenuationDB from the stopband's. pass and stop are the same type of band, with stop's edges in the stopband. By default the passband edge is met exactly and the stopband gets the margin, and MatchStopband swaps them. A bandpass's tighter stopband edge is the one met, and a bandstop's passband edges are first moved inward until its stopband's edges are equally hard to meet.

order, wn, err := dsp.EllipOrd(dsp.Lowpass(0.2), dsp.Lowpass(0.3), 1, 40)
f, err := dsp.Ellip(order, 1, 40, wn)

Units:

  • pass's and stop's edges, and wn's, are fractions of Nyquist
  • rippleDB and attenuationDB are in dB, positive
  • order is the prototype's order

Returns:

  • ErrInvalidBand for the zero Band, an edge outside (0, 1), or a low edge not below the high, for pass and stop of different types, for stop's edges not beyond pass's, or for edges too close together to meet.
  • ErrInvalidParameter for a rippleDB or attenuationDB that isn't positive and finite, or an attenuationDB that isn't greater than rippleDB.

Equivalent to:

  • scipy.signal.ellipord(wp, ws, rippleDB, attenuationDB), whose bandstop edges come from a numerical minimiser, to about 1e-5
  • MATLAB ellipord(wp, ws, rippleDB, attenuationDB), except for a bandstop, whose passband edges MATLAB returns unmoved

func Highpass

func Highpass(cutoff float64) (band Band)

Highpass is the band above cutoff. A design checks cutoff, so Highpass itself can't fail.

Units: cutoff is a fraction of Nyquist

Equivalent to:

  • SciPy's btype='highpass', with Wn = cutoff
  • MATLAB's 'high', with Wn = cutoff

func Lowpass

func Lowpass(cutoff float64) (band Band)

Lowpass is the band below cutoff. A design checks cutoff, so Lowpass itself can't fail.

Units: cutoff is a fraction of Nyquist

Equivalent to:

  • SciPy's btype='lowpass', with Wn = cutoff
  • MATLAB's default ftype, with Wn = cutoff

func (Band) Edges added in v0.10.0

func (band Band) Edges() (edges []float64)

Edges returns a copy of the band's edges: the cutoff for a lowpass or highpass, and low and high for a bandpass or bandstop. The zero Band has none.

Units: the edges are fractions of Nyquist

func (Band) String

func (band Band) String() (s string)

String formats the band the way it was built, e.g. "Bandpass(0.2, 0.5)", or "Band{}" for the zero Band.

type BesselOption added in v0.10.0

type BesselOption func(*besselConfig)

BesselOption configures Bessel: BesselNormMagnitude, BesselNormPhase or BesselNormDelay.

func BesselNormDelay added in v0.10.0

func BesselNormDelay() BesselOption

BesselNormDelay gives the prototype a group delay of 1 s at DC, so the digital filter's delay at DC is 1/(2·tan(π·wn/2)) samples, about 1/(π·wn) for a low edge wn.

Equivalent to:

  • scipy.signal.bessel's norm='delay'
  • MATLAB has none

func BesselNormMagnitude added in v0.10.0

func BesselNormMagnitude() BesselOption

BesselNormMagnitude puts the band edge at the -3 dB point, same as Butter. It's the default, where SciPy's is BesselNormPhase.

Equivalent to:

  • scipy.signal.bessel's norm='mag'
  • MATLAB has none

func BesselNormPhase added in v0.10.0

func BesselNormPhase() BesselOption

BesselNormPhase scales the prototype so it falls as 1/ω^N at high frequency, same as a Butterworth filter of the same edge, and its phase is near -N·π/4 at the edge.

Equivalent to:

  • scipy.signal.bessel's norm='phase', its default
  • MATLAB besself

type ConvolveOption added in v0.10.0

type ConvolveOption func(*convolveConfig)

ConvolveOption configures Convolve and Correlate: ConvolveSame or ConvolveValid for the output, and ConvolveAuto, ConvolveDirect or ConvolveFFT for the method.

func ConvolveAuto added in v0.10.0

func ConvolveAuto() ConvolveOption

ConvolveAuto chooses ConvolveDirect or ConvolveFFT by which is faster for the inputs' lengths, which is ConvolveFFT for all but the shortest inputs. If either input has a NaN or infinite sample it uses ConvolveDirect, so that sample affects only the outputs it's summed into. It's the default. For inputs with a high dynamic range, use ConvolveDirect.

Equivalent to:

  • scipy.signal.convolve's method='auto', its default
  • MATLAB has none, as conv always sums directly

func ConvolveDirect added in v0.10.0

func ConvolveDirect() ConvolveOption

ConvolveDirect sums every product directly, each kept exactly and summed with compensation, so each output is within about 1 ULP of its exact value, however small it is beside the others. It takes O(len(a)·len(v)).

Equivalent to:

  • scipy.signal.convolve's method='direct', which sums plainly
  • MATLAB conv, which sums plainly

func ConvolveFFT added in v0.10.0

func ConvolveFFT() ConvolveOption

ConvolveFFT multiplies the inputs' spectra, in O(n log n). Its error is relative to the largest output, so outputs much smaller than that lose relative accuracy, e.g. 1e-3 noise beside 1e8 spikes keeps only a few digits. A NaN or infinite sample spreads to every output.

Equivalent to:

  • scipy.signal.convolve's method='fft', and scipy.signal.fftconvolve
  • MATLAB has none

func ConvolveSame added in v0.10.0

func ConvolveSame() ConvolveOption

ConvolveSame returns the central len(a) outputs of the full result, from (len(v)-1)/2 rounded down.

Equivalent to:

  • scipy.signal.convolve's mode='same', and numpy.convolve's
  • MATLAB conv's 'same', except that it starts one output later for an even len(v)

func ConvolveValid added in v0.10.0

func ConvolveValid() ConvolveOption

ConvolveValid returns only the outputs where the shorter input lies wholly inside the longer, |len(a) - len(v)| + 1 of them. Convolution is commutative, so it doesn't matter which input is longer.

Equivalent to:

  • scipy.signal.convolve's mode='valid'
  • MATLAB conv's 'valid', except that it's empty when v is longer than a

type Correlation added in v0.10.0

type Correlation struct {
	Values []float64 // in a's unit times v's
	Lags   []int     // in samples, a positive lag meaning a is later than v
}

Correlation is a cross-correlation, where Values[i] is at lag Lags[i].

func Correlate added in v0.10.0

func Correlate(a, v []float64, opts ...ConvolveOption) (c Correlation, err error)

Correlate returns the cross-correlation of a and v, Σ a[n+k]·v[n] at each lag k: by default every lag at which they overlap, -(len(v)-1) to len(a)-1, or the part ConvolveSame or ConvolveValid selects. If a is v delayed by d samples, the largest value is at lag d. It sums directly or by FFT, whichever is faster, unless ConvolveDirect or ConvolveFFT says.

corr, err := dsp.Correlate(received, sent)
delay := corr.Lags[slices.Index(corr.Values, slices.Max(corr.Values))]

Units:

  • Values is in a's unit times v's
  • Lags are in samples

Returns: ErrSignalTooShort for an empty a or v.

Equivalent to:

  • scipy.signal.correlate(a, v, mode), with Lags from scipy.signal.correlation_lags, except that correlation_lags labels mode='same' one lag high for an odd len(a) and an even len(v)
  • MATLAB [r, lags] = xcorr(a, v) at the lags where a and v overlap, as xcorr pads the shorter with zeros and gives every lag up to the longer's length

type DetrendMode added in v0.5.0

type DetrendMode struct {
	// contains filtered or unexported fields
}

DetrendMode is what Detrend removes, built by DetrendLinear or DetrendConstant. Its zero value is DetrendLinear.

func DetrendConstant added in v0.5.0

func DetrendConstant() (mode DetrendMode)

DetrendConstant removes the mean.

Equivalent to:

  • scipy.signal.detrend's type='constant'
  • MATLAB detrend(x, 0)

func DetrendLinear added in v0.5.0

func DetrendLinear() (mode DetrendMode)

DetrendLinear removes the least-squares straight line. It's DetrendMode's zero value.

Equivalent to:

  • scipy.signal.detrend's type='linear', its default
  • MATLAB detrend(x), or detrend(x, 1)

type EnvelopeMethod added in v0.6.0

type EnvelopeMethod struct {
	// contains filtered or unexported fields
}

EnvelopeMethod is how Envelope measures a signal's envelope: EnvelopeAnalytic, the zero EnvelopeMethod, or EnvelopeRMS.

func EnvelopeAnalytic added in v0.6.0

func EnvelopeAnalytic() (method EnvelopeMethod)

EnvelopeAnalytic is the magnitude of the analytic signal, from Hilbert. It follows each oscillation's peaks closely, so suits a signal with one main frequency.

Equivalent to:

  • scipy.signal.envelope, except at Nyquist
  • MATLAB envelope(x)

func EnvelopeRMS added in v0.6.0

func EnvelopeRMS(n int) (method EnvelopeMethod)

EnvelopeRMS is the moving RMS over a window of n samples centred on each sample. For an even n the extra sample is after, so n = 10 covers k-4 to k+5. The window shrinks where it would pass either end of the signal.

Units: n is a number of samples

Equivalent to:

  • SciPy has none
  • MATLAB envelope(x, n, 'rms')

type FIROption added in v0.10.0

type FIROption func(*firConfig)

FIROption configures FIRWin: FIRNoScale.

func FIRNoScale added in v1.0.0

func FIRNoScale() FIROption

FIRNoScale leaves FIRWin's taps unscaled, the windowed ideal response as it is.

Equivalent to:

  • scipy.signal.firwin's scale=False
  • MATLAB fir1's 'noscale'

type Fill added in v0.5.0

type Fill struct {
	// contains filtered or unexported fields
}

Fill is how FillMissing replaces missing samples, which are NaN: FillLinear, the zero Fill, or FillConstant.

func FillConstant added in v0.5.0

func FillConstant(value float64) (fill Fill)

FillConstant fills every missing sample with value. FillConstant(math.NaN()) leaves x as it is.

Units: value is in x's unit

Equivalent to:

  • SciPy has none
  • MATLAB fillmissing(x, 'constant', value)

func FillLinear added in v0.5.0

func FillLinear() (fill Fill)

FillLinear fills each gap by linear interpolation between the known samples either side, and each end by extending the line through its nearest two. It's the zero Fill.

Equivalent to:

  • SciPy has none
  • MATLAB fillmissing(x, 'linear')

type FiltOption

type FiltOption func(*filtConfig)

FiltOption configures FiltFilt's and SOSFiltFilt's edge handling: PadLen, MATLABPadLen, BySection, and the paddings PaddingOdd, PaddingEven, PaddingConstant and PaddingNone.

func BySection added in v0.11.0

func BySection() (option FiltOption)

BySection makes SOSFiltFilt filter each section forward and backward in turn, each padded by the whole filter's padding length, rather than the whole cascade forward then backward. The two differ by their edge transients, which for a slow filter reach well into the signal. A FiltFilt filter is one section, so BySection doesn't change it.

Equivalent to:

  • SciPy has none, as sosfiltfilt filters the whole cascade
  • MATLAB filtfilt(sos, g, x), with MATLABPadLen

func MATLABPadLen

func MATLABPadLen() (option FiltOption)

MATLABPadLen uses MATLAB's padding length, 3 times the filter's order and at least 1, in place of SciPy's. The order counts b and a up to their last nonzero coefficients, and for SOSFiltFilt each section's, summed. So an odd-order Butterworth's first section, its real pole with two zeros, is order 2. Both forms are checked against MATLAB R2025a.

Equivalent to:

  • SciPy's padlen=3*order
  • MATLAB filtfilt(b, a, x) with FiltFilt, and filtfilt(sos, g, x) with SOSFiltFilt and BySection

func PadLen

func PadLen(n int) (option FiltOption)

PadLen sets how many samples FiltFilt and SOSFiltFilt add beyond each end of x, which must be longer than n. The default is SciPy's 3·ntaps, and each function's doc says how it counts ntaps.

Units: n is a number of samples

Equivalent to:

  • scipy.signal.filtfilt's and sosfiltfilt's padlen=n
  • MATLAB has none, as its length is fixed

func PaddingConstant

func PaddingConstant() (option FiltOption)

PaddingConstant extends x past each end by repeating its end sample, so the slope drops to 0 across the end.

Equivalent to:

  • scipy.signal.filtfilt's padtype='constant'
  • MATLAB has none

func PaddingEven

func PaddingEven() (option FiltOption)

PaddingEven extends x past each end by mirroring it about its end sample, so the slope flips across the end.

Equivalent to:

  • scipy.signal.filtfilt's padtype='even'
  • MATLAB has none

func PaddingNone

func PaddingNone() (option FiltOption)

PaddingNone filters x as given, with no extension, so the startup transients land on its ends. The padding length is then ignored.

Equivalent to:

  • scipy.signal.filtfilt's padtype=None
  • MATLAB has none

func PaddingOdd

func PaddingOdd() (option FiltOption)

PaddingOdd extends x past each end by reflecting it through its end sample, so the slope continues across the end. It's the default.

Equivalent to:

  • scipy.signal.filtfilt's padtype='odd', its default
  • MATLAB filtfilt, which has no other

type FindSignalOption added in v0.7.0

type FindSignalOption func(*findSignalConfig)

FindSignalOption configures FindSignal: SearchHybrid, SearchDirect or SearchFast.

func SearchDirect added in v0.7.0

func SearchDirect() FindSignalOption

SearchDirect scores every window exactly, summing its squared differences with compensation, in O(len(data)·len(signal)). It's the simplest, but the slowest at every size measured, e.g. 77 s where SearchHybrid takes 29 ms, for a 30,000-sample signal in 400,000 samples.

Equivalent to:

  • SciPy has none
  • MATLAB has none

func SearchFast added in v0.7.0

func SearchFast() FindSignalOption

SearchFast scores every window by FFT correlation alone, which rounds the same way as MATLAB's findsignal: a perfect match may not score exactly 0, and windows whose distances differ by less than that rounding may be confused. It's 2 to 5% faster than SearchHybrid, and about twice as fast on near-periodic data, where many windows are nearly as close as the best.

Equivalent to:

  • SciPy has none
  • MATLAB findsignal

func SearchHybrid added in v0.7.0

func SearchHybrid() FindSignalOption

SearchHybrid scores every window by FFT correlation, then rescores exactly each window that, within the correlation's rounding, could be the closest. It gives SearchDirect's answer at close to SearchFast's cost. It's the default.

Equivalent to:

  • SciPy has none
  • MATLAB findsignal's answer, but exact where findsignal rounds

type FrequencyUnit added in v1.0.0

type FrequencyUnit int

FrequencyUnit is a unit of frequency, for ConvertFrequency. Its zero value is UnitNyquist.

const (
	// UnitNyquist is a fraction of the Nyquist frequency, fs/2,
	// the unit of a Band's edges, IIRNotch's w0 and FIRWin's band.
	UnitNyquist FrequencyUnit = iota
	// UnitRadPerSample is radians per sample, where Nyquist is π,
	// the unit of Freqz's and GroupDelay's frequencies.
	UnitRadPerSample
	// UnitCyclesPerSample is cycles per sample, f/fs, where Nyquist is 0.5,
	// the unit of fft.Freq(n, 1).
	UnitCyclesPerSample
	// UnitHz is cycles per second, where Nyquist is fs/2,
	// the unit of the spectral functions' frequencies.
	UnitHz
)

type MedFiltOption added in v0.10.0

type MedFiltOption func(*medFiltConfig)

MedFiltOption configures MedFilt: MedFiltTruncate or MedFiltZeroPad.

func MedFiltTruncate added in v0.10.0

func MedFiltTruncate() MedFiltOption

MedFiltTruncate takes the median of only the samples inside x, so a window near the ends is shorter, and may hold an even count. It's the default, as the ends stay where the signal is, wherever that is.

Equivalent to:

  • SciPy has none
  • MATLAB medfilt1's 'truncate'

func MedFiltZeroPad added in v0.10.0

func MedFiltZeroPad() MedFiltOption

MedFiltZeroPad fills the window past the ends with zeros, which pulls the ends towards 0, so it suits a signal centred on 0.

Equivalent to:

  • scipy.signal.medfilt, which has no other
  • MATLAB medfilt1's 'zeropad', its default

type OrderOption added in v0.10.0

type OrderOption func(*orderConfig)

OrderOption configures ButterOrd, Cheby1Ord, Cheby2Ord and EllipOrd: MatchPassband or MatchStopband.

func MatchPassband added in v0.10.0

func MatchPassband() OrderOption

MatchPassband meets the passband edge exactly, at -rippleDB, so the stopband is attenuated more than asked from its edge. The lowest order meeting a specification usually has margin to spare, and the band returned decides where it goes. It's the default.

Equivalent to:

  • scipy.signal.buttord, cheb1ord, cheb2ord and ellipord, which have no other
  • MATLAB cheb1ord and ellipord

func MatchStopband added in v0.10.0

func MatchStopband() OrderOption

MatchStopband meets the stopband edge exactly, at -attenuationDB, so the passband reaches further than its edge.

Equivalent to:

  • SciPy has none
  • MATLAB buttord and cheb2ord

type Peak added in v0.6.0

type Peak struct {
	Index  int     // a sample index
	Height float64 // in the signal's unit
}

Peak is a local maximum of a signal: its index, and the signal's value there.

func FindPeaks added in v0.6.0

func FindPeaks(x []float64, opts ...PeakOption) (peaks []Peak, err error)

FindPeaks returns the local maxima of x, in index order. A local maximum is a sample, or a flat run of samples, higher than the samples either side. The first and last samples are never peaks, so an x shorter than 3 has none. Options narrow the peaks down:

  • MinPeakHeight, PeakThreshold, MinPeakProminence and MinPeakWidth each judge a peak on its own
  • MinPeakDistance removes the lower of any two peaks that are too close together

A NaN is never a peak, nor is a sample beside one, as it isn't known to be higher. A peak whose prominence or width search reaches a NaN has neither, so fails MinPeakProminence and MinPeakWidth. An infinite limit is allowed: -Inf is no limit, and +Inf passes no peak.

peaks, err := dsp.FindPeaks(x, dsp.MinPeakProminence(0.5), dsp.MinPeakDistance(10))

Units: Peak's Index is a sample index, and its Height is in x's unit

Returns: ErrInvalidParameter for a MinPeakDistance below 1, or a NaN limit.

Equivalent to:

  • scipy.signal.find_peaks(x)
  • MATLAB findpeaks(x), with MATLABPeaks, which errors for an x shorter than 3, and for a 'MinPeakDistance' of len(x)-1 or more
Example
package main

import (
	"fmt"
	"log"

	"github.com/cxd309/tukey/dsp"
)

func main() {
	x := []float64{0, 2, 1, 3, 2.5, 2.8, 0, 4, 1, 0}

	// every local maximum, then only those standing at least 1.5 above their surroundings
	all, err := dsp.FindPeaks(x)
	if err != nil {
		log.Fatal(err)
	}
	prominent, err := dsp.FindPeaks(x, dsp.MinPeakProminence(1.5))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("all: %+v\n", all)
	fmt.Printf("prominent: %+v\n", prominent)
}
Output:
all: [{Index:1 Height:2} {Index:3 Height:3} {Index:5 Height:2.8} {Index:7 Height:4}]
prominent: [{Index:3 Height:3} {Index:7 Height:4}]

type PeakOption added in v0.6.0

type PeakOption func(*peakConfig)

PeakOption configures FindPeaks. Options are applied in order, so a later one overrides an earlier one.

func DistanceLast added in v0.6.0

func DistanceLast() PeakOption

DistanceLast applies MinPeakDistance after MinPeakProminence and MinPeakWidth, so a peak that fails those can't remove a neighbour that passes them. Without it, distance is applied first.

Equivalent to:

  • SciPy has none, as find_peaks applies distance first
  • MATLAB findpeaks, which has no other

func MATLABPeaks added in v0.6.0

func MATLABPeaks() PeakOption

MATLABPeaks applies MATLAB findpeaks' rules, same as PlateauFirst, TieEarlier and DistanceLast together:

  • a plateau's first sample
  • ties to the earlier peak
  • distance applied last

It doesn't change MinPeakDistance, which is d+1 for MATLAB's d.

Equivalent to:

  • SciPy has none
  • MATLAB findpeaks

func MinPeakDistance added in v0.6.0

func MinPeakDistance(d int) PeakOption

MinPeakDistance keeps peaks at least d samples apart, removing the lower of any two that are closer, highest peak first.

Units: d is a number of samples

Equivalent to:

  • scipy.signal.find_peaks' distance=d
  • MATLAB findpeaks' 'MinPeakDistance', d-1, as MATLAB keeps peaks more than its distance apart

func MinPeakHeight added in v0.6.0

func MinPeakHeight(h float64) PeakOption

MinPeakHeight keeps peaks at least h high. -Inf is no limit, and +Inf passes no peak.

Units: h is in x's unit

Equivalent to:

  • scipy.signal.find_peaks' height=h
  • MATLAB findpeaks' 'MinPeakHeight', h

func MinPeakProminence added in v0.6.0

func MinPeakProminence(p float64) PeakOption

MinPeakProminence keeps peaks with a prominence, from PeakProminences, of at least p. -Inf is no limit, and +Inf passes no peak.

Units: p is in x's unit

Equivalent to:

  • scipy.signal.find_peaks' prominence=p
  • MATLAB findpeaks' 'MinPeakProminence', p

func MinPeakWidth added in v0.6.0

func MinPeakWidth(w float64) PeakOption

MinPeakWidth keeps peaks at least w samples wide at half their prominence, from PeakWidths. -Inf is no limit, and +Inf passes no peak.

Units: w is in samples

Equivalent to:

  • scipy.signal.find_peaks' width=w
  • MATLAB findpeaks' 'MinPeakWidth', w

func PeakThreshold added in v0.6.0

func PeakThreshold(t float64) PeakOption

PeakThreshold keeps peaks at least t above both of their neighbouring samples. -Inf is no limit, and +Inf passes no peak.

Units: t is in x's unit

Equivalent to:

  • scipy.signal.find_peaks' threshold=t
  • MATLAB findpeaks' 'Threshold', t

func PlateauFirst added in v0.6.0

func PlateauFirst() PeakOption

PlateauFirst reports a flat-topped peak at its first sample.

Equivalent to:

  • SciPy has none
  • MATLAB findpeaks, which has no other

func PlateauMiddle added in v0.6.0

func PlateauMiddle() PeakOption

PlateauMiddle reports a flat-topped peak at its middle sample, rounding down for an even plateau. It's the default.

Equivalent to:

  • scipy.signal.find_peaks, which has no other
  • MATLAB has none

func TieEarlier added in v0.6.0

func TieEarlier() PeakOption

TieEarlier keeps the earlier of two equal peaks closer than MinPeakDistance.

Equivalent to:

  • SciPy has none
  • MATLAB findpeaks, which has no other

func TieLater added in v0.6.0

func TieLater() PeakOption

TieLater keeps the later of two equal peaks closer than MinPeakDistance. It's the default.

Equivalent to:

  • scipy.signal.find_peaks, which has no other
  • MATLAB has none

type PeakProminence added in v0.6.0

type PeakProminence struct {
	Prominence float64 // in the signal's unit
	LeftBase   int     // a sample index
	RightBase  int     // a sample index
}

PeakProminence is how far a peak stands above the higher of the lowest points either side of it, before the signal rises above the peak again. LeftBase and RightBase are the indices of those lowest points.

func PeakProminences added in v0.6.0

func PeakProminences(x []float64, peaks []int) (prominences []PeakProminence, err error)

PeakProminences returns the prominence of each of peaks in x, and the bases it's measured from: how far the peak stands above the higher of the lowest points either side of it, before the signal rises above the peak again. A peak whose search reaches a NaN before a higher sample has a NaN prominence, as the NaN might be higher.

prominences, err := dsp.PeakProminences(x, []int{12, 40})

Units:

  • peaks are sample indices
  • each Prominence is in x's unit, and LeftBase and RightBase are sample indices

Returns: ErrInvalidParameter for a peak outside x.

Equivalent to:

  • scipy.signal.peak_prominences(x, peaks)
  • MATLAB findpeaks' fourth output

type PeakWidth added in v0.6.0

type PeakWidth struct {
	Width  float64 // in samples, Right - Left
	Height float64 // in the signal's unit
	Left   float64 // a fractional sample index
	Right  float64 // a fractional sample index
}

PeakWidth is a peak's width at Height, measured between where the signal crosses Height either side of the peak. Left and Right are those crossings, as fractional indices interpolated between samples.

func PeakWidths added in v0.6.0

func PeakWidths(x []float64, peaks []int, relHeight float64) (widths []PeakWidth, err error)

PeakWidths returns the width of each of peaks in x, measured relHeight of the way down its prominence: 0.5 is half the prominence, and 1 is at its bases. The crossings are interpolated between samples. A peak with a NaN prominence, from PeakProminences, has a NaN width.

widths, err := dsp.PeakWidths(x, []int{12, 40}, 0.5)

Units:

  • peaks are sample indices
  • relHeight is a fraction of the prominence
  • each Width is in samples, its Height in x's unit, and Left and Right are fractional sample indices

Returns: ErrInvalidParameter for a relHeight that isn't at least 0 and finite, or a peak outside x.

Equivalent to:

  • scipy.signal.peak_widths(x, peaks, rel_height=relHeight)
  • MATLAB findpeaks' third output, at relHeight 0.5

type PercentileOption added in v0.9.0

type PercentileOption func(*percentileConfig)

PercentileOption configures Percentile: PercentileLinear or PercentileHazen.

func PercentileHazen added in v0.9.0

func PercentileHazen() PercentileOption

PercentileHazen interpolates at sorted position p/100·n - 0.5, clamped to the ends.

Equivalent to:

  • numpy.percentile's method='hazen'
  • MATLAB prctile

func PercentileLinear added in v0.9.0

func PercentileLinear() PercentileOption

PercentileLinear interpolates at sorted position p/100·(n-1), so 0 and 100 give the minimum and maximum exactly. It's the default, and R's and Excel's too.

Equivalent to:

  • numpy.percentile's method='linear', its default
  • MATLAB has none

type SOS added in v0.2.0

type SOS [][6]float64

SOS is a filter as a cascade of second-order sections, applied in order. Each row is one section's coefficients, b0, b1, b2, a0, a1, a2, the same layout as SciPy's sos arrays, with a0 = 1. Its coefficients are dimensionless. ZPK's SOS method builds one from a design.

type SavGolOption added in v0.10.0

type SavGolOption func(*savGolConfig)

SavGolOption configures SavGolFilter: SavGolDeriv.

func SavGolDeriv added in v0.10.0

func SavGolDeriv(order int, dx float64) SavGolOption

SavGolDeriv makes SavGolFilter return the order-th derivative of each fitted polynomial, for samples dx apart, rather than its value, which gives a smoothed derivative. Without it, the order is 0, the value.

v, err := dsp.SavGolFilter(position, 21, 3, dsp.SavGolDeriv(1, 1/fs)) // smoothed velocity

Units:

  • order is the derivative's order
  • dx is the time between samples, e.g. 1/fs in seconds

Equivalent to:

  • scipy.signal.savgol_filter's deriv=order and delta=dx
  • MATLAB has none in sgolayfilt

type SignalMatch added in v0.7.0

type SignalMatch struct {
	Start    int     // a sample index
	Stop     int     // a sample index, inclusive, same as MATLAB's istop
	Distance float64 // the sum of squared differences, in data's unit squared
}

SignalMatch is the window of data closest to the signal FindSignal looks for.

func FindSignal added in v0.7.0

func FindSignal(data, signal []float64, opts ...FindSignalOption) (match SignalMatch, err error)

FindSignal returns the window of data closest to signal, by the sum of squared differences, with ties to the earliest window. By default it's SearchHybrid, exact at close to the cost of an FFT. A NaN in data makes its windows' distances NaN, and a NaN distance never wins.

match, err := dsp.FindSignal(recording, template)
found := recording[match.Start : match.Stop+1]

Units:

  • Start and Stop are sample indices, Stop inclusive
  • Distance is in data's unit squared

Returns: ErrSignalTooShort for an empty signal, or one longer than data.

Equivalent to:

  • SciPy has none
  • MATLAB [istart, istop, dist] = findsignal(data, signal), with 0-based indices
Example
package main

import (
	"fmt"
	"log"

	"github.com/cxd309/tukey/dsp"
)

func main() {
	// a short template hidden in a longer recording
	recording := []float64{0, 1, 0, -1, 0, 2, 5, 3, -2, 0, 1, 0}
	template := []float64{2, 5, 3}

	match, err := dsp.FindSignal(recording, template)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("samples %d to %d, distance %g\n", match.Start, match.Stop, match.Distance)
}
Output:
samples 5 to 7, distance 0

type SpectralOption added in v0.8.0

type SpectralOption func(*spectralConfig)

SpectralOption configures STFT, Spectrogram, Welch and Periodogram. A function given an option that doesn't apply to it returns ErrInvalidOption.

func AtFrequencies added in v0.8.0

func AtFrequencies(f []float64) SpectralOption

AtFrequencies evaluates each segment's transform at the frequencies f, rather than at the FFT's bins, to look closely at a band without a huge NFFT. It applies to STFT only, and can't be combined with NFFT or TwoSided.

Units: f is in Hz

Equivalent to:

  • SciPy has none
  • MATLAB spectrogram(x, window, noverlap, f, fs)

func AverageMean added in v0.8.0

func AverageMean() SpectralOption

AverageMean combines Welch's segments' spectra by their mean. It's the default, and applies to Welch only.

Equivalent to:

  • scipy.signal.welch's average='mean', its default
  • MATLAB pwelch, which has no other

func AverageMedian added in v0.8.0

func AverageMedian() SpectralOption

AverageMedian combines Welch's segments' spectra by their median, corrected for its bias, which is robust to a few segments with transients in them. Any NaN segment, or one holding an infinite sample, makes the median NaN. It applies to Welch only.

Equivalent to:

  • scipy.signal.welch's average='median'
  • MATLAB has none

func NFFT added in v0.8.0

func NFFT(n int) SpectralOption

NFFT zero-pads each segment to n samples before transforming it, for more finely spaced frequencies. It's the window's length by default.

Units: n is a number of samples

Equivalent to:

  • SciPy's nfft=n
  • MATLAB's nfft

func Overlap added in v0.8.0

func Overlap(n int) SpectralOption

Overlap sets how many samples neighbouring segments share, which is half the window by default. It applies to STFT, Spectrogram and Welch.

Units: n is a number of samples

Equivalent to:

  • SciPy's noverlap=n
  • MATLAB's noverlap

func ScalingDensity added in v0.8.0

func ScalingDensity() SpectralOption

ScalingDensity gives power spectral density, in x's unit² per Hz, comparable across sample rates and windows. It's the default, and doesn't apply to STFT.

Equivalent to:

  • SciPy's scaling='density', its default
  • MATLAB's 'psd', its default

func ScalingSpectrum added in v0.8.0

func ScalingSpectrum() SpectralOption

ScalingSpectrum gives power spectrum, in x's unit², so a sine's peak reads its power. It doesn't apply to STFT.

Equivalent to:

  • SciPy's scaling='spectrum'
  • MATLAB's 'power'

func SegmentDetrend added in v0.8.0

func SegmentDetrend(mode DetrendMode) SpectralOption

SegmentDetrend detrends each segment before it's windowed, same as Detrend. There's no detrending by default, and to remove the whole signal's mean or trend, call Detrend first.

Equivalent to:

  • SciPy's detrend='linear' or 'constant', whose default is 'constant' for welch, periodogram and spectrogram
  • MATLAB has none

func TwoSided added in v0.8.0

func TwoSided() SpectralOption

TwoSided keeps the negative frequencies too, in fft.Freq's order. Spectra are one-sided by default, as a real signal's negative frequencies mirror its positive ones.

Equivalent to:

  • SciPy's return_onesided=False
  • MATLAB's 'twosided', which orders the bins from 0 to fs rather than as fft.Freq does

type Spectrum added in v0.8.0

type Spectrum struct {
	Frequencies []float64 // in Hz
	Power       []float64 // in the signal's unit² per Hz, or its unit² with ScalingSpectrum
}

Spectrum is a power spectrum, one value per frequency.

func Periodogram added in v0.8.0

func Periodogram(x []float64, fs float64, window []float64, opts ...SpectralOption) (spectrum Spectrum, err error)

Periodogram returns x's power spectrum, sampled at fs Hz, from one transform of the whole signal, multiplied by window, which must be as long as x. window.Boxcar(len(x)) gives the plain periodogram. Power is a density by default, and ScalingSpectrum gives power instead.

w, err := window.Hann(len(x), window.Periodic())
psd, err := dsp.Periodogram(x, fs, w)

Units:

  • fs is in Hz
  • window is dimensionless
  • Frequencies are in Hz, and Power in x's unit² per Hz, or x's unit² with ScalingSpectrum

Returns:

  • ErrInvalidLength for an empty window, a window that isn't x's length, or an NFFT shorter than the window.
  • ErrInvalidParameter for an fs that isn't positive and finite, or a NaN or infinite window tap.
  • ErrInvalidOption for Overlap, AtFrequencies or an Average option.

Equivalent to:

  • scipy.signal.periodogram(x, fs, window, detrend=False)
  • MATLAB [pxx, f] = periodogram(x, window, nfft, fs), and 'power' for ScalingSpectrum

func Welch added in v0.8.0

func Welch(x []float64, fs float64, window []float64, opts ...SpectralOption) (spectrum Spectrum, err error)

Welch returns x's power spectrum, sampled at fs Hz, by Welch's method: the average of its segments' power spectra, which is much less noisy than one periodogram, at the cost of the coarser frequency spacing of a segment's length. Segments are len(window) samples, half a window apart unless Overlap says. Power is a density by default, and ScalingSpectrum gives power instead.

w, err := window.Hann(1024, window.Periodic())
psd, err := dsp.Welch(x, fs, w)

Units:

  • fs is in Hz
  • window is dimensionless
  • Frequencies are in Hz, and Power in x's unit² per Hz, or x's unit² with ScalingSpectrum

Returns:

  • ErrInvalidLength for an empty window, or an NFFT shorter than the window.
  • ErrSignalTooShort for a window longer than x.
  • ErrInvalidParameter for an fs that isn't positive and finite, a NaN or infinite window tap, or an Overlap that's negative or at least the window's length.
  • ErrInvalidOption for AtFrequencies.

Equivalent to:

  • scipy.signal.welch(x, fs, window, detrend=False)
  • MATLAB [pxx, f] = pwelch(x, window, noverlap, nfft, fs), with AverageMean, and 'power' for ScalingSpectrum
Example
package main

import (
	"fmt"
	"log"

	"github.com/cxd309/tukey/dsp"
	"github.com/cxd309/tukey/waveform"
	"github.com/cxd309/tukey/window"
)

func main() {
	// two sines, at 62.5 Hz and 187.5 Hz, sampled at 1 kHz for 4 s
	const fs = 1000.0
	t, err := waveform.Timebase(4000, fs)
	if err != nil {
		log.Fatal(err)
	}
	low, err := waveform.Tone(t, 62.5, waveform.Phase(-90))
	if err != nil {
		log.Fatal(err)
	}
	high, err := waveform.Tone(t, 187.5, waveform.Phase(-90))
	if err != nil {
		log.Fatal(err)
	}
	x := make([]float64, len(t))
	for i := range x {
		x[i] = low[i] + 0.5*high[i]
	}

	// ScalingSpectrum reads each tone's power, A²/2, at its peak
	w, err := window.Hann(256, window.Periodic())
	if err != nil {
		log.Fatal(err)
	}
	spectrum, err := dsp.Welch(x, fs, w, dsp.ScalingSpectrum())
	if err != nil {
		log.Fatal(err)
	}
	for k, f := range spectrum.Frequencies {
		if f == 62.5 || f == 187.5 {
			fmt.Printf("%.1f Hz: %.3f\n", f, spectrum.Power[k])
		}
	}
}
Output:
62.5 Hz: 0.500
187.5 Hz: 0.125

type TimeFrequency added in v0.8.0

type TimeFrequency[T complex128 | float64] struct {
	Frequencies []float64 // in Hz, one for each value in a segment's spectrum
	Times       []float64 // in seconds, the centre of each segment
	Values      [][]T     // Values[segment][frequency], in the unit its function says
}

TimeFrequency is a signal's spectrum over time, one spectrum per segment.

func STFT added in v0.8.0

func STFT(x []float64, fs float64, window []float64, opts ...SpectralOption) (tf TimeFrequency[complex128], err error)

STFT returns the short-time Fourier transform of x, sampled at fs Hz: x cut into segments of len(window) samples, half a window apart unless Overlap says, each multiplied by window and transformed. Each segment's transform is plain, with its phase measured from the segment's start:

X(f) = Σ w[n]·x[n]·e^(-2πi·f·n/fs)

Divide by the window's sum for amplitudes. A partial last segment is dropped.

w, err := window.Hann(256, window.Periodic())
tf, err := dsp.STFT(x, fs, w)

Units:

  • fs is in Hz
  • window is dimensionless
  • Frequencies are in Hz, Times in seconds, and Values in x's unit

Returns:

  • ErrInvalidLength for an empty window, or an NFFT shorter than the window.
  • ErrSignalTooShort for a window longer than x.
  • ErrInvalidParameter for an fs that isn't positive and finite, a NaN or infinite window tap, or an Overlap that's negative or at least the window's length.
  • ErrInvalidLength for AtFrequencies with no frequencies.
  • ErrInvalidOption for ScalingDensity, ScalingSpectrum, AverageMean or AverageMedian, or AtFrequencies with NFFT or TwoSided.

Equivalent to:

  • scipy.signal.stft(x, fs, window, boundary=None, padded=False, detrend=False), multiplied by the window's sum
  • MATLAB [S, F, T] = spectrogram(x, window, noverlap, nfft, fs), with S transposed

func Spectrogram added in v0.8.0

func Spectrogram(x []float64, fs float64, window []float64, opts ...SpectralOption) (tf TimeFrequency[float64], err error)

Spectrogram returns the power spectrum of each segment of x, sampled at fs Hz: x cut into segments of len(window) samples, half a window apart unless Overlap says, each multiplied by window and transformed, as STFT's are. Power is a density by default, and ScalingSpectrum gives power instead.

w, err := window.Hann(256, window.Periodic())
tf, err := dsp.Spectrogram(x, fs, w)

Units:

  • fs is in Hz
  • window is dimensionless
  • Frequencies are in Hz, Times in seconds, and Values in x's unit² per Hz, or x's unit² with ScalingSpectrum

Returns:

  • ErrInvalidLength for an empty window, or an NFFT shorter than the window.
  • ErrSignalTooShort for a window longer than x.
  • ErrInvalidParameter for an fs that isn't positive and finite, a NaN or infinite window tap, or an Overlap that's negative or at least the window's length.
  • ErrInvalidOption for AtFrequencies or an Average option.

Equivalent to:

  • scipy.signal.spectrogram(x, fs, window, detrend=False, mode='psd'), transposed
  • MATLAB [~, F, T, P] = spectrogram(x, window, noverlap, nfft, fs), with P transposed, and 'power' for ScalingSpectrum

type ZPK added in v0.2.0

type ZPK struct {
	Zeros []complex128 // in the z-plane
	Poles []complex128 // in the z-plane, inside the unit circle for a stable filter
	Gain  float64      // dimensionless
}

ZPK is a digital filter described by its zeros, poles and gain:

H(z) = Gain·Π (z - zero)/Π (z - pole)

Every IIR design returns one, and one can be built by hand. Complex zeros and poles must come in conjugate pairs, for the filter to be real. Use its SOS method for filtering, and its BA method for low orders or for interchange.

func Bessel added in v0.10.0

func Bessel(order int, band Band, opts ...BesselOption) (f ZPK, err error)

Bessel designs a digital Bessel filter for band. Its analog prototype has a maximally flat group delay, so a pulse in the passband keeps its shape. After the bilinear transform the delay is only close to flat, more so the lower the band edge. Its transition is the gentlest of the IIR designs for its order. By default a band edge is the -3 dB point, same as Butter, and BesselNormPhase and BesselNormDelay move it. Its poles are found exactly, which takes about 2 ms at order 8 and 30 ms at order 25, growing as the cube of the order.

f, err := dsp.Bessel(4, dsp.Lowpass(0.3))

Units:

  • order is the prototype's order
  • band's edges are fractions of Nyquist

Returns:

  • ErrInvalidOrder for an order below 1.
  • ErrInvalidBand for the zero Band, an edge outside (0, 1), or a low edge not below the high.

Equivalent to:

  • scipy.signal.bessel(order, wn, btype, norm='mag', output='zpk'), whose default is norm='phase'
  • MATLAB bilinear(z, p, k, 2) of [z, p, k] = besself(order, 4*tan(pi*wn/2), ftype), with BesselNormPhase, up to order 25, as MATLAB has no digital Bessel design

func Butter

func Butter(order int, band Band) (f ZPK, err error)

Butter designs a digital Butterworth filter for band: maximally flat in the passband, falling monotonically through the band edge, which is its -3 dB point. A Bandpass or Bandstop design has order 2·order, as each prototype pole becomes a pair. Use the ZPK's SOS method for filtering.

f, err := dsp.Butter(4, dsp.Lowpass(0.3))
sos, err := f.SOS()
y, err := dsp.SOSFilter(sos, x)

Units:

  • order is the prototype's order
  • band's edges are fractions of Nyquist

Returns:

  • ErrInvalidOrder for an order below 1.
  • ErrInvalidBand for the zero Band, an edge outside (0, 1), or a low edge not below the high.

Equivalent to:

  • scipy.signal.butter(order, wn, btype, output='zpk')
  • MATLAB butter(order, wn, ftype)
Example
package main

import (
	"fmt"
	"log"

	"github.com/cxd309/tukey/dsp"
)

func main() {
	// a 2nd-order lowpass at 150Hz, for a signal sampled at 1000 Hz
	f, err := dsp.Butter(2, dsp.Lowpass(150.0/(1000.0/2)))
	if err != nil {
		log.Fatal(err)
	}
	b, a, err := f.BA()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("b = %.4f\na = %.4f\n", b, a)
}
Output:
b = [0.1311 0.2622 0.1311]
a = [1.0000 -0.7478 0.2722]

func Cheby1 added in v0.10.0

func Cheby1(order int, rippleDB float64, band Band) (f ZPK, err error)

Cheby1 designs a digital Chebyshev type I filter for band. It has equal ripple of rippleDB in the passband and falls monotonically after it, a sharper transition than Butter's for the same order. A band edge is where the gain first drops below -rippleDB, not -3 dB.

f, err := dsp.Cheby1(4, 1, dsp.Lowpass(0.3))

Units:

  • order is the prototype's order
  • rippleDB is in dB, positive
  • band's edges are fractions of Nyquist

Returns:

  • ErrInvalidOrder for an order below 1.
  • ErrInvalidBand for the zero Band, an edge outside (0, 1), or a low edge not below the high.
  • ErrInvalidParameter for a rippleDB that isn't positive and finite.

Equivalent to:

  • scipy.signal.cheby1(order, rippleDB, wn, btype, output='zpk')
  • MATLAB cheby1(order, rippleDB, wn, ftype)

func Cheby2 added in v0.10.0

func Cheby2(order int, attenuationDB float64, band Band) (f ZPK, err error)

Cheby2 designs a digital Chebyshev type II filter for band. It's flat in the passband, with equal ripple in the stopband at least attenuationDB down. A band edge is the start of the stopband, where the gain first reaches -attenuationDB, not the end of the passband, which it is for Butter and Cheby1.

f, err := dsp.Cheby2(4, 40, dsp.Lowpass(0.3))

Units:

  • order is the prototype's order
  • attenuationDB is in dB, positive
  • band's edges are fractions of Nyquist

Returns:

  • ErrInvalidOrder for an order below 1.
  • ErrInvalidBand for the zero Band, an edge outside (0, 1), or a low edge not below the high.
  • ErrInvalidParameter for an attenuationDB that isn't positive and finite.

Equivalent to:

  • scipy.signal.cheby2(order, attenuationDB, wn, btype, output='zpk')
  • MATLAB cheby2(order, attenuationDB, wn, ftype)

func Ellip added in v0.10.0

func Ellip(order int, rippleDB, attenuationDB float64, band Band) (f ZPK, err error)

Ellip designs a digital elliptic, or Cauer, filter for band. It has equal ripple of rippleDB in the passband, and equal ripple at least attenuationDB down in the stopband, the sharpest transition of any filter of its order. A band edge is where the gain first drops below -rippleDB, same as Cheby1.

f, err := dsp.Ellip(4, 1, 40, dsp.Lowpass(0.3))

Units:

  • order is the prototype's order
  • rippleDB and attenuationDB are in dB, positive
  • band's edges are fractions of Nyquist

Returns:

  • ErrInvalidOrder for an order below 1.
  • ErrInvalidBand for the zero Band, an edge outside (0, 1), or a low edge not below the high.
  • ErrInvalidParameter for a rippleDB or attenuationDB that isn't positive and finite, or an attenuationDB that isn't greater than rippleDB.

Equivalent to:

  • scipy.signal.ellip(order, rippleDB, attenuationDB, wn, btype, output='zpk')
  • MATLAB ellip(order, rippleDB, attenuationDB, wn, ftype)

func IIRNotch added in v0.10.0

func IIRNotch(w0, q float64) (f ZPK, err error)

IIRNotch designs a second-order notch filter, which removes the frequency w0 and passes the rest at 0 dB. The quality factor q sets the -3 dB bandwidth, w0/q, so the higher q, the narrower the notch. Its zeros are on the unit circle at w0, and its poles just inside them. For mains hum at 50 Hz, sampled at 1 kHz:

w0, err := dsp.HzToNyquist(50.0, 1000)
f, err := dsp.IIRNotch(w0, 30)

Units:

  • w0 is a fraction of Nyquist
  • q is dimensionless

Returns: ErrInvalidParameter for a w0 outside (0, 1), a q that isn't positive and finite, or a bandwidth w0/q that isn't below Nyquist.

Equivalent to:

  • scipy.signal.iirnotch(w0, q), which returns (b, a) where IIRNotch returns zeros, poles and gain
  • MATLAB iirnotch(w0, w0/q), in the DSP System Toolbox

func IIRPeak added in v0.10.0

func IIRPeak(w0, q float64) (f ZPK, err error)

IIRPeak designs a second-order peak filter, which passes the frequency w0 at 0 dB and rejects DC and Nyquist. The quality factor q sets the -3 dB bandwidth, w0/q, so the higher q, the narrower the peak.

f, err := dsp.IIRPeak(0.3, 10)

Units:

  • w0 is a fraction of Nyquist
  • q is dimensionless

Returns: ErrInvalidParameter for a w0 outside (0, 1), a q that isn't positive and finite, or a bandwidth w0/q that isn't below Nyquist.

Equivalent to:

  • scipy.signal.iirpeak(w0, q), which returns (b, a), and forms the gain as 1 - 1/(1 + β), losing digits for a narrow bandwidth, 6e-13 at w0 = 0.002, q = 30. IIRPeak's is β/(1 + β), exact to rounding.
  • MATLAB iirpeak(w0, w0/q), in the DSP System Toolbox

func (ZPK) BA added in v0.2.0

func (f ZPK) BA() (b, a []float64, err error)

BA returns the filter's transfer-function coefficients, b over a, from its zeros and poles, with a[0] = 1. As the order rises or the band narrows, b and a lose digits, and SOS keeps them.

b, a, err := f.BA()
y, err := dsp.Filter(b, a, x)

Units: b and a are dimensionless

Returns: ErrInvalidZPK if complex zeros or poles aren't in conjugate pairs, or the gain, a zero or a pole isn't finite.

Equivalent to:

  • scipy.signal.zpk2tf(z, p, k)
  • MATLAB zp2tf(z, p, k)

func (ZPK) SOS added in v0.2.0

func (f ZPK) SOS() (sos SOS, err error)

SOS returns the filter as second-order sections, for filtering at any order. Each pole is paired with its nearest zero, starting from the poles closest to the unit circle, which go in the last sections. That keeps each section's peak gain small, so SOS stays accurate at orders where BA's coefficients don't. The algorithm follows SciPy's, as THIRD_PARTY_NOTICES records.

f, err := dsp.Butter(8, dsp.Lowpass(0.1))
sos, err := f.SOS()
y, err := dsp.SOSFilter(sos, x)

Units: sos's coefficients are dimensionless

Returns: ErrInvalidZPK if complex zeros or poles aren't in conjugate pairs, or the gain, a zero or a pole isn't finite.

Equivalent to:

  • scipy.signal.zpk2sos(z, p, k), with its default pairing='nearest'
  • MATLAB zp2sos(z, p, k)

Jump to

Keyboard shortcuts

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