RiptideRiptide
Download Riptide SDKInstall Riptorch
Menu
Raya docs · Numerical computing

FFT and signal processing

Mixed-radix and Bluestein FFT, real and n-D FFT, DCT, convolution, FIR and IIR filter design, windows, resampling and spectral analysis.

import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'package:riptide_numerics_signal/fft.ray';
import 'package:riptide_numerics_signal/signal.ray';
18 classes105 functions and methods97 of 182 documented96 runnable examplesWhat numpy.fft and scipy.signal do

Overview

FFT and signal processing.

LibraryContents
fft.rayFftPlan (mixed-radix \frac{\frac{\frac{4}{2}}{3}}{5} + generic, Bluestein for large prime factors), RealFftPlan, numpy.fft-shaped fft/ifft/rfft/irfft/fftn/ifftn/rfftn/irfftn/fftfreq/fftshift, dct/idct/dst/idst types I-IV, fftGraph (batched GPU FFT as a riptide_tensor graph)
signal.rayconvolve/correlate (direct, FFT, overlap-add, auto), fftconvolveNd; Window (hann, hamming, blackman, blackman-harris, bartlett, flattop, kaiser, gaussian, tukey); firwin; butter/cheby1/cheby2 (zpk, .toSos, .toBa); lfilter, sosfilt, filtfilt, sosfiltfilt, freqz, sosfreqz; resample, resamplePoly, upfirdn, decimate; periodogram, welch, spectrogram, stft/istft
final spec = rfft(samples);                                   // n/2+1 interleaved complex bins
final plan = FftPlan(4096);                                   // reusable, no allocation per call
plan.forward(buffer);                                         // in place, interleaved re/im
final sos = butter(4, [0.1, 0.3], btype: BandType.bandpass).toSos();
final clean = sosfiltfilt(sos, signal);                       // zero phase
final psd = welch(signal, fs: 48000, nperseg: 1024);

Separate from riptide_numerics_calculus because nothing here needs derivatives or dense solves, and an audio or image pipeline should not pull in the solvers. Complex data is interleaved Float64List (re, im, re, im...), the layout NumPy's complex128 and part A's complex NDArray use. The hard-coded FFT passes run on Float64x2List views of that memory (one complex per SIMD register), 1.2-1.5x faster than scalar passes on other runtimes AOT.

Ported from PocketFFT C (BSD-3-Clause, Martin Reinecke; KissFFT, BSD-3-Clause, uses the same decomposition); filter design, filtering, resampling and spectral semantics follow SciPy's scipy.signal (BSD-3-Clause). Never GPL. Timing: benchmark/fft_bench.ray (AOT).

Functions and constants

Functions

fftPlanfunction
FftPlan fftPlan(int n)

The cached complex plan for length n.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

double mag(Float64List c, int k) => math.sqrt(c[2 * k] * c[2 * k] + c[2 * k + 1] * c[2 * k + 1]);

void main() {
  // 64 samples at 64 Hz: 5 Hz plus a weaker 12 Hz tone.
  const n = 64;
  final x = Float64List.fromList([for (var i = 0; i < n; i++) math.sin(2 * math.pi * 5 * i / n) + 0.5 * math.sin(2 * math.pi * 12 * i / n)]);
  final c = Float64List(2 * n);
  for (var i = 0; i < n; i++) {
    c[2 * i] = x[i];
  }
  final plan = fftPlan(n); // reuse for many transforms of length 64
  plan.forward(c);
  print('peaks at k = 5: ${mag(c, 5).toStringAsFixed(3)}, k = 12: ${mag(c, 12).toStringAsFixed(3)}');
}
Output
peaks at k = 5: 32.000, k = 12: 16.000
realFftPlanfunction
RealFftPlan realFftPlan(int n)

The cached real plan for length n.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

double mag(Float64List c, int k) => math.sqrt(c[2 * k] * c[2 * k] + c[2 * k + 1] * c[2 * k + 1]);

void main() {
  // 64 samples at 64 Hz: 5 Hz plus a weaker 12 Hz tone.
  const n = 64;
  final x = Float64List.fromList([for (var i = 0; i < n; i++) math.sin(2 * math.pi * 5 * i / n) + 0.5 * math.sin(2 * math.pi * 12 * i / n)]);
  final plan = realFftPlan(n);
  final out = Float64List(n + 2);
  plan.forward(x, out);
  print('${out.length ~/ 2} bins; |X_5| = ${mag(out, 5).toStringAsFixed(3)}');
}
Output
33 bins; |X_5| = 32.000
fftfunction
Float64List fft(Float64List x, {int? n, FftNorm norm = FftNorm.backward})

The DFT of interleaved complex x (numpy.fft.fft). n pads or truncates (default x.length/2).

Example
import 'raya:typed_data';
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';

void main() {
  // A complex FFT of [1, 2, 3, 4] (interleaved re, im), and back again.
  final x = Float64List.fromList([1, 0, 2, 0, 3, 0, 4, 0]);
  final X = fft(x);
  print('fft:  ${[for (final v in X) v.toStringAsFixed(3)]}');
  final back = ifft(X);
  print('ifft: ${[for (final v in back) v.toStringAsFixed(3)]}');
}
Output
fft:  [10.000, 0.000, -2.000, 2.000, -2.000, 0.000, -2.000, -2.000]
ifft: [1.000, 0.000, 2.000, 0.000, 3.000, 0.000, 4.000, 0.000]
ifftfunction
Float64List ifft(Float64List x, {int? n, FftNorm norm = FftNorm.backward})

The inverse DFT of interleaved complex x (numpy.fft.ifft).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // 64 samples at 64 Hz: 5 Hz plus a weaker 12 Hz tone.
  const n = 64;
  final x = Float64List.fromList([for (var i = 0; i < n; i++) math.sin(2 * math.pi * 5 * i / n) + 0.5 * math.sin(2 * math.pi * 12 * i / n)]);
  final c = Float64List(2 * n);
  for (var i = 0; i < n; i++) {
    c[2 * i] = x[i];
  }
  final back = ifft(fft(c));
  var err = 0.0;
  for (var i = 0; i < n; i++) {
    err = math.max(err, (back[2 * i] - x[i]).abs());
  }
  print('round trip error below 1e-14: ${err < 1e-14}');
}
Output
round trip error below 1e-14: true
rfftfunction
Float64List rfft(Float64List x, {int? n, FftNorm norm = FftNorm.backward})

The DFT of real x as \frac{n}{2} + 1 interleaved complex bins (numpy.fft.rfft).

Example
import 'raya:math' as math;
import 'raya:typed_data';
import 'raya:convert';
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';

void main() {
  // One second at 64 Hz: a 5 Hz tone plus a weaker 12 Hz tone.
  const fs = 64, n = 64;
  final x = Float64List.fromList([
    for (var i = 0; i < n; i++) math.sin(2 * math.pi * 5 * i / fs) + 0.5 * math.sin(2 * math.pi * 12 * i / fs)
  ]);
  final spec = rfft(x); // interleaved re, im
  final amp = [for (var k = 0; k < spec.length ~/ 2; k++) 2 * math.sqrt(spec[2 * k] * spec[2 * k] + spec[2 * k + 1] * spec[2 * k + 1]) / n];
  final freqs = rfftfreq(n, 1 / fs);
  for (var k = 0; k < amp.length; k++) {
    if (amp[k] > 0.1) print('peak at ${freqs[k].toStringAsFixed(0)} Hz, amplitude ${amp[k].toStringAsFixed(3)}');
  }
        {'label': 'amplitude', 'points': [for (var k = 0; k < amp.length; k++) [freqs[k], amp[k]]]}
      ]})}');
}
Output
peak at 5 Hz, amplitude 1.000
peak at 12 Hz, amplitude 0.500
irfftfunction
Float64List irfft(Float64List spec, {int? n, FftNorm norm = FftNorm.backward})

