waveform

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: 8 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 waveform generates test signals, matching scipy.signal and matlab waveforms. It's checked against SciPy, MATLAB and exact values from mpmath, measurements in docs/accuracy.md.

t, err := waveform.Timebase(96000, 48000) // 2 seconds at 48kHz
x, err := waveform.Chirp(t, 20, 2, 20e3, waveform.Logarithmic()) // a 20Hz to 20kHz sweep

Sample times

Each waveform takes t, an array with the time of each sample, and returns an array of the values at the corresponding index. For a uniform signal at rate fs, Timebase(n, fs) gives t[i] = i/fs, but t can start anywhere, run negative, irregular, or discontinuous.

Exceptions to this general rule:

  • UnitImpulse takes a length and an index instead, as it's a sequence,
  • Sinc and Diric take x, as they're functions rather than signals,
  • the noise functions take a length n, as their samples are random rather than functions of t.

Waveforms

tukey                SciPy                         MATLAB
Chirp                chirp                         chirp
SweepPoly            sweep_poly
Tone
Square               square                        square
Sawtooth             sawtooth                      sawtooth

Square and Sawtooth have a period of 2π in t, same as SciPy and MATLAB, so pass 2π·f·t for a frequency f. Tone is a cosine at f, which SciPy and MATLAB leave to cos(2*pi*f*t).

Pulses

tukey                SciPy                         MATLAB
GaussPulse           gausspulse                    gauspuls
GaussPulseCutoff     gausspulse("cutoff")          gauspuls("cutoff")
RectPuls                                           rectpuls
TriPuls                                            tripuls
GMonoPuls                                          gmonopuls
UnitImpulse          unit_impulse

Functions

tukey                SciPy                         MATLAB
Sinc                 numpy.sinc                    sinc
Diric                scipy.special.diric           diric

Noise

tukey                SciPy                         MATLAB
WhiteNoise           Generator.standard_normal     randn, dsp.ColoredNoise("white")
ColouredNoise                                      dsp.ColoredNoise("custom")
PinkNoise                                          dsp.ColoredNoise("pink")
BrownNoise                                         dsp.ColoredNoise("brown")
BlueNoise                                          dsp.ColoredNoise("blue")
VioletNoise                                        dsp.ColoredNoise("purple")

ColouredNoise's power spectral density is proportional to 1/f^alpha, for an alpha from -2 to 2, and the four colours are its alphas of 1, 2, -1 and -2. The noise isn't scaled, so its variance depends on alpha, but every colour has about the same level at fs/6. Seed makes any of them repeatable.

Accuracy

The phase of each cosine is computed in cycles in double-double, and its whole cycles are removed before the cosine, which is exact, so a waveform keeps its digits however long it runs.

SciPy and MATLAB take the cosine of the phase in radians, which loses digits as it grows: cos(2*pi*f*t) is 2.9e-7 from exact for 440 Hz at t = 10^6 seconds, and scipy.signal.chirp is 1.8e-10 away over ten seconds of audio. Sinc and Diric reduce their arguments exactly in the same way, where numpy.sinc and scipy.special.diric are up to 3.5e-10 and 1.2e-7 away.

Kasdin's filter coefficients are computed in double-double, so each is correctly rounded, and the noise is within a few ULP of the exact filter applied to the same white noise.

Conventions

Every function is stateless, apart from unseeded noise, which draws from math/rand/v2's global generator: a new slice comes back, inputs are never modified, and all functions are safe for concurrent use. An empty t, or an n of 0, gives an empty slice, never nil. Invalid input returns an error wrapping ErrInvalidLength, ErrInvalidParameter or ErrInvalidOption, so check for one with errors.Is. Sinc can't fail, so it returns no error.

A NaN time gives NaN at that sample. An infinite time gives the waveform's limit where it has one, 0 for the pulses and Sinc, and NaN for Chirp, SweepPoly, Tone, Square, Sawtooth and Diric, which have none.

Options

One Option type serves every waveform, and a waveform given an option that doesn't apply to it returns ErrInvalidOption:

  • Linear, Quadratic, Logarithmic and Hyperbolic choose Chirp's sweep, linear by default, and VertexAtT1 moves Quadratic's vertex from t = 0 to t1.
  • Phase starts Chirp, SweepPoly or Tone at phi degrees, so Phase(-90) gives a sine.
  • Duty sets the fraction of each period in Square's high part, or Sawtooth's rising ramp.
  • Bandwidth and BandwidthLevel set GaussPulse's spectrum, and CutoffLevel the level GaussPulseCutoff finds.
  • Width sets RectPuls's and TriPuls's width, and Skew where TriPuls peaks.
  • Seed makes WhiteNoise and the coloured noise repeatable.
  • Kasdin, KasdinTaps and FFTShaping choose how the noise is coloured, Kasdin by default.

