Calculus and Signal
Integrate a function or sampled data, interpolate between samples, take a Fourier transform and filter a signal from a script.
01Overview
What This Page Covers
Two jobs: turn a function or a table of samples into a number (integration) or a new set of samples (interpolation), and look at or change a signal in the frequency domain (the transform and filters).
| Job | Routines | Scripts |
|---|---|---|
| The integral of a function, finite or infinite limits | integral | Luau and Rune |
| The integral of sampled data | trapz, cumtrapz | Rune only |
| Values between samples | interp1 (linear, nearest, pchip, spline), plus pchip and spline on their own | interp1: Luau and Rune; the others, Rust only |
| The Fourier transform | fft, ifft, fft_real, and the plan-based form FftPlan | fft and ifft: Luau and Rune; FftPlan: Rune only; fft_real: Rust only |
| Filtering | filter, and the sample-by-sample form IirFilter | Rune only |
| The frequency response of a filter | freqz | Rune only |
The page covers thirteen routines. Luau reaches four of them: integral, interp1, fft and ifft, five names with integral_with. Rune reaches six more, marked Rune only in the table; choose Rune at the top of the page to read their script forms. Rune reaches ten: integral, interp1, fft, ifft, trapz, cumtrapz, filter, freqz, FftPlan and IirFilter; the names are integral_with and filter_with besides, and FftPlan and IirFilter are types that Rune builds with numerics::FftPlan::new(n)? and numerics::IirFilter::new(b, a)?. Luau reaches the first four. The remaining three (pchip and spline on their own, and fft_real) belong to the Rust crate eustress-numerics alone. The conventions shared by every routine are on the Numerics overview.
A signal in a script is an array of numbers: a Luau table counted from 1a Rune array counted from 0. A complex value is two arrays of the same length: {re = {...}, im = {...}}#{re: [...], im: [...]}. fft and ifft accept either a plain array, which is read as a real signal, or the re and im form, and both return the re and im form.
02Integration
integral
integral integrates a function of one variable over an interval by adaptive Gauss-Kronrod (7, 15) quadrature. Either limit may be infinite: the routine maps an infinite range onto a finite one before it integrates. Reversed limits flip the sign of the result, and equal limits give 0 with no function evaluations.
It starts from 10 equal subintervals and splits every subinterval whose share of the error is too large. It stops when the error estimate is within the larger of the absolute tolerance and the relative tolerance times the size of the integral.
| Option | Default |
|---|---|
| Absolute tolerance | 1e-10 |
| Relative tolerance | 1e-6 |
| Largest number of subintervals | 5000 |
The result holds three numbers: the value of the integral, an estimate of the absolute error, and the number of times the function was evaluated.
A result that misses its tolerance is an error and not a result. The kinds and messages are:
no convergence: integral: tolerance not met with N intervals (error estimate E)when 5000 subintervals are not enough.no convergence: integral: intervals shrank to rounding size with error estimate E; the integrand may be singular.no convergence: integral: the integrand returned a non-finite value.invalid argument: integral: limits must not be NaN.
The test suite checks integral against SciPy quad (computed at 1e-14) or a closed form:
| Integral | Tolerances used | Agreement the test enforces |
|---|---|---|
| e^(-x) sin(5x) from 0 to 3 | 1e-13 absolute and relative | Relative error 1e-12 |
| e^(-x^2) over the whole real line | 1e-13 | 1e-12 against the square root of pi |
| 1 / (1 + x^2) from 0 to infinity | 1e-13 | 1e-12 |
| 1 / sqrt(x) from 0 to 1, an integrable endpoint singularity | The defaults | 1e-5 against the exact value 2 |
| x^2 from 2 to 0 | 1e-13 | -8/3 to 1e-14 |
| 1 / x from 0 to 1, which has a non-integrable pole | 1e-13 | Reported as an error |
The call is Numerics.integral(f, a, b, opts), with the options table optional. The call is numerics::integral(f, a, b)? with the defaults and numerics::integral_with(f, a, b, opts)? with options. The function takes one number and returns one number. math.huge and -math.huge are the infinite limits. The options are named abs_tol, rel_tol and max_intervals (a whole number). The result has the fields value, error and evaluations.
The example integrates x^2 from 2 to 0 at tolerances of 1e-13, the reversed-limits row of the table above. The result is -8/3, which is -2.6667 to four decimals.
local r = Numerics.integral(function(x) return x * x end, 2, 0, {abs_tol = 1e-13, rel_tol = 1e-13})
print(string.format("%.4f", r.value)) -- -2.6667use eustress::log_info;
use eustress::realism::numerics;
pub fn on_init() {
let r = numerics::integral_with(|x| x * x, 2.0, 0.0, #{abs_tol: 1e-13, rel_tol: 1e-13})?;
let value = r["value"];
log_info(`value = ${value}`); // -2.6667 to four decimals
}trapz
trapz integrates sampled data by the trapezoid rule. It takes the sample positions and the sample values, which must have the same length; otherwise it fails with dimension mismatch: trapz: x and y lengths differ. The positions need not be evenly spaced.
cumtrapz returns the running integral: one value per sample, 0 at the first, and the last value equals the trapz result. It fails with dimension mismatch: cumtrapz: x and y lengths differ on a length mismatch.
The test suite compares both with NumPy and SciPy on 12 points at random sorted positions between 0 and 5, with values sin x + 0.1 x, and requires agreement to 1e-14.
Rune calls numerics::trapz(x, y)?, which returns a number, and numerics::cumtrapz(x, y)?, which returns an array with one value per sample. Both take two arrays of the same length.
Luau does not reach trapz or cumtrapz.
The example integrates samples of x^2 at the positions 0, 1 and 2, with the values 0, 1 and 4. By hand the trapezoids hold 0.5 and 2.5, so the area is 3, and the running integral is 0, 0.5 and 3.
use eustress::log_info;
use eustress::realism::numerics;
pub fn on_init() {
let area = numerics::trapz([0.0, 1.0, 2.0], [0.0, 1.0, 4.0])?;
let running = numerics::cumtrapz([0.0, 1.0, 2.0], [0.0, 1.0, 4.0])?;
log_info(`area = ${area}`); // 3
log_info(`running = ${running[0]}, ${running[1]}, ${running[2]}`); // 0, 0.5 and 3
}03Interpolation
interp1
interp1 estimates values between samples. Give the sample positions, the sample values and the query positions, and choose a method:
| Method | What it does | Default outside the sample range |
|---|---|---|
| Linear | Straight lines between neighboring samples | NaN |
| Nearest | The value of the closest sample; a query exactly halfway takes the later sample | NaN |
| Pchip | Shape-preserving piecewise cubic (Fritsch-Carlson) | Continues the end pieces |
| Spline | Cubic spline with not-a-knot end conditions; three points give the parabola through them | Continues the end pieces |
You can replace the default outside the range with NaN, with continuing the end pieces, or with a fixed value. A NaN query returns NaN. The positions must be finite and strictly increasing, and there must be at least two samples. The messages are invalid argument: interp1: x must be strictly increasing, invalid argument: interp1: samples must be finite, invalid argument: interp1: need at least two samples and dimension mismatch: interp1: x and y lengths differ.
pchip and spline are also available on their own: they build the piecewise cubic once, and you evaluate it as many times as you like.
The test suite uses 8 samples at positions from 0 to 5.2 and 27 query positions. It compares linear against NumPy interp, pchip against SciPy PchipInterpolator and spline against SciPy CubicSpline with not-a-knot ends, to 1e-14, 1e-13 and 1e-12. Two queries outside the range, at -0.5 and 6, check the pchip and spline extrapolation to 1e-12 and 1e-11. A three-point spline through (0, 1), (1, 2) and (3, 10) evaluates to 5 at 2, the parabola x^2 + 1, to 1e-14.
A script calls interp1 with the sample positions, the sample values, the query positions (all three arrays) and the method as a string: "linear", "nearest", "pchip" or "spline". The method is optional and defaults to "linear": Numerics.interp1(x, y, xq). The method is required: numerics::interp1(x, y, xq, "linear")?. The result is an array with one value per query position. Any other method name fails with a message that lists the four valid names.
A script cannot choose the behavior outside the sample range: the defaults in the table apply (NaN for linear and nearest, the continued end pieces for pchip and spline). pchip and spline on their own, which build the piecewise cubic once for repeated evaluation, are part of the Rust crate and are not callable from scripts; a script uses the "pchip" or "spline" method of interp1.
The example uses the three points (0, 1), (1, 2) and (3, 10) and asks for the value at 2. Linear interpolation gives 6, on the line from (1, 2) to (3, 10). The spline gives 5, the parabola x^2 + 1 from the test above.
local x, y = {0, 1, 3}, {1, 2, 10}
local lin = Numerics.interp1(x, y, {2}) -- {6}
local spl = Numerics.interp1(x, y, {2}, "spline") -- {5}use eustress::log_info;
use eustress::realism::numerics;
pub fn on_init() {
let x = [0.0, 1.0, 3.0];
let y = [1.0, 2.0, 10.0];
let lin = numerics::interp1(x, y, [2.0], "linear")?; // [6.0]
let spl = numerics::interp1(x, y, [2.0], "spline")?; // [5.0]
let a = lin[0];
let b = spl[0];
log_info(`linear = ${a}, spline = ${b}`);
}The figure uses the eight samples of the interpolation test and evaluates each method at 201 points. Linear stays between neighboring samples, and so does pchip. The spline passes about 0.03 below the lowest sample and about 0.05 above the highest one.
04The Fourier Transform
fft
fft computes the discrete Fourier transform of a one-dimensional signal. It accepts any length, not only powers of two. The transform of a signal of length N is N complex values, in the standard order and unscaled. ifft is the inverse and is scaled by 1/N, so ifft of fft returns the original signal. fft_real takes a real signal and returns the same N complex values. An empty signal gives an empty result. Two-dimensional and N-dimensional transforms are not covered.
Inside the library, fft has four kernels. When the machine has AVX2 and FMA and every prime factor of the length is at most 13, the default is the built-in mixed-radix kernel (radix 8, 4, 2, 3, 5, 7, 11 and 13, two complex values per instruction): its direct form below 32768 points, and its depth-first form from 32768 points on. The depth-first form makes one decimation pass of radix 8 (or the largest radix the length has), finishes each part while it is in cache, splitting again while a part is longer than 16384 points, and interleaves the outputs in one pass. A cache-blocked six-step form stays available as an explicit choice, and the default does not pick it. Every other case uses the rustfft crate: other machines (wasm32 included) and lengths with a larger prime factor. A plan can force a kernel and report which one it got. The kernels are tested against NumPy and SciPy.
The test suite compares fft and ifft with NumPy on random complex signals of lengths 16, 10, 17 and 1000, requiring a largest error of 1e-13 relative to the largest bin magnitude.
A script calls Numerics.fft(x)numerics::fft(x)?, and ifft the same way. The argument is a plain array of numbers, read as a real signal, or the re and im form with two arrays of the same length. If re and im differ in length the call fails with a message that gives both counts. The result is always the re and im form with N values in each array, unscaled for fft and scaled by 1/N for ifft. fft_real is not callable from scripts; fft of a plain array computes the same transform.
The example is the transform of an impulse, the signal 1, 0, 0, 0. Every bin of its transform is 1, and every imaginary part is 0.
local X = Numerics.fft({1, 0, 0, 0})
print(X.re[1], X.re[2], X.re[3], X.re[4]) -- 1 1 1 1
print(X.im[1], X.im[2], X.im[3], X.im[4]) -- 0 0 0 0use eustress::log_info;
use eustress::realism::numerics;
pub fn on_init() {
let x = numerics::fft([1.0, 0.0, 0.0, 0.0])?;
let re = x["re"];
let a = re[0];
let b = re[1];
let c = re[2];
let d = re[3];
log_info(`re = ${a}, ${b}, ${c}, ${d}`); // 1, 1, 1, 1; every imaginary part is 0
}To reach bin k of a transform from a script, read X.re[k + 1] and X.im[k + 1]x["re"][k] and x["im"][k], where bin 0 is the first value.
The library run transformed 1000 samples, taken at 1000 Hz, of a 50 Hz sine of amplitude 1 plus a 120 Hz sine of amplitude 0.5, with fft_real. Scaling each magnitude by 2/N gives an amplitude of 1.0 at 50 Hz and 0.5 at 120 Hz. Every other bin is below 1e-14.
FftPlan
FftPlan plans a transform of one fixed length once. After that, it transforms a buffer of that length in place, forward or inverse, and does not allocate. This is the form to use inside a real-time loop. The inverse is scaled by 1/N, as in ifft. A buffer of the wrong length fails with invalid argument: FftPlan: buffer length differs from the planned length, and a length of 0 fails with invalid argument: FftPlan: length must be at least 1.
A transform through a plan gives the same bits as the one-shot fft. The test suite also runs 10 forward and 10 inverse transforms of length 1024, next to 10000 steps of a control loop, under a counting memory allocator and requires zero allocations.
Rune builds a plan with numerics::FftPlan::new(n)? or numerics::FftPlan::with_engine(n, engine)?, where the engine is the string "auto", "rustfft", "mixed_radix", "six_step" or "depth_first". The methods are plan.fft(x) and plan.ifft(X), which take a plain array or the re and im form and return the re and im form, plan.len() for the planned length and plan.engine() for the kernel's name. An input of another length fails the call, and the message gives the planned length and the length it got.
Luau does not reach FftPlan; it calls fft and ifft on the whole array each time.
The example plans four points, transforms the unit impulse (1, 0, 0, 0), whose spectrum is 1 in every bin, and transforms it back.
use eustress::log_info;
use eustress::realism::numerics;
pub fn on_init() {
let plan = numerics::FftPlan::new(4)?;
let spectrum = plan.fft([1.0, 0.0, 0.0, 0.0])?;
let back = plan.ifft(spectrum)?;
let bins = spectrum["re"];
let samples = back["re"];
log_info(`bins = ${bins[0]}, ${bins[1]}, ${bins[2]}, ${bins[3]}`); // 1, 1, 1, 1
log_info(`samples = ${samples[0]}, ${samples[1]}, ${samples[2]}, ${samples[3]}`); // 1, 0, 0, 0
}Finding the Frequency Axis
Bin k of an N-point transform belongs to the frequency of k/N cycles per sample. If the samples are taken at a sample rate fs, in samples per second, bin k belongs to k times fs / N hertz, and the spacing between bins is fs / N. The bins from N/2 upward are the negative frequencies. For a real signal, bin N - k is the complex conjugate of bin k, so only the first half carries new information.
The library's own routines use angular frequency, in radians per time unit, never hertz, and freqz takes radians per sample. The spectrum figure above is in hertz only because the example computed it that way: it scaled bin k by the sample rate (1000 Hz) divided by N.
A script builds the frequency axis with ordinary arithmetic from the sample rate fs and the length N: bin k, counting from 0, is at k times fs divided by N. The example transforms 8 samples of a sine that completes 2 cycles in the 8 samples: 0, 1, 0, -1, 0, 1, 0, -1. Taken at fs = 8 samples per second, the bin spacing is 8 / 8 = 1 Hz, so bin 2 is at 2 Hz, the frequency of the sine. By hand, bin 2 of this signal is -4i and bin 6 is 4i, and the amplitude is 2 times 4 divided by 8, which is 1. Apart from rounding error, every other bin is 0.
local X = Numerics.fft({0, 1, 0, -1, 0, 1, 0, -1})
-- bin k is at k * fs / N, so bin 2 is at 2 * 8 / 8 = 2 Hz
print(string.format("%.3f %.3f", X.im[3], X.im[7])) -- -4.000 4.000use eustress::log_info;
use eustress::realism::numerics;
pub fn on_init() {
let x = numerics::fft([0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0])?;
let im = x["im"];
let bin2 = im[2];
let bin6 = im[6];
log_info(`im = ${bin2}, ${bin6}`); // about -4 and 4; bin 2 is at 2 * 8 / 8 = 2 Hz
}05Filtering
filter
filter applies a rational digital filter, in transposed direct form II. Give a numerator b and a denominator a, both written in powers of z^-1: entry i multiplies the signal delayed by i samples. The first entry of a must be nonzero; both lists are divided by it. For each input sample the output is
- y[n] = (b0 x[n] + b1 x[n-1] + ... - a1 y[n-1] - a2 y[n-2] - ...) / a0
The filter starts from rest unless you give it a starting state. The state has length max(len a, len b) - 1. The call returns the output, one value per input, and the final state, which you can pass to the next call to continue a signal in pieces. With a equal to 1 the filter is a finite impulse response filter.
The messages are invalid argument: filter: a[0] must be nonzero, invalid argument: filter: b must not be empty and invalid argument: filter: zi has the wrong length.
The test suite compares filter with SciPy lfilter. It uses the coefficients that SciPy generates for a fourth-order Butterworth design with its cutoff argument set to 0.2, 60 random input samples and a random starting state. The output and the final state agree to 1e-12, and so does the output from rest.
Rune calls numerics::filter(b, a, x)? with three arrays and numerics::filter_with(b, a, x, opts)? with an options object whose one option is zi, the starting state as an array. Both return an object with y, the output, and zf, the final state; pass zf as zi of the next call to continue a signal.
Luau does not reach filter; a Luau script that needs to filter samples can apply the equation above itself with ordinary arithmetic, keeping the previous inputs and outputs in its own variables.
The example runs the two-point moving average b = (0.5, 0.5), a = (1) over the input (2, 4, 6). By hand the output is 1, 3 and 5: the first value averages 2 with the zero before it.
use eustress::log_info;
use eustress::realism::numerics;
pub fn on_init() {
let out = numerics::filter([0.5, 0.5], [1.0], [2.0, 4.0, 6.0])?;
let y = out["y"];
log_info(`y = ${y[0]}, ${y[1]}, ${y[2]}`); // 1, 3 and 5
}IirFilter
IirFilter is a filter with its state built in, for processing one sample at a time. It takes the same b and a as filter. Its step processes one sample and does not allocate. You can read the state, set it, or reset it to zero.
Running a signal through step one sample at a time gives the same bits as the batch call; the test suite checks that on the Butterworth example. It also runs an IirFilter with the numerator (0.2, 0.3, 0.2) and the denominator (1, -0.5, 0.2) inside the allocation-counting test above.
Rune builds one with numerics::IirFilter::new(b, a)?. The methods are f.step(x), which takes one number and returns one number, f.state(), which returns the state as an array, f.set_state(z)?, which sets it, and f.reset(), which zeroes it. A state of the wrong length fails the call.
Luau does not reach IirFilter; a Luau script keeps its own previous values.
The example is the one-pole filter b = (1), a = (1, -0.5), fed the impulse 1, 0. By hand the outputs are 1 and 0.5 and the state afterwards is 0.25.
use eustress::log_info;
use eustress::realism::numerics;
pub fn on_init() {
let f = numerics::IirFilter::new([1.0], [1.0, -0.5])?;
let first = f.step(1.0)?;
let second = f.step(0.0)?;
let state = f.state();
log_info(`outputs = ${first}, ${second}`); // 1 and 0.5
log_info(`state = ${state[0]}`); // 0.25
}freqz
freqz evaluates the frequency response of a digital filter at angular frequencies that you list, in radians per sample. The value at each frequency is a complex number: the numerator polynomial over the denominator polynomial, evaluated on the unit circle. Its magnitude is the gain and its argument is the phase shift. Radians per sample runs from 0 to pi, where pi is half the sample rate.
The test suite compares freqz with SciPy at 9 frequencies from 0.01 to 3.1 for the Butterworth filter above, requiring a distance of at most 1e-11 times the reference magnitude (taken as at least 0.001).
Rune calls numerics::freqz(b, a, w)? with the numerator, the denominator and an array of frequencies in radians per sample. The result is an object with the arrays re and im, one value per frequency; an empty b or a fails the call. For the two-point sum b = (1, 1), a = (1) at the frequencies 0 and pi, the real parts are 2 and 0 and the imaginary parts are 0.
Luau does not reach freqz.
Examples: A Moving Average and a Low-Pass
The library's test runs a two-point moving average: b = (0.5, 0.5) and a = (1), over the input (2, 4, 6). The output is (1, 3, 5). The first output is 1 because the filter starts from rest: it averages 2 with the zero that came before it.
The library has no routine that designs filter coefficients. To get a low-pass or other design, build the filter in continuous time as a transfer function and discretize it with c2d_tf using the Tustin method with prewarping (TustinPrewarp).
The second example runs 60 samples through a fourth-order Butterworth low-pass filter with its cutoff at 0.2 of the Nyquist frequency, from rest. The input is 60 random samples from a normal distribution of unit spread, so it is noise throughout, with no signal underneath. The input swings between about -2.2 and 2.0 and the output stays between about -0.9 and 0.6: the filter removes the fast changes and keeps a slow wave.
The coefficients came from SciPy (scipy.signal.butter with order 4 and cutoff 0.2), because the library has no filter design routine. The numerator is 0.004824, 0.019297, 0.028946, 0.019297, 0.004824 and the denominator is 1, -2.369513, 2.313988, -1.054665, 0.187379.
Both examples run through the Rust crate. Rune reaches the moving average through filter, as the example above shows.In Luau the moving average is a one-line equation that a script computes itself, with output 0.5 x[n] plus 0.5 x[n-1] at sample n.
06Inside a Frame
The Frame Budget
Design calls belong outside the frame loop: a 200 by 200 eigenproblem takes about 18 ms and a 100-state Riccati solve about 60 ms, which is too long for a frame at 60 Hz. The per-sample blocks are the ones meant to run inside it: IirFilter step and FftPlan in-place transforms on this page, and the two control blocks DiscreteStepper and DiscretePid. None of them allocate.
A long call cannot be cancelled from outside and reports no progress. With one thread, the default, every routine returns the same bits on every run.
Luau reaches fft and ifft only as whole-array calls, and none of the per-sample blocks named above; a Luau script that runs a per-sample filter writes the arithmetic itself and keeps its state in variables that it creates once, outside the frame loop. Rune builds IirFilter and FftPlan once, outside the frame loop, and calls their methods inside it; the control blocks DiscreteStepper and DiscretePid are Rune types too, described on the Control Design page. The times quoted here are of the Rust routines called directly. A script call adds the cost of converting tables to arrays and back, and that cost is not measured on this page.
07What Is Not Covered
Missing Routines and Alternatives
These MATLAB routines are not in the library. Where the table gives an alternative, it is the nearest one.
| Not covered | Use instead |
|---|---|
integral2, integral3 | Nested integral calls |
interp2 | interp1 along each axis |
filtfilt | filter forward, reverse the samples, filter again, reverse |
butter and other filter design | Design in continuous time as a Tf, then c2d_tf with TustinPrewarp |
makima (interpolation method) | The pchip method, which is also shape preserving |
previous, next (interpolation methods) | The nearest method, or index the samples yourself |
griddata, fft2, fftn, window functions, pwelch, conv2, xcorr | None listed |
08What's Next
Where to Go from Here
Control Design is the next page and builds on the per-sample blocks. Performance holds the measured results.
Differential Equations and Optimization cover the other two groups of routines in the library.