The real inverse of a half spectrum (numpy.fft.irfft). n defaults to 2·(bins-1); the spectrum is truncated or zero-padded to \frac{n}{2} + 1 bins.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // 64 samples at 64 Hz: 5 Hz plus a weaker 12 Hz tone.
  const n = 64;
  final x = Float64List.fromList([for (var i = 0; i < n; i++) math.sin(2 * math.pi * 5 * i / n) + 0.5 * math.sin(2 * math.pi * 12 * i / n)]);
  final spec = rfft(x);
  // Zero the 12 Hz bin: a brick-wall filter in the frequency domain.
  spec[24] = 0;
  spec[25] = 0;
  final y = irfft(spec, n: n);
  print('kept the 5 Hz tone: y[3] = ${y[3].toStringAsFixed(6)}, sin(2π·5·3/64) = ${math.sin(2 * math.pi * 5 * 3 / 64).toStringAsFixed(6)}');
}
Output
kept the 5 Hz tone: y[3] = 0.995185, sin(2π·5·3/64) = 0.995185
fftnfunction
Float64List fftn(Float64List x, List<int> shape, {List<int>? axes, FftNorm norm = FftNorm.backward})

n-D DFT of interleaved complex x with row-major shape over axes (default all), numpy.fft.fftn.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // An 8 × 8 image of horizontal stripes (period 4 rows).
  const r = 8, c = 8;
  final img = Float64List(2 * r * c);
  for (var i = 0; i < r; i++) {
    for (var j = 0; j < c; j++) {
      img[2 * (i * c + j)] = math.cos(2 * math.pi * i / 4);
    }
  }
  final f = fftn(img, [r, c]);
  final rows = [for (var i = 0; i < r; i++) [for (var j = 0; j < c; j++) (math.sqrt(f[2 * (i * c + j)] * f[2 * (i * c + j)] + f[2 * (i * c + j) + 1] * f[2 * (i * c + j) + 1]) * 100).roundToDouble() / 100]];
  print('energy at (2, 0) and (6, 0): ${rows[2][0]}, ${rows[6][0]}');
}
Output
energy at (2, 0) and (6, 0): 32.0, 32.0
ifftnfunction
Float64List ifftn(Float64List x, List<int> shape, {List<int>? axes, FftNorm norm = FftNorm.backward})

n-D inverse DFT (numpy.fft.ifftn).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // An 8 × 8 image of horizontal stripes (period 4 rows).
  const r = 8, c = 8;
  final img = Float64List(2 * r * c);
  for (var i = 0; i < r; i++) {
    for (var j = 0; j < c; j++) {
      img[2 * (i * c + j)] = math.cos(2 * math.pi * i / 4);
    }
  }
  final back = ifftn(fftn(img, [r, c]), [r, c]);
  print('round trip: ${(back[2 * 8] - img[2 * 8]).abs() < 1e-14}');
  print('transform only axis 1: ${ifftn(fftn(img, [r, c], axes: [1]), [r, c], axes: [1])[0].toStringAsFixed(6)}');
}
Output
round trip: true
transform only axis 1: 1.000000
rfftnfunction
(Float64List, List<int>) rfftn(Float64List x, List<int> shape, {List<int>? axes, FftNorm norm = FftNorm.backward})

n-D real DFT (numpy.fft.rfftn): rfft over the last of axes, then complex FFTs over the rest. The result has shape shape with that axis replaced by shapelast/2 + 1; it is returned with its shape.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const r = 4, c = 6;
  final x = Float64List.fromList([for (var i = 0; i < r * c; i++) (i % c).toDouble()]);
  final (spec, shape) = rfftn(x, [r, c]);
  print('spectrum shape $shape (last axis halved + 1)');
  final back = irfftn(spec, shape, [r, c]);
  print('round trip: ${back.map((v) => v.round()).toList().sublist(0, 6)}');
}
Output
spectrum shape [4, 4] (last axis halved + 1)
round trip: [0, 1, 2, 3, 4, 5]
irfftnfunction
Float64List irfftn(Float64List spec, List<int> specShape, List<int> outShape, {List<int>? axes, FftNorm norm = FftNorm.backward})

Inverse of rfftn: spec has specShape (last of axes holding \frac{n}{2} + 1 bins); outShape is the real result's shape (numpy's s).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const r = 4, c = 4;
  final x = Float64List.fromList([for (var i = 0; i < 16; i++) i == 5 ? 1.0 : 0.0]); // one bright pixel
  final (spec, shape) = rfftn(x, [r, c]);
  final y = irfftn(spec, shape, [r, c]);
}
Output
fftfreqfunction
Float64List fftfreq(int n, [double d = 1.0])

Sample frequencies of an n-point DFT with spacing d (numpy.fft.fftfreq).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';

void main() {
  print('fftfreq(8, 0.1):  ${fftfreq(8, 0.1)}');
  print('rfftfreq(8, 0.1): ${rfftfreq(8, 0.1)}');
}
Output
fftfreq(8, 0.1):  [0.0, 1.25, 2.5, 3.75, -5.0, -3.75, -2.5, -1.25]
rfftfreq(8, 0.1): [0.0, 1.25, 2.5, 3.75, 5.0]
rfftfreqfunction
Float64List rfftfreq(int n, [double d = 1.0])

Sample frequencies of an n-point real DFT (numpy.fft.rfftfreq).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  print(rfftfreq(8, 0.1));
  print('n = 9: ${rfftfreq(9)}');
}
Output
[0.0, 1.25, 2.5, 3.75, 5.0]
n = 9: [0.0, 0.1111111111111111, 0.2222222222222222, 0.3333333333333333, 0.4444444444444444]
fftshiftfunction
Float64List fftshift(Float64List x, {int width = 1})

Moves the zero-frequency element to the centre (numpy.fft.fftshift) for a 1-D list of width-double elements (1 for real, 2 for interleaved complex).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final f = fftfreq(8);
  print('fftfreq: $f');
  print('shifted: ${fftshift(f)}');
  final c = Float64List.fromList([0, 0, 1, 0, 2, 0, 3, 0]);
  print('complex (width 2): ${fftshift(c, width: 2)}');
}
Output
fftfreq: [0.0, 0.125, 0.25, 0.375, -0.5, -0.375, -0.25, -0.125]
shifted: [-0.5, -0.375, -0.25, -0.125, 0.0, 0.125, 0.25, 0.375]
complex (width 2): [2.0, 0.0, 3.0, 0.0, 0.0, 0.0, 1.0, 0.0]
ifftshiftfunction
Float64List ifftshift(Float64List x, {int width = 1})

Inverse of fftshift (numpy.fft.ifftshift).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final f = fftshift(fftfreq(7));
  print('centred: $f');
  print('ifftshift restores: ${ifftshift(f)}');
}
Output
centred: [-0.42857142857142855, -0.2857142857142857, -0.14285714285714285, 0.0, 0.14285714285714285, 0.2857142857142857, 0.42857142857142855]
ifftshift restores: [0.0, 0.14285714285714285, 0.2857142857142857, 0.42857142857142855, -0.42857142857142855, -0.2857142857142857, -0.14285714285714285]
dctfunction
Float64List dct(Float64List x, {int type = 2, DctNorm norm = DctNorm.backward})

The DCT of real x of type 1-4 (scipy.fft.dct).

Example
import 'raya:typed_data';
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';

void main() {
  final x = Float64List.fromList([1, 2, 3, 4]);
  final c = dct(x);
  print('dct:  ${[for (final v in c) v.toStringAsFixed(4)]}');
  print('idct: ${[for (final v in idct(c)) v.toStringAsFixed(4)]}');
}
Output
dct:  [20.0000, -6.3086, 0.0000, -0.4483]
idct: [1.0000, 2.0000, 3.0000, 4.0000]
idctfunction
Float64List idct(Float64List x, {int type = 2, DctNorm norm = DctNorm.backward})

The inverse DCT (scipy.fft.idct): idct(dct(x, type), type) == x for every norm.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final x = Float64List.fromList([1, 2, 3, 4, 5, 6, 7, 8]);
  final c = dct(x);
  c[6] = 0;
  c[7] = 0; // drop the two highest coefficients
  final y = idct(c);
  print('compressed: ${y.map((v) => v.toStringAsFixed(3)).toList()}');
}
Output
compressed: [1.005, 1.986, 3.021, 3.975, 5.025, 5.979, 7.014, 7.995]
dstfunction
Float64List dst(Float64List x, {int type = 2, DctNorm norm = DctNorm.backward})

The DST of real x of type 1-4 (scipy.fft.dst).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final x = Float64List.fromList([1, 2, 3, 4]);
  print('DST-II: ${dst(x).map((v) => v.toStringAsFixed(4)).toList()}');
  print('DST-I:  ${dst(x, type: 1).map((v) => v.toStringAsFixed(4)).toList()}');
}
Output
DST-II: [13.0656, -5.6569, 5.4120, -4.0000]
DST-I:  [15.3884, -6.8819, 3.6327, -1.6246]
idstfunction
Float64List idst(Float64List x, {int type = 2, DctNorm norm = DctNorm.backward})