Where tukey differs

  • Duty is a fraction for Square, same as SciPy, where MATLAB's square takes a percentage
  • GaussPulse returns its in-phase part, quadrature part and envelope together, in place of SciPy's retquad and retenv flags
  • GaussPulse and GMonoPuls take fc with no default, where SciPy and MATLAB default to 1 kHz
  • the pulses and Sinc give 0 at an infinite time, their limit, where SciPy, NumPy and MATLAB give NaN
  • Sawtooth at Duty(1) gives 1 for a tiny negative t, the end of the ramp, where SciPy's sawtooth gives NaN
  • RectPuls's edges are exact, -w/2 ≤ t < w/2, where MATLAB's rectpuls sits an ULP to the left
  • TriPuls is closed at both ends, same as MATLAB, so at a Skew of ±1 it keeps its peak of 1 where it jumps
  • UnitImpulse takes its index from the start, where SciPy's unit_impulse also takes "mid", which is n/2, and negative indices, which count from the end
  • Chirp's Hyperbolic and VertexAtT1 and SweepPoly have no MATLAB equivalent, nor RectPuls, TriPuls and GMonoPuls a SciPy one
  • the coloured noise uses Kasdin's filter at full length by default, where MATLAB truncates it, so its spectrum keeps its slope down to the lowest frequency, and KasdinTaps truncates it the same way as MATLAB
  • the same Seed gives different samples to MATLAB's, as the generators differ
  • VioletNoise is MATLAB's "purple", and FFTShaping has no SciPy or MATLAB equivalent

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidLength is a length that's wrong in itself
	ErrInvalidLength = errors.New("waveform: invalid length")
	// ErrInvalidParameter is a value outside its domain.
	ErrInvalidParameter = errors.New("waveform: invalid parameter")
	// ErrInvalidOption is an option that's unknown or doesn't apply.
	ErrInvalidOption = errors.New("waveform: invalid option")
)

Errors returned for invalid input. Each is wrapped with the detail of what was wrong, so check for one with errors.Is. They mean the same in every tukey package.

Functions

func BlueNoise added in v1.2.0

func BlueNoise(n int, opts ...Option) (x []float64, err error)

BlueNoise returns n samples of blue noise, 'half-differentiated' white noise: Gaussian noise whose power spectral density is proportional to f.

x, err := waveform.BlueNoise(48000, waveform.Seed(1))

Methods, each colouring white noise of variance 1:

  • Kasdin (default), a full length causal filter, so a longer n keeps the earlier samples, but starts quiet
  • KasdinTaps(m) (matching MATLAB), fast for a small m, but flattens below about fs/m
  • FFTShaping (fastest), follows f up to fs/2 and loops without a jump, but has nothing at 0 Hz and a new signal for every n

If more than one is given, the last wins. It has about the same level at fs/6 as the other colours. The noise isn't scaled, so its variance isn't 1.

Seed makes it repeatable.

Safe to use concurrently.

Units:

  • n is a count of samples
  • x is dimensionless

Returns:

  • ErrInvalidLength for an n below 0, or a KasdinTaps m below 1
  • ErrInvalidOption for an option not in Seed, Kasdin, KasdinTaps or FFTShaping

Equivalent to:

  • MATLAB dsp.ColoredNoise with Color "blue", which is close to KasdinTaps(256), with different samples

func BrownNoise added in v1.2.0

func BrownNoise(n int, opts ...Option) (x []float64, err error)

BrownNoise returns n samples of brown noise, 'integrated' white noise, a running-sum giving a random walk: Gaussian noise whose power spectral density is proportional to 1/f^2.

x, err := waveform.BrownNoise(48000, waveform.Seed(1))

Methods, each colouring white noise of variance 1:

  • Kasdin (default), a full length causal filter, so a longer n keeps the earlier samples, but starts quiet
  • KasdinTaps(m) (matching MATLAB), fast for a small m, but flattens below about fs/m
  • FFTShaping (fastest), follows 1/f^2 up to fs/2 and loops without a jump, but has nothing at 0 Hz and a new signal for every n

If more than one is given, the last wins. It has about the same level at fs/6 as the other colours. The noise isn't scaled, so its variance grows with time, and it has no steady level.

Seed makes it repeatable.

Safe to use concurrently.

Units:

  • n is a count of samples
  • x is dimensionless

Returns:

  • ErrInvalidLength for an n below 0, or a KasdinTaps m below 1
  • ErrInvalidOption for an option not in Seed, Kasdin, KasdinTaps or FFTShaping

Equivalent to:

  • MATLAB dsp.ColoredNoise with Color "brown", which uses its own filter, with different samples

func Chirp

func Chirp(t []float64, f0, t1, f1 float64, opts ...Option) (x []float64, err error)

