Documentation
¶
Overview ¶
Package signal is signal processing in pure Go: filter design and filtering, spectral estimation and resampling, with SciPy's semantics (scipy.signal) and, where they differ, a note on MATLAB's.
All vectors are []float64 and filters have real coefficients. Filters travel as transfer-function coefficients (TF), zeros-poles-gain (ZPK) or second-order sections (SOS); prefer SOS above order 8, where the transfer function form loses accuracy.
Index ¶
- Variables
- func Barthann(n int, sym bool) []float64
- func Bartlett(n int, sym bool) []float64
- func Bilinear(b, a []float64, fs float64) ([]float64, []float64, error)
- func Blackman(n int, sym bool) []float64
- func BlackmanHarris(n int, sym bool) []float64
- func Bohman(n int, sym bool) []float64
- func Boxcar(n int, sym bool) []float64
- func ButtOrd(wp, ws []float64, gpass, gstop float64, analog bool, fs float64) (int, []float64, error)
- func CSD(x, y []float64, o *SpectralOptions) (f []float64, p []complex128, err error)
- func Cheb1Ord(wp, ws []float64, gpass, gstop float64, analog bool, fs float64) (int, []float64, error)
- func Cheb2Ord(wp, ws []float64, gpass, gstop float64, analog bool, fs float64) (int, []float64, error)
- func CheckCOLA(win []float64, nperseg, noverlap int, tol float64) (bool, error)
- func CheckNOLA(win []float64, nperseg, noverlap int, tol float64) (bool, error)
- func Coherence(x, y []float64, o *SpectralOptions) (f, c []float64, err error)
- func Convolve(a, b []float64, mode ConvMode, method ConvMethod) ([]float64, error)
- func Correlate(a, b []float64, mode ConvMode, method ConvMethod) ([]float64, error)
- func CorrelationLags(n1, n2 int, mode ConvMode) ([]int, error)
- func Cosine(n int, sym bool) []float64
- func DPSS(m int, nw float64, kmax int, sym bool, norm DPSSNorm) (windows [][]float64, ratios []float64, err error)
- func Decimate(x []float64, q int, o *DecimateOptions) ([]float64, error)
- func Deconvolve(signal, divisor []float64) (quot, rem []float64, err error)
- func Detrend(x []float64, t DetrendType, bp []int) ([]float64, error)
- func EllipOrd(wp, ws []float64, gpass, gstop float64, analog bool, fs float64) (int, []float64, error)
- func Ellipj(u, m float64) (sn, cn, dn float64)
- func FFTConvolve(a, b []float64, mode ConvMode) ([]float64, error)
- func FiltFilt(b, a, x []float64, o *FiltFiltOptions) ([]float64, error)
- func Firls(numtaps int, bands, desired, weight []float64, fs float64) ([]float64, error)
- func Firwin(numtaps int, cutoff []float64, o *FirwinOptions) ([]float64, error)
- func Firwin2(numtaps int, freq, gain []float64, o *Firwin2Options) ([]float64, error)
- func Flattop(n int, sym bool) []float64
- func Freqs(b, a []float64, o *FreqOptions) (w []float64, h []complex128, err error)
- func FreqsZPK(s ZPK, o *FreqOptions) (w []float64, h []complex128, err error)
- func Freqz(b, a []float64, o *FreqOptions) (w []float64, h []complex128, err error)
- func FreqzZPK(s ZPK, o *FreqOptions) (w []float64, h []complex128, err error)
- func GetWindow(name string, n int, fftbins bool, params ...float64) ([]float64, error)
- func GroupDelay(b, a []float64, o *FreqOptions) (w, gd []float64, err error)
- func Hamming(n int, sym bool) []float64
- func Hann(n int, sym bool) []float64
- func Hilbert(x []float64, n int) ([]complex128, error)
- func IIRNotch(w0, q, fs float64) (b, a []float64, err error)
- func IIRPeak(w0, q, fs float64) (b, a []float64, err error)
- func ISTFT(z [][]complex128, o *ISTFTOptions) (t, x []float64, err error)
- func KaiserAtten(numtaps int, width float64) float64
- func KaiserBeta(a float64) float64
- func KaiserOrd(ripple, width float64) (numtaps int, beta float64, err error)
- func LFilter(b, a, x, zi []float64) (y, zf []float64, err error)
- func LFilterIC(b, a, y, x []float64) ([]float64, error)
- func LFilterZI(b, a []float64) ([]float64, error)
- func LP2BP(b, a []float64, wo, bw float64) ([]float64, []float64, error)
- func LP2BS(b, a []float64, wo, bw float64) ([]float64, []float64, error)
- func LP2HP(b, a []float64, wo float64) ([]float64, []float64, error)
- func LP2LP(b, a []float64, wo float64) ([]float64, []float64, error)
- func Lombscargle(x, y, freqs []float64, o *LombOptions) ([]float64, error)
- func LombscargleAmplitude(x, y, freqs []float64, o *LombOptions) ([]complex128, error)
- func Normalize(b, a []float64) ([]float64, []float64, error)
- func Nuttall(n int, sym bool) []float64
- func OAConvolve(a, b []float64, mode ConvMode) ([]float64, error)
- func Overlap(n int) *int
- func Parzen(n int, sym bool) []float64
- func PeakProminences(x []float64, peaks []int, wlen float64) (prom []float64, left, right []int, err error)
- func PeakWidths(x []float64, peaks []int, relHeight float64, prom []float64, left, right []int) (widths, heights, leftIP, rightIP []float64, err error)
- func Periodogram(x []float64, o *SpectralOptions) (f, p []float64, err error)
- func Remez(numtaps int, bands, desired []float64, o *RemezOptions) ([]float64, error)
- func Resample(x []float64, num int, o *ResampleOptions) ([]float64, error)
- func ResamplePoly(x []float64, up, down int, o *ResamplePolyOptions) ([]float64, error)
- func Roots(p []float64) ([]complex128, error)
- func SOS2TF(sos SOS) (b, a []float64)
- func SOSFilt(sos SOS, x []float64, zi [][2]float64) (y []float64, zf [][2]float64, err error)
- func SOSFiltFilt(sos SOS, x []float64, o *FiltFiltOptions) ([]float64, error)
- func SOSFiltZI(sos SOS) ([][2]float64, error)
- func SOSFreqz(sos SOS, o *FreqOptions) (w []float64, h []complex128, err error)
- func STFT(x []float64, o *STFTOptions) (f, t []float64, z [][]complex128, err error)
- func Spectrogram(x []float64, o *SpectralOptions, mode SpectrogramMode) (f, t []float64, s [][]float64, err error)
- func Triang(n int, sym bool) []float64
- func Upfirdn(h, x []float64, up, down int, mode PadMode, cval float64) ([]float64, error)
- func Welch(x []float64, o *SpectralOptions) (f, p []float64, err error)
- func ZPK2TF(s ZPK) (b, a []float64, err error)
- type Average
- type BandType
- type BesselNorm
- type ConvMethod
- type ConvMode
- type DPSSNorm
- type DecimateOptions
- type DetrendType
- type FiltFiltOptions
- type FiltMethod
- type FilterType
- type FindPeaksOptions
- type FirPass
- type Firwin2Options
- type FirwinOptions
- type FreqOptions
- type IIROptions
- type ISTFTOptions
- type Interval
- type LombOptions
- type PadMode
- type PadType
- type Pairing
- type PeakProperties
- type RemezOptions
- type RemezType
- type ResampleOptions
- type ResamplePolyOptions
- type SOS
- type STFTOptions
- type Scaling
- type SpectralOptions
- type SpectrogramMode
- type Window
- func Chebwin(at float64) Window
- func Exponential(center, tau float64) Window
- func Gaussian(std float64) Window
- func GeneralCosine(a []float64) Window
- func GeneralGaussian(p, sig float64) Window
- func GeneralHamming(alpha float64) Window
- func Kaiser(beta float64) Window
- func Tukey(alpha float64) Window
- type ZPK
- func BesselAP(n int, norm BesselNorm) (ZPK, error)
- func BesselFilter(n int, wn []float64, bt BandType, norm BesselNorm, o *IIROptions) (ZPK, error)
- func BilinearZPK(s ZPK, fs float64) (ZPK, error)
- func ButtAP(n int) (ZPK, error)
- func Butter(n int, wn []float64, bt BandType, o *IIROptions) (ZPK, error)
- func Cheb1AP(n int, rp float64) (ZPK, error)
- func Cheb2AP(n int, rs float64) (ZPK, error)
- func Cheby1(n int, rp float64, wn []float64, bt BandType, o *IIROptions) (ZPK, error)
- func Cheby2(n int, rs float64, wn []float64, bt BandType, o *IIROptions) (ZPK, error)
- func Ellip(n int, rp, rs float64, wn []float64, bt BandType, o *IIROptions) (ZPK, error)
- func EllipAP(n int, rp, rs float64) (ZPK, error)
- func IIRDesign(wp, ws []float64, gpass, gstop float64, ft FilterType, o *IIROptions) (ZPK, error)
- func IIRFilter(n int, wn []float64, bt BandType, ft FilterType, o *IIROptions) (ZPK, error)
- func LP2BPZPK(s ZPK, wo, bw float64) (ZPK, error)
- func LP2BSZPK(s ZPK, wo, bw float64) (ZPK, error)
- func LP2HPZPK(s ZPK, wo float64) (ZPK, error)
- func LP2LPZPK(s ZPK, wo float64) (ZPK, error)
- func SOS2ZPK(sos SOS) (ZPK, error)
- func TF2ZPK(b, a []float64) (ZPK, error)
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrNotConverged = errors.New("signal: the Remez exchange did not converge; try a wider transition band")
ErrNotConverged is returned by Remez, with the best filter found, when the exchange does not converge within MaxIter iterations or its deviation stops growing (SciPy raises "Failure to converge" there). For a degenerate design whose filter would not be finite, the filter returned is nil.
Functions ¶
func Bilinear ¶
Bilinear maps an analog transfer function b/a (in s) to a digital one (in z) by the bilinear transform at sampling frequency fs (scipy.signal.bilinear).
func BlackmanHarris ¶
BlackmanHarris is the 4-term Blackman–Harris window.
func ButtOrd ¶
func ButtOrd(wp, ws []float64, gpass, gstop float64, analog bool, fs float64) (int, []float64, error)
ButtOrd returns the minimum order and the natural (-3 dB) frequencies of a Butterworth filter meeting the passband (wp, gpass dB) and stopband (ws, gstop dB) specification (scipy.signal.buttord). wp and ws hold one frequency (lowpass/highpass) or two (bandpass/bandstop); with fs == 0 they are normalised to the Nyquist frequency.
func CSD ¶
func CSD(x, y []float64, o *SpectralOptions) (f []float64, p []complex128, err error)
CSD estimates the cross power spectral density of x and y by Welch's method (scipy.signal.csd; MATLAB cpsd). The shorter signal is zero padded.
func Cheb1Ord ¶
func Cheb1Ord(wp, ws []float64, gpass, gstop float64, analog bool, fs float64) (int, []float64, error)
Cheb1Ord returns the minimum order and the passband edge frequencies of a Chebyshev type I filter (scipy.signal.cheb1ord).
func Cheb2Ord ¶
func Cheb2Ord(wp, ws []float64, gpass, gstop float64, analog bool, fs float64) (int, []float64, error)
Cheb2Ord returns the minimum order and the stopband-start frequencies of a Chebyshev type II filter (scipy.signal.cheb2ord).
func CheckCOLA ¶
CheckCOLA reports whether the window and overlap satisfy the constant overlap-add condition, so that STFT with those parameters is invertible and the overlapped windows sum to a constant (scipy.signal.check_COLA).
func CheckNOLA ¶
CheckNOLA reports whether the window and overlap satisfy the nonzero overlap-add condition: the squared windows sum to a nonzero value everywhere, the minimum requirement for ISTFT (scipy.signal.check_NOLA).
func Coherence ¶
func Coherence(x, y []float64, o *SpectralOptions) (f, c []float64, err error)
Coherence estimates the magnitude-squared coherence of x and y, |Pxy|^2/(Pxx Pyy) (scipy.signal.coherence; MATLAB mscohere).
func Convolve ¶
func Convolve(a, b []float64, mode ConvMode, method ConvMethod) ([]float64, error)
Convolve convolves a and b (scipy.signal.convolve; MATLAB conv).
Example ¶
package main
import (
"fmt"
"github.com/go-dsp/signal"
)
func main() {
y, _ := signal.Convolve([]float64{1, 2, 3}, []float64{0, 1, 0.5}, signal.ConvFull, signal.ConvAuto)
fmt.Println(y)
}
Output: [0 1 2.5 4 1.5]
func Correlate ¶
func Correlate(a, b []float64, mode ConvMode, method ConvMethod) ([]float64, error)
Correlate cross-correlates a and b: out[k] = sum_n a[n+k] b[n] (scipy.signal.correlate; MATLAB xcorr up to its lag convention).
func CorrelationLags ¶
CorrelationLags returns the lag of each output of Correlate for inputs of the given lengths (scipy.signal.correlation_lags).
func DPSS ¶
func DPSS(m int, nw float64, kmax int, sym bool, norm DPSSNorm) (windows [][]float64, ratios []float64, err error)
DPSS returns the first kmax discrete prolate spheroidal (Slepian) sequences of length m and time-half-bandwidth product nw, the multitaper windows of Thomson, computed from the symmetric tridiagonal eigenproblem of Percival and Walden. ratios holds the spectral concentration ratios.
func Decimate ¶
func Decimate(x []float64, q int, o *DecimateOptions) ([]float64, error)
Decimate downsamples x by the integer factor q after low-pass filtering to prevent aliasing (scipy.signal.decimate; MATLAB decimate).
func Deconvolve ¶
Deconvolve divides the polynomial signal by divisor, returning the quotient and remainder (scipy.signal.deconvolve): signal = conv(divisor, quot) + rem.
func Detrend ¶
func Detrend(x []float64, t DetrendType, bp []int) ([]float64, error)
Detrend removes a constant or piecewise-linear trend from x, with breakpoints bp between the linear pieces (scipy.signal.detrend).
func EllipOrd ¶
func EllipOrd(wp, ws []float64, gpass, gstop float64, analog bool, fs float64) (int, []float64, error)
EllipOrd returns the minimum order and the passband edge frequencies of an elliptic filter (scipy.signal.ellipord).
func Ellipj ¶
Ellipj evaluates the Jacobi elliptic functions sn, cn and dn of argument u and parameter m = k^2 in [0, 1] (the algorithm of Cephes' ellpj, via the arithmetic-geometric mean; NaN outside the domain).
func FFTConvolve ¶
FFTConvolve convolves a and b using the FFT (scipy.signal.fftconvolve).
func FiltFilt ¶
func FiltFilt(b, a, x []float64, o *FiltFiltOptions) ([]float64, error)
FiltFilt applies the filter b/a forward and backward, giving zero phase distortion and squared magnitude response (scipy.signal.filtfilt; MATLAB filtfilt). The signal is extended at both ends to reduce transients.
func Firls ¶
Firls designs a linear-phase FIR filter by least squares (scipy.signal.firls; MATLAB firls). numtaps must be odd. bands holds pairs of band edges (increasing, between 0 and fs/2), desired the gain at each edge, and weight (optional, one per band) the relative weight of each band. fs defaults to 2.
func Firwin ¶
func Firwin(numtaps int, cutoff []float64, o *FirwinOptions) ([]float64, error)
Firwin designs a linear-phase FIR filter with the window method (scipy.signal.firwin; MATLAB fir1). cutoff holds one or more strictly increasing frequencies between 0 and Fs/2.
Example ¶
package main
import (
"fmt"
"github.com/go-dsp/signal"
)
func main() {
h, _ := signal.Firwin(21, []float64{0.3}, nil)
var sum float64
for _, v := range h {
sum += v
}
fmt.Printf("%d taps, DC gain %.6f\n", len(h), sum)
}
Output: 21 taps, DC gain 1.000000
func Firwin2 ¶
func Firwin2(numtaps int, freq, gain []float64, o *Firwin2Options) ([]float64, error)
Firwin2 designs an FIR filter by frequency sampling: freq and gain describe a piecewise-linear desired response from 0 to Fs/2 (scipy.signal.firwin2; MATLAB fir2).
func Freqs ¶
func Freqs(b, a []float64, o *FreqOptions) (w []float64, h []complex128, err error)
Freqs returns the frequency response H(jw) = B(jw)/A(jw) of the analog filter b/a (scipy.signal.freqs); o.W is in rad/s and o.N defaults to 200 logarithmically spaced points chosen from the poles and zeros.
func FreqsZPK ¶
func FreqsZPK(s ZPK, o *FreqOptions) (w []float64, h []complex128, err error)
FreqsZPK is Freqs for a filter given as zeros, poles and gain.
func Freqz ¶
func Freqz(b, a []float64, o *FreqOptions) (w []float64, h []complex128, err error)
Freqz returns the frequency response H(e^jw) = B(e^-jw)/A(e^-jw) of the digital filter b/a at the frequencies w (in the units of o.Fs), like scipy.signal.freqz (MATLAB freqz).
func FreqzZPK ¶
func FreqzZPK(s ZPK, o *FreqOptions) (w []float64, h []complex128, err error)
FreqzZPK is Freqz for a filter given as zeros, poles and gain.
func GetWindow ¶
GetWindow returns the named window (scipy.signal.get_window): the name is one of boxcar, triang, bartlett, hann, hamming, blackman, blackmanharris, nuttall, flattop, cosine, bohman, parzen, barthann, kaiser(beta), gaussian(std), general_gaussian(p, sig), general_hamming(alpha), general_cosine(a...), tukey(alpha), exponential(tau), chebwin(at) and dpss(NW), with the parameters in params. fftbins selects the periodic (true) form; a "_symmetric" or "_periodic" suffix overrides it.
func GroupDelay ¶
func GroupDelay(b, a []float64, o *FreqOptions) (w, gd []float64, err error)
GroupDelay returns the group delay, in samples, of the digital filter b/a (scipy.signal.group_delay). Where the delay is singular it is set to zero.
func Hilbert ¶
func Hilbert(x []float64, n int) ([]complex128, error)
Hilbert returns the analytic signal x + i*H(x), computed in the frequency domain (scipy.signal.hilbert; MATLAB hilbert). n is the FFT length (0 means len(x)).
func IIRNotch ¶
IIRNotch designs a second-order notch (band-reject) filter at frequency w0 with quality factor q (scipy.signal.iirnotch; MATLAB iirnotch). fs == 0 means 2, so that w0 is relative to the Nyquist frequency.
func IIRPeak ¶
IIRPeak designs a second-order peaking (band-pass) filter (scipy.signal.iirpeak; MATLAB iirpeak).
func ISTFT ¶
func ISTFT(z [][]complex128, o *ISTFTOptions) (t, x []float64, err error)
ISTFT inverts STFT by weighted overlap-add (scipy.signal.istft).
func KaiserAtten ¶
KaiserAtten returns the attenuation in dB of a Kaiser-window FIR filter with numtaps taps and a transition width relative to Nyquist (scipy.signal.kaiser_atten).
func KaiserBeta ¶
KaiserBeta returns the Kaiser window shape parameter for a given stopband attenuation a in dB (scipy.signal.kaiser_beta).
func KaiserOrd ¶
KaiserOrd returns the number of taps and the Kaiser beta needed for a ripple (attenuation) of the given dB and a transition width relative to Nyquist (scipy.signal.kaiserord).
func LFilter ¶
LFilter filters x with the IIR or FIR filter b/a using the direct form II transposed structure (scipy.signal.lfilter; MATLAB filter). zi, if not nil, holds the initial state (length max(len(a), len(b))-1), and the final state zf is returned so that long signals can be filtered in pieces.
func LFilterIC ¶
LFilterIC constructs the initial state of lfilter for given past outputs y and inputs x (most recent first), scipy.signal.lfiltic. x may be nil (zero input history).
func LFilterZI ¶
LFilterZI returns the initial state of the filter b/a for a step input of unit amplitude: the state in which a constant input of 1 gives a constant output (scipy.signal.lfilter_zi).
func LP2BP ¶
LP2BP transforms a lowpass prototype b/a to a bandpass centred on wo with bandwidth bw (scipy.signal.lp2bp).
func LP2BS ¶
LP2BS transforms a lowpass prototype b/a to a bandstop centred on wo with bandwidth bw (scipy.signal.lp2bs).
func LP2HP ¶
LP2HP transforms a lowpass prototype b/a to a highpass with cutoff wo (scipy.signal.lp2hp).
func LP2LP ¶
LP2LP transforms a lowpass prototype b/a to a lowpass with cutoff wo (scipy.signal.lp2lp).
func Lombscargle ¶
func Lombscargle(x, y, freqs []float64, o *LombOptions) ([]float64, error)
Lombscargle computes the Lomb–Scargle periodogram of the unevenly sampled y(x) at the angular frequencies freqs (scipy.signal.lombscargle).
func LombscargleAmplitude ¶
func LombscargleAmplitude(x, y, freqs []float64, o *LombOptions) ([]complex128, error)
LombscargleAmplitude is Lombscargle returning the complex best-fit amplitude and phase a + ib, rotated by the phase offset (normalize='amplitude').
func Normalize ¶
Normalize scales the transfer function b/a so that a[0] == 1, trims the leading zeros of a and the leading numerator coefficients that are all below 1e-14 (keeping at least one), like scipy.signal.normalize.
func OAConvolve ¶
OAConvolve convolves a and b by the overlap-add method, which is faster than FFTConvolve when one input is much longer than the other (scipy.signal.oaconvolve).
func PeakProminences ¶
func PeakProminences(x []float64, peaks []int, wlen float64) (prom []float64, left, right []int, err error)
PeakProminences calculates the prominence of each peak: its height above the higher of the two lowest contours towards the next higher peaks (scipy.signal.peak_prominences). wlen <= 1 means the whole signal.
func PeakWidths ¶
func PeakWidths(x []float64, peaks []int, relHeight float64, prom []float64, left, right []int) (widths, heights, leftIP, rightIP []float64, err error)
PeakWidths calculates the width of each peak at relHeight times its prominence below the peak (scipy.signal.peak_widths). The prominence data are those of PeakProminences.
func Periodogram ¶
func Periodogram(x []float64, o *SpectralOptions) (f, p []float64, err error)
Periodogram estimates the power spectral density of x from one windowed FFT (scipy.signal.periodogram; MATLAB periodogram). The default window is rectangular.
func Remez ¶
func Remez(numtaps int, bands, desired []float64, o *RemezOptions) ([]float64, error)
Remez designs an optimal equiripple FIR filter with the Parks–McClellan exchange algorithm (scipy.signal.remez; MATLAB firpm). bands holds pairs of band edges between 0 and Fs/2, desired the gain in each band.
func Resample ¶
func Resample(x []float64, num int, o *ResampleOptions) ([]float64, error)
Resample resamples x to num samples using the FFT, assuming x is periodic (scipy.signal.resample). It is best for periodic signals; use ResamplePoly otherwise.
func ResamplePoly ¶
func ResamplePoly(x []float64, up, down int, o *ResamplePolyOptions) ([]float64, error)
ResamplePoly resamples x by the rational factor up/down with a polyphase FIR filter (scipy.signal.resample_poly; MATLAB resample). The filter is linear phase and the output is aligned with the input.
Example ¶
package main
import (
"fmt"
"github.com/go-dsp/signal"
)
func main() {
x := make([]float64, 100)
for i := range x {
x[i] = float64(i)
}
y, _ := signal.ResamplePoly(x, 3, 2, nil)
fmt.Println(len(y))
}
Output: 150
func Roots ¶
func Roots(p []float64) ([]complex128, error)
Roots returns the roots of the polynomial p[0]*x^n + ... + p[n], like numpy.roots: the eigenvalues of the companion matrix (balanced, reduced by the shifted QR algorithm). Leading zeros are dropped and trailing zeros give exact zero roots. Roots of a real polynomial come in conjugate pairs.
The order of the returned roots is unspecified.
func SOSFilt ¶
SOSFilt filters x with a cascade of second-order sections (scipy.signal.sosfilt). zi, if not nil, holds the initial state of each section (len(sos) rows of two values); the final state is returned.
func SOSFiltFilt ¶
func SOSFiltFilt(sos SOS, x []float64, o *FiltFiltOptions) ([]float64, error)
SOSFiltFilt is the zero-phase forward-backward filter for second-order sections (scipy.signal.sosfiltfilt).
func SOSFiltZI ¶
SOSFiltZI returns the initial state of each section for a unit step input (scipy.signal.sosfilt_zi).
func SOSFreqz ¶
func SOSFreqz(sos SOS, o *FreqOptions) (w []float64, h []complex128, err error)
SOSFreqz returns the frequency response of a cascade of sections (scipy.signal.sosfreqz).
func STFT ¶
func STFT(x []float64, o *STFTOptions) (f, t []float64, z [][]complex128, err error)
STFT computes the short-time Fourier transform of x (scipy.signal.stft; legacy API): Z[f][t] with the default Hann window of 256 samples, 50% overlap, zero boundary extension and padding, scaled as a spectrum.
func Spectrogram ¶
func Spectrogram(x []float64, o *SpectralOptions, mode SpectrogramMode) (f, t []float64, s [][]float64, err error)
Spectrogram computes a spectrogram of x from consecutive Fourier transforms (scipy.signal.spectrogram; MATLAB spectrogram): S[f][t], with the default Tukey window (alpha 0.25) and Nperseg/8 overlap.
func Upfirdn ¶
Upfirdn upsamples x by up (inserting zeros), filters with h, and downsamples by down, computing only the samples that are kept (scipy.signal.upfirdn). mode and cval define the signal beyond its ends.
func Welch ¶
func Welch(x []float64, o *SpectralOptions) (f, p []float64, err error)
Welch estimates the power spectral density of x by Welch's method of averaged, windowed, overlapping periodograms (scipy.signal.welch; MATLAB pwelch).
Example ¶
package main
import (
"fmt"
"math"
"github.com/go-dsp/signal"
)
func main() {
x := make([]float64, 4096)
for i := range x {
x[i] = math.Sin(2 * math.Pi * 100 * float64(i) / 1000) // 100 Hz at fs = 1000 Hz
}
f, p, _ := signal.Welch(x, &signal.SpectralOptions{Fs: 1000, Nperseg: 500})
best := 0
for i := range p {
if p[i] > p[best] {
best = i
}
}
fmt.Printf("peak at %.0f Hz\n", f[best])
}
Output: peak at 100 Hz
Types ¶
type BesselNorm ¶
type BesselNorm int
BesselNorm selects the frequency normalisation of the Bessel prototype.
const ( // BesselPhase (the default) matches the phase to half of the asymptotic // shift at 1 rad/s; the asymptotes are those of a Butterworth filter. BesselPhase BesselNorm = iota // BesselDelay normalises the low-frequency group delay to 1 s. BesselDelay // BesselMag puts the -3 dB magnitude point at 1 rad/s. BesselMag )
type ConvMethod ¶
type ConvMethod int
ConvMethod selects the algorithm of Convolve and Correlate.
const ( // ConvAuto picks the faster of direct and FFT (scipy's choose_conv_method). ConvAuto ConvMethod = iota // ConvDirect sums the products directly. ConvDirect // ConvFFT uses the FFT. ConvFFT )
func ChooseConvMethod ¶
func ChooseConvMethod(n1, n2 int, mode ConvMode) ConvMethod
ChooseConvMethod returns the faster method for convolving inputs of length n1 and n2, by SciPy's fitted cost model (scipy.signal.choose_conv_method without measuring).
type DPSSNorm ¶
type DPSSNorm int
DPSSNorm selects the normalisation of discrete prolate spheroidal sequences.
const ( // DPSSApproximate (the default for a single window) scales the peak to 1 // and corrects for even lengths by an analytic approximation. DPSSApproximate DPSSNorm = iota // DPSSSubsample scales to 1 at the interpolated centre of even lengths. DPSSSubsample // DPSSNorm2 normalises to unit energy (the default for several windows). DPSSNorm2 )
type DecimateOptions ¶
type DecimateOptions struct {
// N is the filter order (default 8 for IIR, 20*q for FIR, where it is the
// number of taps minus one).
N int
// FIR uses a Hamming-window FIR filter instead of a Chebyshev type I IIR.
FIR bool
// NoZeroPhase filters once instead of forward and backward.
NoZeroPhase bool
}
DecimateOptions are the optional parameters of Decimate.
type DetrendType ¶
type DetrendType int
DetrendType selects what is removed from each segment before analysis.
const ( // DetrendDefault is the default of the function it is passed to: // constant for Welch, CSD, Periodogram and Spectrogram, none for STFT. DetrendDefault DetrendType = iota // DetrendConstant removes the mean. DetrendConstant // DetrendLinear removes the least-squares line. DetrendLinear // DetrendNone leaves the data alone. DetrendNone )
type FiltFiltOptions ¶
type FiltFiltOptions struct {
PadType PadType
// PadLen is the number of samples to extend at each end; zero means the
// default of 3*max(len(a), len(b)). Use PadNone for no padding.
PadLen int
Method FiltMethod
// IRLen is the impulse response length used by FiltGust (0: the whole
// signal).
IRLen int
}
FiltFiltOptions are the optional parameters of FiltFilt.
type FiltMethod ¶
type FiltMethod int
FiltMethod selects the way FiltFilt handles the ends of the signal.
const ( // FiltPad pads the signal (default). FiltPad FiltMethod = iota // FiltGust uses Gustafsson's method, choosing initial conditions that // make the forward-backward and backward-forward results agree. FiltGust )
type FilterType ¶
type FilterType int
FilterType is the family of an IIR design.
const ( Butterworth FilterType = iota Chebyshev1 Chebyshev2 Elliptic Bessel )
type FindPeaksOptions ¶
type FindPeaksOptions struct {
// Height is the required peak height.
Height *Interval
// Threshold is the required vertical distance to the neighbouring samples.
Threshold *Interval
// Distance is the required minimal horizontal distance (in samples, >= 1)
// between neighbouring peaks; the smaller peaks are removed first.
Distance float64
// Prominence is the required prominence of the peaks.
Prominence *Interval
// Width is the required width at RelHeight.
Width *Interval
// Wlen limits the window (in samples, > 1) in which prominence is evaluated.
Wlen float64
// RelHeight is the fraction of the prominence at which widths are measured
// (default 0.5; widths at 0 are not available, use a tiny value).
RelHeight float64
// PlateauSize is the required size of a flat peak.
PlateauSize *Interval
}
FindPeaksOptions are the optional conditions of FindPeaks; a nil condition is not applied.
type FirPass ¶
type FirPass int
FirPass selects the passband layout of Firwin, like the pass_zero argument of scipy.signal.firwin.
const ( // FirPassZeroTrue: the response at DC is passed (pass_zero=True). FirPassZeroTrue FirPass = iota // FirPassZeroFalse: the response at DC is blocked (pass_zero=False). FirPassZeroFalse // FirLowpass: a single cutoff, DC passed. FirLowpass // FirHighpass: a single cutoff, DC blocked. FirHighpass // FirBandpass: at least two cutoffs, DC blocked. FirBandpass // FirBandstop: at least two cutoffs, DC passed. FirBandstop )
type Firwin2Options ¶
type Firwin2Options struct {
// Nfreqs is the size of the interpolation grid (default 1 + 2^ceil(log2(numtaps))).
Nfreqs int
// Window defaults to Hamming; NoWindow disables windowing.
Window Window
NoWindow bool
// Antisymmetric designs a type III/IV filter (Hilbert transformers,
// differentiators).
Antisymmetric bool
// Fs is the sampling frequency (default 2).
Fs float64
}
Firwin2Options are the optional parameters of Firwin2.
type FirwinOptions ¶
type FirwinOptions struct {
// Width, if positive, is the approximate transition width in the units of
// Fs; it selects a Kaiser window and overrides Window.
Width float64
// Window defaults to Hamming.
Window Window
// PassZero selects how the cutoffs are read (default FirPassZeroTrue).
PassZero FirPass
// NoScale disables scaling the passband gain to exactly 1.
NoScale bool
// Fs is the sampling frequency (default 2: cutoffs relative to Nyquist=1).
Fs float64
}
FirwinOptions are the optional parameters of Firwin.
type FreqOptions ¶
type FreqOptions struct {
// N is the number of frequencies when W is nil (default 512 for digital
// responses, 200 for analog ones).
N int
// W lists the frequencies to evaluate, in the units of Fs (rad/s for
// analog responses, where Fs does not apply).
W []float64
// Whole evaluates around the whole unit circle, [0, 2π), instead of
// the upper half [0, π).
Whole bool
// Fs is the sampling frequency; zero means 2π, so that frequencies are
// in rad/sample.
Fs float64
// IncludeNyquist includes the Nyquist frequency when Whole is false
// and N points are generated.
IncludeNyquist bool
}
FreqOptions selects the frequencies of a response. The zero value means the defaults of scipy.signal.freqz: 512 points on [0, π) in rad/sample.
type IIROptions ¶
type IIROptions struct {
// Rp is the maximum passband ripple in dB (Chebyshev I, elliptic).
Rp float64
// Rs is the minimum stopband attenuation in dB (Chebyshev II, elliptic).
Rs float64
// Analog designs an analog filter, with Wn in rad/s.
Analog bool
// Fs is the sampling frequency of a digital design: Wn is then in the
// same units. Zero means Wn is normalised to the Nyquist frequency (1).
Fs float64
// Bessel selects the Bessel normalisation (default BesselPhase).
Bessel BesselNorm
}
IIROptions holds the optional parameters of an IIR design.
type ISTFTOptions ¶
type ISTFTOptions struct {
SpectralOptions
// TwoSidedInput says z holds the full spectrum rather than 0..Fs/2.
TwoSidedInput bool
// NoBoundary says the forward transform used no boundary extension.
NoBoundary bool
}
ISTFTOptions are the parameters of ISTFT.
type LombOptions ¶
type LombOptions struct {
// Weights are non-negative sample weights (default uniform).
Weights []float64
// Normalize scales the periodogram by the signal variance (range [0, 1]).
Normalize bool
// FloatingMean fits a constant offset together with the sinusoid.
FloatingMean bool
}
LombOptions are the optional parameters of Lombscargle.
type PadMode ¶
type PadMode string
PadMode is the signal extension used by Upfirdn and ResamplePoly beyond the ends of the input.
const ( PadModeConstant PadMode = "constant" PadModeEdge PadMode = "edge" PadModeWrap PadMode = "wrap" PadModeSymmetric PadMode = "symmetric" PadModeReflect PadMode = "reflect" PadModeAntisymmetric PadMode = "antisymmetric" PadModeAntireflect PadMode = "antireflect" // PadModeSmooth extends by the slope of the last two points at each end. PadModeSmooth PadMode = "smooth" // PadModeLine extends by the line through the first and last points. PadModeLine PadMode = "line" )
Extension modes; the first group are those of numpy.pad.
type Pairing ¶
type Pairing int
Pairing selects how ZPK2SOS pairs poles with zeros.
const ( // PairNearest (the default for digital filters) pairs each pole nearest // the unit circle with the closest zero and pads to an even order. PairNearest Pairing = iota // PairKeepOdd keeps the odd section last, like PairNearest but without // padding the pole and zero counts to an even number. PairKeepOdd // PairMinimal gives sections of the lowest necessary order; it is the // only valid choice for analog filters. PairMinimal )
type PeakProperties ¶
type PeakProperties struct {
PlateauSizes, LeftEdges, RightEdges []int
PeakHeights []float64
LeftThresholds, RightThresholds []float64
Prominences []float64
LeftBases, RightBases []int
Widths, WidthHeights []float64
LeftIPs, RightIPs []float64
}
PeakProperties holds the properties computed for the peaks found; a slice is nil when the condition that computes it was not requested.
func FindPeaks ¶
func FindPeaks(x []float64, o *FindPeaksOptions) (peaks []int, props PeakProperties, err error)
FindPeaks finds the local maxima of x satisfying the conditions of o (scipy.signal.find_peaks; MATLAB findpeaks). A flat peak is reported at its middle sample. Conditions apply in the order plateau size, height, threshold, distance, prominence, width.
Example ¶
package main
import (
"fmt"
"github.com/go-dsp/signal"
)
func main() {
peaks, props, _ := signal.FindPeaks([]float64{0, 1, 0, 2, 0, 1.5, 0}, &signal.FindPeaksOptions{Height: signal.AtLeast(1.2)})
fmt.Println(peaks, props.PeakHeights)
}
Output: [3 5] [2 1.5]
type RemezOptions ¶
type RemezOptions struct {
// Weight has one relative weight per band (default all 1).
Weight []float64
// Type defaults to RemezBandpass.
Type RemezType
// MaxIter defaults to 25.
MaxIter int
// GridDensity defaults to 16.
GridDensity int
// Fs is the sampling frequency (default 1).
Fs float64
}
RemezOptions are the optional parameters of Remez.
type ResampleOptions ¶
type ResampleOptions struct {
// Window, if not nil, weights the spectrum (a frequency-domain window,
// generated for len(x) points and centred on DC like SciPy's).
Window Window
// WindowFreq, if not nil, is the spectral weighting in FFT order.
WindowFreq []float64
}
ResampleOptions are the optional parameters of Resample.
type ResamplePolyOptions ¶
type ResamplePolyOptions struct {
// Window designs the anti-aliasing filter (default Kaiser with beta 5).
Window Window
// Taps, if not nil, is the FIR filter to use instead.
Taps []float64
// PadType is how the signal is extended: "mean", "median", "minimum" or
// "maximum" (the signal minus that value is filtered, then it is added
// back), or one of the PadMode values (default PadModeConstant).
PadType string
// Cval is the value for PadModeConstant.
Cval float64
}
ResamplePolyOptions are the optional parameters of ResamplePoly.
type SOS ¶
type SOS [][6]float64
SOS is a cascade of second-order sections, each [b0 b1 b2 a0 a1 a2]; the digital form is b0 + b1 z^-1 + b2 z^-2 over a0 + a1 z^-1 + a2 z^-2 with a0 == 1. The gain is carried by the first section.
type STFTOptions ¶
type STFTOptions struct {
SpectralOptions
// Boundary extends the signal at both ends so that the first window is
// centred on the first sample: "zeros" (the default when empty and
// NoBoundary is false), "even", "odd" or "constant".
Boundary string
// NoBoundary disables the extension.
NoBoundary bool
// NoPad disables zero padding to a whole number of segments.
NoPad bool
}
STFTOptions are the parameters of STFT beyond SpectralOptions.
type Scaling ¶
type Scaling int
Scaling selects the units of a spectrum.
const ( // ScaleDefault is the default of the function it is passed to: density for // Welch, CSD, Periodogram and Spectrogram, spectrum for STFT and ISTFT. ScaleDefault Scaling = iota // ScaleDensity gives a power spectral density (units^2/Hz). ScaleDensity // ScaleSpectrum gives a power spectrum (units^2). ScaleSpectrum )
type SpectralOptions ¶
type SpectralOptions struct {
// Fs is the sampling frequency (default 1).
Fs float64
// Window generates the window (periodic form) of Nperseg samples;
// WindowTaps, if not nil, is used instead and sets Nperseg.
Window Window
WindowTaps []float64
// Nperseg is the length of each segment (default 256, or the signal
// length if shorter).
Nperseg int
// Noverlap is the number of overlapping samples (default depends on the
// estimator: Nperseg/2 for Welch, Nperseg/8 for Spectrogram).
Noverlap *int
// Nfft is the FFT length, at least Nperseg (default Nperseg).
Nfft int
// Detrend is applied to each segment.
Detrend DetrendType
// Scaling is the density (default) or spectrum.
Scaling Scaling
// TwoSided returns both halves of the spectrum instead of 0..Fs/2.
TwoSided bool
// Average is used by Welch, CSD and Coherence.
Average Average
}
SpectralOptions are the optional parameters of the spectral estimators. The zero value is SciPy's defaults for the function it is passed to.
type SpectrogramMode ¶
type SpectrogramMode int
SpectrogramMode selects what Spectrogram returns.
const ( // SpecPSD is the power spectral density or spectrum of each segment. SpecPSD SpectrogramMode = iota // SpecMagnitude is the magnitude of the STFT. SpecMagnitude // SpecAngle is the angle of the STFT in radians. SpecAngle // SpecPhase is the unwrapped angle along time. SpecPhase )
type Window ¶
Window generates an n-point window: symmetric when sym is true (for filter design), periodic otherwise (for spectral analysis, the DFT-even form of get_window's default). A window that cannot be generated for the given parameters returns nil.
func Exponential ¶
Exponential is the Poisson window exp(-|n - center|/tau). A NaN center means the middle of the window; as in SciPy an explicit center is only allowed for a periodic window (sym false), otherwise nil is returned.
func GeneralCosine ¶
GeneralCosine is the sum of cosines sum_k a[k] cos(k*x), x in [-π, π] (scipy.signal.windows.general_cosine).
func GeneralGaussian ¶
GeneralGaussian is exp(-0.5 |n/sig|^(2p)); p = 1 is Gaussian.
func GeneralHamming ¶
GeneralHamming is alpha - (1-alpha) cos(2πn/(M-1)); alpha 0.54 is Hamming and 0.5 Hann.
type ZPK ¶
type ZPK struct {
Z, P []complex128
K float64
}
ZPK is a filter as zeros, poles and gain. Roots of a real filter are real or come in conjugate pairs. In the digital case the transfer function is H(z) = K * prod(z - Z[i]) / prod(z - P[i]); in the analog case the same with s.
func BesselAP ¶
func BesselAP(n int, norm BesselNorm) (ZPK, error)
BesselAP returns the analog Bessel (Thomson) lowpass prototype of order n (scipy.signal.besselap).
func BesselFilter ¶
func BesselFilter(n int, wn []float64, bt BandType, norm BesselNorm, o *IIROptions) (ZPK, error)
BesselFilter designs a Bessel/Thomson filter with the given normalisation.
func BilinearZPK ¶
BilinearZPK maps an analog filter to a digital one with the bilinear transform at sampling frequency fs (scipy.signal.bilinear_zpk). Zeros at infinity go to the Nyquist frequency.
func ButtAP ¶
ButtAP returns the zeros, poles and gain of the analog Butterworth lowpass prototype of order n, with cutoff 1 rad/s (scipy.signal.buttap).
func Butter ¶
Butter designs a Butterworth filter (scipy.signal.butter).
Example ¶
package main
import (
"fmt"
"github.com/go-dsp/signal"
)
func main() {
z, _ := signal.Butter(2, []float64{0.2}, signal.Lowpass, nil)
b, a, _ := z.TF()
fmt.Printf("b = %.6f\na = %.6f\n", b, a)
}
Output: b = [0.067455 0.134911 0.067455] a = [1.000000 -1.142981 0.412802]
func Cheb1AP ¶
Cheb1AP returns the analog Chebyshev type I lowpass prototype of order n with rp dB of passband ripple, passband edge 1 rad/s (scipy.signal.cheb1ap).
func Cheb2AP ¶
Cheb2AP returns the analog Chebyshev type II lowpass prototype of order n with rs dB of stopband attenuation, stopband edge 1 rad/s (scipy.signal.cheb2ap).
func EllipAP ¶
EllipAP returns the analog elliptic (Cauer) lowpass prototype of order n with rp dB of passband ripple and rs dB of stopband attenuation, passband edge 1 rad/s (scipy.signal.ellipap).
func IIRDesign ¶
func IIRDesign(wp, ws []float64, gpass, gstop float64, ft FilterType, o *IIROptions) (ZPK, error)
IIRDesign designs the lowest-order filter of the given family meeting a passband/stopband specification (scipy.signal.iirdesign): wp and ws are the passband and stopband edges (one or two each), gpass the maximum passband loss and gstop the minimum stopband attenuation in dB. Bessel has no order selection.
func IIRFilter ¶
func IIRFilter(n int, wn []float64, bt BandType, ft FilterType, o *IIROptions) (ZPK, error)
IIRFilter designs an order-n IIR filter of the given family and band layout (scipy.signal.iirfilter). wn holds one critical frequency for a lowpass or highpass filter and two for a bandpass or bandstop filter; for Chebyshev I the frequency is the edge of the ripple band, for Chebyshev II the start of the stopband. The result is zeros, poles and gain; use TF or SOS to convert (prefer SOS above order 8).
func LP2BPZPK ¶
LP2BPZPK transforms a lowpass prototype to a bandpass filter centred on wo with bandwidth bw (scipy.signal.lp2bp_zpk).
func LP2BSZPK ¶
LP2BSZPK transforms a lowpass prototype to a bandstop filter centred on wo with bandwidth bw (scipy.signal.lp2bs_zpk).
func LP2HPZPK ¶
LP2HPZPK transforms a lowpass prototype to a highpass filter with cutoff wo (scipy.signal.lp2hp_zpk).
func LP2LPZPK ¶
LP2LPZPK transforms a lowpass prototype to a lowpass filter with cutoff wo (scipy.signal.lp2lp_zpk).