Signal processing: effects (filters), spectral analysis, convolution, filtering, smoothing and signal generation.
A signal is any sequence of doubles.
An effect is a stateful sample-by-sample filter created by the effect multimethod. Apply effects with apply-effects (any sequence) or apply-effects-raw (double-array only), compose them with compose-effects, reset them with reset-effects. An effect can be called as a function: with a sample it returns the effect with the next state, without arguments it returns the last output.
Every effect is created with (effect name) (default parameters) or (effect name params). All names are listed in effects-list. Unknown keyword options (:kind, :tan, :method) throw ex-info. Effects which keep a mutable buffer (:echo, :mda-thru-zero, :iir) should not be shared between threads.
One pole RC filter (highpass is x - lowpass(x)).
:rate - sample rate (default 44100.0):cutoff - cutoff frequency (default 2000.0)Audio EQ Cookbook biquads (see fastmath.signal.biquad): peaking equalizer, high and low shelf, lowpass, highpass, bandpass.
:fc - center or corner frequency (default 1000.0):gain - gain in dB for :biquad-eq, :biquad-hs, :biquad-ls (default 0.0):bw - bandwidth in octaves for :biquad-eq, :biquad-lp, :biquad-hp, :biquad-bp (default 1.0):slope - shelf slope S for :biquad-hs, :biquad-ls (default 1.5, S = 1 is the steepest monotonic shelf), converted with biquad/shelf-slope->Q:fs - sample rate (default 44100.0)High shelf at 10 kHz, peaking equalizers at 1 kHz and 100 Hz (frequencies scaled by rate/44100).
:hi - high frequency gain in dB (default 0.0):mid - mid frequency gain in dB (default 0.0):low - low frequency gain in dB (default 0.0):shelf-slope - shelf slope for the high shelf (default 1.5):peak-bw - bandwidth in octaves for mid and low (default 1.0):rate - sample rate (default 44100.0)First order allpass, coefficient (1 - delay) / (1 + delay).
:delay - delay factor (default 0.5)Octave divider, swh divider_1186.
:denom - divisor, an integer at least 1 (default 2, the original 1)Modulate the signal on a cosine carrier, quantize, demodulate.
:quant - quantization levels (0.0 - no quantization, default 10.0):omega - carrier factor (default 0.014):phase - deviation factor (default 0.00822)CMT lofi bandwidth limiter (slew of freq/rate per sample).
:rate - sample rate (default 44100.0):freq - cutoff frequency (default 1000.0)(1 + factor) x / (factor + |x|)
:factor - distortion factor (default 1.0)Fast overdrive, swh foverdrive_1196.
:drive - drive (default 2.0)Sample rate and bit depth reduction, swh decimator_1202 (bits outside [1, 31) disable bit reduction, fs >= rate disables rate reduction).
:bits - bit depth (default 2.0):fs - decimator sample rate (default 4410.0):rate - input sample rate (default 44100.0)Audacity BassTreble (2.4.2) shelves.
:bass - bass gain in dB (default 1.0, the original 0.0):treble - treble gain in dB (default 1.0, the original 0.0):gain - output gain in dB (default 0.0):rate - sample rate (default 44100.0):slope - shelf slope for both (default 0.4):bass-freq - bass frequency (default 250.0):treble-freq - treble frequency (default 4000.0)Audacity Echo.
:delay - delay time in seconds, from one sample to 1e7 samples (default 0.5):decay - amount of echo in the signal (default 0.5):rate - sample rate (default 44100.0)CMT vcf303 (TB-303 like resonant filter with envelope).
:rate - sample rate (default 44100.0):trigger - when true, the envelope fires when the effect is created or reset (default false); the original fires on a rising edge of a trigger input, use the reset argument of apply-effects to retrigger:cutoff - cutoff (0-1, default 0.8):resonance - resonance (0-1, default 0.8):env-mod - envelope modulation (0-1, default 0.5):decay - decay (0-1, default 1.0):gain - output gain (default 1.0)omins slew_limiter.
:rate - sample rate (default 44100.0):maxrise - maximum rise per second (default 500.0):maxfall - maximum fall per second (default 500.0)mda ThruZero flanger (mda-vst3 processor, one channel, without per-block parameter smoothing and denormal guard). All parameters are in [0, 1].
:rate - sample rate (default 44100.0):speed - modulation rate, 10^(3 speed - 2) seconds per period, below 0.01 the modulation stops (default 0.3):depth - depth (default 0.43):mix - wet amount, the wet signal is subtracted (default 0.47):depth-mod - depth modulation (default 1.0):feedback - feedback (default 0.3)(effect :iir filter) wraps an IIR filter created in fastmath.signal.iir. The filter is reset when the effect is created or reset. There is no 1-arity (throws ex-info).
(effect :gain g) or (effect :gain {:gain g}) multiplies the signal by g (default 1.0).
:method - :hard (clamp to [-1, 1]), :hyperbolic (tanh), :soft (cubic x - x^3/3, ±2/3 outside [-1, 1]), default :hard:pregain - gain applied before clipping (default 1.0)State variable filter, swh svf_1214 (LADSPA). Faithful to the original: :allpass is low - high (not a unit gain allpass), when oversampling the output of the previous pass is the input of the next one, the input is scaled by sqrt(q/2 + 0.01) (so the lowpass DC gain is below 1), Q above about 1.0655 gives NaN in the original and throws ex-info here.
:rate - sample rate (default 44100.0):cutoff - cutoff frequency (default 1000.0):kind - :lowpass (default), :highpass, :bandpass, :notch, :allpass:Q - resonance in [0, 1.0655] (default 0.5):oversamples - oversampling, at least 1 (default 1, the original 3):resonance - feedback of the band output (default 0.01, the original 0.0)State variable filter, Mutable Instruments stmlib Svf.
:rate - sample rate (default 44100.0):cutoff - cutoff frequency (default 1000.0):Q - quality factor, positive (default 0.5):kind - :lowpass (default), :highpass, :bandpass, :bandpass-normalized (bandpass divided by Q, unit gain at cutoff), :notch (lowpass + highpass):tan - tan approximation: :exact (default), :dirty, :fast, :accurateLinear trapezoidal state variable filter by Andrew Simper (Cytomic), Common-DSP SvfLinearTrapOptimised2.
:rate - sample rate (default 44100.0):cutoff - cutoff frequency (default 1000.0):Q - quality factor, positive (default 0.5):kind - :lowpass (default), :bandpass, :highpass, :notch, :peak (high - low, as Common-DSP), :allpass, :bell, :lowshelf, :highshelf:gaindb - gain in dB for :bell, :lowshelf, :highshelf (default 0.0):tan - as in :svf2fft-energy, fft-magnitude, fft-amplitude, fft-power scale coefficients from fastmath.transform/fft; spectrum, stft and periodogram analyse a signal.
convolve, correlate (direct), fft-convolve, fft-correlate (FFT based), filter-signal, filter-filter-signal apply FIR coefficients (fastmath.signal.fir) or IIR filters (fastmath.signal.iir).
Savitzky-Golay savgol-filter, moving-average-filter, kernel-smoothing-filter.
waveform, chirp, add-waveforms, gain-waveform, sample-waveform.
save-signal, load-signal: 16 bit signed, big endian. Use Audacity or SoX to convert to/from audio files.
Signal processing: effects (filters), spectral analysis, convolution, filtering, smoothing and signal generation.
A signal is any sequence of doubles.
## Effects
An effect is a stateful sample-by-sample filter created by the [[effect]] multimethod. Apply effects with [[apply-effects]] (any sequence) or [[apply-effects-raw]] (`double-array` only), compose them with [[compose-effects]], reset them with [[reset-effects]]. An effect can be called as a function: with a sample it returns the effect with the next state, without arguments it returns the last output.
Every effect is created with `(effect name)` (default parameters) or `(effect name params)`. All names are listed in [[effects-list]]. Unknown keyword options (`:kind`, `:tan`, `:method`) throw `ex-info`. Effects which keep a mutable buffer (`:echo`, `:mda-thru-zero`, `:iir`) should not be shared between threads.
#### :simple-lowpass, :simple-highpass
One pole RC filter (highpass is `x - lowpass(x)`).
* `:rate` - sample rate (default 44100.0)
* `:cutoff` - cutoff frequency (default 2000.0)
#### :biquad-eq, :biquad-hs, :biquad-ls, :biquad-lp, :biquad-hp, :biquad-bp
Audio EQ Cookbook biquads (see `fastmath.signal.biquad`): peaking equalizer, high and low shelf, lowpass, highpass, bandpass.
* `:fc` - center or corner frequency (default 1000.0)
* `:gain` - gain in dB for `:biquad-eq`, `:biquad-hs`, `:biquad-ls` (default 0.0)
* `:bw` - bandwidth in octaves for `:biquad-eq`, `:biquad-lp`, `:biquad-hp`, `:biquad-bp` (default 1.0)
* `:slope` - shelf slope `S` for `:biquad-hs`, `:biquad-ls` (default 1.5, `S = 1` is the steepest monotonic shelf), converted with `biquad/shelf-slope->Q`
* `:fs` - sample rate (default 44100.0)
#### :dj-eq
High shelf at 10 kHz, peaking equalizers at 1 kHz and 100 Hz (frequencies scaled by `rate/44100`).
* `:hi` - high frequency gain in dB (default 0.0)
* `:mid` - mid frequency gain in dB (default 0.0)
* `:low` - low frequency gain in dB (default 0.0)
* `:shelf-slope` - shelf slope for the high shelf (default 1.5)
* `:peak-bw` - bandwidth in octaves for mid and low (default 1.0)
* `:rate` - sample rate (default 44100.0)
#### :phaser-allpass
First order allpass, coefficient `(1 - delay) / (1 + delay)`.
* `:delay` - delay factor (default 0.5)
#### :divider
Octave divider, swh `divider_1186`.
* `:denom` - divisor, an integer at least 1 (default 2, the original 1)
#### :fm
Modulate the signal on a cosine carrier, quantize, demodulate.
* `:quant` - quantization levels (0.0 - no quantization, default 10.0)
* `:omega` - carrier factor (default 0.014)
* `:phase` - deviation factor (default 0.00822)
#### :bandwidth-limit
CMT `lofi` bandwidth limiter (slew of `freq/rate` per sample).
* `:rate` - sample rate (default 44100.0)
* `:freq` - cutoff frequency (default 1000.0)
#### :distort
`(1 + factor) x / (factor + |x|)`
* `:factor` - distortion factor (default 1.0)
#### :foverdrive
Fast overdrive, swh `foverdrive_1196`.
* `:drive` - drive (default 2.0)
#### :decimator
Sample rate and bit depth reduction, swh `decimator_1202` (`bits` outside `[1, 31)` disable bit reduction, `fs >= rate` disables rate reduction).
* `:bits` - bit depth (default 2.0)
* `:fs` - decimator sample rate (default 4410.0)
* `:rate` - input sample rate (default 44100.0)
#### :basstreble
Audacity `BassTreble` (2.4.2) shelves.
* `:bass` - bass gain in dB (default 1.0, the original 0.0)
* `:treble` - treble gain in dB (default 1.0, the original 0.0)
* `:gain` - output gain in dB (default 0.0)
* `:rate` - sample rate (default 44100.0)
* `:slope` - shelf slope for both (default 0.4)
* `:bass-freq` - bass frequency (default 250.0)
* `:treble-freq` - treble frequency (default 4000.0)
#### :echo
Audacity `Echo`.
* `:delay` - delay time in seconds, from one sample to `1e7` samples (default 0.5)
* `:decay` - amount of echo in the signal (default 0.5)
* `:rate` - sample rate (default 44100.0)
#### :vcf303
CMT `vcf303` (TB-303 like resonant filter with envelope).
* `:rate` - sample rate (default 44100.0)
* `:trigger` - when `true`, the envelope fires when the effect is created or reset (default `false`); the original fires on a rising edge of a trigger input, use the `reset` argument of [[apply-effects]] to retrigger
* `:cutoff` - cutoff (0-1, default 0.8)
* `:resonance` - resonance (0-1, default 0.8)
* `:env-mod` - envelope modulation (0-1, default 0.5)
* `:decay` - decay (0-1, default 1.0)
* `:gain` - output gain (default 1.0)
#### :slew-limit
omins `slew_limiter`.
* `:rate` - sample rate (default 44100.0)
* `:maxrise` - maximum rise per second (default 500.0)
* `:maxfall` - maximum fall per second (default 500.0)
#### :mda-thru-zero
mda ThruZero flanger (mda-vst3 processor, one channel, without per-block parameter smoothing and denormal guard). All parameters are in `[0, 1]`.
* `:rate` - sample rate (default 44100.0)
* `:speed` - modulation rate, `10^(3 speed - 2)` seconds per period, below 0.01 the modulation stops (default 0.3)
* `:depth` - depth (default 0.43)
* `:mix` - wet amount, the wet signal is subtracted (default 0.47)
* `:depth-mod` - depth modulation (default 1.0)
* `:feedback` - feedback (default 0.3)
#### :iir
`(effect :iir filter)` wraps an IIR filter created in `fastmath.signal.iir`. The filter is reset when the effect is created or reset. There is no 1-arity (throws `ex-info`).
#### :gain
`(effect :gain g)` or `(effect :gain {:gain g})` multiplies the signal by `g` (default 1.0).
#### :clipping
* `:method` - `:hard` (clamp to `[-1, 1]`), `:hyperbolic` (`tanh`), `:soft` (cubic `x - x^3/3`, `±2/3` outside `[-1, 1]`), default `:hard`
* `:pregain` - gain applied before clipping (default 1.0)
#### :svf1
State variable filter, swh `svf_1214` (LADSPA). Faithful to the original: `:allpass` is `low - high` (not a unit gain allpass), when oversampling the output of the previous pass is the input of the next one, the input is scaled by `sqrt(q/2 + 0.01)` (so the lowpass DC gain is below 1), `Q` above about 1.0655 gives `NaN` in the original and throws `ex-info` here.
* `:rate` - sample rate (default 44100.0)
* `:cutoff` - cutoff frequency (default 1000.0)
* `:kind` - `:lowpass` (default), `:highpass`, `:bandpass`, `:notch`, `:allpass`
* `:Q` - resonance in `[0, 1.0655]` (default 0.5)
* `:oversamples` - oversampling, at least 1 (default 1, the original 3)
* `:resonance` - feedback of the band output (default 0.01, the original 0.0)
#### :svf2
State variable filter, Mutable Instruments stmlib `Svf`.
* `:rate` - sample rate (default 44100.0)
* `:cutoff` - cutoff frequency (default 1000.0)
* `:Q` - quality factor, positive (default 0.5)
* `:kind` - `:lowpass` (default), `:highpass`, `:bandpass`, `:bandpass-normalized` (bandpass divided by `Q`, unit gain at `cutoff`), `:notch` (lowpass + highpass)
* `:tan` - `tan` approximation: `:exact` (default), `:dirty`, `:fast`, `:accurate`
#### :svf3
Linear trapezoidal state variable filter by Andrew Simper (Cytomic), Common-DSP `SvfLinearTrapOptimised2`.
* `:rate` - sample rate (default 44100.0)
* `:cutoff` - cutoff frequency (default 1000.0)
* `:Q` - quality factor, positive (default 0.5)
* `:kind` - `:lowpass` (default), `:bandpass`, `:highpass`, `:notch`, `:peak` (`high - low`, as Common-DSP), `:allpass`, `:bell`, `:lowshelf`, `:highshelf`
* `:gaindb` - gain in dB for `:bell`, `:lowshelf`, `:highshelf` (default 0.0)
* `:tan` - as in `:svf2`
## Spectral analysis
[[fft-energy]], [[fft-magnitude]], [[fft-amplitude]], [[fft-power]] scale coefficients from `fastmath.transform/fft`; [[spectrum]], [[stft]] and [[periodogram]] analyse a signal.
## Convolution and filtering
[[convolve]], [[correlate]] (direct), [[fft-convolve]], [[fft-correlate]] (FFT based), [[filter-signal]], [[filter-filter-signal]] apply FIR coefficients (`fastmath.signal.fir`) or IIR filters (`fastmath.signal.iir`).
## Smoothing
Savitzky-Golay [[savgol-filter]], [[moving-average-filter]], [[kernel-smoothing-filter]].
## Generation
[[waveform]], [[chirp]], [[add-waveforms]], [[gain-waveform]], [[sample-waveform]].
## File operations
[[save-signal]], [[load-signal]]: 16 bit signed, big endian. Use Audacity or SoX to convert to/from audio files.(add-waveforms w)(add-waveforms w1 w2)(add-waveforms w1 w2 w3)(add-waveforms w1 w2 w3 w4)(add-waveforms w1 w2 w3 w4 w5)(add-waveforms w1 w2 w3 w4 w5 & r)Adds waveforms.
Parameters:
w, w1, w2, ... (functions): Waveforms, functions (fn [t]) of the time in seconds returning the amplitude, as created by waveform or chirp.Returns the waveform which is the sum of the given ones at t. A single waveform is returned unchanged.
See also gain-waveform, sample-waveform.
Adds waveforms. Parameters: - `w`, `w1`, `w2`, ... (functions): Waveforms, functions `(fn [t])` of the time in seconds returning the amplitude, as created by [[waveform]] or [[chirp]]. Returns the waveform which is the sum of the given ones at `t`. A single waveform is returned unchanged. See also [[gain-waveform]], [[sample-waveform]].
(amplitude-envelope xs)Calculates the amplitude envelope of a real signal: the magnitude of its analytic signal (hilbert).
Parameters:
xs (sequence of numbers): Real signal, not empty.Returns a lazy sequence of doubles of the same length. Throws ex-info for an empty signal.
See also instantaneous-phase, instantaneous-frequency.
Calculates the amplitude envelope of a real signal: the magnitude of its analytic signal ([[hilbert]]). Parameters: - `xs` (sequence of numbers): Real signal, not empty. Returns a lazy sequence of doubles of the same length. Throws `ex-info` for an empty signal. See also [[instantaneous-phase]], [[instantaneous-frequency]].
(apply-effects in effects)(apply-effects in effects reset)Applies an effect to a signal given as any sequence of numbers.
Parameters:
in (sequence of numbers): Input signal.effects (effect): Effect or composition of effects, see effect and compose-effects.reset (integer, optional): When positive, the state of the effect is reset (see reset-effects) after every reset samples. Default 0, no reset.Returns the filtered signal, a sequence of doubles of the same length (nil for an empty signal).
See apply-effects-raw for the notes on the reuse of effects with a mutable buffer.
Applies an effect to a signal given as any sequence of numbers. Parameters: - `in` (sequence of numbers): Input signal. - `effects` (effect): Effect or composition of effects, see [[effect]] and [[compose-effects]]. - `reset` (integer, optional): When positive, the state of the effect is reset (see [[reset-effects]]) after every `reset` samples. Default `0`, no reset. Returns the filtered signal, a sequence of doubles of the same length (`nil` for an empty signal). See [[apply-effects-raw]] for the notes on the reuse of effects with a mutable buffer.
(apply-effects-raw in effects)(apply-effects-raw in effects reset)Applies an effect to a signal given as double-array.
Parameters:
in (double-array): Input signal.effects (effect): Effect or composition of effects, see effect and compose-effects.reset (integer, optional): When positive, the state of the effect is reset (see reset-effects) after every reset samples. Default 0, no reset.Returns a new double-array of the same length; the input array is not changed.
The effects value is not advanced, so the same effect can be applied to several signals. The exceptions are the effects with a mutable buffer (:echo, :mda-thru-zero, :iir): do not reuse them for another signal.
See also apply-effects, single-pass.
Applies an effect to a signal given as `double-array`. Parameters: - `in` (`double-array`): Input signal. - `effects` (effect): Effect or composition of effects, see [[effect]] and [[compose-effects]]. - `reset` (integer, optional): When positive, the state of the effect is reset (see [[reset-effects]]) after every `reset` samples. Default `0`, no reset. Returns a new `double-array` of the same length; the input array is not changed. The `effects` value is not advanced, so the same effect can be applied to several signals. The exceptions are the effects with a mutable buffer (`:echo`, `:mda-thru-zero`, `:iir`): do not reuse them for another signal. See also [[apply-effects]], [[single-pass]].
(chirp chirp-type)(chirp chirp-type options)Create a frequency-swept sine wave (chirp) oscillator.
Generates a signal where the instantaneous frequency changes over a specified time interval according to a defined modulation profile. Chirps are essential in radar, sonar, and system identification to analyze frequency-dependent responses and impulse behavior.
Input parameters:
chirp-type - A keyword specifying the sweep profile (see fastmath.signal.chirp):
:linear - Frequency changes linearly with time.:quadratic-up - Frequency changes quadratically, parabola vertex at $t=0$.:quadratic-down - Frequency changes quadratically, parabola vertex at $t=time$.:logarithmic - Frequency changes exponentially (geometric sweep), frequencies must be positive.:hyperbolic - Frequency follows a hyperbolic curve, frequencies must be positive.:constant - Constant frequency :f0.options - A map of configuration keys:
:f0 - Starting frequency in Hz at $t=0$ (default 0.0; 1e-10 for :logarithmic and :hyperbolic).:f1 - Ending frequency in Hz at $t=time$ (default 5.0).:time - The time (in seconds) at which the frequency reaches :f1 (default 1.0, must be positive).:phase0 - Phase offset of the sweep in cycles (default 0.0).:amplitude - Peak amplitude. Can be a number or a modulation function (fn [t]).:phase - Additional phase offset in cycles, as for waveform.The value is amplitude * sin(2 pi phase(t)); it equals scipy.signal.chirp(t, f0, time, f1, method, phi=-90 + 360 phase0) (:quadratic-up/-down are method='quadratic' with vertex_zero true/false).
Returns a stateless function (fn [t]) that accepts time t as a double and returns the signal value as a double. Throws ex-info for an unknown chirp-type or invalid options.
Create a frequency-swept sine wave (chirp) oscillator.
Generates a signal where the instantaneous frequency changes over a specified time interval according to a defined modulation profile. Chirps are essential in radar, sonar, and system identification to analyze frequency-dependent responses and impulse behavior.
Input parameters:
* `chirp-type` - A keyword specifying the sweep profile (see `fastmath.signal.chirp`):
* `:linear` - Frequency changes linearly with time.
* `:quadratic-up` - Frequency changes quadratically, parabola vertex at $t=0$.
* `:quadratic-down` - Frequency changes quadratically, parabola vertex at $t=time$.
* `:logarithmic` - Frequency changes exponentially (geometric sweep), frequencies must be positive.
* `:hyperbolic` - Frequency follows a hyperbolic curve, frequencies must be positive.
* `:constant` - Constant frequency `:f0`.
* `options` - A map of configuration keys:
* `:f0` - Starting frequency in Hz at $t=0$ (default 0.0; 1e-10 for `:logarithmic` and `:hyperbolic`).
* `:f1` - Ending frequency in Hz at $t=time$ (default 5.0).
* `:time` - The time (in seconds) at which the frequency reaches `:f1` (default 1.0, must be positive).
* `:phase0` - Phase offset of the sweep in cycles (default 0.0).
* `:amplitude` - Peak amplitude. Can be a number or a modulation function `(fn [t])`.
* `:phase` - Additional phase offset in cycles, as for [[waveform]].
The value is `amplitude * sin(2 pi phase(t))`; it equals `scipy.signal.chirp(t, f0, time, f1, method, phi=-90 + 360 phase0)` (`:quadratic-up`/`-down` are `method='quadratic'` with `vertex_zero` true/false).
Returns a stateless function `(fn [t])` that accepts time `t` as a double and returns the signal value as a double. Throws `ex-info` for an unknown `chirp-type` or invalid options.(compose-effects e & es)Composes effects into a single effect, as comp does for functions.
(compose-effects e1 e2 ... en) passes a sample through en first and through e1 last; the output of e1 is the output of the composition.
Parameters:
e, es (effects): One or more effects created with effect.Returns the composed effect, which is applied, called and reset as a single effect while each part keeps its own state. With one effect the effect itself is returned. The arguments are not changed.
See also effect, apply-effects, reset-effects.
Composes effects into a single effect, as `comp` does for functions. `(compose-effects e1 e2 ... en)` passes a sample through `en` first and through `e1` last; the output of `e1` is the output of the composition. Parameters: - `e`, `es` (effects): One or more effects created with [[effect]]. Returns the composed effect, which is applied, called and reset as a single effect while each part keeps its own state. With one effect the effect itself is returned. The arguments are not changed. See also [[effect]], [[apply-effects]], [[reset-effects]].
(convolve sig1 sig2)(convolve sig1 sig2 mode)Computes the direct convolution of two signals, zero padded outside.
Needs time proportional to N1 N2, for long signals see fft-convolve.
Parameters:
sig1, sig2 (sequences of numbers): Signals of lengths N1 and N2, not empty.mode (keyword, optional): The part of the result to return, as in scipy.signal.convolve:
:full (default, alias :all) - the full convolution, length N1 + N2 - 1:same (alias :first) - length N1, centred with respect to :full:valid - length |N1 - N2| + 1, values computed without zero paddingReturns a vector. Throws ex-info for an empty signal or an unknown mode.
See also fft-convolve, correlate, filter-signal.
Computes the direct convolution of two signals, zero padded outside. Needs time proportional to `N1 N2`, for long signals see [[fft-convolve]]. Parameters: - `sig1`, `sig2` (sequences of numbers): Signals of lengths `N1` and `N2`, not empty. - `mode` (keyword, optional): The part of the result to return, as in `scipy.signal.convolve`: - `:full` (default, alias `:all`) - the full convolution, length `N1 + N2 - 1` - `:same` (alias `:first`) - length `N1`, centred with respect to `:full` - `:valid` - length `|N1 - N2| + 1`, values computed without zero padding Returns a vector. Throws `ex-info` for an empty signal or an unknown mode. See also [[fft-convolve]], [[correlate]], [[filter-signal]].
(correlate sig1 sig2)(correlate sig1 sig2 mode)Computes the direct cross-correlation of two real signals, zero padded outside.
It is the convolution of sig1 with the reversed sig2, as scipy.signal.correlate.
Parameters:
sig1, sig2 (sequences of numbers): Real signals, not empty.mode (keyword, optional): The part of the result to return, :full (default), :same or :valid, see convolve.Returns a vector. Throws ex-info for an empty signal or an unknown mode.
See also fft-correlate, convolve.
Computes the direct cross-correlation of two real signals, zero padded outside. It is the convolution of `sig1` with the reversed `sig2`, as `scipy.signal.correlate`. Parameters: - `sig1`, `sig2` (sequences of numbers): Real signals, not empty. - `mode` (keyword, optional): The part of the result to return, `:full` (default), `:same` or `:valid`, see [[convolve]]. Returns a vector. Throws `ex-info` for an empty signal or an unknown mode. See also [[fft-correlate]], [[convolve]].
(db->linear x)Converts a gain in decibels to the linear amplitude ratio 10^(x/20).
0 dB gives 1.0, 20 dB gives 10.0, -20 dB gives 0.1, about 6.02 dB gives 2.0. For a power ratio the exponent is x/10 instead.
Returns a double. See also linear->db.
Converts a gain in decibels to the linear amplitude ratio `10^(x/20)`. `0` dB gives `1.0`, `20` dB gives `10.0`, `-20` dB gives `0.1`, about `6.02` dB gives `2.0`. For a power ratio the exponent is `x/10` instead. Returns a double. See also [[linear->db]].
Creates an effect: a stateful sample-by-sample filter, given its name.
Parameters:
name (keyword): Name of the effect, one of effects-list.params (map, optional): Parameters of the effect, missing keys take the defaults. All parameters are listed for each effect in the docstring of the namespace. :gain also accepts the gain number and :iir requires an IIR filter from fastmath.signal.iir.Returns the effect. An effect is a function: called with a sample it returns the effect with the next state, called without arguments it returns the last output sample (0.0 for a new effect). It prints as the names of its parts and the last sample.
Throws IllegalArgumentException for an unknown name and ex-info for an invalid parameter (for example an unknown :kind).
See also apply-effects, compose-effects, reset-effects, single-pass.
Creates an effect: a stateful sample-by-sample filter, given its name. Parameters: - `name` (keyword): Name of the effect, one of [[effects-list]]. - `params` (map, optional): Parameters of the effect, missing keys take the defaults. All parameters are listed for each effect in the docstring of the namespace. `:gain` also accepts the gain number and `:iir` requires an IIR filter from `fastmath.signal.iir`. Returns the effect. An effect is a function: called with a sample it returns the effect with the next state, called without arguments it returns the last output sample (`0.0` for a new effect). It prints as the names of its parts and the last sample. Throws `IllegalArgumentException` for an unknown name and `ex-info` for an invalid parameter (for example an unknown `:kind`). See also [[apply-effects]], [[compose-effects]], [[reset-effects]], [[single-pass]].
(effect-node effect-name f)Creates a single effect from the step function f of a stateful sample-by-sample filter.
This is the constructor used by the methods of effect; to create an effect use effect.
Parameters:
effect-name (keyword): Name of the effect, shown when the effect is printed.f (function): The step function. Called without arguments it returns the initial state, called with a sample and a state it returns the output sample together with the next state (SampleAndState).Returns the effect with the initial state (f) and the last output sample 0.0.
See also effect, compose-effects.
Creates a single effect from the step function `f` of a stateful sample-by-sample filter. This is the constructor used by the methods of [[effect]]; to create an effect use [[effect]]. Parameters: - `effect-name` (keyword): Name of the effect, shown when the effect is printed. - `f` (function): The step function. Called without arguments it returns the initial state, called with a sample and a state it returns the output sample together with the next state (`SampleAndState`). Returns the effect with the initial state `(f)` and the last output sample `0.0`. See also [[effect]], [[compose-effects]].
Sorted sequence of the names (keywords) of all effects which can be created with effect.
Sorted sequence of the names (keywords) of all effects which can be created with [[effect]].
(fft-amplitude txs)(fft-amplitude txs options)Returns the amplitude spectrum, fft-magnitude divided by the signal length N: a one-sided spectrum gives the peak amplitude of each sinusoidal component (and the mean at DC).
Coefficients and options as in fft-energy. Returns a vector of doubles.
Returns the amplitude spectrum, [[fft-magnitude]] divided by the signal length `N`: a one-sided spectrum gives the peak amplitude of each sinusoidal component (and the mean at DC). Coefficients and options as in [[fft-energy]]. Returns a vector of doubles.
(fft-convolve sig1 sig2)(fft-convolve sig1 sig2 mode)Computes the convolution of two signals using FFT (zero padded to a power of two).
The result is the same as of convolve up to rounding errors, in time proportional to N log N, N = N1 + N2 - 1, so it is faster for long signals.
Parameters:
sig1, sig2 (sequences of numbers): Signals, not empty.mode (keyword, optional): The part of the result to return, :full (default), :same or :valid, see convolve.Returns a vector. Throws ex-info for an empty signal or an unknown mode.
See also convolve, fft-correlate.
Computes the convolution of two signals using FFT (zero padded to a power of two). The result is the same as of [[convolve]] up to rounding errors, in time proportional to `N log N`, `N = N1 + N2 - 1`, so it is faster for long signals. Parameters: - `sig1`, `sig2` (sequences of numbers): Signals, not empty. - `mode` (keyword, optional): The part of the result to return, `:full` (default), `:same` or `:valid`, see [[convolve]]. Returns a vector. Throws `ex-info` for an empty signal or an unknown mode. See also [[convolve]], [[fft-correlate]].
(fft-correlate sig1 sig2)(fft-correlate sig1 sig2 mode)Computes the cross-correlation of two real signals using FFT, the result of correlate up to rounding errors.
Parameters:
sig1, sig2 (sequences of numbers): Real signals, not empty.mode (keyword, optional): The part of the result to return, :full (default), :same or :valid, see convolve.Returns a vector. Throws ex-info for an empty signal or an unknown mode.
See also correlate, fft-convolve.
Computes the cross-correlation of two real signals using FFT, the result of [[correlate]] up to rounding errors. Parameters: - `sig1`, `sig2` (sequences of numbers): Real signals, not empty. - `mode` (keyword, optional): The part of the result to return, `:full` (default), `:same` or `:valid`, see [[convolve]]. Returns a vector. Throws `ex-info` for an empty signal or an unknown mode. See also [[correlate]], [[fft-convolve]].
(fft-energy txs)(fft-energy txs options)Returns the energy spectrum |X_k|^2 of the coefficients txs (from fastmath.transform/fft).
Coefficients are complex numbers: anything fastmath.complex/ensure-complex accepts, e.g. Vec2, [re im] pairs or numbers (zero imaginary part).
For a one-sided spectrum the bins standing for two coefficients (all but DC and, for even N, Nyquist) are doubled, so the sum equals the sum over the two-sided spectrum (Parseval).
Options (default: the :fastmath.transform/fft metadata of txs):
:kind - :real for a one-sided spectrum (N/2+1 coefficients of a real signal), :complex for a two-sided spectrum (N coefficients):n - signal length N:nyquist? - without :n and metadata, true when N is even (N = 2(count-1)), false for odd N (N = 2 count - 1); a one-sided spectrum without metadata, :n and :nyquist? throws ex-info:norm - normalization used by fft: :backward (default), :ortho, :forward; values are computed for the unnormalized DFTReturns a vector of doubles. Throws ex-info when a coefficient is not a complex number or :n does not match the number of coefficients.
Returns the energy spectrum `|X_k|^2` of the coefficients `txs` (from `fastmath.transform/fft`). Coefficients are complex numbers: anything `fastmath.complex/ensure-complex` accepts, e.g. `Vec2`, `[re im]` pairs or numbers (zero imaginary part). For a one-sided spectrum the bins standing for two coefficients (all but DC and, for even `N`, Nyquist) are doubled, so the sum equals the sum over the two-sided spectrum (Parseval). Options (default: the `:fastmath.transform/fft` metadata of `txs`): * `:kind` - `:real` for a one-sided spectrum (`N/2+1` coefficients of a real signal), `:complex` for a two-sided spectrum (`N` coefficients) * `:n` - signal length `N` * `:nyquist?` - without `:n` and metadata, `true` when `N` is even (`N = 2(count-1)`), `false` for odd `N` (`N = 2 count - 1`); a one-sided spectrum without metadata, `:n` and `:nyquist?` throws `ex-info` * `:norm` - normalization used by `fft`: `:backward` (default), `:ortho`, `:forward`; values are computed for the unnormalized DFT Returns a vector of doubles. Throws `ex-info` when a coefficient is not a complex number or `:n` does not match the number of coefficients.
(fft-frequencies fs N)Returns the frequencies of the N DFT bins for sample rate fs: k fs / N for k = 0, ..., N-1 (from 0 up to fs - fs/N; bins above N/2 stand for negative frequencies (k - N) fs / N).
For a one-sided spectrum take the first N/2+1 values. Returns a vector of doubles.
Returns the frequencies of the `N` DFT bins for sample rate `fs`: `k fs / N` for `k = 0, ..., N-1` (from 0 up to `fs - fs/N`; bins above `N/2` stand for negative frequencies `(k - N) fs / N`). For a one-sided spectrum take the first `N/2+1` values. Returns a vector of doubles.
(fft-magnitude txs)(fft-magnitude txs options)Returns the magnitude spectrum |X_k| of the coefficients txs (from fastmath.transform/fft).
For a one-sided spectrum the bins standing for two coefficients (all but DC and, for even N, Nyquist) are doubled, so a sine of amplitude A at bin k gives A N.
Coefficients and options as in fft-energy. Returns a vector of doubles.
Returns the magnitude spectrum `|X_k|` of the coefficients `txs` (from `fastmath.transform/fft`). For a one-sided spectrum the bins standing for two coefficients (all but DC and, for even `N`, Nyquist) are doubled, so a sine of amplitude `A` at bin `k` gives `A N`. Coefficients and options as in [[fft-energy]]. Returns a vector of doubles.
(fft-power txs)(fft-power txs options)Returns the power spectrum, fft-energy divided by N^2: the mean square of each component, sums to the mean square of the signal (scipy.signal.periodogram with scaling='spectrum').
Coefficients and options as in fft-energy. Returns a vector of doubles.
Returns the power spectrum, [[fft-energy]] divided by `N^2`: the mean square of each component, sums to the mean square of the signal (`scipy.signal.periodogram` with `scaling='spectrum'`). Coefficients and options as in [[fft-energy]]. Returns a vector of doubles.
(filter-filter-signal FIR-or-IIR xs)Applies a filter twice, forward and backward, to cancel the phase shift (zero-phase filtering).
Parameters:
FIR-or-IIR: FIR coefficients or an IIR filter, see filter-signal.xs (sequence of numbers): Signal to filter.An IIR filter is reset between the passes but not before the forward pass. There is no edge padding, unlike scipy.signal.filtfilt. The magnitude response is squared.
Returns the filtered signal as a vector, of the same length as xs.
See also filter-signal, zero-phase.
Applies a filter twice, forward and backward, to cancel the phase shift (zero-phase filtering). Parameters: - `FIR-or-IIR`: FIR coefficients or an IIR filter, see [[filter-signal]]. - `xs` (sequence of numbers): Signal to filter. An IIR filter is reset between the passes but not before the forward pass. There is no edge padding, unlike `scipy.signal.filtfilt`. The magnitude response is squared. Returns the filtered signal as a vector, of the same length as `xs`. See also [[filter-signal]], [[zero-phase]].
(filter-signal FIR-or-IIR xs)Applies FIR coefficients or an IIR filter to a signal.
Parameters:
FIR-or-IIR: One of:
fastmath.signal.fir) - centred convolution, mode :same of convolve (as numpy.convolve(xs, fir, 'same') for N >= M, not a causal lfilter); computed directly for short signals and with FFT for long ones.fastmath.signal.iir) - causal filtering, sample by sample. The filter is mutable and keeps its state between calls, reset it with reset-IIR! before filtering another signal.xs (sequence of numbers): Signal to filter.Returns the filtered signal as a vector, of the same length as xs.
See also filter-filter-signal (zero-phase), filter-signal-1, convolve.
Applies FIR coefficients or an IIR filter to a signal. Parameters: - `FIR-or-IIR`: One of: - FIR coefficients (a sequence of numbers, see `fastmath.signal.fir`) - centred convolution, mode `:same` of [[convolve]] (as `numpy.convolve(xs, fir, 'same')` for `N >= M`, not a causal `lfilter`); computed directly for short signals and with FFT for long ones. - an IIR filter (see `fastmath.signal.iir`) - causal filtering, sample by sample. The filter is mutable and keeps its state between calls, reset it with [[reset-IIR!]] before filtering another signal. - `xs` (sequence of numbers): Signal to filter. Returns the filtered signal as a vector, of the same length as `xs`. See also [[filter-filter-signal]] (zero-phase), [[filter-signal-1]], [[convolve]].
(filter-signal-1 IIR)(filter-signal-1 IIR x)Applies an IIR filter to a single sample or creates the function doing it.
Parameters:
IIR: Filter from fastmath.signal.iir.x (double, optional): Sample to filter.With x returns the filtered sample as a double. Without x returns a function of one sample which does the same.
The filter is mutable: every call advances its internal state, use reset-IIR! to start again.
See also filter-signal, reset-IIR!.
Applies an IIR filter to a single sample or creates the function doing it. Parameters: - `IIR`: Filter from `fastmath.signal.iir`. - `x` (double, optional): Sample to filter. With `x` returns the filtered sample as a double. Without `x` returns a function of one sample which does the same. The filter is mutable: every call advances its internal state, use [[reset-IIR!]] to start again. See also [[filter-signal]], [[reset-IIR!]].
(gain-waveform w gain)Scales the amplitude of a waveform.
Parameters:
w (function): Waveform, a function (fn [t]) of the time in seconds returning the amplitude, see waveform.gain (double): Factor, a negative value inverts the waveform.Returns the waveform (fn [t]) equal to gain * (w t).
See also add-waveforms, sample-waveform.
Scales the amplitude of a waveform. Parameters: - `w` (function): Waveform, a function `(fn [t])` of the time in seconds returning the amplitude, see [[waveform]]. - `gain` (double): Factor, a negative value inverts the waveform. Returns the waveform `(fn [t])` equal to `gain * (w t)`. See also [[add-waveforms]], [[sample-waveform]].
(hilbert xs)Calculates the analytic signal x + i H(x) of a real signal with FFT, as scipy.signal.hilbert.
H(x) is the Hilbert transform of x: the signal with every component shifted in phase by 90 degrees. The analytic signal is the base of amplitude-envelope, instantaneous-phase and instantaneous-frequency.
Parameters:
xs (sequence of numbers): Real signal, not empty.Returns a vector of complex numbers (Vec2: real and imaginary part) of the same length, the real part is xs. Throws ex-info for an empty signal.
Calculates the analytic signal `x + i H(x)` of a real signal with FFT, as `scipy.signal.hilbert`. `H(x)` is the Hilbert transform of `x`: the signal with every component shifted in phase by 90 degrees. The analytic signal is the base of [[amplitude-envelope]], [[instantaneous-phase]] and [[instantaneous-frequency]]. Parameters: - `xs` (sequence of numbers): Real signal, not empty. Returns a vector of complex numbers (`Vec2`: real and imaginary part) of the same length, the real part is `xs`. Throws `ex-info` for an empty signal.
(instantaneous-frequency xs)(instantaneous-frequency xs fs)Calculates the instantaneous frequency of a real signal: the differences of the unwrapped instantaneous-phase times fs / (2 pi).
Parameters:
xs (sequence of numbers): Real signal of N samples, not empty.fs (double, optional): Sampling frequency. Default 1.0, the frequency is then in cycles per sample; with fs in Hz it is in Hz.Returns a vector of N - 1 doubles. Throws ex-info for an empty signal.
See also amplitude-envelope, hilbert.
Calculates the instantaneous frequency of a real signal: the differences of the unwrapped [[instantaneous-phase]] times `fs / (2 pi)`. Parameters: - `xs` (sequence of numbers): Real signal of `N` samples, not empty. - `fs` (double, optional): Sampling frequency. Default `1.0`, the frequency is then in cycles per sample; with `fs` in Hz it is in Hz. Returns a vector of `N - 1` doubles. Throws `ex-info` for an empty signal. See also [[amplitude-envelope]], [[hilbert]].
(instantaneous-phase xs)(instantaneous-phase xs unwrap?)Calculates the instantaneous phase of a real signal in radians: the argument of its analytic signal (hilbert).
Parameters:
xs (sequence of numbers): Real signal, not empty.unwrap? (boolean, optional): When true (default), jumps larger than pi are removed by adding multiples of 2 pi, so the phase is continuous. With false the values are in [-pi, pi].Returns a lazy sequence of doubles of the same length. Throws ex-info for an empty signal.
See also instantaneous-frequency, amplitude-envelope.
Calculates the instantaneous phase of a real signal in radians: the argument of its analytic signal ([[hilbert]]). Parameters: - `xs` (sequence of numbers): Real signal, not empty. - `unwrap?` (boolean, optional): When `true` (default), jumps larger than `pi` are removed by adding multiples of `2 pi`, so the phase is continuous. With `false` the values are in `[-pi, pi]`. Returns a lazy sequence of doubles of the same length. Throws `ex-info` for an empty signal. See also [[instantaneous-frequency]], [[amplitude-envelope]].
(kernel-smoothing-filter kernel)(kernel-smoothing-filter kernel length)(kernel-smoothing-filter kernel length step)Creates Nadaraya-Watson kernel-weighted average.
Arguments:
(kernel x y), e.g. (fastmath.kernel/kernel :gaussian)Weights kernel(0, i step), i = -(length-1)/2, ..., (length-1)/2, are normalized to sum 1. Boundary rule is to pad with zeros (weights are not renormalized at edges).
Returns filtering function which returns a vector. See also savgol-filter.
Creates Nadaraya-Watson kernel-weighted average. Arguments: * kernel - function of two numbers `(kernel x y)`, e.g. `(fastmath.kernel/kernel :gaussian)` * length - odd length of the kernel (default: 5) * step - distance between consecutive samples (default: 1.0) Weights `kernel(0, i step)`, `i = -(length-1)/2, ..., (length-1)/2`, are normalized to sum 1. Boundary rule is to pad with zeros (weights are not renormalized at edges). Returns filtering function which returns a vector. See also [[savgol-filter]].
(linear->db x)Converts a linear amplitude ratio to decibels: 20 log10(x).
1.0 gives 0, 10.0 gives 20, 2.0 gives about 6.02. 0.0 gives -Infinity and a negative x gives NaN. For a power ratio the factor is 10 instead of 20.
Returns a double. See also db->linear.
Converts a linear amplitude ratio to decibels: `20 log10(x)`. `1.0` gives `0`, `10.0` gives `20`, `2.0` gives about `6.02`. `0.0` gives `-Infinity` and a negative `x` gives `NaN`. For a power ratio the factor is `10` instead of `20`. Returns a double. See also [[db->linear]].
(load-signal filename)Reads a signal from a file of 16 bit signed samples, big endian.
Samples are mapped linearly from [-32768, 32767] onto [-1, 1] (see save-signal). Use Audacity or SoX to convert an audio file to this format.
Parameters:
filename (string or java.io.File): Path of the file.Returns the signal as a double-array of length floor(bytes / 2), a trailing odd byte is ignored. Throws java.io.FileNotFoundException when the file does not exist.
Reads a signal from a file of 16 bit signed samples, big endian. Samples are mapped linearly from `[-32768, 32767]` onto `[-1, 1]` (see [[save-signal]]). Use Audacity or SoX to convert an audio file to this format. Parameters: - `filename` (string or `java.io.File`): Path of the file. Returns the signal as a `double-array` of length `floor(bytes / 2)`, a trailing odd byte is ignored. Throws `java.io.FileNotFoundException` when the file does not exist.
(moving-average-filter)(moving-average-filter length)Creates a moving average filter: every sample is replaced by the mean of length samples centred at it, the signal is zero padded at both ends.
Parameters:
length (odd positive integer, optional): Size of the window. Default 5.Returns a function which accepts a sequence of numbers and returns the smoothed signal as a vector of the same length. Throws ex-info for an even or non-positive length.
This is savgol-filter of order 0. See also kernel-smoothing-filter.
Creates a moving average filter: every sample is replaced by the mean of `length` samples centred at it, the signal is zero padded at both ends. Parameters: - `length` (odd positive integer, optional): Size of the window. Default `5`. Returns a function which accepts a sequence of numbers and returns the smoothed signal as a vector of the same length. Throws `ex-info` for an even or non-positive `length`. This is [[savgol-filter]] of order 0. See also [[kernel-smoothing-filter]].
(pad signal)(pad signal N)(pad signal N pad-method)(pad signal N pad-method side)Pad a 1D signal to a specified length using various boundary conditions.
Extends a signal to a target length N, which is a common preprocessing step for transforms that require power-of-two input sizes (like FFT or DWT) or to mitigate edge artifacts during filtering and convolution. The function supports multiple padding strategies to maintain signal continuity or satisfy specific boundary assumptions.
Parameters:
signal - A sequence or array of real numbers representing the input signal.N - The desired target length (must be greater than or equal to the current signal length). If not provided, defaults to the smallest power of two greater than or equal to the signal length.pad-method - A keyword specifying the padding strategy (default is :periodic):
:zero - Appends zeros.:edge - Repeats the last/first value.:linear - Linear ramp between the edge and zero.:periodic - Circular padding (repeats the signal).:symmetric - Mirroring at the edge (repeats edge values).:antisymmetric - Mirroring with sign inversion.:reflect - Mirroring at the edge (does not repeat edge values).:antireflect - Anti-mirroring at the edge.side - A keyword specifying where to apply the padding: :left, :right, or :both (default).Returns a double array of length N containing the padded signal.
Pad a 1D signal to a specified length using various boundary conditions.
Extends a signal to a target length `N`, which is a common preprocessing step for transforms that require power-of-two input sizes (like FFT or DWT) or to mitigate edge artifacts during filtering and convolution. The function supports multiple padding strategies to maintain signal continuity or satisfy specific boundary assumptions.
Parameters:
* `signal` - A sequence or array of real numbers representing the input signal.
* `N` - The desired target length (must be greater than or equal to the current signal length). If not provided, defaults to the smallest power of two greater than or equal to the signal length.
* `pad-method` - A keyword specifying the padding strategy (default is `:periodic`):
* `:zero` - Appends zeros.
* `:edge` - Repeats the last/first value.
* `:linear` - Linear ramp between the edge and zero.
* `:periodic` - Circular padding (repeats the signal).
* `:symmetric` - Mirroring at the edge (repeats edge values).
* `:antisymmetric` - Mirroring with sign inversion.
* `:reflect` - Mirroring at the edge (does not repeat edge values).
* `:antireflect` - Anti-mirroring at the edge.
* `side` - A keyword specifying where to apply the padding: `:left`, `:right`, or `:both` (default).
Returns a double array of length `N` containing the padded signal.(periodogram xs)(periodogram
xs
{:keys [method average db?] :or {method :psd average :mean} :as options})Estimate the spectral density of a signal with Welch's method.
The signal is split into windowed segments (see stft), spectral values are calculated for each segment and averaged. It equals scipy.signal.welch with detrend=False and noverlap = wlen - round((1 - overlap) wlen).
Input parameters:
xs - Input time-domain signal (sequence of doubles), not shorter than the window.options - A map of configuration keys:
:method - values calculated for segments, as in stft: :psd (default, scaling='density'), :power (scaling='spectrum'), :energy, :magnitude, :amplitude, :asd, :phase, :real, :imag.:average - aggregation of segments: :mean (default), :median or :umedian (median divided by the bias of the median for the number of segments, average='median' in scipy).:db? - convert the averaged values to decibels, as in stft.:window, :overlap, :fs, :spectrum, :norm - as in stft.Returns a map containing:
:freqs - Frequencies of the bins.:spectrum - Averaged spectral values.Throws ex-info for a signal shorter than the window, an unknown :method (also :complex) or :average.
Estimate the spectral density of a signal with Welch's method. The signal is split into windowed segments (see [[stft]]), spectral values are calculated for each segment and averaged. It equals `scipy.signal.welch` with `detrend=False` and `noverlap = wlen - round((1 - overlap) wlen)`. Input parameters: * `xs` - Input time-domain signal (sequence of doubles), not shorter than the window. * `options` - A map of configuration keys: * `:method` - values calculated for segments, as in [[stft]]: `:psd` (default, `scaling='density'`), `:power` (`scaling='spectrum'`), `:energy`, `:magnitude`, `:amplitude`, `:asd`, `:phase`, `:real`, `:imag`. * `:average` - aggregation of segments: `:mean` (default), `:median` or `:umedian` (median divided by the bias of the median for the number of segments, `average='median'` in scipy). * `:db?` - convert the averaged values to decibels, as in [[stft]]. * `:window`, `:overlap`, `:fs`, `:spectrum`, `:norm` - as in [[stft]]. Returns a map containing: * `:freqs` - Frequencies of the bins. * `:spectrum` - Averaged spectral values. Throws `ex-info` for a signal shorter than the window, an unknown `:method` (also `:complex`) or `:average`.
(resample xs nsize)Resamples a signal to nsize samples using FFT interpolation, as scipy.signal.resample.
The signal is assumed to be periodic, so for a signal which is not, the edges can show ringing.
Parameters:
xs (sequence of numbers): Real signal, not empty.nsize (integer): Number of samples of the result, at least 1. For nsize equal to the length of xs the signal is returned as doubles.Returns a vector of doubles. Throws ex-info for an empty signal or nsize less than 1.
Resamples a signal to `nsize` samples using FFT interpolation, as `scipy.signal.resample`. The signal is assumed to be periodic, so for a signal which is not, the edges can show ringing. Parameters: - `xs` (sequence of numbers): Real signal, not empty. - `nsize` (integer): Number of samples of the result, at least `1`. For `nsize` equal to the length of `xs` the signal is returned as doubles. Returns a vector of doubles. Throws `ex-info` for an empty signal or `nsize` less than `1`. See also [[pad]], [[spectrum]].
(reset-effects e)Resets the state of an effect (single or composed) to the initial one.
Parameters:
e (effect): Effect created with effect or compose-effects.Returns a new effect with the initial state of every part and the last output sample 0.0. The argument is not changed.
See also apply-effects (its reset argument), compose-effects.
Resets the state of an effect (single or composed) to the initial one. Parameters: - `e` (effect): Effect created with [[effect]] or [[compose-effects]]. Returns a new effect with the initial state of every part and the last output sample `0.0`. The argument is not changed. See also [[apply-effects]] (its `reset` argument), [[compose-effects]].
(reset-IIR! IIR)Resets the internal state of an IIR filter.
The filter keeps its state between calls of filter-signal and filter-signal-1, reset it before filtering another signal.
Parameters:
IIR: Filter from fastmath.signal.iir.Returns the same (mutated) filter.
Resets the internal state of an IIR filter. The filter keeps its state between calls of [[filter-signal]] and [[filter-signal-1]], reset it before filtering another signal. Parameters: - `IIR`: Filter from `fastmath.signal.iir`. Returns the same (mutated) filter.
(sample-waveform waveform-fn fs)(sample-waveform waveform-fn fs time)Discretize a continuous waveform function into a sequence of samples.
Evaluates a time-dependent function at t = i / fs for every i >= 0 with t < time (ceil(fs time) samples, as numpy.arange(0, time, 1/fs); a product fs time within 1e-9 relative of an integer counts as that integer, so fs 10, time 0.3 gives 3 samples).
Input parameters:
waveform-fn - A function (fn [t]) that accepts time as a double and returns the signal amplitude. Usually created via waveform or chirp.fs - Sampling frequency in Hz (samples per second), positive.time - The total duration of the signal to generate in seconds. Defaults to 1.0.Returns a vector of doubles. Throws ex-info when fs is not positive.
Discretize a continuous waveform function into a sequence of samples. Evaluates a time-dependent function at `t = i / fs` for every `i >= 0` with `t < time` (`ceil(fs time)` samples, as `numpy.arange(0, time, 1/fs)`; a product `fs time` within `1e-9` relative of an integer counts as that integer, so `fs 10, time 0.3` gives 3 samples). Input parameters: * `waveform-fn` - A function `(fn [t])` that accepts time as a double and returns the signal amplitude. Usually created via [[waveform]] or [[chirp]]. * `fs` - Sampling frequency in Hz (samples per second), positive. * `time` - The total duration of the signal to generate in seconds. Defaults to `1.0`. Returns a vector of doubles. Throws `ex-info` when `fs` is not positive.
(save-signal sig filename)Saves a signal to a file as 16 bit signed samples, big endian.
Values are clipped to [-1, 1] and mapped linearly onto [-32768, 32767], so 0.0 reads back as about 1.5e-5 (see load-signal). Use Audacity or SoX to convert the file to or from an audio format.
Parameters:
sig (sequence of numbers): Signal to save.filename (string or java.io.File): Path of the file. Missing parent directories are created, an existing file is overwritten.Returns the signal as a double-array (not clipped).
Saves a signal to a file as 16 bit signed samples, big endian. Values are clipped to `[-1, 1]` and mapped linearly onto `[-32768, 32767]`, so `0.0` reads back as about `1.5e-5` (see [[load-signal]]). Use Audacity or SoX to convert the file to or from an audio format. Parameters: - `sig` (sequence of numbers): Signal to save. - `filename` (string or `java.io.File`): Path of the file. Missing parent directories are created, an existing file is overwritten. Returns the signal as a `double-array` (not clipped).
(savgol-filter)(savgol-filter length)(savgol-filter length order)(savgol-filter length order derivative)(savgol-filter length order derivative delta)Creates Savitzky-Golay smoothing (or differentiating) filter.
Arguments:
length (default: 2)0 <= derivative <= order (default: 0)Boundary rule is to pad with zeros (as scipy.signal.savgol_filter with mode='constant').
Returns filtering function which accepts collection of numbers and returns filtered signal (a vector). Throws ex-info for invalid arguments.
Creates Savitzky-Golay smoothing (or differentiating) filter. Arguments: * length - odd length of the kernel (default: 5) * order - polynomial order, less than `length` (default: 2) * derivative - order of the derivative, `0 <= derivative <= order` (default: 0) * delta - spacing of the samples, used for derivatives (default: 1.0) Boundary rule is to pad with zeros (as `scipy.signal.savgol_filter` with `mode='constant'`). Returns filtering function which accepts collection of numbers and returns filtered signal (a vector). Throws `ex-info` for invalid arguments.
(single-pass e sample)Processes one sample with an effect.
Parameters:
e (effect): Effect created with effect or compose-effects.sample (double): Input sample.Returns a new effect with the advanced state. The output sample is the value of the returned effect called without arguments: ((single-pass e x)). The argument is not changed. Calling an effect with a sample, (e x), is the same as (single-pass e x).
See also apply-effects, reset-effects.
Processes one sample with an effect. Parameters: - `e` (effect): Effect created with [[effect]] or [[compose-effects]]. - `sample` (double): Input sample. Returns a new effect with the advanced state. The output sample is the value of the returned effect called without arguments: `((single-pass e x))`. The argument is not changed. Calling an effect with a sample, `(e x)`, is the same as `(single-pass e x)`. See also [[apply-effects]], [[reset-effects]].
(spectrum xs)(spectrum xs
{:keys [method db? fs domain]
:or {method :amplitude db? false fs 1.0 domain :time}
:as options})Returns the frequency spectrum of a signal using FFT.
Values follow scipy.signal.periodogram with a boxcar window and no detrending.
Input parameters:
xs - Input signal. Can be a sequence of doubles (time-domain) or a sequence of complex coefficients, e.g. from fastmath.transform/fft (frequency-domain): anything fastmath.complex/ensure-complex accepts, e.g. Vec2, [re im] pairs or numbers (zero imaginary part).options - A map of configuration keys:
:method - :magnitude (|X_k|), :amplitude (default, magnitude / N), :energy (|X_k|^2), :power (energy / N^2, scaling='spectrum'), :psd (power spectral density, energy / (N fs), scaling='density'), :asd (amplitude spectral density, sqrt(psd)), :phase (angle in radians), :real, :imag or :complex (coefficients as Vec2). For a one-sided spectrum magnitude and energy of the bins standing for two coefficients (all but DC and, for even N, Nyquist) are doubled.:db? - convert to decibels: 10 log10 for :energy, :power, :psd, 20 log10 for :magnitude, :amplitude, :asd (0 gives -Infinity); other methods unchanged. Default false.:fs - The sampling frequency. Default is 1.0.:domain - :time (default, xs is transformed with fastmath.transform/fft, options are passed to it, e.g. :spectrum :double-sided, :norm) or :frequency (xs are coefficients).:kind, :n, :nyquist?, :norm - layout of coefficients for :domain :frequency when they have no fft metadata, see fft-energy.Returns a map containing:
:N - The number of samples of the signal.:spectrum - A vector of spectral values.:freqs - Frequencies of the bins (see fft-frequencies).Throws ex-info for an empty signal, a coefficient which is not a complex number, an unknown :method or :domain.
Returns the frequency spectrum of a signal using FFT. Values follow `scipy.signal.periodogram` with a boxcar window and no detrending. Input parameters: * `xs` - Input signal. Can be a sequence of doubles (time-domain) or a sequence of complex coefficients, e.g. from `fastmath.transform/fft` (frequency-domain): anything `fastmath.complex/ensure-complex` accepts, e.g. `Vec2`, `[re im]` pairs or numbers (zero imaginary part). * `options` - A map of configuration keys: * `:method` - `:magnitude` (`|X_k|`), `:amplitude` (default, magnitude / N), `:energy` (`|X_k|^2`), `:power` (energy / N^2, `scaling='spectrum'`), `:psd` (power spectral density, energy / (N fs), `scaling='density'`), `:asd` (amplitude spectral density, `sqrt(psd)`), `:phase` (angle in radians), `:real`, `:imag` or `:complex` (coefficients as `Vec2`). For a one-sided spectrum magnitude and energy of the bins standing for two coefficients (all but DC and, for even `N`, Nyquist) are doubled. * `:db?` - convert to decibels: `10 log10` for `:energy`, `:power`, `:psd`, `20 log10` for `:magnitude`, `:amplitude`, `:asd` (0 gives `-Infinity`); other methods unchanged. Default `false`. * `:fs` - The sampling frequency. Default is `1.0`. * `:domain` - `:time` (default, `xs` is transformed with `fastmath.transform/fft`, `options` are passed to it, e.g. `:spectrum :double-sided`, `:norm`) or `:frequency` (`xs` are coefficients). * `:kind`, `:n`, `:nyquist?`, `:norm` - layout of coefficients for `:domain :frequency` when they have no `fft` metadata, see [[fft-energy]]. Returns a map containing: * `:N` - The number of samples of the signal. * `:spectrum` - A vector of spectral values. * `:freqs` - Frequencies of the bins (see [[fft-frequencies]]). Throws `ex-info` for an empty signal, a coefficient which is not a complex number, an unknown `:method` or `:domain`.
(stft xs)(stft xs
{:keys [window overlap fs method db?]
:or {overlap 0.5 fs 1.0 method :power}
:as options})Computes the Short-Time Fourier Transform (STFT) of a 1D signal.
The signal is split into segments of the window length, shifted by round((1 - overlap) wlen) samples (at least 1); the last partial segment is dropped. Each segment is multiplied by the window and transformed.
Input parameters:
xs - Input time-domain signal (sequence of doubles), not shorter than the window.options - A map of configuration keys:
:window - A sequence of window coefficients (e.g., from fastmath.kernel/window). Default: Gaussian window of length min(N, 256) (256 is the scipy default segment length).:overlap - The fraction of overlap between adjacent segments, in [0, 1). Default is 0.5.:fs - The sampling frequency. Default is 1.0.:method - Values for each segment, as in spectrum with the window taken into account: :power (energy / (sum of window)^2, scipy.signal.spectrogram with scaling='spectrum'), :psd (energy / (fs sum of squared window), scaling='density'), :asd (sqrt(psd)), :energy, :magnitude, :amplitude (magnitude / sum of window), :phase, :real, :imag, :complex (coefficients). Default is :power. Like spectrum, one-sided :magnitude and :amplitude are doubled on the bins standing for two coefficients (peak amplitude; scipy mode='magnitude' does not double), so there amplitude^2 = 2 power (peak versus mean square).:db? - convert values to decibels: 10 log10 for :energy, :power, :psd, 20 log10 for :magnitude, :amplitude, :asd (0 gives -Infinity); other methods unchanged. Default false.:spectrum, :norm - passed to fastmath.transform/fft (one-sided by default).Returns a map containing:
:N - The number of samples in the input signal.:spectrum - A vector of spectra (vectors), one for each segment.:freqs - Frequencies of the bins.:times - Times of the segment centres, (wlen/2 + i shift) / fs.Throws ex-info for an empty signal or window, a signal shorter than the window, :overlap outside [0, 1) or an unknown method.
Computes the Short-Time Fourier Transform (STFT) of a 1D signal. The signal is split into segments of the window length, shifted by `round((1 - overlap) wlen)` samples (at least 1); the last partial segment is dropped. Each segment is multiplied by the window and transformed. Input parameters: * `xs` - Input time-domain signal (sequence of doubles), not shorter than the window. * `options` - A map of configuration keys: * `:window` - A sequence of window coefficients (e.g., from `fastmath.kernel/window`). Default: Gaussian window of length `min(N, 256)` (256 is the scipy default segment length). * `:overlap` - The fraction of overlap between adjacent segments, in `[0, 1)`. Default is `0.5`. * `:fs` - The sampling frequency. Default is `1.0`. * `:method` - Values for each segment, as in [[spectrum]] with the window taken into account: `:power` (energy / (sum of window)^2, `scipy.signal.spectrogram` with `scaling='spectrum'`), `:psd` (energy / (fs sum of squared window), `scaling='density'`), `:asd` (`sqrt(psd)`), `:energy`, `:magnitude`, `:amplitude` (magnitude / sum of window), `:phase`, `:real`, `:imag`, `:complex` (coefficients). Default is `:power`. Like [[spectrum]], one-sided `:magnitude` and `:amplitude` are doubled on the bins standing for two coefficients (peak amplitude; scipy `mode='magnitude'` does not double), so there `amplitude^2 = 2 power` (peak versus mean square). * `:db?` - convert values to decibels: `10 log10` for `:energy`, `:power`, `:psd`, `20 log10` for `:magnitude`, `:amplitude`, `:asd` (0 gives `-Infinity`); other methods unchanged. Default `false`. * `:spectrum`, `:norm` - passed to `fastmath.transform/fft` (one-sided by default). Returns a map containing: * `:N` - The number of samples in the input signal. * `:spectrum` - A vector of spectra (vectors), one for each segment. * `:freqs` - Frequencies of the bins. * `:times` - Times of the segment centres, `(wlen/2 + i shift) / fs`. Throws `ex-info` for an empty signal or window, a signal shorter than the window, `:overlap` outside `[0, 1)` or an unknown method.
(waveform wave-type)(waveform wave-type options)Create a waveform function (oscillator) for signal generation.
This function returns a stateless oscillator that maps time (as a double) to a signal value. It supports a variety of wave shapes, including standard geometric oscillators, 'analog-style' approximations, and additive band-limited synthesis to reduce aliasing. Parameters such as frequency, amplitude, and phase can be provided as constant numbers or as functions of time, enabling complex modulations (FM/AM).
Input parameters:
wave-type - A keyword selecting the waveform shape:
:sine, :square, :saw, :triangle.:analog-sine, :analog-saw, :analog-triangle.:band-limited-square, :band-limited-saw, :band-limited-triangle.options - A map of configuration keys:
:f - Frequency in Hz (number, default 1.0), or a phase function (fn [t]) returning the phase in cycles (used instead of f t), for frequency modulation as in chirp.:phase - Phase offset in cycles [0.0 to 1.0]. Can be a number or a function (fn [t]). Default: 0.0.:amplitude - Peak amplitude. Can be a number or a function (fn [t]) for amplitude modulation. Default: 1.0.:duty - Duty cycle for :square waves, ranging from 0.0 to 1.0 or (fn [t]) for modulation. Default: 0.5.:up? - Boolean for :saw and :analog-saw waves. Set to true (default) for a rising ramp, false for a falling ramp.:bands - Number of harmonics for :band-limited-* types. Increasing this value improves shape accuracy but increases computation. Default: 5.The waves are periodic also for negative time; shapes and their relation to scipy.signal.square / sawtooth are described in fastmath.signal.waveform.
Returns a function (fn [t]) that accepts time t as a double and returns the signal value as a double. Throws ex-info for an unknown wave-type.
Create a waveform function (oscillator) for signal generation.
This function returns a stateless oscillator that maps time (as a double) to a signal value. It supports a variety of wave shapes, including standard geometric oscillators, 'analog-style' approximations, and additive band-limited synthesis to reduce aliasing. Parameters such as frequency, amplitude, and phase can be provided as constant numbers or as functions of time, enabling complex modulations (FM/AM).
Input parameters:
* `wave-type` - A keyword selecting the waveform shape:
* Basic: `:sine`, `:square`, `:saw`, `:triangle`.
* Analog-style: `:analog-sine`, `:analog-saw`, `:analog-triangle`.
* Band-limited: `:band-limited-square`, `:band-limited-saw`, `:band-limited-triangle`.
* `options` - A map of configuration keys:
* `:f` - Frequency in Hz (number, default `1.0`), or a phase function `(fn [t])` returning the phase in cycles (used instead of `f t`), for frequency modulation as in [[chirp]].
* `:phase` - Phase offset in cycles [0.0 to 1.0]. Can be a number or a function `(fn [t])`. Default: `0.0`.
* `:amplitude` - Peak amplitude. Can be a number or a function `(fn [t])` for amplitude modulation. Default: `1.0`.
* `:duty` - Duty cycle for `:square` waves, ranging from 0.0 to 1.0 or `(fn [t])` for modulation. Default: `0.5`.
* `:up?` - Boolean for `:saw` and `:analog-saw` waves. Set to `true` (default) for a rising ramp, `false` for a falling ramp.
* `:bands` - Number of harmonics for `:band-limited-*` types. Increasing this value improves shape accuracy but increases computation. Default: `5`.
The waves are periodic also for negative time; shapes and their relation to `scipy.signal.square` / `sawtooth` are described in `fastmath.signal.waveform`.
Returns a function `(fn [t])` that accepts time `t` as a double and returns the signal value as a double. Throws `ex-info` for an unknown `wave-type`.(zero-phase xs)Sets the phase of every component of the spectrum of a signal to zero and keeps the magnitudes.
The signal is transformed with FFT, every coefficient is replaced by its magnitude and the result is transformed back. The result is real and symmetric (the sample k equals the sample N - k), so its energy is concentrated around the first sample.
Parameters:
xs (sequence of numbers): Real signal, not empty.Returns a vector of the same length. Throws ex-info for an empty signal.
See also filter-filter-signal (zero-phase filtering), hilbert.
Sets the phase of every component of the spectrum of a signal to zero and keeps the magnitudes. The signal is transformed with FFT, every coefficient is replaced by its magnitude and the result is transformed back. The result is real and symmetric (the sample `k` equals the sample `N - k`), so its energy is concentrated around the first sample. Parameters: - `xs` (sequence of numbers): Real signal, not empty. Returns a vector of the same length. Throws `ex-info` for an empty signal. See also [[filter-filter-signal]] (zero-phase filtering), [[hilbert]].
cljdoc builds & hosts documentation for Clojure/Script libraries
| Ctrl+k | Jump to recent docs |
| ← | Move to previous article |
| → | Move to next article |
| Ctrl+/ | Jump to the search field |