Chirp returns cos(2π·φ(t) + phi) at each sample time in t, a cosine whose frequency, the derivative of φ, sweeps from f0 at t = 0 to f1 at t = t1. The sweep is Linear by default, or Quadratic, Logarithmic or Hyperbolic, and carries on past t1 and before 0.

t, err := waveform.Timebase(1000, 1000) // 1 second at 1kHz
x, err := waveform.Chirp(t, 10, 1, 200) // 10 Hz to 200 Hz

The phase φ is in cycles and computed in double-double arithmetic, then its whole cycles removed before the cosine, so a sample is within a few ULP of exact however many cycles have passed. A NaN or infinite time gives NaN at that sample.

Units:

  • t and t1 are in seconds, or any time unit
  • f0 and f1 are in hertz, or cycles per t's unit
  • x is dimensionless, between -1 and 1

Returns:

  • ErrInvalidParameter for a NaN or infinite f0, t1, f1 or Phase, a t1 at or below 0, an f0 or f1 of 0 or of opposite signs with Logarithmic, or an f0 or f1 of 0 with Hyperbolic.
  • ErrInvalidOption for VertexAtT1 without Quadratic, or an option other than Linear, Quadratic, Logarithmic, Hyperbolic, VertexAtT1 or Phase.

Equivalent to:

  • scipy.signal.chirp(t, f0, t1, f1, method, phi, vertex_zero)
  • MATLAB chirp(t, f0, t1, f1, method, phi), which has no hyperbolic sweep, and no quadratic with its vertex at t1

func ColouredNoise added in v1.2.0

func ColouredNoise(n int, alpha float64, opts ...Option) (x []float64, err error)

ColouredNoise returns n samples of Gaussian noise whose power spectral density is proportional to 1/f^alpha.

x, err := waveform.ColouredNoise(48000, 0.5, waveform.Seed(1))

Alphas:

  • 0 white
  • 1 pink
  • 2 brown
  • -1 blue
  • -2 violet

Methods, each colouring white noise of variance 1:

  • Kasdin (default), a full length causal filter, so a longer n keeps the earlier samples, but starts quiet
  • KasdinTaps(m) (matching MATLAB), fast for a small m, but flattens below about fs/m
  • FFTShaping (fastest), follows 1/f^alpha up to fs/2 and loops without a jump, but has nothing at 0 Hz and a new signal for every n

If more than one is given, the last wins. Every alpha has about the same level at fs/6, so alpha tilts the spectrum about that point. The noise isn't scaled, so its variance depends on alpha, and from an alpha of 1 it has no steady level.

Seed makes it repeatable.

Safe to use concurrently.

Units:

  • n is a count of samples
  • alpha is dimensionless, the power that 1/f is raised to
  • x is dimensionless

Returns:

  • ErrInvalidLength for an n below 0, or a KasdinTaps m below 1
  • ErrInvalidParameter for an alpha that isn't between -2 and 2
  • ErrInvalidOption for an option not in Seed, Kasdin, KasdinTaps or FFTShaping

Equivalent to:

  • MATLAB dsp.ColoredNoise with Color "custom" and InverseFrequencyPower alpha, which is close to KasdinTaps(64) for an alpha above 0 and KasdinTaps(256) below, with different samples

func Diric

func Diric(x []float64, n int) (y []float64, err error)

Diric returns the Dirichlet function of order n at each point in x, sin(n·x/2)/(n·sin(x/2)), and its limit, ±1, where sin(x/2) is 0. It's the periodic sinc, the DTFT of an n-point boxcar divided by n, less its linear phase. Its period is 2π for an odd n and 4π for an even n.

y, err := waveform.Diric(x, 8)

x/2 is reduced by π in double-double, to x/2 = k·π + d, which is exact to about 10^-23, and the function is (-1)^(k·(n-1))·sin(n·d)/(n·sin(d)), so each value is within 2 ULP of exact, including at the peaks, x = 2π·k. scipy.special.diric rounds n·x/2 before the sine, and returns exactly ±1 where |sin(x/2)| < 1e-7: it's 2.4e-9 from exact near its peaks, and 1.2e-7 near x = 10^6. From |x| = 2^30, the sines are taken directly, with math.Sin's own exact reduction. A NaN or infinite x gives NaN at that point.

Units:

  • x radians
  • n is a count, the number of points in the boxcar
  • y dimensionless, from -1 to 1

Returns:

  • ErrInvalidParameter for an n below 1

Equivalent to:

  • scipy.special.diric(x, n)
  • matlab diric(x, n)

func GMonoPuls

func GMonoPuls(t []float64, fc float64) (x []float64, err error)

GMonoPuls returns a Gaussian monopulse at each sample time in t, with centre frequency fc: the first derivative of a Gaussian, scaled to peak at 1

