API reference¶
All public names are importable from fastgoertzel. The signatures below are those of
the shipped type stubs (fastgoertzel/_core.pyi), which CI checks against the compiled
module. ArrayLike is anything NumPy converts to a 1-D float64 array; str arguments
named scale accept "amplitude", "magnitude" or "power".
One frequency¶
- fastgoertzel.goertzel(x: ArrayLike, frequency: float, *, fs: float | None = None, scale: str = 'amplitude') tuple[float, float]¶
Amplitude and phase of
xat exactlyfrequency(generalized Goertzel).- Parameters:
x (array_like) – 1-dimensional sequence of samples. Converted to a contiguous float64 array.
frequency (float) – Frequency to evaluate. In cycles per sample,
[0, 1), unlessfsis given, in which case it is in the same unit asfsand must be in[0, fs). Any value is evaluated exactly; nothing is rounded to a DFT bin. Values above half the sample rate alias onto their mirror image.fs (float, optional) – Sample rate.
frequency / fsis the normalized frequency.scale ({'amplitude', 'magnitude', 'power'}) –
'amplitude'(default) returns2|X|/N, the amplitude of a sinusoid at that frequency (|X|/Nat DC and Nyquist).'magnitude'returns|X|and'power'returns|X|**2, both without normalization.
- Returns:
tuple[float, float] –
(value, phase).phaseis in radians, cosine-referenced as innumpy.fft:cos(2*pi*f*n + p)reportsp.- Raises:
ValueError – Empty or non-1-D
x;frequencyoutside its range or not finite;fsnot positive and finite; unknownscale.
Notes
Single-threaded by design (predictable latency). Signals of 1024 samples or more are split into independent blocks of at least 512 samples (up to eight) so that the recurrence’s dependency chain does not limit throughput; the blocks are combined exactly.
Examples
>>> import numpy as np, fastgoertzel >>> t = np.arange(4410) # 44 whole cycles of 440 Hz at 44.1 kHz >>> x = np.cos(2 * np.pi * 440 / 44100 * t + 0.25) >>> amp, phase = fastgoertzel.goertzel(x, 440, fs=44100) >>> round(amp, 3), round(phase, 3) (1.0, 0.25)
- fastgoertzel.goertzel_complex(x: ArrayLike, frequency: float, *, fs: float | None = None) complex¶
Unscaled complex DTFT value
X = sum x[n] exp(-2j*pi*f*n)atfrequency.Same arguments and validation as
goertzel(). Use this when you need the complex value or want to avoid thesqrt/atan2of the amplitude form.
- fastgoertzel.goertzel_bin(x: ArrayLike, k: int, *, scale: str = 'amplitude') tuple[float, float]¶
Amplitude and phase of DFT bin
kofx(kin[0, len(x))).Equivalent to
goertzel(x, k / len(x))but with the twiddles computed in exact integer arithmetic, so it matchesnumpy.fft.fft(x)[k]as closely as the recurrence allows. This is what versions 1.x computed for every call after truncatingfrequency * len(x)to an integer.
Several frequencies¶
- fastgoertzel.goertzel_batch(x: ArrayLike, frequencies: ArrayLike, *, fs: float | None = None, scale: str = 'amplitude', threads: int | None = None, out: NDArray[np.float64] | None = None) NDArray[np.float64]¶
goertzel()for every entry offrequenciesin one call.- Parameters:
x (array_like) – 1-dimensional sequence of samples.
frequencies (array_like) – 1-dimensional sequence of frequencies (cycles per sample, or in the unit of
fswhen given).fs – As in
goertzel().scale – As in
goertzel().threads (int, optional) – OpenMP thread count for this call.
Noneuses the OpenMP default (OMP_NUM_THREADS);1forces serial execution. Ignored in builds without OpenMP. Results do not depend on the thread count.out (numpy.ndarray, optional) – Preallocated result array: float64, C-contiguous, writeable, shape
(len(frequencies), 2), not sharing memory withx. The call then allocates nothing and returnsout.
- Returns:
numpy.ndarray – Shape
(len(frequencies), 2): column 0 is the scaled value, column 1 the phase. Rowiisgoertzel(x, frequencies[i], ...)up to rounding.
Notes
Up to eight frequencies share one pass over the signal; fewer frequencies are padded with signal blocks of at least 512 samples so that up to eight independent chains run, and large batches use more lanes still. The parallel region is entered only when
len(x) * len(frequencies) >= 65536. The GIL is released during computation.
- fastgoertzel.goertzel_batch_complex(x: ArrayLike, frequencies: ArrayLike, *, fs: float | None = None, threads: int | None = None, out: NDArray[np.complex128] | None = None) NDArray[np.complex128]¶
goertzel_complex()for every entry offrequencies; returns a complex128 array of shape(len(frequencies),).outmay be a preallocated complex128 array of that shape, as ingoertzel_batch().
Sliding windows¶
- fastgoertzel.goertzel_sliding_batch(x: ArrayLike, window_size: int, frequencies: ArrayLike, *, step: int = 1, fs: float | None = None, scale: str = 'amplitude', threads: int | None = None, out: NDArray[np.float64] | None = None) NDArray[np.float64]¶
goertzel_batch()over sliding windows ofx.- Parameters:
x (array_like) – 1-dimensional sequence of samples.
window_size (int) – Length of each window, in
[1, len(x)].frequencies (array_like) – 1-dimensional sequence of frequencies.
step (int) – Hop between consecutive windows (default 1). Window
wcoversx[w*step : w*step + window_size]and there are(len(x) - window_size) // step + 1windows.fs – As in
goertzel_batch().scale – As in
goertzel_batch().threads – As in
goertzel_batch().out (numpy.ndarray, optional) – Preallocated result array: float64, C-contiguous, writeable, shape
(n_windows, len(frequencies), 2), not sharing memory withx. With a reusedoutthe call allocates nothing; see Notes.
- Returns:
numpy.ndarray – Shape
(n_windows, len(frequencies), 2).
Notes
When
4 * step < window_sizeconsecutive windows are obtained with the sliding DFT update, which costs a constant amount per hop regardless ofwindow_size; every 256 windows the value is recomputed exactly, so rounding error cannot accumulate. Otherwise each window is computed from scratch. Work is distributed over OpenMP threads by (frequency, 256-window chunk); results do not depend on the thread count. The GIL is released.The result array is large (
n_windows * len(frequencies) * 16bytes) and, when freshly allocated, is page-faulted in by the writing threads, which serialises in the kernel and bounds the thread scaling. In a loop that calls this repeatedly, pass the sameouteach time.
- fastgoertzel.goertzel_sliding_batch_complex(x: ArrayLike, window_size: int, frequencies: ArrayLike, *, step: int = 1, fs: float | None = None, threads: int | None = None, out: NDArray[np.complex128] | None = None) NDArray[np.complex128]¶
goertzel_sliding_batch()returning the unscaled complex DTFT of every window.Same arguments as
goertzel_sliding_batch()withoutscale. Returns a complex128 array of shape(n_windows, len(frequencies)), oroutif given. Skips thesqrtandatan2per window, which dominate the cost of the (value, phase) form once the sliding update has made the window length irrelevant.
Streaming¶
- class fastgoertzel.GoertzelFilter(frequency: float, *, fs: float | None = None)¶
Stateful Goertzel filter for streaming input.
Create it for one frequency,
pushsamples as they arrive (scalars or arrays, any chunking), and readresult()at any time; it isgoertzelapplied to everything pushed so far (equal to rounding).reset()clears the state. Instances are cheap and hold no buffers. Do notpushto the same instance from two threads at once.Examples
>>> import numpy as np, fastgoertzel >>> flt = fastgoertzel.GoertzelFilter(440, fs=44100) >>> for chunk in np.array_split(np.cos(2 * np.pi * 440 / 44100 * np.arange(4410)), 7): ... flt.push(chunk) >>> amp, phase = flt.result() >>> round(amp, 6), flt.n_samples (1.0, 4410)
- property frequency¶
Frequency as passed to the constructor.
- property fs¶
Sample rate, or
None.
- property n_samples¶
Number of samples pushed since construction or the last reset.
- property normalized_frequency¶
Frequency in cycles per sample.