The inverse DST (scipy.fft.idst).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final x = Float64List.fromList([1, -1, 2, 0.5]);
  final back = idst(dst(x, norm: DctNorm.ortho), norm: DctNorm.ortho);
  print('round trip: ${back.map((v) => v.toStringAsFixed(12)).toList()}');
}
Output
round trip: [1.000000000000, -1.000000000000, 2.000000000000, 0.500000000000]
fftGraphfunction
TensorGraph fftGraph(String name, int batch, int n, {bool inverse = false})

A tensor graph computing batch complex FFTs of length n (a power of two) in float32. Inputs 're' and 'im' ([batch, n]); outputs 'out_re' and 'out_im' ([batch, n]). inverse uses conjugate twiddles and scales by \frac{1}{n} (numpy's ifft).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
import 'package:riptide_tensor/riptide_tensor.ray';

void main() {
  // A batch of 2 FFTs of length 8 recorded as a tensor graph, run on the CPU interpreter.
  final g = fftGraph('fft8', 2, 8);
  final re = Float32List(16), im = Float32List(16);
  re[0] = 1; // an impulse: flat spectrum
  for (var i = 0; i < 8; i++) {
    re[8 + i] = math.cos(2 * math.pi * i / 8); // one cycle: energy at k = 1 and 7
  }
  final out = CpuInterpreter(g).run({'re': re, 'im': im});
  print('impulse: ${(out['out_re']! as Float32List).sublist(0, 8)}');
  print('cosine:  ${(out['out_re']! as Float32List).sublist(8, 16).map((v) => v.toStringAsFixed(3)).toList()}');
}
Output
impulse: [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
cosine:  [-0.000, 4.000, 0.000, 0.000, -0.000, 0.000, 0.000, 4.000]
fftFlopsfunction
double fftFlops(int batch, int n)

Floating-point operations of batch FFTs of length n by the 5 \cdot n·log2(n) convention (for GFLOP/s figures).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  for (final n in [64, 1024, 65536]) {
    print('n = $n: ${fftFlops(1, n).toStringAsExponential(3)} flops (5 n log2 n)');
  }
}
Output
n = 64: 1.920e+3 flops (5 n log2 n)
n = 1024: 5.120e+4 flops (5 n log2 n)
n = 65536: 5.243e+6 flops (5 n log2 n)
fftScalefunction
double fftScale(int n, FftNorm norm, {required bool forward})

The scale factor a transform of length n in direction forward applies under norm.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  for (final norm in FftNorm.values) {
    print('${norm.name.padRight(8)} forward ${fftScale(16, norm, forward: true)}, inverse ${fftScale(16, norm, forward: false)}');
  }
}
Output
backward forward 1.0, inverse 0.0625
ortho    forward 0.25, inverse 0.25
forward  forward 0.0625, inverse 1.0
sinCos2PiByNfunction
(double, double) sinCos2PiByN(int k, int n)

(cos, sin) of \frac{2\pi k}{n}, reduced to the first octant first so large k and n keep full precision (PocketFFT's sincos_2pibyn does the same).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final (s, c) = sinCos2PiByN(1, 8);
  print('sin(2π/8) = $s, cos = $c');
  print('exact at k = n/4: ${sinCos2PiByN(4, 16)}');
}
Output
sin(2π/8) = 0.7071067811865475, cos = 0.7071067811865476
exact at k = n/4: (-0.0, 1.0)
goodSizefunction
int goodSize(int n)

The smallest length >= n whose prime factors are all 2, 3, 5, 7 or 11 (fast for the mixed-radix passes; scipy's next_fast_len).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  for (final n in [97, 1000, 1025, 4097]) {
    print('$n -> ${goodSize(n)}');
  }
}
Output
97 -> 98
1000 -> 1000
1025 -> 1029
4097 -> 4116
goodSizeRealfunction
int goodSizeReal(int n)

The smallest length >= n made of 2, 3 and 5 only (real-input transforms; scipy's next_fast_len(n, real=True)).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  for (final n in [97, 1001, 4097]) {
    print('$n -> ${goodSizeReal(n)}');
  }
}
Output
97 -> 100
1001 -> 1024
4097 -> 4320
Float64List convolveDirect(Float64List a, Float64List v, {ConvMode mode = ConvMode.full})

The direct sum \sum a[j] \cdot v[k-j] (O(n \cdot m)).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final a = Float64List.fromList([1, 2, 3, 4, 5]), v = Float64List.fromList([1, 0, -1]);
  print('full:  ${convolveDirect(a, v)}');
  print('same:  ${convolveDirect(a, v, mode: ConvMode.same)}');
  print('valid: ${convolveDirect(a, v, mode: ConvMode.valid)}');
}
Output
full:  [1.0, 2.0, 2.0, 2.0, 2.0, -4.0, -5.0]
same:  [2.0, 2.0, 2.0, 2.0, -4.0]
valid: [2.0, 2.0, 2.0]
fftconvolvefunction
Float64List fftconvolve(Float64List a, Float64List v, {ConvMode mode = ConvMode.full})

Convolution by real FFTs of a fast length \ge n + m - 1 (scipy.signal.fftconvolve).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(3);
  final a = Float64List.fromList([for (var i = 0; i < 200; i++) rng.nextDouble() - 0.5]);
  final box = Float64List.fromList(List.filled(15, 1 / 15));
  final s = fftconvolve(a, box, mode: ConvMode.same);
  print('matches direct: ${(s[100] - convolveDirect(a, box, mode: ConvMode.same)[100]).abs() < 1e-12}');
}
Output
matches direct: true
oaconvolvefunction
Float64List oaconvolve(Float64List a, Float64List v, {ConvMode mode = ConvMode.full, int? blockSize})

Overlap-add convolution (scipy.signal.oaconvolve): the longer input in blocks, each convolved with the shorter by FFTs of one fixed size. Best when one input is much longer than the other.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final x = Float64List.fromList([for (var i = 0; i < 1000; i++) math.sin(i / 20)]);
  final h = Float64List.fromList([0.25, 0.5, 0.25]);
  final y = oaconvolve(x, h, mode: ConvMode.same, blockSize: 128);
  print('overlap-add equals direct: ${(y[500] - convolveDirect(x, h, mode: ConvMode.same)[500]).abs() < 1e-12}');
}
Output
overlap-add equals direct: true
convolvefunction
Float64List convolve(Float64List a, Float64List v, {ConvMode mode = ConvMode.full, ConvMethod method = ConvMethod.auto})

Convolution of a and v (scipy.signal.convolve). same is centred and as long as a; valid keeps the part computed without zero padding.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final a = Float64List.fromList([1, 2, 3, 4, 5]), v = Float64List.fromList([1, 0, -1]);
  for (final m in ConvMethod.values) {
    print('${m.name.padRight(11)} ${convolve(a, v, method: m).map((x) => x.toStringAsFixed(1)).toList()}');
  }
}
Output
auto        [1.0, 2.0, 2.0, 2.0, 2.0, -4.0, -5.0]
direct      [1.0, 2.0, 2.0, 2.0, 2.0, -4.0, -5.0]
fft         [1.0, 2.0, 2.0, 2.0, 2.0, -4.0, -5.0]
overlapAdd  [1.0, 2.0, 2.0, 2.0, 2.0, -4.0, -5.0]
correlatefunction
Float64List correlate(Float64List a, Float64List v, {ConvMode mode = ConvMode.full, ConvMethod method = ConvMethod.auto})

Cross-correlation \sum a[k + j] \cdot v[j] (scipy.signal.correlate for real input): convolution with the reversed v.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // Find a delayed copy: the correlation peaks at the delay.
  final s = Float64List.fromList([0, 0, 1, 3, 2, 0, 0, 0, 0, 0]);
  final d = Float64List.fromList([0, 0, 0, 0, 0, 1, 3, 2, 0, 0]);
  final r = correlate(d, s);
  var best = 0;
  for (var i = 0; i < r.length; i++) {
    if (r[i] > r[best]) best = i;
  }
  print('peak at lag ${best - (s.length - 1)}');
}
Output
peak at lag 3
(Float64List, List<int>) fftconvolveNd(Float64List a, List<int> aShape, Float64List b, List<int> bShape, {ConvMode mode = ConvMode.full})