y = 2√e·π·fc·t·exp(-2·(π·fc·t)²)

It's -1 at t = -1/(2π·fc), 0 at t = 0, and 1 at t = 1/(2π·fc), and its spectrum peaks at fc.

x, err := waveform.GMonoPuls(t, 2e9) // a 2GHz ultra-wideband pulse

With u = π·fc·t in double-double, it's 2u·exp(1/2 - 2u²), so √e joins the exponent, and each sample is within an ULP of exact, except where it's subnormal. A NaN time gives NaN at that sample, and an infinite time gives 0, the limit of the pulse.

Units:

  • t seconds
  • fc hertz
  • x dimensionless, from -1 to 1

Returns:

  • ErrInvalidParameter for an fc that isn't above 0 and finite

Equivalent to:

  • matlab gmonopuls(t, fc)
  • scipy has no equivalent

func GaussPulseCutoff

func GaussPulseCutoff(fc float64, opts ...Option) (tc float64, err error)

GaussPulseCutoff returns the time after t= 0 where GaussPulse's envelope falls to CutoffLevel, -60dB by default, for the same fc, Bandwidth and BandwidthLevel. The pulse is symmetric, so it's below that level outside -tc to tc.

tc, err:= waveform.GaussPulseCutoff(50e3, waveform.Bandwidth(0.6), waveform.CutoffLevel(-40))

It's tc= ln(10)· √(tpr· bwr)/ (10π· fc· bw), with tpr the CutoffLevel and bwr the BandwidthLevel, computed in double-double, so it's within an ULP of exact.

Units:

  • fc hertz, above 0
  • tc seconds

Returns:

  • ErrInvalidParameter for: an fc that isn't above 0 and finite, a Bandwidth that isn't above 0 and finite, a BandwidthLevel that isn't below 0 and finite, or, a CutoffLevel that isn't below 0 and finite.
  • ErrInvalidOption for an option not in Bandwidth, BandwidthLevel or CutoffLevel

Equivalent to:

  • scipy.signal.gausspulse("cutoff", fc, bw, bwr, tpr)
  • MATLAB gauspuls("cutoff", fc, bw, bwr, tpr)

func PinkNoise added in v1.2.0

func PinkNoise(n int, opts ...Option) (x []float64, err error)

PinkNoise returns n samples of pink noise, 'half-integrated' white noise with equal power in every octave: Gaussian noise whose power spectral density is proportional to 1/f.

x, err := waveform.PinkNoise(48000, waveform.Seed(1))

Methods, each colouring white noise of variance 1:

  • Kasdin (default), a full length causal filter, so a longer n keeps the earlier samples, but starts quiet
  • KasdinTaps(m) (matching MATLAB), fast for a small m, but flattens below about fs/m
  • FFTShaping (fastest), follows 1/f up to fs/2 and loops without a jump, but has nothing at 0 Hz and a new signal for every n

If more than one is given, the last wins. It has about the same level at fs/6 as the other colours. The noise isn't scaled, so its variance isn't 1, and it has no steady level.

Seed makes it repeatable.

Safe to use concurrently.

Units:

  • n is a count of samples
  • x is dimensionless

Returns:

  • ErrInvalidLength for an n below 0, or a KasdinTaps m below 1
  • ErrInvalidOption for an option not in Seed, Kasdin, KasdinTaps or FFTShaping

Equivalent to:

  • MATLAB dsp.ColoredNoise with Color "pink", which uses its own filter, with different samples

func RectPuls

func RectPuls(t []float64, opts ...Option) (x []float64, err error)

RectPuls returns a rectangular pulse centred on t = 0 at each sample time in t: 1 for -w/2 ≤ t < w/2, and 0 elsewhere, with Width w, 1 second by default. It's open on the right, so at the default width t = -0.5 gives 1 and t = 0.5 gives 0.

x, err := waveform.RectPuls(t, waveform.Width(1e-3)) // a 1ms pulse

w/2 is exact for any normal Width, so every sample is too. A NaN time gives NaN at that sample.

Units:

  • t seconds
  • x dimensionless, 0 or 1

Returns:

  • ErrInvlaidParameter for a Width that isn't above 0 and finite.
  • ErrInvalidOption for an option other than Width.

Equivalent to:

  • matlab rectpuls(t, w)
  • scipy no equiv.

func Sawtooth

func Sawtooth(t []float64, opts ...Option) (x []float64, err error)

Sawtooth returns a sawtooth wave of period 2π at each sample time in t: rising from -1 to 1 over the first duty of each period, then falling back to -1 over the rest. Its duty is 1 by default, a rising ramp, or set with Duty, where 0 is a falling ramp and 0.5 a triangle.

x, err := waveform.Sawtooth(t, waveform.Duty(0.5)) // a triangle wave

For a frequency f in hertz, pass `2* math.Pi* f* t`. t is reduced modulo the float64 2π, same as SciPy, so a t of 2π·k built from math.Pi is the start of a cycle. The ramps are computed in double-double from the exact remainder, so each sample is within an ULP of exact. A NaN or infinite time gives NaN at that sample.

Units:

  • t is in radians
  • x is dimensionless, from -1 to 1

Returns:

  • ErrInvalidParameter for a Duty outside 0 and 1, or NaN
  • ErrInvalidOption for an option other than Duty

Equivalent to:

  • scipy.signal.sawtooth(t, width), which returns NaN at width 1 for a tiny negative t, where t% 2π rounds up to 2π
  • matlab sawtooth(t, xmax), whose rem puts a t within round-off of 2π·k at the start of a cycle

func Sinc

func Sinc(x []float64) (y []float64)

Sinc returns the normalised sinc at each point in x, sin(π·x)/(π·x), and 1 at x= 0.

y:= waveform.Sinc(x)

The sine is taken with x's whole half-cycles removed first, which is exact, and divided by π·x in double-double, so all values retain accurancy when x grows large. numpy.sinc rounds π·x before the sine, and loses digits as x grows: it's 3.5e-10 from exact, relative, near x= 10^6. Every float64 from 2^52 up is an integer, a zero of sinc, so Sinc is 0 there, and at ±∞ , its limit. A NaN gives NaN.

Units:

  • x dimensionless
  • y dimensionless, from about -0.217 to 1

Equivalent to:

  • numpy.sinc(x)
  • matlab sinc(x)
  • the exception to both is at ±∞ where both matlab and numpy gives NaN

func Square

func Square(t []float64, opts ...Option) (x []float64, err error)

Square returns a square wave of period 2π at each sample time in t: 1 for the first duty of each period, and -1 for the rest. Its duty is 0.5 by default, or set with Duty.

x, err := waveform.Square(t, waveform.Duty(0.25)) // high for a quarter of each period

For a frequency f in hertz, pass `2* math.Pi* f* t`. t is reduced modulo the float64 2π, same as SciPy, which is exact, so a t of 2π·k built from math.Pi is the start of a cycle, and gives 1. A NaN or infinite time gives NaN at that sample.

Units:

  • t is in radians
  • x is dimensionless, 1 or -1

Returns:

  • ErrInvalidParameter for a Duty outside 0 to 1, or NaN.
  • ErrInvalidOption for an option other than Duty.

Equivalent to:

  • scipy.signal.square(t, duty), which returns NaN for a duty outside 0 to -1, and -1 for a NaN time
  • MATLAB square(t, 100*duty), which takes duty as a percentage, and whose mod puts a t within round-off of 2π·k at the start of a cycle

func SweepPoly

func SweepPoly(t, poly []float64, opts ...Option) (x []float64, err error)

SweepPoly returns cos(2π·φ(t) + phi) at each sample time in t, a cosine whose frequency, the derivative of φ, is the polynomial poly at t, its coefficients highest power first.

x, err := waveform.SweepPoly(t, []float64{0.025, -0.36, 1.25, 2}) // 0.025t³ - 0.36t² + 1.25t + 2 Hz

The phase φ is the polynomial's integral from 0, in cycles, computed in double-double arithmetic, then its whole cycles removed before the cosine, same as Chirp. A NaN or infinite time gives NaN at that sample.

Units:

  • t is in seconds, or any time unit
  • poly is in hertz, its coefficient of t^k in hertz per second^k
  • x is dimensionless, between -1 and 1

Returns:

  • ErrInvalidParameter for an empty poly, or a NaN or infinite coefficient or Phase.
  • ErrInvalidOption for an option other than Phase.

Equivalent to:

  • scipy.signal.sweep_poly(t, poly, phi)
  • MATLAB has no equivalent

func Timebase

func Timebase(n int, fs float64) (t []float64, err error)

Timebase returns the times of n samples at rate fs, from t = 0: t[i] = i/fs. Each time is i/fs rounded once, so it's exact to half a ULP, where adding 1/fs at each step drifts: tested to 3.1e-9 seconds after a minute at 48kHz.

t, err := waveform.Timebase(96000, 48000) // 2 seconds at 48kHz
t, err := waveform.Timebase(int(math.Round(duration*fs)), fs)

Units:

  • n count of samples
  • fs hertz
  • t seconds

Returns:

  • ErrInvalidLength for an n below 0
  • ErrInvalidParameter for an fs that isn't above 0 and finite

Equivalent to:

  • numpy.arange(n)/fs
  • matlab (0:n-1)/fs

func Tone

func Tone(t []float64, f float64, opts ...Option) (x []float64, err error)