n-D convolution of row-major a (aShape) and b (bShape) by real n-D FFTs (scipy.signal.fftconvolve with n-D input). Returns the data and its shape.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // Blur a 6 × 6 image with a 3 × 3 box.
  final img = Float64List(36);
  img[14] = 9;
  img[21] = 9;
  final k = Float64List.fromList(List.filled(9, 1 / 9));
  final (out, shape) = fftconvolveNd(img, [6, 6], k, [3, 3], mode: ConvMode.same);
  print('shape $shape');
}
Output
shape [6, 6]
lfilterfunction
Float64List lfilter(Float64List b, Float64List a, Float64List x, {Float64List? zi})

Filters x with the rational transfer function \frac{b(z)}{a(z)} (scipy.signal.lfilter, direct form II transposed). zi, when given (length max(len a, len b) - 1), is the initial state and receives the final state.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // First-order low-pass (exponential smoothing): y[n] = 0.2 x[n] + 0.8 y[n−1].
  final b = Float64List.fromList([0.2]), a = Float64List.fromList([1, -0.8]);
  final x = Float64List.fromList([for (var i = 0; i < 30; i++) i < 5 ? 0.0 : 1.0]);
  final y = lfilter(b, a, x);
  print('y[29] = ${y[29].toStringAsFixed(6)}');
}
Output
y[29] = 0.996222
lfilterZifunction
Float64List lfilterZi(Float64List b, Float64List a)

The initial state of lfilter for a step response's steady state (scipy.signal.lfilter_zi): filtering a constant c with zi = c·lfilterZi(b, a) gives c \cdot \frac{sum(b)}{sum(a)} from the first sample.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // First-order low-pass (exponential smoothing): y[n] = 0.2 x[n] + 0.8 y[n−1].
  final b = Float64List.fromList([0.2]), a = Float64List.fromList([1, -0.8]);
  final zi = lfilterZi(b, a);
  final x = Float64List.fromList(List.filled(10, 3));
  final cold = lfilter(b, a, x);
  final warm = lfilter(b, a, x, zi: Float64List.fromList([for (final z in zi) z * 3]));
  print('cold start: ${cold.first.toStringAsFixed(3)}, steady start: ${warm.first.toStringAsFixed(3)}');
}
Output
cold start: 0.600, steady start: 3.000
sosfiltfunction
Float64List sosfilt(Float64List sos, Float64List x, {Float64List? zi})

Filters x through cascaded second-order sections sos (row-major [n \times 6], scipy.signal.sosfilt). zi, when given ([n \times 2]), is the initial state and receives the final state.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final sos = butter(4, [0.2]).toSos(); // normalised cutoff 0.2 (Nyquist = 1)
  final x = Float64List.fromList([for (var i = 0; i < 100; i++) math.sin(i * 0.1) + 0.5 * math.sin(i * 2.5)]);
  final y = sosfilt(sos, x);
  print('${sos.length ~/ 6} second-order sections');
}
Output
2 second-order sections
sosfiltZifunction
Float64List sosfiltZi(Float64List sos)

Initial state of sosfilt for a step response's steady state (scipy.signal.sosfilt_zi), [n \times 2].

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final sos = butter(4, [0.2]).toSos(); // normalised cutoff 0.2 (Nyquist = 1)
  final zi = sosfiltZi(sos);
  print('${zi.length} state values (2 per section)');
  final x = Float64List.fromList(List.filled(5, 1));
  print('starts in steady state: ${sosfilt(sos, x, zi: zi).map((v) => v.toStringAsFixed(4)).toList()}');
}
Output
4 state values (2 per section)
starts in steady state: [1.0000, 1.0000, 1.0000, 1.0000, 1.0000]
oddExtendfunction
Float64List oddExtend(Float64List x, int n)

Odd extension by n samples at each end: 2 \cdot x[0] - x[n..1] | x \mid 2 \cdot x[-1] - x[-2..-n - 1] (scipy odd_ext).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final x = Float64List.fromList([1, 2, 4, 7]);
  print(oddExtend(x, 2));
}
Output
[-2.0, 0.0, 1.0, 2.0, 4.0, 7.0, 10.0, 12.0]
filtfiltfunction
Float64List filtfilt(Float64List b, Float64List a, Float64List x, {int? padlen})

Zero-phase filtering: forward then backward through \frac{b}{a}, odd-extended by padlen samples (default 3 \cdot \max(len a, len b)), with steady-state initial conditions (scipy.signal.filtfilt, method 'pad').

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // First-order low-pass (exponential smoothing): y[n] = 0.2 x[n] + 0.8 y[n−1].
  final b = Float64List.fromList([0.2]), a = Float64List.fromList([1, -0.8]);
  final x = Float64List.fromList([for (var i = 0; i < 60; i++) (i - 30).abs() < 8 ? 1.0 : 0.0]);
  final once = lfilter(b, a, x), zero = filtfilt(b, a, x);
  print('forward-backward keeps the pulse centred');
}
Output
forward-backward keeps the pulse centred
sosfiltfiltfunction
Float64List sosfiltfilt(Float64List sos, Float64List x, {int? padlen})

Zero-phase filtering through second-order sections (scipy.signal.sosfiltfilt). Default padlen is 3·(2·sections + 1 - \min(#(b_{2} = 0), #(a_{2} = 0))).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final sos = butter(4, [0.2]).toSos(); // normalised cutoff 0.2 (Nyquist = 1)
  final x = Float64List.fromList([for (var i = 0; i < 120; i++) math.sin(i * 0.08) + 0.4 * math.sin(i * 1.9)]);
  final y = sosfiltfilt(sos, x);
  print('y[60] = ${y[60].toStringAsFixed(4)}, slow tone ${math.sin(60 * 0.08).toStringAsFixed(4)}');
}
Output
y[60] = -0.9962, slow tone -0.9962
freqzfunction
({Float64List w, Float64List h}) freqz(Float64List b, Float64List a, {int worN = 512, bool whole = false, double? fs})

Frequency response of \frac{b}{a} at worN frequencies (scipy.signal.freqz): w from 0 to \pi (2\pi if whole), endpoint excluded, in rad/sample, or in the units of fs when given. h is interleaved complex.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

double absAt(Float64List h, int i) => math.sqrt(h[2 * i] * h[2 * i] + h[2 * i + 1] * h[2 * i + 1]);

void main() {
  // First-order low-pass (exponential smoothing): y[n] = 0.2 x[n] + 0.8 y[n−1].
  final b = Float64List.fromList([0.2]), a = Float64List.fromList([1, -0.8]);
  final r = freqz(b, a, worN: 128);
  print('gain at DC ${absAt(r.h, 0).toStringAsFixed(4)}, at π ${absAt(r.h, 127).toStringAsFixed(4)}');
}
Output
gain at DC 1.0000, at π 0.1111
sosfreqzfunction
({Float64List w, Float64List h}) sosfreqz(Float64List sos, {int worN = 512, bool whole = false, double? fs})

Frequency response of second-order sections (scipy.signal.sosfreqz / freqz_sos).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

double absAt(Float64List h, int i) => math.sqrt(h[2 * i] * h[2 * i] + h[2 * i + 1] * h[2 * i + 1]);

void main() {
  final series = <Map<String, Object>>[];
  for (final order in [2, 4, 8]) {
    final r = sosfreqz(butter(order, [100], fs: 1000).toSos(), worN: 200, fs: 1000);
    series.add({'label': 'order $order', 'points': [for (var i = 0; i < 200; i++) [r.w[i], absAt(r.h, i)]]});
  }
  print('Butterworth low-pass at 100 Hz, fs = 1000');
}
Output
Butterworth low-pass at 100 Hz, fs = 1000
firwinfunction
Float64List firwin(int numtaps, List<double> cutoff, {Window window = Window.hamming, bool passZero = true, bool scale = true, double fs = 2.0})

Linear-phase FIR taps (scipy.signal.firwin). cutoff are band edges in the units of fs (default: normalised so Nyquist = 1); passZero passes DC (lowpass/bandstop) or not (highpass/bandpass).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

double absAt(Float64List h, int i) => math.sqrt(h[2 * i] * h[2 * i] + h[2 * i + 1] * h[2 * i + 1]);

void main() {
  final h = firwin(31, [0.3]);
  print('31 taps, sum ${h.reduce((a, b) => a + b).toStringAsFixed(6)} (unit DC gain)');
  final r = freqz(h, Float64List.fromList([1]), worN: 256);
}
Output
31 taps, sum 1.000000 (unit DC gain)
buttapfunction
Zpk buttap(int order)

Analog Butterworth prototype of order (scipy buttap).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final f = buttap(5);
  print('${f.p.length} poles on the unit circle, gain ${f.k}');
  print('first pole ${f.p.first}');
}
Output
5 poles on the unit circle, gain 1.0
first pole (-0.30901699437494745+0.9510565162951535j)
cheb1apfunction
Zpk cheb1ap(int order, double rp)