Tone returns a cosine of frequency f at each sample time in t, cos(2π·f·t), starting at Phase degrees.

x, err := waveform.Tone(t, 440, waveform.Phase(-90)) // a 440 Hz sine wave

The phase f·t is computed in double-double and reduced to its fraction of a cycle before the cosine, so each sample is within an ULP of exact, independent of how large f·t grows. math.Cos(2*math.Pi*f*t) rounds 2π·f·t first, and loses digits as it grows: it's 2.9e-7 from exact for 440 Hz at t = 10^6 seconds. It's Chirp with f0 = f1 = f. A NaN or infinite time gives NaN at that sample.

Units:

  • t is in seconds
  • f is in hertz
  • x is dimensionless, from -1 to 1

Returns:

  • ErrInvalidParameter for: an f that isn't finite, or a Phase that isn't finite.
  • ErrInvalidOption for an option other than Phase.

Equivalent to:

  • scipy and matlab have no direct equivalent
  • cos(2*pi*f*t + phi) with phi in radians is used as a vector comparison

func TriPuls

func TriPuls(t []float64, opts ...Option) (x []float64, err error)

TriPuls returns a triangular pulse centred on t = 0 at each sample time in t, with base Width w, 1 second by default: it rises from 0 at -w/2 to 1 at its peak, s·w/2, and falls to 0 at w/2, with Skew s, 0 by default. It's closed at both ends, so at a Skew of -1 or 1 it keeps its peak of 1 where it jumps, at -w/2 or w/2.

x, err := waveform.TriPuls(t, waveform.Width(2e-3), waveform.Skew(0.5))

Each side, (t + w/2)/(w/2·(1 + s)) rising and (w/2 - t)/(w/2·(1 - s)) falling, is computed in double-double, and the pulse is the lower of the two, so each sample is within an ULP of exact. A NaN time gives NaN at that sample.

Units:

  • t is in seconds
  • x is dimensionless, from 0 to 1

Returns:

  • ErrInvalidParameter for: a Width that isn't above 0 and finite, or, a Skew that isn't between -1 and 1.
  • ErrInvalidOption for an option not in Width or Skew.

Equivalent to:

  • MATLAB tripuls(t, w, s)
  • scipy has no equiv.

func UnitImpulse

func UnitImpulse(n, index int) (x []float64, err error)

UnitImpulse returns n samples of a unit impulse, 0 everywhere apart from 1 at index. Unlike the other waveforms it takes a length rather than sample times, as it's a sequence, not a function of t.

x, err := waveform.UnitImpulse(1024, 512) // an impulse at the centre, idx='mid' in scipy

Units:

  • n is a count of samples
  • index is a sample index, from 0
  • x is dimensionless, 0 or 1

Returns:

  • ErrInvalidLength for an n below 0
  • ErrInvalidParameter for an index outside 0 to n - 1, including any index when n is 0

Equivalent to:

  • scipy.signal.unit_impulse(n, index), with scipy's idx='mid' as n/2, and without its negative indicies, which count from the end
  • matlab has no equivalent

func VioletNoise added in v1.2.0

func VioletNoise(n int, opts ...Option) (x []float64, err error)

VioletNoise returns n samples of violet noise, 'differentiated' white noise, the difference between consecutive values: Gaussian noise whose power spectral density is proportional to f^2.

x, err := waveform.VioletNoise(48000, waveform.Seed(1))

Methods, each colouring white noise of variance 1:

  • Kasdin (default), a full length causal filter, so a longer n keeps the earlier samples, but starts quiet
  • KasdinTaps(m) (matching MATLAB), fast for a small m, but flattens below about fs/m
  • FFTShaping (fastest), follows f^2 up to fs/2 and loops without a jump, but has nothing at 0 Hz and a new signal for every n

If more than one is given, the last wins. It has about the same level at fs/6 as the other colours. The noise isn't scaled, so its variance isn't 1.

Seed makes it repeatable.

Safe to use concurrently.

Units:

  • n is a count of samples
  • x is dimensionless

Returns:

  • ErrInvalidLength for an n below 0, or a KasdinTaps m below 1
  • ErrInvalidOption for an option not in Seed, Kasdin, KasdinTaps or FFTShaping

Equivalent to:

  • MATLAB dsp.ColoredNoise with Color "purple", which is close to KasdinTaps(256), with different samples

func WhiteNoise added in v1.2.0

func WhiteNoise(n int, opts ...Option) (x []float64, err error)

WhiteNoise returns n samples of white Gaussian noise: mean 0 and variance 1.

x, err := waveform.WhiteNoise(48000, waveform.Seed(1))

Each sample is independent, so its power spectral density is flat. With Seed it's repeatable, from a PCG generator, which Go keeps the same in all versions. Without Seed it's drawn from math/rand/v2's global generator, so every call is different.