Analog Chebyshev type I prototype with rp dB passband ripple (scipy cheb1ap).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final f = cheb1ap(5, 1);
  print('${f.p.length} poles on an ellipse, k = ${f.k.toStringAsFixed(6)}');
}
Output
5 poles on an ellipse, k = 0.122827
cheb2apfunction
Zpk cheb2ap(int order, double rs)

Analog Chebyshev type II prototype with rs dB stopband attenuation (scipy cheb2ap).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final f = cheb2ap(4, 40);
  print('${f.z.length} zeros on the imaginary axis, ${f.p.length} poles');
}
Output
4 zeros on the imaginary axis, 4 poles
lp2lpZpkfunction
Zpk lp2lpZpk(Zpk f, double wo)
Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final f = lp2lpZpk(buttap(3), 2);
  print('zeros ${f.z.length}, poles ${f.p.length}, gain ${f.k.toStringAsFixed(6)}');
}
Output
zeros 0, poles 3, gain 8.000000
lp2hpZpkfunction
Zpk lp2hpZpk(Zpk f, double wo)
Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final f = lp2hpZpk(buttap(3), 2);
  print('zeros ${f.z.length}, poles ${f.p.length}, gain ${f.k.toStringAsFixed(6)}');
}
Output
zeros 3, poles 3, gain 1.000000
lp2bpZpkfunction
Zpk lp2bpZpk(Zpk f, double wo, double bw)
Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final f = lp2bpZpk(buttap(3), 2, 1);
  print('zeros ${f.z.length}, poles ${f.p.length}, gain ${f.k.toStringAsFixed(6)}');
}
Output
zeros 3, poles 6, gain 1.000000
lp2bsZpkfunction
Zpk lp2bsZpk(Zpk f, double wo, double bw)
Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final f = lp2bsZpk(buttap(3), 2, 1);
  print('zeros ${f.z.length}, poles ${f.p.length}, gain ${f.k.toStringAsFixed(6)}');
}
Output
zeros 6, poles 6, gain 1.000000
bilinearZpkfunction
Zpk bilinearZpk(Zpk f, double fs)

Bilinear transform s = 2 \cdot fs \cdot \frac{z - 1}{z + 1} of an analog zpk (scipy bilinear_zpk).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final d = bilinearZpk(lp2lpZpk(buttap(4), 2 * 1000 * math.tan(math.pi * 100 / 1000)), 1000);
  print('digital poles inside the unit circle: ${d.p.every((p) => p.re * p.re + p.im * p.im < 1)}');
}
Output
digital poles inside the unit circle: true
iirFilterfunction
Zpk iirFilter(Zpk prototype, List<double> wn, {BandType btype = BandType.lowpass, bool analog = false, double? fs})

Digital (or, with analog, analog) IIR design from a prototype (scipy iirfilter). wn holds one critical frequency for lowpass/highpass and two for bandpass/bandstop: normalised to Nyquist (0..1) for digital filters, in the units of fs when fs is given, in rad/s for analog filters.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

double absAt(Float64List h, int i) => math.sqrt(h[2 * i] * h[2 * i] + h[2 * i + 1] * h[2 * i + 1]);

void main() {
  final f = iirFilter(buttap(4), [0.2, 0.4], btype: BandType.bandpass);
  final r = sosfreqz(f.toSos(), worN: 200);
  print('band-pass, ${f.p.length} poles');
}
Output
band-pass, 8 poles
butterfunction
Zpk butter(int order, List<double> wn, {BandType btype = BandType.lowpass, bool analog = false, double? fs})

Butterworth filter (scipy.signal.butter, output='zpk'; call .toSos or .toBa).

Example
import 'raya:math' as math;
import 'raya:typed_data';
import 'raya:convert';
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';

void main() {
  // A 4th-order Butterworth low-pass at 8 Hz, run forwards and backwards (zero phase).
  const fs = 100.0, n = 200;
  final t = [for (var i = 0; i < n; i++) i / fs];
  final x = Float64List.fromList([for (final s in t) math.sin(2 * math.pi * 2 * s) + 0.4 * math.sin(2 * math.pi * 30 * s)]);
  final sos = butter(4, [8], fs: fs).toSos();
  final y = sosfiltfilt(sos, x);
  double rms(List<double> v) => math.sqrt(v.fold<double>(0, (a, b) => a + b * b) / v.length);
  final noise = [for (var i = 0; i < n; i++) y[i] - math.sin(2 * math.pi * 2 * t[i])];
  print('rms of the 30 Hz part before: ${(0.4 / math.sqrt(2)).toStringAsFixed(3)}, after: ${rms(noise.sublist(20, 180)).toStringAsFixed(3)}');
        {'label': 'input', 'points': [for (var i = 0; i < n; i++) [t[i], x[i]]]},
        {'label': 'filtered', 'points': [for (var i = 0; i < n; i++) [t[i], y[i]]]},
      ]})}');
}
Output
rms of the 30 Hz part before: 0.283, after: 0.001
cheby1function
Zpk cheby1(int order, double rp, List<double> wn, {BandType btype = BandType.lowpass, bool analog = false, double? fs})

Chebyshev type I filter with rp dB passband ripple (scipy.signal.cheby1).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

double absAt(Float64List h, int i) => math.sqrt(h[2 * i] * h[2 * i] + h[2 * i + 1] * h[2 * i + 1]);

void main() {
  final r1 = sosfreqz(cheby1(5, 1, [0.3]).toSos(), worN: 200);
  final rb = sosfreqz(butter(5, [0.3]).toSos(), worN: 200);
  print('ripple in the passband, a sharper edge');
}
Output
ripple in the passband, a sharper edge
cheby2function
Zpk cheby2(int order, double rs, List<double> wn, {BandType btype = BandType.lowpass, bool analog = false, double? fs})

Chebyshev type II filter with rs dB minimum stopband attenuation (scipy.signal.cheby2).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

double absAt(Float64List h, int i) => math.sqrt(h[2 * i] * h[2 * i] + h[2 * i + 1] * h[2 * i + 1]);

void main() {
  final r = sosfreqz(cheby2(5, 40, [0.3]).toSos(), worN: 200);
  print('flat passband, ripple in the stopband (40 dB)');
}
Output
flat passband, ripple in the stopband (40 dB)
zpk2sosfunction
Float64List zpk2sos(List<Complex> zeros, List<Complex> poles, double k)

Zeros, poles and gain to second-order sections (scipy zpk2sos, pairing 'nearest', digital).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final f = butter(4, [0.25]);
  final sos = zpk2sos(f.z, f.p, f.k);
  for (var s = 0; s < sos.length ~/ 6; s++) {
    print('section $s: ${sos.sublist(6 * s, 6 * s + 6).map((v) => v.toStringAsFixed(4)).toList()}');
  }
}
Output
section 0: [0.0102, 0.0204, 0.0102, 1.0000, -0.8554, 0.2097]
section 1: [1.0000, 2.0000, 1.0000, 1.0000, -1.1130, 0.5741]
resamplefunction
Float64List resample(Float64List x, int num)

Resamples real x to num samples by truncating or zero-padding its spectrum (scipy.signal.resample): assumes x is periodic. An unpaired Nyquist bin is doubled when downsampling and halved when upsampling.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final x = Float64List.fromList([for (var i = 0; i < 20; i++) math.sin(2 * math.pi * i / 20)]);
  final y = resample(x, 50);
  print('20 -> ${y.length} samples');
}
Output
20 -> 50 samples
upfirdnfunction
Float64List upfirdn(Float64List h, Float64List x, {int up = 1, int down = 1})