Safe to use concurrently.

Units:

  • n is a count of samples
  • x is dimensionless, with variance 1

Returns:

  • ErrInvalidLength for an n below 0
  • ErrInvalidOption for an option other than Seed

Equivalent to:

  • MATLAB dsp.ColoredNoise with Color "white", and randn(n, 1), with the same distribution but different samples, as the generators differ
  • numpy.random.default_rng(seed).standard_normal(n), the same way

Types

type GaussianPulse

type GaussianPulse struct {
	// InPhase is the pulse, the envelope times cos(2π·fc·t)
	InPhase []float64
	// Quadrature is the envelope times sin(2π·fc·t), 90° behind InPhase
	Quadrature []float64
	// Envelope is exp(-a·t²), peaking at 1 at t= 0
	Envelope []float64
}

GaussianPulse is a Guassian-modulated sinusoid, sampled at each time in t

func GaussPulse

func GaussPulse(t []float64, fc float64, opts ...Option) (pulse GaussianPulse, err error)

GaussPulse returns a Guassian-modulated sinusoid centred on t= 0 at each sample time in t, with the centre frequency fc, its in-phase part, its quadrature part, and its envelope. The envelope is exp(-a·t²), where a sets the bandwidth, so the spectrum falls to BandwidthLevel, -6dB by default, at fc·(1± bw/ 2), with Bandwidth bw, 0.5 by default.

pulse, err:= waveform.GaussPulse(t, 50e3, waveform.Bandwidth(0.6)) // 50kHz ultrasound pulse

The envelope is computed in double-double, and the carrier's phase reduced to its fraction of a cycle first, so each sample is within 1ULP of exact. A NaN time gives NaN at that sample, and an infinite time gives 0, the limit of the pulse.

Units:

  • t seconds
  • fc hertz, above 0
  • outputs are dimensionless, from -1 to 1

Returns:

  • ErrInvalidParameter for: an fc that isn't above 0 and finite, a Bandwidth that isn't above 0 and finite, or, a BandwidthLevel that isn't below 0 and finite.
  • ErrInvalidOption for an option not in Bandwidth or BandwidthLevel

Equivalent to:

  • scipy.signal.gausspulse(t, fc, bw, bwr, retquad= True, retenv= True), which takes fc= 0 too, and gives NaN at an infinite time
  • MATLAB [yi, yq, ye]= gausepuls(t, fc, bw, bwr)

type Option

type Option func(*config)

Option configures a waveform. One Option type serves every waveform, and each option means the same wherever it applies. A waveform given an option that doesn't apply to it returns ErrInvalidOption.

func Bandwidth

func Bandwidth(bw float64) (option Option)

Bandwidth sets GaussPulse's bandwidth as a fraction of its centre frequency fc: its spectrum falls to BandwidthLevel at fc·(1 ± bw/2). It's 0.5 by default, and must be above 0.

Units: bw is a fraction of fc

Equivalent to:

  • scipy.signal.gausspulse bw
  • MATLAB gauspuls bw

func BandwidthLevel

func BandwidthLevel(levelDB float64) (option Option)

BandwidthLevel sets the level below its peak where GaussPulse's spectrum is Bandwidth wide. It's -6 dB by default, and must be below 0.

Units: levelDB is in dB, negative

Equivalent to:

  • scipy.signal.gausspulse bwr
  • MATLAB gauspuls bwr

func CutoffLevel

func CutoffLevel(levelDB float64) (option Option)

CutoffLevel sets the level below its peak where GaussPulseCutoff finds the envelope. It's -60 dB by default, and must be below 0.

Units: levelDB is in dB, negative

Equivalent to:

  • scipy.signal.gausspulse tpr
  • MATLAB gauspuls tpr

func Duty

func Duty(duty float64) (option Option)

Duty sets the fraction of each period a waveform spends in the first part of its cycle: Square's high part, 0.5 by default. It must be between 0 and 1, where 0 is never high and 1 always.

Units: duty is a fraction of the period

Equivalnet to:

  • scipy.signal.square duty
  • MATLAB square's duty, which is a percentage, so Duty(0.25) is MATLAB 25

func FFTShaping added in v1.2.0

func FFTShaping() (option Option)

FFTShaping colours noise by scaling a white noise spectrum by (2πf)^(-alpha/2), with f as a fraction of the sample rate. The spectrum follows 1/f^alpha at every frequency up to fs/2, with nothing at 0Hz. It matches Kasdin's level at low frequencies. The noise is periodic so it has no start-up transient and loops without a jump.

Equivalent to:

  • MATLAB and scipy have no equivalent

func Hyperbolic

func Hyperbolic() (option Option)