Upsample by up (zero insertion), FIR-filter with h, downsample by down (scipy.signal.upfirdn), computed polyphase: only the kept outputs, only the non-zero inputs.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final x = Float64List.fromList([1, 2, 3]);
  print('up 3 (zeros inserted): ${upfirdn(Float64List.fromList([1]), x, up: 3)}');
  print('up 3 + hold filter: ${upfirdn(Float64List.fromList([1, 1, 1]), x, up: 3)}');
  print('down 2: ${upfirdn(Float64List.fromList([1]), Float64List.fromList([1, 2, 3, 4, 5, 6]), down: 2)}');
}
Output
up 3 (zeros inserted): [1.0, 0.0, 0.0, 2.0, 0.0, 0.0, 3.0]
up 3 + hold filter: [1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0]
down 2: [1.0, 3.0, 5.0]
resamplePolyfunction
Float64List resamplePoly(Float64List x, int up, int down, {Window window = const Window.kaiser(5.0), Float64List? taps})

Resamples x by up/down with a polyphase FIR filter (scipy.signal.resample_poly, padtype 'constant'). The default filter is a \operatorname{Kaiser}(\beta = 5) firwin of length 2 \cdot 10 \cdot \max(up, down)+1; taps overrides it.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final x = Float64List.fromList([for (var i = 0; i < 30; i++) math.cos(2 * math.pi * i / 15)]);
  final y = resamplePoly(x, 3, 2);
  print('30 -> ${y.length} samples (×3/2)');
}
Output
30 -> 45 samples (×3/2)
decimatefunction
Float64List decimate(Float64List x, int q, {int? n, bool fir = false, bool zeroPhase = true})

Downsamples x by q after an anti-aliasing filter (scipy.signal.decimate): by default an order-8 Chebyshev I (0.05 dB ripple, cutoff \frac{0.8}{q}) applied forward and backward; with fir a Hamming firwin of n+1 taps (default n = 20q) through resamplePoly.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final x = Float64List.fromList([for (var i = 0; i < 200; i++) math.sin(2 * math.pi * i / 50) + 0.3 * math.sin(2 * math.pi * i / 3)]);
  final y = decimate(x, 4);
  print('200 -> ${y.length} samples, the fast tone filtered out first');
}
Output
200 -> 50 samples, the fast tone filtered out first
welchfunction
Psd welch(Float64List x, {double fs = 1.0, Window window = Window.hann, int? nperseg, int? noverlap, int? nfft, Detrend detrend = Detrend.constant, SpectralScaling scaling = SpectralScaling.density, bool onesided = true, bool median = false})

Welch's method: the mean of the periodograms of overlapping windowed segments (scipy.signal.welch). Defaults as scipy: periodic Hann window, nperseg 256 (or the signal length if shorter), 50% overlap, constant detrend.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(1);
  const fs = 100.0;
  final x = Float64List.fromList([for (var i = 0; i < 2048; i++) math.sin(2 * math.pi * 12 * i / fs) + rng.nextDouble() - 0.5]);
  final p = welch(x, fs: fs, nperseg: 256);
  var k = 0;
  for (var i = 0; i < p.f.length; i++) {
    if (p.pxx[i] > p.pxx[k]) k = i;
  }
  print('peak at ${p.f[k]} Hz');
}
Output
peak at 12.109375 Hz
periodogramfunction
Psd periodogram(Float64List x, {double fs = 1.0, Window window = Window.boxcar, int? nfft, Detrend detrend = Detrend.constant, SpectralScaling scaling = SpectralScaling.density, bool onesided = true})

Periodogram: one segment covering the whole signal (scipy.signal.periodogram; default boxcar window).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(1);
  const fs = 100.0;
  final x = Float64List.fromList([for (var i = 0; i < 2048; i++) math.sin(2 * math.pi * 12 * i / fs) + rng.nextDouble() - 0.5]);
  final p = periodogram(x, fs: fs);
  print('${p.f.length} frequencies, resolution ${p.f[1]} Hz');
}
Output
1025 frequencies, resolution 0.048828125 Hz
spectrogramfunction
Spectrogram spectrogram(Float64List x, {double fs = 1.0, Window window = const Window.tukey(0.25), int? nperseg, int? noverlap, int? nfft, Detrend detrend = Detrend.constant, SpectralScaling scaling = SpectralScaling.density, bool onesided = true})

Power spectrogram (scipy.signal.spectrogram, mode 'psd'): defaults Tukey(0.25) periodic window, nperseg 256 (or the signal length), overlap nperseg/8.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const fs = 200.0;
  final x = Float64List.fromList([for (var i = 0; i < 2000; i++) math.sin(2 * math.pi * (5 + 20 * i / 2000) * i / fs)]);
  final s = spectrogram(x, fs: fs, nperseg: 128, noverlap: 64);
  print('${s.f.length} frequencies × ${s.t.length} times');
  final nf = s.f.length, nt = s.t.length;
  final rows = [for (var i = 0; i < 24; i++) [for (var j = 0; j < nt; j += 3) (s.sxx[i * nt + j] * 1000).roundToDouble() / 1000]];
}
Output
65 frequencies × 30 times
stftfunction
Stft stft(Float64List x, {double fs = 1.0, Window window = Window.hann, int nperseg = 256, int? noverlap, int? nfft, bool boundary = true, bool padded = true})

Short-time Fourier transform of real x (scipy.signal.stft): one-sided, scaled by \frac{1}{\Sigma w} ('spectrum'), with nperseg/2 zeros added at both ends (boundary) and the end zero-padded to whole segments (padded).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const fs = 200.0;
  final x = Float64List.fromList([for (var i = 0; i < 2000; i++) math.sin(2 * math.pi * (5 + 20 * i / 2000) * i / fs)]);
  final z = stft(x, fs: fs, nperseg: 64);
  print('${z.f.length} × ${z.t.length} complex coefficients');
}
Output
33 × 64 complex coefficients
istftfunction
({Float64List t, Float64List x}) istft(Stft s, {double fs = 1.0, Window window = Window.hann, int nperseg = 256, int? noverlap, int? nfft, bool boundary = true})

Inverse STFT by weighted overlap-add (scipy.signal.istft): undoes stft with the same parameters, returning the times and the signal (with the boundary padding removed).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const fs = 200.0;
  final x = Float64List.fromList([for (var i = 0; i < 2000; i++) math.sin(2 * math.pi * (5 + 20 * i / 2000) * i / fs)]);
  final z = stft(x, fs: fs, nperseg: 64);
  final r = istft(z, fs: fs, nperseg: 64);
  var err = 0.0;
  for (var i = 0; i < 2000; i++) {
    err = math.max(err, (r.x[i] - x[i]).abs());
  }
  print('reconstruction error below 1e-12: ${err < 1e-12}');
}
Output
reconstruction error below 1e-12: true
getWindowfunction
Float64List getWindow(Window window, int n, {bool fftbins = true})

Scipy.signal.get_window: periodic (fftbins) by default.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';

void main() {
  final w = getWindow(Window.hann, 8);
  print('Hann window, 8 points: ${[for (final v in w) v.toStringAsFixed(4)]}');
}
Output
Hann window, 8 points: [0.0000, 0.1464, 0.5000, 0.8536, 1.0000, 0.8536, 0.5000, 0.1464]
besselI0function
double besselI0(double x)

The modified Bessel function of the first kind, order 0: the power series \sum ((\frac{x}{2})^{k} / k!)^{2} below 15, the asymptotic expansion e^{x} / \sqrt{2\pi x} · (1 + \frac{1}{8x} + \frac{9}{128x^{2}} +...) above.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  print('I0(0) = ${besselI0(0)}, I0(1) = ${besselI0(1)}');
}
Output
I0(0) = 1.0, I0(1) = 1.2660658777520082

Classes

enum DctNorm

Scipy.fft normalisation for the trigonometric transforms.

Values

backward
orthovalue
ortho
forwardvalue
forward
abstract interface class NativeFft

An in-place complex transform of one length (interleaved re, im).

Properties

namegetter
String get name

Methods

transformmethod
void transform(List<double> data, {required bool forward, double scale = 1.0})

The unnormalised transform in direction forward of data (2n doubles, interleaved), times scale.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final nf = FftBackend.forLength(8);
  print(nf == null ? 'no native FFT for length 8 here: the Raya FFT runs' : 'native backend ${nf.name}');
  final data = Float64List.fromList([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
  fftPlan(8).transform(data, forward: true);
  print('impulse -> flat: ${data.sublist(0, 4)}');
}
Output
no native FFT for length 8 here: the Raya FFT runs
impulse -> flat: [1.0, 0.0, 1.0, 0.0]
abstract final class FftBackend

Native FFTs on or off for plans made from now on (default: on where available).

Static

enabledstaticfield
static bool enabled
forLengthstaticmethod
static NativeFft? forLength(int n)

A native transform of length n, or null.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  print('native FFT enabled: ${FftBackend.enabled}');
  for (final n in [8, 1000]) {
    final b = FftBackend.forLength(n);
    print('n = $n: ${b == null ? 'none' : b.name}');
  }
}
Output from the Raya VM
native FFT enabled: true
n = 8: none
n = 1000: none
enum FftNorm

Normalisation, as numpy.fft: backward scales the inverse by \frac{1}{n}, forward scales the forward transform by \frac{1}{n}, ortho scales both by \frac{1}{\sqrt{n}}.

Values

backward
orthovalue
ortho
forwardvalue
forward
class

FftPlan

final class FftPlan

A reusable plan for complex FFTs of length n. Twiddles and scratch are allocated once; forward and inverse transform in place and allocate nothing.

Constructors

FftPlanconstructor
FftPlan(this.n)
Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

double mag(Float64List c, int k) => math.sqrt(c[2 * k] * c[2 * k] + c[2 * k + 1] * c[2 * k + 1]);

void main() {
  const n = 8;
  final plan = FftPlan(n);
  final d = Float64List(2 * n);
  for (var i = 0; i < n; i++) {
    d[2 * i] = math.cos(2 * math.pi * 2 * i / n);
  }
  plan.forward(d);
  print('|X| = ${[for (var k = 0; k < n; k++) mag(d, k).toStringAsFixed(2)]}');
}
Output
|X| = [0.00, 0.00, 4.00, 0.00, 0.00, 0.00, 4.00, 0.00]

Properties

nfield
final int n
String? get nativeBackend

The native transform this plan runs ("vdsp"), or null for the pure-Raya one.

bool get usesBluestein

True when this length uses Bluestein's algorithm.

factorsgetter
List<int> get factors

The mixed-radix factors (empty for Bluestein plans).

Methods

forwardmethod
void forward(Float64List data, {FftNorm norm = FftNorm.backward})

Forward transform X[k] = \sum x[j] e^{-2\pi i jk/n} of interleaved data (length \ge 2n) in place.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

double mag(Float64List c, int k) => math.sqrt(c[2 * k] * c[2 * k] + c[2 * k + 1] * c[2 * k + 1]);

void main() {
  const n = 8;
  final plan = FftPlan(n);
  final d = Float64List(2 * n);
  for (var i = 0; i < n; i++) {
    d[2 * i] = math.cos(2 * math.pi * 2 * i / n);
  }
  plan.forward(d, norm: FftNorm.ortho);
  print('orthonormal: |X_2| = ${mag(d, 2).toStringAsFixed(6)} (√8/2)');
}
Output
orthonormal: |X_2| = 1.414214 (√8/2)
inversemethod
void inverse(Float64List data, {FftNorm norm = FftNorm.backward})

Inverse transform x[j] = (\frac{1}{n}) \sum X[k] e^{+2\pi i jk/n} (with the default norm) in place.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const n = 8;
  final plan = FftPlan(n);
  final d = Float64List(2 * n);
  for (var i = 0; i < n; i++) {
    d[2 * i] = math.cos(2 * math.pi * 2 * i / n);
  }
  final orig = Float64List.fromList(d);
  plan.forward(d);
  plan.inverse(d);
  print('back: ${(d[2] - orig[2]).abs() < 1e-15}');
}
Output
back: true
transformmethod
void transform(Float64List data, {required bool forward, double scale = 1.0})

The unnormalised transform in direction forward, multiplied by scale.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const n = 8;
  final plan = FftPlan(n);
  final d = Float64List(2 * n);
  for (var i = 0; i < n; i++) {
    d[2 * i] = math.cos(2 * math.pi * 2 * i / n);
  }
  plan.transform(d, forward: true, scale: 1 / n);
  print('scaled by 1/n: X_2 = ${d[4].toStringAsFixed(4)}');
}
Output
scaled by 1/n: X_2 = 0.5000
final class RealFftPlan

A reusable plan for real FFTs of length n. No allocation per transform.

Constructors

RealFftPlanconstructor
RealFftPlan(this.n)
Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

double mag(Float64List c, int k) => math.sqrt(c[2 * k] * c[2 * k] + c[2 * k + 1] * c[2 * k + 1]);

void main() {
  const n = 16;
  final plan = RealFftPlan(n);
  final x = Float64List.fromList([for (var i = 0; i < n; i++) i < 4 ? 1.0 : 0.0]); // a pulse
  final spec = Float64List(n + 2);
  plan.forward(x, spec);
  print('${spec.length ~/ 2} complex bins for $n real samples');
}
Output
9 complex bins for 16 real samples

Properties

nfield
final int n
binsgetter
int get bins

Number of complex output bins, \frac{n}{2} + 1.

Methods

forwardmethod
void forward(Float64List x, Float64List out, {FftNorm norm = FftNorm.backward})

Rfft: x (length n, real) to out (length 2 \cdot \mathrm{bins}, interleaved complex).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const n = 16;
  final plan = RealFftPlan(n);
  final x = Float64List.fromList([for (var i = 0; i < n; i++) i < 4 ? 1.0 : 0.0]); // a pulse
  final spec = Float64List(n + 2);
  plan.forward(x, spec);
  print('X_0 = ${spec[0]} (the sum), X_1 = (${spec[2].toStringAsFixed(4)}, ${spec[3].toStringAsFixed(4)})');
}
Output
X_0 = 4.0 (the sum), X_1 = (3.0137, -2.0137)
inversemethod
void inverse(Float64List spec, Float64List out, {FftNorm norm = FftNorm.backward})

Irfft: spec (2 \cdot \mathrm{bins} doubles, Hermitian half spectrum) to out (n reals). The imaginary parts of the DC and (for even n) Nyquist bins are ignored, as numpy does.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const n = 16;
  final plan = RealFftPlan(n);
  final x = Float64List.fromList([for (var i = 0; i < n; i++) i < 4 ? 1.0 : 0.0]); // a pulse
  final spec = Float64List(n + 2);
  plan.forward(x, spec);
  final back = Float64List(n);
  plan.inverse(spec, back);
  print(back.map((v) => v.toStringAsFixed(3)).toList());
}
Output
[1.000, 1.000, 1.000, 1.000, 0.000, 0.000, 0.000, 0.000, -0.000, 0.000, 0.000, -0.000, 0.000, 0.000, 0.000, 0.000]
class

Complex

final class Complex

A complex number for filter design (zeros, poles, frequency responses). Bulk complex data elsewhere is interleaved Float64List.

Constructors

Complexconstructor
const Complex(this.re, [this.im = 0])
Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const z = Complex(3, 4), w = Complex(1, -2);
  print('z = $z, w = $w');
}
Output
z = (3.0+4.0j), w = (1.0-2.0j)

Static

zeroconstant
static const zero = Complex(0)
oneconstant
static const one = Complex(1)
expstaticmethod
static Complex exp(Complex z)
Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  print('e^(iπ) = ${Complex.exp(const Complex(0, math.pi))}');
}
Output
e^(iπ) = (-1.0+1.2246467991473532e-16j)
polarstaticmethod
static Complex polar(double r, double theta)

e^{i\theta}.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  print(Complex.polar(2, math.pi / 2));
}
Output
(1.2246467991473532e-16+2.0j)

Properties

refield
final double re
imfield
final double im
conjgetter
Complex get conj
absgetter
double get abs
arggetter
double get arg
isRealgetter
bool get isReal

Methods

scalemethod
Complex scale(double s)
Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const z = Complex(3, 4), w = Complex(1, -2);
  print(z.scale(0.5));
}
Output
(1.5+2.0j)
sqrtmethod
Complex sqrt()

Principal square root.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  print('√(−9) = ${const Complex(-9).sqrt()}');
  print('√(3 + 4i) = ${const Complex(3, 4).sqrt()}');
}
Output
√(−9) = (0.0+3.0j)
√(3 + 4i) = (2.0+1.0j)
toStringmethod
String toString()
Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  print(const Complex(1.5, -2));
}
Output
(1.5-2.0j)

Operators