Hyperbolic sweeps Chirp's frequency from f0 at t = 0 to f1 at t = t1 with a constant change in period: f(t) = f0·f1·t1/((f0 - f1)·t + f1·t1). f0 and f1 must be non-zero. The frequency is infinite at t = f1·t1/(f1 - f0), which for an upward sweep is after t1.

Equivalent to:

  • scipy.signal.chirp method='hyperbolic'
  • MATLAB has none

func Kasdin added in v1.2.0

func Kasdin() (option Option)

Kasdin colours noise by passing white noise through Kasdin's filter, (1-z^-1)^(-alpha/2), at full length. It's the default option. The spectrum follows 1/f^alpha down to the lowest frequency, up to about fs/4. The filter starts from rest, so for an alpha near 1 the first samples are quieter that the rest.

Equivalent to:

  • MATLAB dsp.ColoredNoise, which truncates the filter, so its low-frequency slope differs

func KasdinTaps added in v1.2.0

func KasdinTaps(m int) (option Option)

KasdinTaps colours noise by Kasdin's filter truncated to m coefficients in the same way as matlab. For an alpha above 0 it truncates the filter's inverse, (1 - z^-1)^(alpha/2), and runs it as an all-pole filter. For an alpha below 0 it truncates the filter itself and runs it as an FIR filter. Below about fs/m the spectrum departs from 1/f^alpha. m must be at least 1.

Units: m is a count of coefficients

Equivalent to:

  • MATLAB dsp.ColoredNoise with Color "custom", which is KasdinTaps(64) for an alpha above 0, and KasdinTaps(256) below, except at an alpha of 1 or 2, where it uses its own pink or brown filter

func Linear

func Linear() (option Option)

Linear sweeps Chirp's frequency linearly from f0 at t = 0 to f1 at t = t1: f(t) = f0 + (f1 - f0)·t/t1. It's the default.

Equivalent to:

  • scipy.signal.chirp method='linear', its default
  • MATLAB chirp "linear", its default

func Logarithmic

func Logarithmic() (option Option)

Logarithmic sweeps Chirp's frequency geometrically from f0 at t = 0 to f1 at t = t1: f(t) = f0·(f1/f0)^(t/t1). f0 and f1 must be non-zero and of the same sign.

Equivalent to:

  • scipy.signal.chirp method='logarithmic'
  • MATLAB chirp "logarithmic", except at f0 = f1, where MATLAB divides by 0

func Phase

func Phase(phi float64) (option Option)

Phase starts the waveform's cosine at phi degrees rather than 0, so -90 is a sine wave and 90 its negative.

Units: phi is in degrees

Equivalent to:

  • scipy.signal.chirp phi
  • MATLAB chirp phi

func Quadratic

func Quadratic() (option Option)

Quadratic sweeps Chirp's frequency along a parabola from f0 at t = 0 to f1 at t = t1, with its vertex at t = 0, f(t) = f0 + (f1 - f0)·(t/t1)², or with VertexAtT1 at t = t1, f(t) = f1 - (f1 - f0)·(1 - t/t1)².

Equivalent to:

  • scipy.signal.chirp method='quadratic'
  • MATLAB chirp "quadratic", with its default shape, for the vertex at t = 0

func Seed added in v1.2.0

func Seed(seed uint64) (option Option)

Seed makes a noise signal repeatable: the same seed gives the same samples, consistent for all Go versions. If not provided, a noise is drawn from math/rand/v2's global generator, and differs on every call.

Equivalent to:

  • MATLAB dsp.ColoredNoise RandomStream "mt19937ar with seed" with Seed. This is an equivalent concept, there is no value equivalence, using the same seed in tukey and matlab will not produce the same signal.

func Skew

func Skew(s float64) (option Option)

Skew sets where TriPuls peaks, at s·w/2 for Width w: 0 is symmetric, -1 jumps to its peak at -w/2 and falls from there, and 1 rises to its peak and drops at w/2. It's 0 by default, and must be between -1 and 1.

Units: s is a fraction of half the width

Equivalent to:

  • matlab tripuls s

func VertexAtT1

func VertexAtT1() (option Option)

VertexAtT1 puts a Quadratic sweep's vertex at t = t1, where the frequency then levels off at f1, rather than at t = 0. It needs Quadratic.

Equivalent to:

  • scipy.signal.chirp vertex_zero=False
  • MATLAB has none, as its other shape evaluates the sweep at fliplr(-t), which depends on how t is laid out

func Width

func Width(width float64) (option Option)

Width sets a pulse's width, centred on t = 0: RectPuls's, or the base of TriPuls's triangle. It's 1 second by default, and must be above 0 and finite.

Units: width seconds

Equivalent to:

  • matlab rectpuls and tripuls w

Jump to

Keyboard shortcuts

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