operator +operator
Complex operator +(Complex o)
Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const z = Complex(3, 4), w = Complex(1, -2);
  print('z + w = ${z + w}');
}
Output
z + w = (4.0+2.0j)
operator -operator
Complex operator -(Complex o)
Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const z = Complex(3, 4), w = Complex(1, -2);
  print('z - w = ${z - w}');
}
Output
z - w = (2.0+6.0j)
operator -operator
Complex operator -()
Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const z = Complex(3, 4), w = Complex(1, -2);
  print('−z = ${-z}');
}
Output
−z = (-3.0-4.0j)
operator *operator
Complex operator *(Complex o)
Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const z = Complex(3, 4), w = Complex(1, -2);
  print('z * w = ${z * w}');
}
Output
z * w = (11.0-2.0j)
operator /operator
Complex operator /(Complex o)
Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  const z = Complex(3, 4), w = Complex(1, -2);
  print('z / w = ${z / w}');
}
Output
z / w = (-1.0+2.0j)
enum ConvMode

Output size, as scipy.signal.convolve.

Values

fullvalue
full
samevalue
same
validvalue
valid
enum ConvMethod

How to convolve. auto picks direct for short kernels and FFT otherwise.

Values

autovalue
auto
directvalue
direct
fftvalue
fft
overlapAdd
enum BandType

The band a filter passes.

Values

lowpassvalue
lowpass
highpass
bandpass
bandstop
class

Zpk

final class Zpk

A filter in zero-pole-gain form.

Constructors

Zpkconstructor
const Zpk(this.z, this.p, this.k)
Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

double absAt(Float64List h, int i) => math.sqrt(h[2 * i] * h[2 * i] + h[2 * i + 1] * h[2 * i + 1]);

void main() {
  // A notch at ω = π/2 with poles just inside: H(z) = (1 + z⁻²)/(1 + 0.81 z⁻²).
  final f = Zpk([const Complex(0, 1), const Complex(0, -1)], [const Complex(0, 0.9), const Complex(0, -0.9)], 1);
  final r = freqz(f.toBa().b, f.toBa().a, worN: 256);
  print('gain at π/2: ${absAt(r.h, 128).toStringAsExponential(2)}');
}
Output
gain at π/2: 6.45e-16

Properties

zfield
final List<Complex> z
pfield
final List<Complex> p
kfield
final double k

Methods

toBamethod
({Float64List b, Float64List a}) toBa()

Transfer-function coefficients b (numerator) and a (denominator), highest power first (scipy's zpk2tf).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final f = butter(2, [0.5]);
  final ba = f.toBa();
  print('b = ${ba.b.map((v) => v.toStringAsFixed(6)).toList()}');
  print('a = ${ba.a.map((v) => v.toStringAsFixed(6)).toList()}');
}
Output
b = [0.292893, 0.585786, 0.292893]
a = [1.000000, -0.000000, 0.171573]
toSosmethod
Float64List toSos()

Second-order sections, row-major [sections × 6]: b0 b1 b2 a0 a1 a2 (scipy's zpk2sos, pairing 'nearest').

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final sos = cheby1(6, 0.5, [0.3]).toSos();
  print('${sos.length ~/ 6} sections (stable for high orders where b/a would lose accuracy)');
}
Output
3 sections (stable for high orders where b/a would lose accuracy)
enum Detrend

Detrending applied to each segment.

Values

nonevalue
none
constant
linearvalue
linear
enum SpectralScaling

'density' (\frac{V^{2}}{Hz}, scaled by \frac{1}{fs \cdot \Sigma w^{2}}) or 'spectrum' (V^{2}, scaled by \frac{1}{(\Sigma w)^{2}}).

Values

densityvalue
density
spectrum
class

Psd

final class Psd

A power spectral density estimate: frequencies f and powers pxx.

Constructors

Psdconstructor
const Psd(this.f, this.pxx)
Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final p = Psd(Float64List.fromList([0, 1, 2]), Float64List.fromList([0.1, 2, 0.1]));
  print('f ${p.f}, pxx ${p.pxx}');
}
Output
f [0.0, 1.0, 2.0], pxx [0.1, 2.0, 0.1]

Properties

ffield
final Float64List f
pxxfield
final Float64List pxx
final class Spectrogram

A spectrogram: f (rows), segment-centre times t (columns), and row-major sxx ([f.length × t.length]).

Constructors

Spectrogramconstructor
const Spectrogram(this.f, this.t, this.sxx)
Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final s = Spectrogram(Float64List.fromList([0, 10]), Float64List.fromList([0, 1, 2]), Float64List.fromList([1, 2, 3, 4, 5, 6]));
  print('${s.f.length} × ${s.t.length}: ${s.sxx}');
}
Output
2 × 3: [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]

Properties

ffield
final Float64List f
tfield
final Float64List t
sxxfield
final Float64List sxx
class

Stft

final class Stft

An STFT: f, t, and row-major interleaved complex zxx ([f.length × t.length]).

Constructors

Stftconstructor
const Stft(this.f, this.t, this.zxx)
Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final z = stft(Float64List.fromList(List.filled(64, 1)), nperseg: 16);
  final s = Stft(z.f, z.t, z.zxx);
  print('${s.f.length} frequencies × ${s.t.length} frames');
}
Output
9 frequencies × 9 frames

Properties

ffield
final Float64List f
tfield
final Float64List t
zxxfield
final Float64List zxx
enum WindowKind

The window families.

Values

boxcarvalue
boxcar
hannvalue
hann
hammingvalue
hamming
blackman
blackmanHarris
bartlett
flattopvalue
flattop
kaiservalue
kaiser
gaussian
tukeyvalue
tukey
class

Window

final class Window

A window: a family plus its parameter (Kaiser \beta, Gaussian \sigma, Tukey \alpha).

Constructors

Windowconstructor
const Window(this.kind, [this.param = 0])
Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final series = <Map<String, Object>>[];
  for (final w in [Window.hann, Window.hamming, Window.blackman, Window.flattop, const Window(WindowKind.bartlett)]) {
    final v = w.generate(65);
    series.add({'label': '$w', 'points': [for (var i = 0; i < 65; i++) [i, v[i]]]});
  }
  print('five windows of length 65');
}
Output
five windows of length 65
Window.kaiserconstructor
const Window.kaiser(double beta)

Kaiser window with shape parameter beta.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final series = [for (final b in [0.0, 5.0, 14.0]) {'label': 'β = $b', 'points': (() { final v = Window.kaiser(b).generate(51); return [for (var i = 0; i < 51; i++) [i, v[i]]]; })()}];
  print('Kaiser windows');
}
Output
Kaiser windows
Window.gaussianconstructor
const Window.gaussian(double std)

Gaussian window with standard deviation std (in samples).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final v = const Window.gaussian(7).generate(51);
  print('centre ${v[25]}, edge ${v[0].toStringAsFixed(4)}');
}
Output
centre 1.0, edge 0.0017
Window.tukeyconstructor
const Window.tukey([double alpha = 0.5])

Tukey (tapered cosine) window; alpha is the tapered fraction (0 = boxcar, 1 = Hann).

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final series = [for (final a in [0.0, 0.5, 1.0]) {'label': 'α = $a', 'points': (() { final v = Window.tukey(a).generate(51); return [for (var i = 0; i < 51; i++) [i, v[i]]]; })()}];
  print('α = 0 is a box, α = 1 is Hann');
}
Output
α = 0 is a box, α = 1 is Hann

Static

boxcarconstant
static const boxcar = Window(WindowKind.boxcar)
hannconstant
static const hann = Window(WindowKind.hann)
hammingconstant
static const hamming = Window(WindowKind.hamming)
blackmanconstant
static const blackman = Window(WindowKind.blackman)
static const blackmanHarris = Window(WindowKind.blackmanHarris)
bartlettconstant
static const bartlett = Window(WindowKind.bartlett)
flattopconstant
static const flattop = Window(WindowKind.flattop)

Properties

kindfield
final WindowKind kind
paramfield
final double param

Methods

generatemethod
Float64List generate(int m, {bool sym = true})

The window of length m: symmetric when sym, periodic otherwise.

Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  print('symmetric: ${Window.hann.generate(5)}');
  print('periodic (for FFTs): ${Window.hann.generate(5, sym: false).map((v) => v.toStringAsFixed(4)).toList()}');
}
Output
symmetric: [0.0, 0.5, 1.0, 0.5, 0.0]
periodic (for FFTs): [0.0000, 0.3455, 0.9045, 0.9045, 0.3455]
toStringmethod
String toString()
Example
import 'package:riptide_numerics_signal/riptide_numerics_signal.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  print(Window.hann);
  print(const Window.kaiser(8.6));
}
Output
hann
kaiser(8.6)