Qu

Every name, on one page

936 builtins, taken from the interpreter's own dispatch table — so this page cannot claim a function the engine lacks, or omit one it has. 932 of them carry a signature and a description here; the rest are listed at the bottom by name, because a gap you can see is better than one you cannot.

Core maths & linear algebra chapter → 100

sin, cos, tansin(x)Standard trigonometric functions, computed elementwise. x is the input angle in radians — a scalar, a Vec of any length, or a Mat/Signal of any shape. Returns exactly the same type and shape as x, one trig value per element.
asin, acos, atanasin(x)Inverse trigonometric functions, single-argument only (there is no two-argument atan2 in this table). x is a scalar, Vec, or Mat/Signal; asin/acos expect values in [-1, 1] and return radians in [-π/2, π/2]/[0, π] (an out-of-domain element gives NaN), while atan accepts any real value and returns radians in (-π/2, π/2). Return shape always matches x. Returns exactly the same type and shape as x, one angle per element.
sinh, cosh, tanhsinh(x)Hyperbolic sine/cosine/tangent, elementwise. x is a scalar, Vec, or Mat/Signal; returns the same shape, one hyperbolic value per input element. Returns exactly the same type and shape as x.
coth, sech, cschcoth(x)The other three hyperbolics: coth(x) = cosh(x)/sinh(x), sech(x) = 1/cosh(x), csch(x) = 1/sinh(x). x is a real number or Complex. coth/csch have a pole at x=0 (and, for a Complex argument, at every x = i*k*pi) — evaluating there is an error, not a silent inf/NaN. sech has no real pole (cosh is never zero).
asinh, acosh, atanhasinh(x)Inverse hyperbolics. asinh is defined and finite on the whole real line. acosh is only real for x >= 1; a real x < 1 gives NaN (same convention as sqrt on a negative real — no silent promotion to a complex result), but an explicit Complex argument still evaluates via the complex branch regardless of value. atanh has a pole at x = +-1 (real or complex) — an error, not a silent inf. All three accept Complex as well as real input.
expexp(x)e^x, elementwise. x is a scalar, Vec, or Mat/Signal; returns the same shape with every element exponentiated. Returns exactly the same type and shape as x.
exp2exp2(x)2^x, elementwise, real only. x is a scalar, Vec, or Mat/Signal. Returns exactly the same type and shape as x.
expm1expm1(x)e^x - 1, computed so it stays accurate for x near zero (expm1(1e-15) does not lose precision to the cancellation that exp(x) - 1 would hit there). x is a scalar, Vec, or Mat/Signal. Returns exactly the same type and shape as x.
log, lnln(x)Natural logarithm, elementwise (log is an alias for ln — it is not base-10; see log10 for that). x is a scalar, Vec, or Mat/Signal; a non-positive element gives NaN/-inf rather than an error. Returns the same shape as x.
log1plog1p(x)ln(1 + x), computed so it stays accurate for x near zero (log1p(1e-15) does not underflow to exactly 0, unlike naively computing 1.0 + x first). x is a scalar, Vec, or Mat/Signal. Returns exactly the same type and shape as x.
log10, log2log10(x)Base-10 / base-2 logarithm, elementwise, same domain behavior as ln on a non-positive element. x is a scalar, Vec, or Mat/Signal. Returns exactly the same type and shape as x.
sqrtsqrt(x)Elementwise square root. x is a scalar, Vec, or Mat/Signal; a negative element gives NaN (there is no automatic promotion to a complex result). Returns the same shape as x.
cbrtcbrt(x)Real cube root, elementwise — unlike x^(1/3), correctly handles a negative x (cbrt(-8) = -2, not NaN). x is a scalar, Vec, or Mat/Signal. Returns exactly the same type and shape as x.
gamma, lgammagamma(x)The gamma function (gamma(n) = (n-1)! for a positive integer n) and its natural log (lgamma(x) = ln|gamma(x)|). x is a real scalar, Vec, or Mat/Signal. Both have a pole at every non-positive integer (0, -1, -2, ...) — evaluating there is an error, not a silent inf/NaN.
erf, erfcerf(x)The error function and its complement (erfc(x) = 1 - erf(x), computed directly rather than by subtraction so it stays accurate for large x, where erf(x) itself has already saturated to 1.0). x is a real scalar, Vec, or Mat/Signal; defined everywhere, no pole.
absabs(x)Absolute value on a real scalar/Vec/Mat; magnitude (sqrt(re^2 + im^2)) on a Complex scalar, CVec, or CMat. x is the value(s) to measure. Returns the same shape as x but always real-valued — a length-N CVec in gives a length-N real Vec out.
angle, arg, phaseangle(x)Complex argument — the angle from the positive real axis, in radians (atan2(im, re)) — on a Complex/CVec/CMat; on a signed real scalar or real Vec/Mat it degrades to 0 for a non-negative value or π for a negative one. x is the value(s) to measure. Returns the same shape as x but always real-valued — a length-N CVec in gives a length-N real Vec out, and a Complex scalar gives a Num.
real, rere(x)Real component of a Complex/CVec/CMat (identity — x passed through unchanged — when x is already real). x is a scalar, Vec, or Mat (real or complex). Returns the same shape as x but always real-valued — a Complex gives a Num, a CVec a real Vec, a CMat a real Mat.
imag, imim(x)Imaginary component of a Complex/CVec/CMat (0 elementwise when x is real). x is a scalar, Vec, or Mat (real or complex). Returns the same shape as x but always real-valued — a Complex gives a Num, a CVec a real Vec, a CMat a real Mat.
conjconj(x)Complex conjugate (negates the imaginary part); passes a real x through unchanged. x is a scalar, Vec, or Mat (real or complex). Returns exactly the same type and shape as x — a Complex stays a Complex, a real Vec stays a real Vec.
floor, ceil, roundfloor(x)Standard rounding functions, elementwise: floor toward negative infinity, ceil toward positive infinity, round to the nearest integer (half away from zero). x is a scalar, Vec, or Mat/Signal. Returns exactly the same type and shape as x, rounded elementwise.
signsign(x)The sign of each element, using Rust's f64::signum semantics: -1 for a negative value (including -0.0), +1 for a non-negative value (including +0.0 — so sign(0) returns 1, never 0, a real edge case worth knowing about), and NaN for a NaN input. x is a scalar, Vec, or Mat/Signal. Returns exactly the same type and shape as x, one sign per element.
sumsum(x, [on_invalid=])Sum of every element of x — a scalar, Vec, or Mat/Signal (real; additionally accepts a CVec/CMat and returns a Complex in that case). With no other argument, reduces to one scalar Num (or Complex). On a Mat, the optional axis= keyword (0 or 1) reduces along just that dimension instead, returning a Vec of length cols (axis=0) or rows (axis=1). on_invalid= ("propagate"/"ignore"/"error", see this section's intro) controls NaN/Inf handling, including for a CVec's complex elements — a NaN/Inf in either the real or the imaginary part counts. Returns a scalar Num — a Complex where sum reduced a CVec/CMat — or that Vec under axis=.
prodprod(x)Product of every element of x — a scalar, Vec, or Mat/Signal, real only (unlike sum, does not accept a CVec/CMat). With no other argument, reduces to one scalar Num. On a Mat, the optional axis= keyword (0 or 1) reduces along just that dimension instead, returning a Vec of length cols/rows. prod does NOT accept on_invalid= — that keyword was added to sum and the other nine reductions listed in this section's intro, not to prod. Returns a scalar Num, or that Vec under axis=.
meanmean(x, [on_invalid=])Arithmetic mean of every element of x — a scalar, Vec, or Mat/Signal. With no other argument, flattens x to one scalar Num (errors on an empty vector). On a Mat, the optional axis= keyword (0 or 1) computes the mean along just that dimension, returning a length-cols or length-rows Vec — see row_mean below for a dedicated column-Mat-returning version of the row case. on_invalid= ("propagate"/"ignore"/"error", see this section's intro) controls NaN/Inf handling; under "ignore" the divisor is the count of elements that survive filtering, not the original length. Returns a scalar Num with no axis=, or that Vec with one.
max, minmax(x, [on_invalid=]) or max(a, b)One argument reduces x (a scalar, Vec, or Mat/Signal) to its largest/smallest element, a scalar Num, and accepts on_invalid= ("propagate"/"ignore"/"error", see this section's intro). Two arguments a, b (matching or broadcastable shapes) instead compare elementwise and keep the larger/smaller of each pair — the "clip" idiom, e.g. max(x, 0); on_invalid= does not apply to this two-argument form. In the one-argument form on a Mat, the optional axis= keyword (0 or 1) reduces along just that dimension instead, returning a length-cols/rows Vec rather than a single scalar.
argmin, argmaxargmin(x, [on_invalid=])0-based index of the first-occurring minimum/maximum element of x (a scalar, Vec, or Mat/Signal, flattened). Returns a scalar Num index. on_invalid= ("propagate"/"ignore"/"error", see this section's intro) controls NaN/Inf handling; under "ignore" the returned index still refers to a position in the original, unfiltered x (or, under axis=, the original row/column), so it can be used to index straight back into the caller's own data. On a Mat, the optional axis= keyword (0 or 1) instead returns the index of the extremum *within* each column or row — a Vec of length cols/rows, each entry an index into that column/row rather than into the flattened matrix.
medianmedian(x, [on_invalid=])Middle order statistic of x (a scalar, Vec, or Mat/Signal, flattened): the middle element for an odd-length input, the average of the two middle elements when len(x) is even. on_invalid= ("propagate"/"ignore"/"error", see this section's intro) controls NaN/Inf handling. On a Mat, the optional axis= keyword (0 or 1) computes the median along just that dimension instead of flattening. Returns a scalar Num with no axis=, or a length-cols/rows Vec with one.
quantilequantile(x, q, [on_invalid=])Linear-interpolation quantile (NumPy's default interpolation="linear" method). x is a scalar, Vec, or Mat/Signal (flattened); q is a scalar rank in [0, 1] (0.5 is the median), interpolated between the two nearest order statistics when it doesn't land exactly on one. on_invalid= ("propagate"/"ignore"/"error", see this section's intro) controls NaN/Inf handling. On a Mat, the optional axis= keyword (0 or 1) reduces along just that dimension instead of flattening. Returns a scalar Num with no axis=, or a length-cols/rows Vec with one.
percentilepercentile(x, p)Same computation as quantile, with p on a 0..100 scale instead of 0..1 (p=50 is the median). x is a scalar, Vec, or Mat/Signal; p must lie in [0, 100] or the call errors. Returns a scalar Num.
iqriqr(x)Interquartile range: percentile(x,75) - percentile(x,25) — a spread measure robust to outliers, unlike std/var. x is a scalar, Vec, or Mat/Signal. Returns a scalar Num.
argmedianargmedian(x)Index into x (a Vec or flattened Mat/Signal) of the element sitting at the median position. Because an even-length x has no single median element, this returns the lower of the two middle indices — a deliberate, documented tie-break (NumPy has no argmedian, precisely for this reason). Returns a scalar Num index (0-based).
argquantileargquantile(x, q)Index into x (a Vec or flattened Mat/Signal) nearest the q-quantile rank, computed as round(q*(n-1)) where n = len(x); q is a scalar in [0, 1]. Unlike quantile, which may interpolate between two elements, this always lands on a real element of x. Returns a scalar Num index (0-based).
argmeanargmean(x)Index into x (a Vec or flattened Mat/Signal) of the element closest to mean(x) (ties broken by first occurrence) — not a true order-statistic index like the others above, since the mean generally isn't any actual data point. Returns a scalar Num index (0-based); errors on an empty x.
clip, clampclip(x, lo, hi)Elementwise clamp of x (a scalar, Vec, or Mat/Signal) into [lo, hi]. lo and hi are scalars (or broadcastable arrays); both are optional, defaulting to -inf/+inf respectively, so e.g. clip(x, 0) floors at zero and leaves the top end open. Returns the same shape as x.
stdstd(x, [on_invalid=])Sample standard deviation (N-1, unbiased, denominator) of every element of x — a scalar, Vec, or Mat/Signal. With no other argument, flattens x to one scalar Num. On a Mat, the optional axis= keyword (0 or 1) computes the standard deviation down each column or across each row instead, returning a length-cols/rows Vec. on_invalid= ("propagate"/"ignore"/"error", see this section's intro) controls NaN/Inf handling; under "ignore" the divisor is the count of elements that survive filtering. Returns a scalar Num with no axis=, or that Vec with one.
varvar(x, [on_invalid=])Sample variance, same N-1 (unbiased) denominator as std, so var(x) == std(x)^2 always holds. x is a scalar, Vec, or Mat/Signal, flattened. On a Mat, the optional axis= keyword (0 or 1) computes the variance down each column or across each row instead, returning a length-cols/rows Vec (same support as std). on_invalid= ("propagate"/"ignore"/"error", see this section's intro) controls NaN/Inf handling. Returns a scalar Num with no axis=, or that Vec with one.
rmsrms(x)Root-mean-square, sqrt(mean(x.^2)), of every element of x — a scalar, Vec, or Mat/Signal, flattened. Returns a scalar Num. Errors on an empty vector.
peakpeak(x)max(abs(x)) over every element of x — a scalar, Vec, or Mat/Signal, flattened. Returns a scalar Num. Errors on an empty vector.
crest_factorcrest_factor(x)peak(x) / rms(x), a dimensionless ratio (a sine wave's is sqrt(2) ≈ 1.414) — the same quantity sinad_estimate(bits, crest_factor) takes as its second argument. x is a scalar, Vec, or Mat/Signal, flattened. Returns a scalar Num. Errors on an empty vector or one whose RMS is zero (silence has no crest factor).
dbfsdbfs(x, [full_scale=1.0])Peak level relative to full scale: 20*log10(peak(abs(x)) / full_scale). x is a scalar, Vec, or Mat/Signal, flattened; full_scale (optional number, default 1.0) must be positive. An uncalibrated digital signal can answer in dBFS with no physical unit attached — anything past that (dB SPL, a sensitivity-based unit) needs a calibration this engine does not carry yet. Returns a scalar Num. Errors on an empty vector.
normnorm(x)Euclidean (L2) norm; for a matrix this is the Frobenius norm (every element treated as one long vector), not a matrix operator norm. x is a scalar, Vec, or Mat (real, or CVec/CMat, which norm by magnitude). Returns a scalar Num.
logsumexp, lselse(x)Numerically stable log(sum(exp(x))), via the usual max-shift so a large input can't overflow exp. x is a scalar, Vec, or Mat/Signal, flattened. Returns a scalar Num — -inf for an empty x.
smoothmaxsmoothmax(x, beta=1)Smooth (differentiable) approximation to max(x): (1/beta) * logsumexp(beta * x), which tracks the true maximum more tightly as beta grows (at the cost of a stiffer gradient). x is a scalar, Vec, or Mat/Signal, flattened; beta is an optional positional scalar defaulting to 1 (a non-positive or non-finite beta falls back to the plain hard max). Returns a scalar Num.
softmaxsoftmax(x)Elementwise exp(x_i) / sum(exp(x)) — the gradient of logsumexp, and a probability distribution that sums to 1. x is a scalar, Vec, or Mat/Signal, flattened. Returns a Vec the same length as x whatever x's original shape was — a Mat in still gives a flat Vec out, and an empty x an empty Vec.
max(x)Largest element of x (a scalar, Vec, or Mat/Signal, flattened) — a single scalar Num.
max(a, b)Elementwise max of a and b (matching or broadcastable shapes) — the "clip" idiom, e.g. max(x, 0). Returns the broadcast shape, not a scalar.
min(x)Smallest element of x (a scalar, Vec, or Mat/Signal, flattened) — a single scalar Num.
min(a, b)Elementwise min of a and b (matching or broadcastable shapes) — the same "clip" idiom as max, from the other side.
rows, colsrows(A)Row / column count of A. On a Vec (shape (n, 1)), a Mat/Signal (shape (r, c)), or a bare scalar (shape (1, 1)), returns the corresponding dimension as a scalar Num. On a Table, returns the same values as nrow(df)/ncol(df) — row count is the record count, column count the field count. Returns a scalar Num.
size, shapeshape(A)The full shape of A as a 2-element Vec, [rows, cols], using the same per-type shape rules as rows/cols above. size is the same builtin — MATLAB's name for it. (sizeof is a third name for it and is deprecated: it means a byte count everywhere else). An Image is the one exception and reports [width, height], not rows-first — because an image's own constructors are width-first (image_new(width, height), resize(img, width, height), crop(img, x0, y0, width, height)), and answering rows-first made image_new(640, 480) report [480, 640]. A Mat of pixels is still a matrix and still [rows, cols]. Returns a 2-element Vec.
length, numelnumel(x)Total element count of x: 1 for a scalar, its length for a Vec/CVec/Signal, rows*cols for a Mat, a Unicode-aware character count for a Str, and the element/node count for List/Record/Dict/fifo/linked_list/graph. Returns a scalar Num.
zeroszeros(n) / zeros(r, c)A vector or matrix of zeros. One numeric argument n gives a length-n Vec; two arguments r, c give an r×c Mat — even a degenerate two-argument shape like zeros(n, 1) stays a genuine oriented matrix, distinct from the plain Vec that zeros(n) returns. Overloaded by argument type: zeros(filt), where filt is a "filter" model (from butter/fir1/etc.), instead returns that filter's zeros as a CVec (see [Signal Processing & Filters](signal-processing.md)).
onesones(n) / ones(r, c)A vector or matrix of ones, with the same one-argument-vs-two-argument shape rules as zeros above. Returns a length-n Vec for ones(n), or an r×c Mat for ones(r, c).
eye, identityeye(n)The n×n identity matrix (ones on the diagonal, zeros elsewhere). n is a single non-negative integer. identity is an alias for eye. Returns an n×n Mat.
reshapereshape(x, r, c)Reinterprets a value as a matrix of a given shape. x is the value being reshaped, a scalar, Vec or Mat; r (number) is the row count of the result; c (number) is the column count, and r * c must equal the number of elements x holds. This is a genuine element relayout (column-major) when x is a scalar or Vec, or when x is already an r×c Mat; when x is a Mat with one dimension equal to 1 it is also a real reshape. Reshaping a matrix that has more than one row *and* more than one column into a different two-dimensional shape does not relayout the data — it falls through to a broadcast check instead and errors unless the two shapes are broadcast-compatible, a real, confirmed engine limitation rather than a documentation simplification. expr -> (r, c) is postfix-style sugar for exactly this call — see below.
hstack, vstackhstack(a, b, ...)Named equivalents of bracket-literal block concatenation ([a, b] horizontally / [a; b] vertically). Each of the 2+ required arguments is a scalar, Vec, or Mat (real or complex — any complex argument makes the whole result complex); hstack needs matching row counts, vstack needs matching column counts. Returns a Mat (or CMat if any input was complex).
catcat(dim, a, b, ...)MATLAB-style concatenation: dim (a scalar, 1 or 2) selects the axis, then the 2+ remaining arguments (same shape rules as hstack/vstack) are joined along it — dim=1 vertical (same as vstack), dim=2 horizontal (same as hstack). Returns a Mat. Taking the axis first means cat is the one array builtin you cannot write as a.cat(b) or a
zeros(n)A length-n Vec of zeros.
zeros(r, c)An r×c Mat of zeros — even zeros(n, 1) stays a genuine oriented matrix, distinct from zeros(n).
zeros(filt)filt a "filter" model (from butter/fir1/etc.), not a count at all — dispatch here is by argument *type*, not count. Returns that filter's zeros as a CVec.
reshape(x, r, c) where x is a scalar, Vec, or a Mat with one dimension equal to 1A genuine element relayout (column-major) into the new r×c shape.
reshape(x, r, c) where x is a Mat with more than one row **and** more than one columnNot a relayout. Falls through to a broadcast check instead and errors unless the two shapes are broadcast-compatible — a real, confirmed engine limitation, not a documentation simplification.
valval(x)Materializes a value; currently the identity on any x (:= is already eager pre-M4) but will force evaluation of a deferred binding once M4 lazy fusion lands. Returns x unchanged, same type and shape.
transposetranspose(A)Matrix/vector transpose: swaps rows and columns. A is a Vec (treated as a single row or column) or Mat/CMat; an r×c input returns a c×r output of the same element type. Returns a Mat, or a CMat for a complex input — including for a Vec argument, which comes back as an n×1 column Mat rather than a Vec.
ctransposectranspose(A)Conjugate transpose (Hermitian): transpose plus elementwise complex conjugation. A is a Vec/Mat/CMat; an r×c input returns a c×r output (real inputs behave exactly like transpose, since conjugation is a no-op on real numbers). Returns a Mat, or a CMat for a complex input.
flipud, fliplr, mirror, flipflip(A, dim=1)Reverses row order (flipud, dim=1) or column order (fliplr/mirror, dim=2) of A, a Str, Vec, Mat, or Image. On a Str every spelling reverses the character order; on a plain Vec (which has no row/column orientation) both directions just reverse element order. dim (only meaningful for flip) is an optional keyword-or-positional scalar, 1 or 2, defaulting to 1. Returns the same type and shape as A.
rot90rot90(A, k=1)Rotates A (a Mat, or anything coercible to one) 90°×k counterclockwise; k is an optional scalar defaulting to 1, may be negative for clockwise rotation, and is taken mod 4. An r×c input becomes c×r after an odd number of quarter-turns, or stays r×c after an even number. Returns a Mat.
wherewhere(mask) or where(cond, a, b)One argument mask (a Vec/Mat of booleans, typically produced by a comparison like x < 0) returns a Vec of the 0-based indices where it is true. Three arguments — cond (a boolean mask), a, b (scalars or arrays broadcastable to cond's shape) — instead select elementwise: a's value where cond is true, b's otherwise (NumPy's where(cond, a, b)), returning the same shape as cond.
findfind(mask) or find(collection, fnName)One argument: identical to where(mask) — the indices where a boolean mask is true, as a Vec. Two arguments: collection (any indexable/iterable value) and fnName (a Str naming an already-defined one-argument predicate function); returns the first element of collection for which that predicate is truthy.
where(mask)Indices where the boolean mask (a Vec/Mat) is true, as a Vec — the 1-argument form.
where(cond, a, b)Elementwise selection: a where cond is true, b otherwise (NumPy's where(cond, a, b)) — the 3-argument form, returning cond's shape rather than a list of indices.
find(mask)Identical to where(mask) — the indices where a boolean Vec/Mat is true.
find(collection, fnName)collection (any indexable/iterable value) and fnName (a Str naming an already-defined one-argument predicate) — returns the *first element* of collection for which that predicate is truthy, not an index.
dotdot(a, b)Dot product of two equal-length vectors a, b (each a Vec; a length mismatch errors). Returns a scalar Num, sum(a_i * b_i).
add, subtract, mul, div, powadd(a, b, ...)The operators as named functions, so an operation can be passed where a name is what you can pass. Variadic and folded left: add(a, b, c) is a + b + c. Each routes through the very same code the operator does, so broadcasting, units, complex, matrices and every error message are whatever a + b already gives — there is no second set of arithmetic rules that could drift from the first. mul/div follow * and /, which on two matrices mean matrix multiply and solve. subtract, not sub — sub is a keyword (it opens a subroutine), so a builtin of that name could never be called. Returns whatever the matching operator returns for those arguments: a Num from two scalars, a Vec from a Vec and a scalar, a Mat from two matrices, a Complex/CVec/CMat as soon as either side is complex.
elemul, elediv, elepowelemul(a, b, ...)The .*, ./ and .^ family: always elementwise, whatever the shapes. The distinction from mul/div/pow only bites on matrices, which is exactly why both families have names. Returns the broadcast shape of the arguments — a Num from two scalars, otherwise a Vec or Mat, or the complex counterpart of either as soon as one side is complex.
rangerange(a, b, [step])Inclusive numeric range as a Vec, from a to b (both scalars) in increments of step (an optional positional scalar, default 1 — step= as a keyword is rejected, unlike most optional Qu arguments) — distinct from the to/a:step:b loop-range syntax. Returns a Vec whose length depends on a, b, and step.
matmul, mtimesmatmul(A, B)Matrix multiplication of A (r×k) and B (k×c), both Mat (inner dimensions must agree). Returns an r×c Mat. mtimes is the exact same builtin under a second, MATLAB-flavored name.
gpu_matmulgpu_matmul(A, B)WebGPU-accelerated matmul via qu-gpu, same A/B shape requirements and r×c Mat return as matmul; only present in builds compiled with --features gpu. f32 precision (~7 significant digits), not f64 — a real, documented tradeoff, not a bug. Returns an m×n Mat from an m×k A and a k×n B.
pinvpinv(A, tol=)Moore-Penrose pseudo-inverse (SVD-based) of A, an r×c Mat or CMat. tol is an optional scalar relative tolerance for treating a singular value as zero; it defaults to f64::EPSILON * max(rows, cols) (real input) — the same tolerance rank reports. Returns a c×r Mat/CMat.
invinv(A)True inverse of A (a square Mat or CMat); requires full rank, errors otherwise. Returns an n×n matrix of the same real/complex kind as A.
cholchol(A)Lower-triangular Cholesky factor L of A = L·Lᵀ, where A is a symmetric positive-definite n×n Mat; errors clearly if A isn't positive-definite. Returns an n×n Mat.
detdet(A)Determinant of a square Mat or CMat, via LU decomposition. Returns a scalar Num (or Complex for a CMat).
rankrank(A, tol=)Numerical rank of A (an r×c Mat or CMat) — the count of singular values clearing the tolerance. tol is an optional scalar, same default and convention as pinv's. Returns a scalar Num (integer-valued).
svdsvd(A)Thin SVD of A (r×c Mat or CMat), A = U·diag(s)·Vᵀ. Returns a Model (kind "svd") with fields: u (r×k Mat), s (length-k Vec of singular values, k = min(r,c)), vt (k×c Mat) for a real A; a CMat input instead reports values (singular values), condition, and rank only.
qrqr(A)Thin QR decomposition of A (r×c Mat), A = Q·R. Returns a Model (kind "qr") with fields q (r×k Mat, orthonormal columns) and r (k×c Mat, upper triangular), k = min(r,c).
lulu(A)LU decomposition with partial pivoting of a square n×n Mat A, P·A = L·U. Returns a Model (kind "lu") with fields l (n×n lower-triangular Mat, unit diagonal), u (n×n upper-triangular Mat), and p (n×n permutation Mat).
eigeig(A)Eigenvalues (and, for symmetric A, real eigenvectors) of a square n×n Mat A. Returns a Model (kind "eig") with fields values (a length-n Vec if all eigenvalues are real, otherwise a length-n CVec) and vectors (an n×n Mat of eigenvectors as columns when A is symmetric, otherwise Nothing).
diagdiag(M) or diag(v)Overloaded on argument type: diag(M), where M is an r×c Mat, returns its main diagonal as a length-min(r,c) Vec; diag(v), where v is a length-n Vec (or scalar/other coercible value), returns an n×n Mat with v's entries on the diagonal and zeros elsewhere. Returns a Vec when handed a Mat, and a Mat when handed a Vec — the argument's type decides, not a keyword.
tracetrace(M)The sum of the diagonal of M, a square (or rectangular — only min(rows,cols) diagonal entries are summed) Mat. Returns a scalar Num, equal to the sum of the eigenvalues — the cheap way to sanity-check an eigendecomposition.
solvesolve(A, b)Solves A·x = b for x by LU with partial pivoting (or, for a CMat/CVec A/b, by complex SVD least squares). A is an n×n Mat/CMat, b is a length-n Vec/CVec or an n×k Mat/CMat of multiple right-hand sides. Returns a Mat/CMat the same shape as b. Prefer it to inv(A) * b: it is faster and numerically better behaved.
condcond(A)The 2-norm condition number of A (an r×c Mat or CMat) — the ratio of its largest to smallest singular value. Returns a scalar Num, +inf for a singular matrix rather than an error (conditioning is routinely measured on matrices that turn out to be singular, and infinity *is* the answer there). Roughly how many digits a solve can lose, so 1e12 on a double means about four digits survive.
nnlsnnls(A, b, max_iter=)Non-negative least squares by Lawson-Hanson, for when a negative coefficient would be physically meaningless — a concentration, a mass, a relaxation strength. A is an m×n Mat, b a length-m Vec; max_iter is an optional scalar iteration cap (unset by default, meaning the solver's own internal limit applies). Returns a Record with fields x (length-n Vec, every entry >= 0) and residual (a scalar Num, ‖A·x - b‖).
least_squaresleast_squares("f", x0, lower=, upper=, max_iter=200, tol=1e-10)Nonlinear least squares on a residual function you named, via Levenberg-Marquardt. "f" is a Str naming an already-defined function that takes a length-p parameter Vec and returns a residual Vec; x0 is the length-p initial guess Vec. lower=/upper= are optional length-p Vecs of box bounds (enforced by clamping every trial point before it is evaluated, rather than by penalty); max_iter= (default 200) caps the iteration count, tol= (default 1e-10) sets the convergence tolerance. Returns a Model (kind "least_squares") with fields params (length-p Vec, the fitted parameters), residual (Vec, the residual at the solution), cost (scalar Num), iterations (scalar Num), and converged (Bool).
meshgridmeshgrid(x, y)The two coordinate matrices a surface or contour needs, from two axis vectors x (length nx) and y (length ny). Returns a Record with fields x and y, each an ny×nx Mat: .x repeats the x vector down every row, .y repeats the y vector across every column, so (.x[j,i], .y[j,i]) is the grid point for x[i], y[j].
ones_like, zeros_likezeros_like(x)A vector or matrix of the same shape as x (a Vec or Mat), filled with one or zero respectively — the shape is read directly from x, so it cannot fall out of step with it. Returns the same type and shape as x.
row_mean, row_sumrow_mean(M)Collapses each row of M (an r×c Mat, or anything coercible to one) to one number, returning an r×1 column Mat (not a plain Vec). mean(M, axis = 0) collapses columns instead and returns a plain Vec — the axes are 0 and 1, not 1 and 2, and note the different return container (Mat here vs. Vec for the axis= form). Returns an r×1 column Mat, one entry per row of M.
mm, cm, inch, ptfigure_size(mm(180), mm(120))Length units as functions, converting a scalar v (millimetres/centimetres/inches/points as named) to the figure's own coordinate space — a tenth of a millimetre, so mm(1) is 10, cm(1) is 100, inch(1) is 254, and pt(1) is ≈3.528 (25.4/72 mm per point). Returns a scalar Num. There is no 180mm literal — a bare number is always taken as figure units directly.
is_empty, is_fullis_empty(q)Whether the fixed-capacity ring buffer q (a Fifo handle created by fifo(capacity)) currently holds nothing, or has no room left for another push without evicting the oldest element. q must be a Fifo. Returns a Bool.

Signal processing chapter → 195

fft / fftcfft(x, [n])Forward DFT (Bluestein/rustfft-accelerated). x is a length-N real or complex vector; n (optional number) zero-pads/truncates x to n samples before transforming, defaulting to N. Returns a length-n complex vector (CVec). fftc is an explicit-complex alias of the same function, identical signature and return.
ifftifft(X, [n])Inverse DFT, same underlying kernel as fft run in reverse. X is a length-N complex vector (CVec); n (optional number, default N) is the target length, same zero-pad/truncate rule as fft. Returns a length-n CVec.
rfftrfft(x)Real-optimized half-spectrum FFT. x is a length-N real vector. Returns a length-floor(N/2)+1 CVec (DC through Nyquist) — a real signal's spectrum is Hermitian-symmetric, so only the non-negative-frequency half is returned.
irfftirfft(half_spectrum, n)Inverse of rfft. half_spectrum is a length-floor(n/2)+1 complex vector (CVec); n (required number), the real output length, can't be recovered from the half-spectrum's length alone (even and odd n can share a half-length). Returns a length-n real vector. (fftr is a deprecated second name for this — see below.)
dftdft(x)x is a length-N real or complex vector. Returns a length-N CVec. The direct, textbook O(n²) transform, kept as an independent reference implementation to validate fft against and as the definitional basis goertzel specializes.
idftidft(X)X is a length-N complex vector (CVec). Returns a length-N CVec. Inverse of dft, same O(n²) direct implementation.
goertzelgoertzel(x, k)x is a length-N real vector; k is the bin index to evaluate (a number, need not be an integer — evaluates the DFT at an arbitrary point between the FFT's grid bins) or a length-K vector of bins. Returns a single complex scalar for a scalar k, or a length-K CVec for a vector — the K-point DFT this is named for: K arbitrary points in O(n·K), each independently, instead of every bin of a full N-point fft whether wanted or not. The standard tool for checking a handful of specific frequencies without paying for a whole FFT.
goertzel_freqgoertzel_freq(x, fs, freq)x is a length-N real vector; fs (number, Hz) is the sample rate; freq is the frequency to evaluate (a number, Hz) or a length-K vector of frequencies. Returns a single complex scalar or a length-K CVec, same batching as goertzel above. goertzel parameterized by real frequencies rather than raw bin indices — the common case of checking one or several known tone frequencies at a fixed sample rate.
vanicekvanicek(t, x, freqs)t is a length-N vector of sample times (need not be uniformly spaced); x is the matching length-N vector of samples; freqs is a length-M vector of frequencies (Hz) to evaluate. Returns a length-M real vector, the power spectrum at each requested frequency — Vanicek's Least-Squares Spectral Analysis, valid for unevenly-sampled (t, x) where fft/dft/goertzel (which all assume uniform sampling) don't apply.
dctdct(x)x is a length-N real vector. Returns a length-N real vector. Orthonormal DCT-II (MATLAB dct / scipy.fft.dct(norm='ortho') convention).
idctidct(X)X is a length-N real vector of DCT coefficients. Returns a length-N real vector. Orthonormal DCT-III, the exact inverse of dct (round-trips exactly since the basis is orthonormal).
dwtdwt(x)x is a length-N real vector (N should be even). Returns a (2, N/2) matrix — row 0 is the approximation band, row 1 is the detail band (Qu has no multi-return). One level of the orthogonal Haar discrete wavelet transform; only the Haar family is implemented.
idwtidwt(m)m is a (2, N) matrix of [approx; detail] rows (each row length N). Returns a length-2N real vector, reconstructing the original signal. Inverse of dwt.
stftstft(x, nfft, [hop=nfft/2])x is a length-N real vector; nfft (number) is the frame/FFT size; hop (optional number, default nfft/2, i.e. 50% overlap) is the sample stride between successive frame starts. Returns an nfft×num_frames complex matrix (CMat, the full per-frame spectrum, not one-sided) — one column per frame, built from a periodic-Hann-windowed FFT per frame. abs(stft(x, ...)) is a spectrogram.
hilberthilbert(x)x is a length-N real vector. Returns a length-N complex vector (CVec), the analytic signal x + j*H[x]. abs(hilbert(x)) is x's envelope; imag(hilbert(x)) is the Hilbert transform of x itself.
convconv(x, h, [mode="full"])x is a length-N vector, h a length-M vector (the kernel/impulse response). mode (optional string) follows MATLAB's conv/NumPy's convolve naming: "full" (default, length N+M-1, every nonzero-overlap sample), "same" (length N, the middle samples aligned with the input), "valid" (length max(N,M)-min(N,M)+1, only where h fully overlaps x). Returns a vector of the length implied by mode.
xcorrxcorr(x, [y])x is a length-N vector; y (optional length-M vector, defaults to x for autocorrelation). Returns a length-N+M-1 vector, the full lag range (zero lag at the middle for equal-length inputs).
find_peaksfind_peaks(x, [height=], [distance=], [prominence=], [width=], [rel_height=0.5])x is a length-N vector. height (optional number): minimum peak value; distance (optional number, samples): minimum separation, enforced greedily by height so a close cluster keeps its tallest member; prominence (optional number): minimum rise above surrounding terrain (the real bounding-minima computation, not just local-maxima detection); width (optional number, samples): minimum width at rel_height (default 0.5, i.e. half-prominence) of the peak's prominence below its height, via linear interpolation of the crossing — matches scipy.signal.find_peaks's own algorithm. Kwarg names match SciPy; the original min_height/min_distance/min_prominence names are still accepted as aliases. Returns a vector of 0-indexed integer indices into x, one per surviving local maximum.
findpeaksfindpeaks(x, [min_peak_height=], [min_peak_distance=])x is a length-N vector; min_peak_height/min_peak_distance (optional numbers) as above. MATLAB-style [peaks, locations] = findpeaks(x, ...). Qu has no multi-return/tuple-unpacking assignment, so this returns a Model (kind "findpeaks") with fields peaks (a vector of the peak values), locations (a vector of their 0-indexed integer indices into x — not MATLAB's 1-indexing), prominences (a vector, one per peak, the real prominence value) and widths (a vector, one per peak, the width in samples at rel_height=0.5) — the same named-field convention qr/lu/svd/eig use. Shares its peak-finding/non-max-suppression logic with find_peaks above.
conv(x, h) / conv(x, h, mode="full")N+M-1Every nonzero-overlap sample — the default.
conv(x, h, mode="same")NThe middle samples, aligned with x.
conv(x, h, mode="valid")max(N,M)-min(N,M)+1Only the samples where h fully overlaps x.
mag2dbmag2db(x)x: a number or vector (amplitude/voltage ratio). Returns the same shape: 20*log10(x). AMPLITUDE/field-quantity convention.
dbdb(x)Alias of mag2db(x) above (20*log10(x), amplitude convention) — the bare SciPy/general-DSP-flavored spelling.
db2magdb2mag(db)db: a number or vector (decibel value). Returns the same shape: 10^(db/20) — inverse of mag2db.
pow2dbpow2db(x)x: a number or vector (power ratio). Returns the same shape: 10*log10(x). POWER-domain convention.
db_powerdb_power(x)Alias of pow2db(x) above (10*log10(x), power convention) — the bare SciPy/general-DSP-flavored spelling.
db2powdb2pow(db)db: a number or vector (decibel value). Returns the same shape: 10^(db/10) — inverse of pow2db/db_power.
gaingain(x, db)x: a number, vector, matrix or Signal; db: a number of decibels, also nameable (gain(x, db = -3)) and accepting a dB-suffixed literal (gain(x, -3 dB), since dB passes through dimensionless). Returns the same shape as x, scaled by 10^(db/20) — the AMPLITUDE convention, the same factor of 20 as db2mag. A Signal keeps its Fs: changing a level does not touch the time axis.
spectrogramspectrogram(x, [nfft=256], [hop=nfft/2], [fs=1])x: a length-N real vector or Signal. nfft/hop (optional numbers): STFT frame size and hop, as in stft. fs (optional number, Hz): scales row ticks to Hz and column ticks to seconds. If x is a Signal, its own Fs is used and fs need not be passed; passing one that disagrees with the signal's rate is an error rather than a silent relabelling (see *Which rate is used*, below). The default of 1 applies only to a plain vector, which carries no rate. Renders a heatmap of stft(x, nfft, hop)'s magnitude, restricted to the positive-frequency half (nfft/2+1 rows), in dB (floored at -120dB); frequency increases upward (row 0 = Nyquist). Draws and returns: the surface would otherwise be unreachable, with no way to read a level off it or hand it to Qu Studio's Interactive Mode. Returns a Record with fields db (an (nfft/2+1, frames) Mat of dB magnitudes, row 0 = DC — the honest axis order, the opposite of the drawn picture's), freq (a length-nfft/2+1 Vec, Hz) and time (a length-frames Vec, seconds).
spectral_entropyspectral_entropy(x, [nfft=256], [hop=nfft/2])x: a length-N real vector. nfft/hop (optional numbers): STFT frame size/hop as in stft. Returns a vector of length num_frames (one value per STFT frame), each the Shannon entropy of that frame's normalized power spectrum, scaled to [0, 1]: low when energy concentrates in a few bins (a clean tone), high when spread across many (broadband noise).
spectrumspectrum(x, [fs], [window="hann"], [scaling="amplitude"])x: a length-N real vector or Signal; fs (number, Hz) — required, either passed or carried by a Signal (the result is a spectrum, whose point is its frequency axis; there is no default rate to mislabel it with). window (optional string: "hann" (default), "hamming", "blackman", "kaiser" (needs beta=), or "rectangular"/"boxcar"/"none" for no taper): the analysis window applied to the record before transforming. scaling (optional string: "amplitude" (default) or "rms"): the convention stamped on X.norm. Returns a spectrum of floor(N/2)+1 one-sided bins (DC to Nyquist). The window is normalised to unit coherent gain (mean(w) == 1) before it is applied, so a bin-aligned tone of amplitude A reads exactly A (A/sqrt(2) under "rms") — an uncompensated Hann taper would read A/2. This is what spectrum adds over rfft(sig, scaling=), which applies no window at all; window="rectangular" makes the two agree bin for bin. Compensation is applied uniformly, not only when scaling="amplitude", so two calls differing only in scaling= differ only by the documented 1/sqrt(2). It corrects a discrete tone's peak, not a broadband level — noise spread across bins is governed by the window's noise-equivalent bandwidth (sum(w^2), 1.5 for Hann), which is what psd/welch are scaled for; integrate power with those, not this. scaling="raw" is deliberately refused: a spectrum carries no window field, so raw bins would be exactly what band_power integrates as if the record had not been tapered — use rfft(sig) for the unwindowed raw transform.
welchwelch(x, fs, [nperseg=min(256,len(x))], [noverlap=nperseg/2], [window="hann"])x: a length-N real vector; fs (number, Hz): sample rate. nperseg (optional number): samples per segment; noverlap (optional number): overlap between segments; window (optional string, e.g. "hann"/"hamming"/"blackman"): window applied to each segment. Returns a length-nperseg/2 + 1 real vector, the one-sided PSD (DC to Nyquist) in SciPy's "density" scaling — Welch's method segments x into overlapping windowed frames and averages their squared-magnitude spectra. Pair with linspace(0, fs/2, length(psd)) for the frequency axis.
periodogramperiodogram(x, fs, [window="hann"])x: a length-N real vector; fs (number, Hz); window (optional string). Returns a length-N/2 + 1 real vector, same scaling as welch. The simplest PSD estimate — welch's one-segment (nperseg=length(x), noverlap=0), no-averaging special case.
psdpsd(x, [fs], [window="hann"], [nfft=min(256,len(x))], [overlap=0.5])x: a length-N real vector or Signal; fs (number, Hz) — required, or carried by a Signal. nfft (optional number): the segment length — the same meaning spectrogram/stft give nfft in this engine, *not* SciPy's zero-padded transform length. overlap (optional number): segment overlap as a fraction in [0, 1) — 0.5 is 50%, where welch's noverlap= is an absolute sample count. window (optional string, as for welch). Returns a length-nfft/2 + 1 real vector, the one-sided Welch PSD in SciPy's "density" scaling, exactly as welch does — literally the same code path, so psd(x, fs) and welch(x, fs) are bit-identical and the defaults are chosen to keep that true. Pair with linspace(0, fs/2, length(p)) for the frequency axis. The result carries no units. toolkit-signal.md §2 sketches a P.unit of V^2/Hz; the engine has no derived/compound unit algebra to propagate one with (unit ppm = 1e-6 declares simple named scalars), so this returns a plain vector and documents the scaling rather than stamping a label it cannot enforce.
csdcsd(x, y, fs, [nperseg=min(256,len(x),len(y))], [noverlap=nperseg/2], [window="hann"])x/y: equal-length real vectors; fs (number, Hz). Returns a length-nperseg/2 + 1 complex vector (CVec), the one-sided cross-spectral density Pxy — Welch's method, sharing welch's own framing/windowing/averaging exactly, so it lines up bin-for-bin with welch(x, ...)/welch(y, ...). abs(csd(x, y, fs)) is cross-power magnitude, angle(csd(x, y, fs)) is phase.
spectral_coherencespectral_coherence(x, y, fs, [nperseg=], [noverlap=], [window="hann"])x/y: equal-length real vectors; fs (number, Hz). Returns a length-nperseg/2 + 1 real vector, the magnitude-squared coherence |Pxy|^2 / (Pxx*Pyy) in [0, 1] — 1 at a frequency where y is an exact linear/time-invariant function of x's content there. Unrelated to coherence(A) (see the Compressed Sensing chapter) — the largest inner product between two different normalised columns of a compressed-sensing matrix — which is a different, pre-existing function under its own name.
nyquistnyquist(Z, [color=], [label=], [marker="o"])Z: a length-N complex vector (CVec, the impedance spectrum). color/label/marker (optional strings): plot styling. The standard EIS plot: Re(Z) on x, -Im(Z) on y (the impedance-spectroscopy sign convention every EIS instrument uses, so capacitive/inductive behavior plots in the upper half-plane). Returns Nothing — this call is made for the figure it draws.
bode_magnitudebode_magnitude(Z, freqs, [color=], [label=], [marker="line"])Z: a length-N complex vector (CVec); freqs: the matching length-N real vector (Hz). color/label/marker (optional strings). Magnitude half of a Bode plot: 20*log10(|Z|) vs. log-scaled frequency. Returns Nothing — this call is made for the figure it draws.
bode_phasebode_phase(Z, freqs, [color=], [label=], [marker="line"])Z: a length-N complex vector (CVec); freqs: the matching length-N real vector (Hz). color/label/marker (optional strings). Phase half of a Bode plot: arg(Z) in degrees vs. log-scaled frequency. Kept as a separate call from bode_magnitude (rather than one builtin silently building a 2-panel figure) so a script stays in control of its own subplot layout. Returns Nothing — this call is made for the figure it draws.
emdemd(x, [max_imfs=])x: a length-N real vector. max_imfs (optional number): caps the number of IMFs extracted. Empirical Mode Decomposition: splits x into oscillatory intrinsic mode functions (IMFs, highest frequency first) plus a residual trend, via the standard sifting algorithm. Returns a Model (kind "emd") with fields imfs (a K×N matrix, one IMF per row), residual (a length-N vector), count (a number, K). sum(e.imfs, axis=0) + e.residual reconstructs x exactly.
vmdvmd(x, k, [alpha=2000])x: a length-N real vector; k (number, integer): the exact number of modes to extract; alpha (optional number): bandwidth-penalty strength. Variational Mode Decomposition: decomposes x into exactly k band-limited modes by minimizing each mode's bandwidth around its own center frequency, solved by ADMM (not sifting, unlike emd). Returns a Model (kind "vmd") with fields modes (a k×N matrix, one mode per row) and center_freqs (a length-k vector, normalized to cycles/sample — 0.5 is Nyquist).
energyenergy(x)x: a length-N vector or Signal. Returns a single number, sum(x.^2) — total signal energy. See tkeo for a per-sample instantaneous estimate instead.
tkeotkeo(x)x: a length-N real vector. Returns a length-(N-2) vector (like diff, doesn't pad — the definition needs a neighbor on each side). Teager-Kaiser Energy Operator, a cheap near-instantaneous nonlinear energy tracker: psi[x(n)] = x(n)^2 - x(n-1)*x(n+1).
steste(x, [win=256], [hop=win/2])x: a length-N real vector. win (optional number): frame length in samples; hop (optional number, default win/2): samples between successive frame starts. Returns a vector of length num_frames, one energy value per frame. Short-time energy: the windowed extension of energy(x) over sliding, overlapping frames — the standard way to track how a signal's power evolves over time (e.g. locating bursts in EMG, or voiced/silent segments in speech).
butterbutter(order, kind, cutoff, fs)order: number (filter order); kind: string; cutoff: number or length-2 vector (Hz); fs: number (Hz). Returns a Model (kind "filter", field sos). Digital Butterworth filter as a cascade of second-order sections — monotonic, ripple-free response.
ellipellip(order, ripple_db, atten_db, kind, cutoff, fs)order: number; ripple_db/atten_db: numbers (dB); kind: string; cutoff: number or length-2 vector (Hz); fs: number (Hz). Returns a Model (kind "filter", field sos). Digital elliptic (Cauer) filter, equiripple in both the passband (within ripple_db dB) and stopband (at least atten_db dB down) — the steepest transition band of the classical IIR families at a given order, at the cost of ripple in both bands. cutoff is where gain first drops below -ripple_db (MATLAB/SciPy convention), not the -3dB point.
cheby1cheby1(order, ripple_db, kind, cutoff, fs)order: number; ripple_db: number (dB); kind: string; cutoff: number or length-2 vector (Hz); fs: number (Hz). Returns a Model (kind "filter", field sos). Digital Chebyshev Type I filter: equiripple passband (bounded by ripple_db dB), monotonic stopband, steeper rolloff than Butterworth at the same order.
cheby2cheby2(order, atten_db, kind, cutoff, fs)order: number; atten_db: number (dB); kind: string; cutoff: number or length-2 vector (Hz); fs: number (Hz). Returns a Model (kind "filter", field sos). Digital Chebyshev Type II (inverse Chebyshev) filter: monotonic passband, equiripple stopband (at least atten_db dB down starting at the stopband edge), flatter passband than Type I at the cost of a wider transition band.
fir1fir1(n, cutoff, [kind="low"], [window="hamming"], [fs=2], [beta=])n: number (order, taps = n+1); cutoff: number or length-2 vector; kind (optional string); window (optional string: "hamming", "hann"/"hanning", "blackman", or "kaiser" — the last needs beta=, a required number when chosen); fs (optional number, default 2.0, MATLAB's normalized convention where 1 = Nyquist) — pass an explicit fs= for butter-style Hz cutoffs. Returns a Model (kind "filter", field b, a length-n+1 vector). Windowed-sinc FIR design (MATLAB/SciPy fir1): the ideal impulse response truncated to n+1 taps and multiplied by the requested window, normalized to unity gain at the passband center.
firlsfirls(n, freq_bands, desired, [weights=])n: number, must be even (taps = n+1); freq_bands: a length-2B vector of band-edge pairs (normalized 0..1, 1=Nyquist); desired: a length-2B vector, the target amplitude at each edge; weights (optional length-B vector, default all 1.0), one weight per band. Returns a Model (kind "filter", field b, a length-n+1 vector). Least-squares FIR design (MATLAB/SciPy firls): given a piecewise-linear desired response, finds the symmetric FIR minimizing weighted squared error.
butter(order, "low"/"high", cutoff, fs)A single Hz number — the low-pass or high-pass edge.
butter(order, "band"/"stop", cutoff, fs)A length-2 [low, high] Hz vector — the passband/stopband edges ("stop"/"notch" cuts that band out instead of keeping it).
ellip(order, ripple_db, atten_db, "low"/"high", cutoff, fs)A single Hz number.
ellip(order, ripple_db, atten_db, "band"/"stop", cutoff, fs)A length-2 [low, high] Hz vector.
cheby1(order, ripple_db, "low"/"high", cutoff, fs)A single Hz number.
cheby1(order, ripple_db, "band"/"stop", cutoff, fs)A length-2 [low, high] Hz vector.
cheby2(order, atten_db, "low"/"high", cutoff, fs)A single Hz number.
cheby2(order, atten_db, "band"/"stop", cutoff, fs)A length-2 [low, high] Hz vector.
fir1(n, cutoff, kind="low"/"high", ...)A single normalized/Hz number.
fir1(n, cutoff, kind="band"/"stop", ...)A length-2 [low, high] number/Hz vector.
sosfiltsosfilt(filt, x)filt: a Model (kind "filter", field sos or b); x: a length-N vector or Signal. Returns a same-length vector or Signal (keeping x's own Fs on the way out, when x is a Signal). Causal (one-pass) filtering, with the usual IIR phase lag. Branches on the filter's representation: sos uses the biquad cascade, b (FIR) is conv(x, b, "full") truncated to len(x).
filter_ba, lfilterfilter_ba(b, a, x)b, a: vectors (numerator/denominator coefficients); x: a length-N vector or Signal. Returns a same-length vector or Signal. Apply a transfer function given as raw numerator and denominator coefficients, direct form II transposed. For a function you derived yourself, or a script ported from MATLAB (filter(b, a, x)) or scipy (lfilter) — filter itself is the higher-order predicate filter here, so the name is taken. Warns above order 8, where a direct form loses accuracy and second-order sections do not.
filtfiltfiltfilt(filt, x)filt: a Model (kind "filter"); x: a length-N vector or Signal. Returns a same-length vector or Signal, same Fs-preserving convention as sosfilt. Zero-phase filtering (forward, then backward): doubles the effective order but cancels phase distortion entirely — the standard offline-analysis choice.
filter_initfilter_init(filt)filt: a Model (kind "filter"). Returns a Model (kind "filter_state") holding fresh all-zero streaming state for sample-at-a-time filtering: field is an (n_sections, 2) biquad-state matrix for an IIR (sos) filter, or a length-(len(b)-1) all-zero delay vector for an FIR (b) filter.
filter_nextfilter_next(state, x)state: a Model (kind "filter_state", from filter_init or a prior filter_next); x: a single number (one new sample). Returns a new "filter_state" Model (field y, a number, holds the filtered output). Use as state = filter_next(state, next_sample) in a loop, reading state.y each time — the real-time/serial-fed-data counterpart to sosfilt/filtfilt.
block_processblock_process(x, f, [block=256])x: a vector or Signal; f: a function (a value or the name of a user function) called once per block; block: block length in samples, positional or named, default 256. Cuts x into consecutive blocks, calls f on each, and concatenates the results. The last block is short when the length is not a multiple of block — passed as-is, never zero-padded. A block of a Signal is itself a Signal at the same Fs, so f can read the rate off its own argument. Carries no state between blocks — see the note below.
freqzfreqz(filt, [n=512])filt: a Model (kind "filter"); n (optional number, default 512): number of frequency points. Returns a length-n complex vector (CVec), the response H(e^{jω}) at n points from DC to Nyquist inclusive. abs(freqz(filt)) is the magnitude response, angle(freqz(filt)) the phase. Pairs with linspace(0, fs/2, n) for the matching frequency axis.
group_delaygroup_delay(filt, [n=512])filt: a Model (kind "filter"); n (optional number, default 512). Returns a length-n real vector, -dφ/dω in samples, same n-point/frequency-axis convention as freqz. For a linear-phase fir1 lowpass this is exactly constant at n_order/2 samples.
fvtoolfvtool(filt, [n=512])filt: a Model (kind "filter"); n (optional number, default 512). MATLAB's Filter Visualization Tool: a 2x2 figure (magnitude response in dB, phase, group delay, impulse response) built from freqz/group_delay/sosfilt. Callable as filt.fvtool(). Returns Nothing — this call is made for the figure it draws.
polespoles(filt)filt: a Model (kind "filter"). Returns a complex vector (CVec), one entry per pole across all sections/taps. For an IIR (sos) filter, each biquad section's z^2 + a1*z + a2 = 0 roots; for an FIR (b) filter, all poles sit at the origin (no feedback).
zeros (filter overload)zeros(filt)filt: a Model (kind "filter") — the sole overload argument. Returns a complex vector (CVec) of that filter's zeros: IIR: each section's b0*z^2+b1*z+b2=0 roots; FIR: the tap polynomial's roots via the companion-matrix eigenvalue method (reusing eig). zeros is otherwise dual-purpose: with a plain size argument it's the ordinary array constructor (zeros(n)/zeros(r, c), returning a zero-filled vector/matrix). Matches MATLAB's zeros/tf2zpk naming, pairing with poles(filt).
is_stableis_stable(filt)filt: a Model (kind "filter"). Returns a boolean, true iff every pole lies strictly inside the unit circle — the standard causal-LTI stability criterion. An FIR filter (poles at the origin) is always stable.
pzplotpzplot(filt)filt: a Model (kind "filter"). Pole-zero plot (MATLAB's zplane concept): an x marker at each pole, o at each zero, and the unit circle as a reference polyline, titled with the filter's stability verdict. Returns Nothing — this call is made for the figure it draws.
zeros(n)A length-n real vector of 0.0s — the plain array constructor.
zeros(r, c)An (r, c) real matrix of 0.0s.
zeros(filt)A CVec of the filter Model's zeros (IIR: each section's b0*z^2+b1*z+b2=0 roots; FIR: the tap polynomial's roots) — nothing to do with array construction at all.
fzerofzero(f, a, b, [tol=1e-10], [max_iter=100])f: a string naming a user-defined function of one number, returning a number; a, b: numbers, the bracket endpoints where f changes sign; tol/max_iter (optional numbers). Returns a single number, the root. Brent's method: robust root finding given a bracket [a,b], no derivative needed.
newtonnewton(f, fprime, x0, [tol=1e-12], [max_iter=100])f, fprime: strings naming user-defined functions of one number (the function and its derivative); x0: number, the starting guess; tol/max_iter (optional numbers). Returns a single number, the root. Newton's method: fast (quadratic convergence) when it works, but needs a derivative and can diverge from a poor starting guess, unlike fzero.
curve_fitcurve_fit(model, xdata, ydata, p0, [max_iter=200], [tol=1e-10])model: a string naming a user-defined function model(x, params) (x a scalar, params a length-P vector) returning a scalar; xdata, ydata: length-N vectors; p0: a length-P vector, the initial parameter guess; max_iter/tol (optional numbers). Returns a Model (kind "curve_fit") with fields params (a length-P vector), cost (a number, residual sum of squares), converged (a boolean). Nonlinear least-squares curve fitting via Levenberg-Marquardt (the Jacobian is numerical, forward differences): finds params minimizing sum((model(x_i, params) - y_i)^2).
minimizeminimize(f, x0, [grad=], [max_iter=200], [tol=1e-8])f: a string naming a user-defined function f(params) (a length-P vector) returning a scalar; x0: a length-P vector, the starting point; grad (optional string naming a gradient function, else the gradient is numerical/central-differences); max_iter/tol (optional numbers). Returns a Model (kind "minimize") with fields params (length-P vector), value (a number), converged (a boolean). L-BFGS quasi-Newton multivariate minimizer.
basin_hoppingbasin_hopping(f, x0, [grad=], [n_iter=100], [step_size=1.0], [temperature=1.0], [seed=])f: a string naming f(params) as in minimize; x0: a length-P vector; grad (optional string); n_iter (optional number, number of hops); step_size/temperature (optional numbers); seed (optional number, RNG seed). Returns a Model (kind "minimize", same fields as minimize). Global optimization: repeats random perturbation + local minimize from there, accepting a worse local minimum with Metropolis probability exp(-(new-old)/temperature) so the search can escape the first local minimum found.
monte_carlomonte_carlo(f, n, [seed=])f: a string naming a zero-argument user-defined function (typically drawing its own randomness via randn/rand) returning a number; n: a number (integer), how many times to call it; seed (optional number). Returns a length-n vector collecting every result.
sinesine(freq, fs, n, [phase=0], [amplitude=1])freq, fs: numbers (Hz); n: number (integer sample count); phase (optional number, radians); amplitude (optional number). Returns a length-n Signal (carries Fs=fs). Single-tone generator built on the same synthesis kernel as multisine (a sine is a one-tone multisine).
multisinemultisine(freqs, amps, fs, n, [phases=])freqs, amps: length-K vectors (Hz, amplitude per tone); fs: number (Hz); n: number (integer sample count); phases (optional length-K vector, radians). Returns a length-n Signal. Sum of cosines at the given frequencies/amplitudes. Defaults to Schroeder's phase formula (phi_k = -k(k-1)*pi/K) when phases isn't given — keeps crest factor low without iterative optimization.
chirp / sweepchirp(f0, f1, fs, n, [method="linear"])f0, f1, fs: numbers (Hz); n: number (integer sample count); method (optional string: "linear" or "logarithmic"/"log"/"exponential"). Returns a length-n Signal. Frequency sweep from f0 to f1 over n samples, reaching f1 exactly at the last sample (MATLAB's chirp convention), using exact analytic-phase formulas (not per-sample numerical integration). sweep is an alias with the same signature and return.
impulseimpulse(n, [index=0], [amplitude=1])n: number (integer length); index (optional number, integer sample position); amplitude (optional number). Returns a length-n plain vector (not a Signal, since no fs is given — wrap in signal(impulse(n), fs) if a sample rate is needed): a Kronecker delta, all zeros except amplitude at index. Also reachable as signals.impulse.
square (signals.square)square(freq, fs, n, [duty=0.5])freq, fs: numbers (Hz); n: number (integer sample count); duty (optional number in (0,1), fraction of each period spent at +1). Returns a length-n Signal, a bipolar (±1) periodic pulse train. Not elementwise squaring — see the warning above.
pwm (signals.pwm)pwm(modulator, carrier_freq, fs, [carrier="triangle"])modulator: a length-N vector or Signal (the message waveform, expected roughly in [-1,1]); carrier_freq, fs: numbers (Hz); carrier (optional string: "triangle" default, or "sawtooth"/"saw"). Returns a length-N Signal (same length as modulator). Natural-sampling pulse-width modulation: +1 where modulator exceeds the carrier wave oscillating in [-1,1] at carrier_freq, else -1.
sawtooth (signals.sawtooth)sawtooth(freq, fs, n)freq, fs: numbers (Hz); n: number (integer sample count). Returns a length-n Signal. Periodic linear ramp from -1 up to (but not including) +1 over each period, then an instant drop back to -1 (MATLAB's default sawtooth convention).
triangle (signals.triangle)triangle(freq, fs, n)freq, fs: numbers (Hz); n: number (integer sample count). Returns a length-n Signal. Periodic, continuous triangle wave: linear rise from -1 to +1 over the first half of each period, linear fall back to -1 over the second half — no discontinuity anywhere, unlike sawtooth.
sigma_deltasigma_delta(x)x: a length-N vector or Signal. Returns a same-length vector or Signal (preserving x's Fs when it's a Signal), each sample +1/-1. First-order (error-feedback) 1-bit noise-shaping quantizer: binarizes x, pushing quantization error to higher frequencies instead of spreading it evenly like plain sign(x) — the technique behind "DIBS-ΔΣ" excitation signals (multisine(...)
resample_toresample_to(signal, new_fs)signal: a length-N Signal (must carry a known Fs); new_fs: a number (Hz), the target sample rate. Returns a new Signal at Fs=new_fs, whose length is whatever it takes to span the *same* start/end time as the input (generally not N). Real resampling, not a relabel: evaluates the signal's own piecewise-linear waveform (through its samples at their original instants i/Fs, via the same kernel interp1's "linear" method uses) at the new instants j/new_fs — e.g. a 4-sample, 1 Hz ramp [0,10,20,30] (spanning t=0..3s) resampled to 2 Hz becomes the 7-sample [0,5,10,15,20,25,30], still spanning t=0..3s — never a same-length signal with Fs merely swapped out (which would silently misstate the recorded duration). signal.resample_to(new_fs) also works, via the generic method-chain sugar. Wrap a plain vector first with signal(data, Fs) if it isn't already a Signal.
interp2interp2(x, y, Z, xq, yq, [method="bilinear"|"nearest"])x: a length-ncols vector, the grid's COLUMN coordinates (strictly increasing); y: a length-nrows vector, the grid's ROW coordinates (strictly increasing); Z: an (nrows, ncols) matrix with Z[i,j] the value at (y[i], x[j]) — Matrix::get(row, col)'s own indexing convention used everywhere else in this codebase, not a swapped axis order; xq/yq: paired query coordinates, either both numbers or both length-M vectors (xq[k]/yq[k] is query point k — not an implied meshgrid over every combination); method (optional string: "bilinear" default or "nearest"). 2-D grid interpolation (MATLAB's interp2): a query exactly at a grid coordinate returns that exact stored value, not an approximation; extrapolation beyond the grid is always on, matching interp1. Returns a number (if xq/yq are numbers) or a length-M vector (if they are vectors).
interp1interp1(x, y, xq, [method="linear"|"spline"|"nearest"])x, y: matching length-N vectors (the known points, x strictly increasing); xq: a number or length-M vector, the query point(s); method (optional string). 1-D interpolation through (x, y) (MATLAB's interp1). Extrapolation beyond x's range is always on — "linear" continues the boundary segment's own slope, "spline" extends the natural cubic spline's boundary segment, "nearest" just keeps returning the nearest endpoint's y — never a clamp or an error, matching what "interpolation *and* extrapolation" implies. Returns a number (if xq is a number) or a length-M vector (if xq is a vector).
interpolate_atinterpolate_at(sig, t_query, [method="linear"|"spline"|"nearest"])sig: a length-N Signal; t_query: a number or length-M vector, query time(s) in seconds; method (optional string, interp1's own three). A Signal-aware interp1: instead of an explicit x, the signal's OWN implicit time axis (sig.t, i.e. i/Fs) is used as x and sig's samples as y. Shares interp1's exact interpolation/extrapolation kernel, so the two never silently diverge in behavior. sig.interpolate_at(t_query, [method]) also works via the generic method-chain sugar. Returns a number (if t_query is a number) or a length-M vector (if t_query is a vector) — never re-wrapped as a Signal: a Signal is a promise of uniform sampling at a known Fs, but the query times here are arbitrary caller-chosen instants with no guaranteed spacing, so there is no honest Fs to attach.
interp1(x, y, xq) / interp1(x, y, xq, "linear")Continues the boundary segment's own slope.
interp1(x, y, xq, "spline")Extends the natural cubic spline's boundary segment.
interp1(x, y, xq, "nearest")Keeps returning the nearest endpoint's y — never a clamp or an error, matching what "interpolation *and* extrapolation" implies.
applyapply(x, f)x: a number, boolean, vector, matrix, or Signal; f: a one-argument function of a number returning a number — the function itself, or a Str naming one you defined. Returns the SAME container type and shape as x (a Signal(xs, fs) comes back as a new Signal at the same fs, a vector/matrix keeps its own shape, a bare number/boolean applies the function once). Elementwise map that PRESERVES x's own container type — unlike map(xs, f) ([Collections, Strings & Data Frames](collections-strings.md)), which always returns a plain List, discarding any Fs/shape information on purpose. A builtin is accepted as a value (apply(x, sin)) but refused as a quoted name (apply(x, "sin")), the same rule map/pmap follow. Argument order is (x, f) — the value first, like every other higher-order builtin — so the receiver lands in args[0] and x.apply(f) works for free via the generic method-chain sugar. Every element's result must be numeric; a function returning something else is a clear error naming the offending element. Any other input type (List, Table, Str, ...) is a clear error — map/pmap already own the arbitrary-result/List-returning case.
cutcut(sig, t_start, t_end)sig: a length-N Signal; t_start, t_end: numbers (seconds, t_start >= 0 and t_end >= t_start). Returns a new Signal at the SAME Fs, shorter than sig. Trims sig to the time range [t_start, t_end] — INCLUSIVE of both ends, like every other range in the language, so cut(s, 0.2, 0.7) contains the sample AT 0.7. (The documented cost: abutting cuts no longer tile — cut(s, 0, 1) and cut(s, 1, 2) share the sample at t = 1. Step the second window's start on by one sample to partition.) t_start/t_end round to the nearest sample via sig's own Fs (i = round(t*Fs), the exact inverse of sig.t's i/Fs). A negative t_start or t_end < t_start is a clear error; t_end past sig's actual duration clamps to the last sample rather than erroring (matching ordinary slice hi-clamping, e.g. x[0:1000] on a 10-element vector). Composes with the @ self-mutation prefix like any other method chain: @s.cut(1.0, 2.0) needs no special-casing — it's an ordinary function under the hood. cut, signal_slice_time and the bracket form sig[t_start s : t_end s] are three spellings of ONE implementation (they share signal_time_span, so they can never silently diverge).
signal_slice_timesignal_slice_time(sig, t0, t1)sig: a length-N Signal; t0, t1: numbers (seconds). Returns a new Signal at the same Fs. The original name for the same operation as cut above — kept as a working alias, not deprecated.
delaydelay(x, n)x: a vector or Signal; n: a whole number of samples, positional or named (delay(x, samples = 4)). Returns the SAME length as x, shifted later by n with the vacated head zero-filled and whatever runs off the end dropped. A negative n advances instead (drops from the head, zero-pads the tail); abs(n) >= length(x) is all zeros rather than an error. A Signal keeps its Fs — moving samples along the time axis does not change how fast they were taken.
wrapwrap(x, [lo=-pi], [hi=pi])x: a number, vector, matrix or Signal; lo/hi (optional numbers, default -pi/pi): the half-open interval [lo, hi) to wrap into. Returns the same shape as x, each value reduced modulo hi - lo into that range — the standard fix for angle/phase data that has accumulated past a full turn (atan2 output, an integrated angular velocity). Defaults to [-pi, pi), the convention atan2/angle already return in. Errors if hi <= lo.
s[a:b], no unitsUnchanged from before: sample positions, both ends inclusive, b past the end clamps.
s[t0 s : t1 s]A Signal at the same Fs — exactly cut(s, t0, t1), through the same code.
s[t s]The single nearest sample, round(t*Fs). Past the end errors rather than clamping, matching what s[999999] does: a scalar lookup has one right answer or none. A time *range* still clamps, matching what a positional range does.
s[: t1 s] / s[t0 s :]The omitted end reads as the start of the signal / its full duration, exactly as an omitted positional bound reads as 0 / the last index.
X[f Hz]The nearest bin, clamped at both ends — the same bin, through the same helper, that spectrum_at(X, f) returns.
X[f0 Hz : f1 Hz]A complex vector of that band's bins, *not* a spectrum. See below.
s[440 Hz], X[0.5 s]An error naming the transform that would make the request meaningful. A signal has no frequency axis; a spectrum has no time axis.
s[0 : 0.2 s]An error. The two readings differ by a factor of Fs, so neither is guessed.
s[t0 s : n : t1 s]An error: a step counts samples, which is a different axis from the one the bounds are written on.
A Signal, no fsThe signal's own Fs. welch(sig) and periodogram(sig) no longer require a rate argument at all.
A Signal *and* a matching fsThat rate. Scripts that already pass the correct rate are unaffected.
A Signal *and* a different fsAn error. This is the temporal analogue of a shape mismatch: one of the two numbers is wrong, and computing an answer from either would be guessing which.
A plain vector and an fsThat rate — a vector carries none of its own.
A plain vector, no fsThe builtin's default where it has one (spectrogram uses 1), otherwise an error asking for a rate or for signal(x, fs).
X.FsnumberThe sample rate the spectrum was transformed from, in Hz.
X.NnumberThe transform length — the number of time-domain samples. fft(sig).N == sig.N. For a half spectrum this is *not* the bin count.
X.binsnumberHow many bins X actually holds: N for a full fft, N/2 + 1 for a half rfft.
X.dfnumberBin spacing in Hz, Fs/N. Errors on an empty spectrum rather than reporting a meaningless 0.
X.nyquistnumberThe Nyquist frequency, Fs/2, in Hz.
X.freqVecThe frequency axis in Hz, one entry per bin (k*Fs/N) — computed, never hand-built.
X.magVecBin magnitudes, sqrt(re^2+im^2). A plain vector, so it can be sliced freely.
X.phaseVecBin phases in radians, atan2(im, re), in (-pi, pi].
X.normstringHow the producer normalised these bins: "raw_transform" (default, fft/rfft) — bin k is the unnormalised DFT sum, so a unit-amplitude tone in an N-sample record reads N/2; "amplitude" (rfft(sig, scaling="amplitude"), and spectrum's default) — a bin reads the peak amplitude of the tone at that frequency, so a unit-amplitude tone's bin reads 1.0; "rms" (rfft(sig, scaling="rms") or spectrum(sig, scaling="rms")) — that tone's RMS value instead (amplitude / sqrt(2)). "amplitude"/"rms" fold the negative-frequency half onto the one-sided bins returned by rfft, so DC and (for even N) Nyquist — which have no distinct mirror — keep the 1/N factor while every other bin gets the folded 2/N (further /sqrt(2) for "rms"). Read-only — stamped at construction, never passed in.
spectrum_atspectrum_at(X, freq)X: a spectrum; freq: a number (Hz). Returns the single complex bin nearest that physical frequency (round(freq/df), clamped to the available bins) — addressing the spectrum in Hz instead of by index.
band_powerband_power(X, f0, f1)X: a raw_transform-scaled spectrum; f0, f1: numbers (Hz, f1 >= f0). Returns the power in that frequency band by Parseval, normalised by N^2 so a tone of amplitude A reads A^2/2. On a full spectrum each conjugate pair is counted once, since the pair is one physical tone. Refuses an "amplitude"/"rms"-scaled X today — call spectrum_unnormalize(X) first.
band_zeroband_zero(X, f0, f1)X: a spectrum; f0, f1: numbers (Hz, f1 >= f0). Returns a new spectrum at the same Fs, N and scaling with that band cleared — an ideal brick-wall notch. On a full spectrum it also clears each bin's conjugate partner (N-k), which is what keeps the inverse transform real; clearing only the positive-frequency half is the classic way to get a silently complex signal back out of ifft.
spectrum_normalizespectrum_normalize(X, [scaling="amplitude"])X: a raw_transform-scaled spectrum; scaling= (optional string, "amplitude" or "rms"). Returns a new spectrum with that convention applied — the same conversion fft/rfft(..., scaling=) do at transform time, usable afterward on a spectrum that already went through band_zero or another raw-bin operation. Errors if X is already normalised — spectrum_unnormalize(X) first if you want a different scaling.
spectrum_unnormalizespectrum_unnormalize(X)X: an "amplitude"/"rms"-scaled spectrum. Returns a new raw_transform-scaled spectrum — the exact inverse of spectrum_normalize/scaling=. Required before ifft/irfft/band_power, which all refuse a non-raw_transform spectrum rather than silently treat scaled bins as the unnormalised DFT sum.
hannhann(n)n: a number (integer window length). Returns a length-n real vector. Raised-cosine window, w[i] = 0.5*(1 - cos(2*pi*i/(n-1))). Symmetric convention (denominator n-1, MATLAB/SciPy sym=True); w[0] == w[n-1] == 0 exactly.
hamminghamming(n)n: a number (integer window length). Returns a length-n real vector. Same raised-cosine family as hann but with coefficients 0.54 - 0.46*cos(...), chosen to minimize the nearest side-lobe (at the cost of slower roll-off). Endpoints are 0.08 exactly, not zero.
blackmanblackman(n)n: a number (integer window length). Returns a length-n real vector. Standard 3-term Blackman window, a0 - a1*cos(...) + a2*cos(2*...) with a0=0.42, a1=0.5, a2=0.08 (textbook "exact" coefficients). Endpoints are 0.0 exactly.
kaiserkaiser(n, beta)n: a number (integer window length); beta: a number, required second positional argument (no default — it fundamentally changes the main-lobe-width/side-lobe-level tradeoff). Returns a length-n real vector, w[i] = I0(beta*sqrt(1-((2i/(n-1))-1)^2)) / I0(beta). Center sample is always 1.0 for any beta.
linspacelinspace([a=0], [b=1], [n=50])a, b (optional numbers): the inclusive endpoints; n (optional number, integer count). Returns a length-n real vector, n linearly spaced points from a to b inclusive — the standard companion for building a time or frequency axis to plot alongside a generated/transformed signal.
logspacelogspace([a=0], [b=1], [n=50])a, b (optional numbers, decade exponents); n (optional number, integer count). Returns a length-n real vector, n logarithmically spaced points, 10^linspace(a, b, n) — used for frequency axes in Bode-style plots and rLKK's default DRT grid.
resistorresistor(R)R
capacitorcapacitor(C)1/(jwC)
inductorinductor(L)jwL
cpecpe(Q, n)1/(Q (jw)^n) — constant-phase element. n=1 is a capacitor, n=0 a resistor, n=0.5 a Warburg.
warburgwarburg(Aw)Aw (1-j)/sqrt(w) — semi-infinite diffusion, a constant −45° phase at every frequency.
warburg_shortwarburg_short(Rw, tau)Rw tanh(x)/x, x = sqrt(jw tau) — finite length, transmissive boundary. Spec-string name Ws.
warburg_openwarburg_open(Rw, tau)Rw coth(x)/x, x = sqrt(jw tau) — finite length, reflecting boundary. Spec-string name Wo.
gerischergerischer(Zg, k)Zg/sqrt(k + jw) — a coupled chemical reaction.
porousporous(Rp, Q, n)sqrt(Rp Zi)/tanh(sqrt(Rp/Zi)), Zi = 1/(Q (jw)^n) — de Levie porous electrode.
havriliak_negamihavriliak_negami(Rh, tau, a, g)Rh/(1 + (jw tau)^a)^g
seriesseries(a, b, ...)Two or more circuits in series; impedances add.
parallelparallel(a, b, ...)Two or more circuits in parallel; admittances add. An ideal short in any branch shorts the block.
impedanceimpedance(c, freqs)c: a circuit; freqs: frequencies in Hz, not rad/s. Returns a complex vector, one impedance per frequency. A zero or negative frequency is an error rather than an infinity: at DC a capacitor's impedance is unbounded and a Warburg's is undefined, and returning inf/NaN into a spectrum hides the mistake instead of reporting it.
circuitcircuit(spec, params)Builds a circuit from a spec string and a flat parameter vector.
R C L Wresistor, capacitor, inductor, Warburg1
Q GCPE, Gerischer2
Ws Wofinite-length Warburg, short / open boundary2
Pporous3
HHavriliak-Negami4
rlkk_reconstructrlkk_reconstruct(Z, freqs, [lambda=1e-4], [fx=])Z: a length-N complex vector (CVec); freqs: a length-N real vector (Hz); lambda (optional number): regularization strength, larger tolerates noisier data at the cost of fitting detail; fx (optional length-M real vector, Hz): overrides the default DRT frequency grid (logspace(-8, 8, 160), i.e. M=160). Returns a Model (kind "rlkk") with fields z (a length-N CVec, the reconstructed spectrum) and gamma (a length-M real vector, the fitted DRT coefficients). Fits the regularized Distribution of Relaxation Times (DRT) and reconstructs Z from it.
rlkk_validaterlkk_validate(Z, freqs, [lambda=1e-3], [threshold=2.0])Z: a length-N complex vector (CVec); freqs: a length-N real vector (Hz); lambda (optional number); threshold (optional number, percent). Returns a Model (kind "rlkk_validation") with fields valid (a boolean, true iff every point's percent residual is under threshold), residuals (a length-N real vector, percent), max_residual (a number). Checks Z against its own rLKK reconstruction.
rlkk_extrapolaterlkk_extrapolate(Z, freqs, target_freqs, [lambda=1e-4])Z: a length-N complex vector (CVec); freqs: a length-N real vector (Hz); target_freqs: a length-M real vector (Hz), which may extend beyond the measured band; lambda (optional number). Returns a single length-M CVec, not a model. Refits the DRT from (Z, freqs) and evaluates it at target_freqs — for reconstructing truncated/incomplete measurements.
fftfft(x, [scaling=])x: a length-N real or complex vector. scaling= (optional string: "raw", the default, "amplitude" or "rms"), same conventions as rfft below, requires x to be a Signal. On the FULL (two-sided) spectrum this returns, a real tone occupies TWO conjugate-symmetric bins, and scaling makes each of them independently read the tone's full peak amplitude (or RMS) rather than half of it — correct per bin, but summing both (or integrating a band across the mirror) double-counts that tone's energy. Use rfft instead when a total is what you want. Returns a length-N complex vector (CVec, plain x) or spectrum (Signal x), the discrete Fourier transform. abs gives magnitude, angle phase.
rfft, fftcrfft(x, [scaling=])x: a length-N real vector (rfft) or real/complex vector (fftc). rfft returns a length-floor(N/2)+1 complex vector, the one-sided half-spectrum; fftc returns a length-N complex vector, the full spectrum. rfft is about twice as fast on real data since it only computes the non-redundant half. scaling= (optional string: "raw", the default, "amplitude" or "rms") picks the normalisation stamped on the result's X.norm — see *Frequency-Based Addressing* below — and requires x to be a Signal (the convention is metadata on Value::Spectrum; a bare CVec has nowhere to record it). Returns a CVec (plain vector x) or a spectrum (Signal x): length floor(N/2)+1 from rfft, length N from fftc.
irfftirfft(X, n)X: a length-floor(n/2)+1 complex vector (a one-sided spectrum); n: a number, the required real output length. Returns a length-n real vector. Back from a one-sided spectrum to a real signal — n is needed because a one-sided spectrum cannot say whether the original length was odd or even. (fftr is a deprecated second name for this — see above.)
fftrfftr(X, n)Deprecated — use irfft. The same function under a name that reads as rfft's forward partner; it is actually rfft's inverse, so the pair reads backwards. Still works, and warns once per run. Returns a length-n real Vec — the inverse transform of the half-spectrum X, exactly what irfft(X, n) returns.
thdthd(x)x: a length-N real vector (the sampled record). Returns a single number, dB below the fundamental. Total harmonic distortion — every non-fundamental component counts, so a two-tone signal reads as distorted. See the full form under [ADC signal-quality metrics](#adc-signal-quality-metrics-thd-snr-sinad-sfdr-enob) above for the tones=/freqs=/bins=/fs=/leak= keyword options shared by this whole family.
thd_nthd_n(x, ...)x: a length-N real vector, same optional keywords as thd above. Returns a single number, dB below the fundamental: harmonics *and* noise together against the signal (-sinad_db, the same noise_power sinad already totals over every non-excitation bin) rather than harmonics alone. Same sign convention as thd — more negative is better.
snr, sinad, sfdrsnr(x, [tones=|freqs=], [fs=|rate=], [bins=], [leak=0])x: a length-N real vector. With no excitation named, the largest non-DC FFT bin is taken as the fundamental (the single-tone case); tones=/freqs= (a vector, Hz, needs fs=/rate= too) or bins= (a vector of integer bin indices) names a multisine's tone set explicitly — treating a multisine as one tone counts every other tone as noise and reads tens of dB low. leak= (optional number, default 0) widens each named tone by that many bins on each side, for a record that isn't exactly bin-coherent. snr/sfdr each return a single number (dB); sinad(x) (no distinguishing suffix) instead returns the whole breakdown as a record with fields sinad, enob, snr, thd, sfdr (numbers), bins (a vector of the fundamental's bin indices), signal_power, noise_power (numbers). Returns a scalar Num in dB for snr and sfdr; sinad returns that eight-field Record instead.
enob, enob_estimateenob(x, [tones=|freqs=], [fs=|rate=], [bins=], [leak=0])x: a length-N real vector, same optional keywords as snr above. Returns a single number, bits — effective number of bits, inverting 6.02·bits + 1.76 on the measured SINAD. What a converter actually delivers, as opposed to what its datasheet says. enob_estimate(bits, crest_factor) is the separate closed-form estimator, documented in the next row. Returns a scalar Num, in bits.
sinad_estimate, enob_estimatesinad_estimate(bits, crest_factor)bits: a number, the converter resolution; crest_factor: a number, the signal's peak-to-RMS ratio (e.g. sqrt(2) for a sine wave) — both required positional scalars, not a data record. Returns a single number: sinad_estimate in dB, enob_estimate in bits. Closed-form estimate of the SINAD/ENOB an ideal bits-resolution converter would show for a signal of the given crest_factor, with no record needed — the theoretical curve the measured sinad(x)/enob(x) above are checked against.
dominant_frequency, estimate_frequencydominant_frequency(x, [fs])x: a length-N real vector or Signal; fs (optional number, Hz) is read off a Signal input the same way welch/rfft do, or passed explicitly — a plain vector with neither returns a normalized frequency in cycles/sample instead of Hz. Returns a single number: the frequency of the largest non-DC bin in x's one-sided spectrum, accurate to the bin's own resolution fs/N. The cheapest of the estimators a full sine-fit or phase-regression method would improve on; both names are the same function.
acfacf(x, [max_lag=])x: a length-N real vector. max_lag (optional number, default min(40, N-1), R's own acf() default): highest lag to compute. Returns a vector of length max_lag+1 (lag 0 through max_lag), the autocorrelation function. The first lag at which it falls below 1/e is the usual correlation-time estimate.
hurst_exponenthurst_exponent(x)x: a length-N real vector. Returns a single number: 0.5 is a random walk, above that persistent, below it mean-reverting — long-range dependence.
periodic_profileperiodic_profile(x, fs, period_seconds, n_bins, [stat="std"])x: a length-N real vector; fs: a number (Hz); period_seconds: a number, the cycle length to fold onto; n_bins: a number (integer), bins per cycle; stat (optional string: "mean", "std", "var", "hurst", or "sad"). Returns a length-n_bins real vector, one summary statistic per bin. Fold a long record onto one cycle and summarise each bin — the way to see whether a disturbance keeps time with something.
minutely_profileminutely_profile(x, fs, [stat="std"])x: a length-N real vector; fs: a number (Hz); stat (optional string, as above). Returns a length-60 real vector. periodic_profile over an hour, in 60 minute-of-hour bins.
hourly_profilehourly_profile(x, fs, [stat="std"])x: a length-N real vector; fs: a number (Hz); stat (optional string). Returns a length-24 real vector, one bin per hour-of-day. A daily rhythm shows up here as a shape, where a spectrum would only give it a peak.
daily_profiledaily_profile(x, fs, [stat="std"])x: a length-N real vector; fs: a number (Hz); stat (optional string). Returns a length-7 real vector, one bin per day-of-week -- so a weekday-against-weekend difference separates out.
monthly_profilemonthly_profile(x, fs, [stat="std"])x: a length-N real vector; fs: a number (Hz); stat (optional string). Returns a length-12 real vector, one bin per equal-width twelfth of a Julian year. Equal width, not calendar months: the language has no calendar type, and bins of unequal length would not be comparable anyway.
is_clippedis_clipped(x, [threshold=], [full_scale=], [tol=], [min_run=3])x: a length-N real vector, Mat or Signal. Returns a Bool: does x contain a flat run at an extreme. threshold=/full_scale= (optional numbers, interchangeable spellings, must be positive) set the magnitude a sample must reach to be a candidate; with neither, the record's own largest magnitude is used — safe because detection is run-based, see above. tol= (optional number, default 1e-9 × threshold) is how nearly equal consecutive samples must be; raise it for soft saturation. min_run= (optional whole number ≥ 1, default 3) is how many consecutive samples make a run — min_run=1 degrades this to the plain "any sample at or beyond the threshold" test. Errors on an empty record, and on an all-zero record with no explicit threshold (there is no level to test against).
find_clippingfind_clipping(x, [threshold=], [full_scale=], [tol=], [min_run=3])Same detection as is_clipped, same keywords, but returns *where*. Returns a Model of kind "find_clipping" (the named-field multi-return findpeaks/qr/svd already use, since Qu has no tuple unpacking) with fields count (a Num, how many runs), starts, ends (Vecs of run bounds, inclusive at both ends like every Qu range), lengths (a Vec), values (a Vec, the level each run is held at — signed, so the positive rail is distinguishable from the negative one), samples (a Num, total samples inside runs), fraction (a Num, samples / N), and threshold, tol, min_run (Nums, echoing back the parameters actually used — when the threshold was inferred, a caller reading only starts has no way to know what level the answer is relative to).
detect_saturationdetect_saturation(x, adc_bits, [full_scale=1.0])x: a length-N real vector, Mat or Signal; adc_bits: a whole number 1–32, positional or as adc_bits=/bits= — required, since there is no rail to check against without it. Has x hit the rails of an adc_bits-bit converter: the clipping question for a converter whose range is *known* rather than inferred, so no flat run is required and a single sample sitting on a rail already counts. full_scale= (optional number, default 1.0, must be positive) sets a range symmetric about zero, [-full_scale, +full_scale]: signal-processing records are bipolar by default, and a unipolar reading would report the entire negative half as railed. The default is the stated convention dbfs already set, not a value read off the data — inferring the range from the record would make the answer trivially "yes" for every record. Returns a Record with fields saturated (a Bool), high, low, total (Nums, samples on the top rail, the bottom rail, and either), fraction (a Num, total / N), lsb, vmin, vmax, top_code (Nums, the code geometry used — note top_code = vmax - lsb), and bits (a Num). Errors on an empty record.
verify_signalverify_signal(x)x: a real vector, Mat or Signal. Structural sanity before any of the semantic diagnostics above is worth running — deliberately narrow: it answers "are these samples a usable record", not "is this signal any good". Returns a Record with fields n (a Num, sample count), nan, inf (Nums, counts — called out separately because a single NaN makes a mean, an FFT or a filter return NaN *throughout*, not just at that position), finite (a Bool), constant (a Bool, every sample equal — reported, but not an error: a DC measurement is a real thing and a stuck channel is the caller's judgement), ok (a Bool) and issues (a List of strings naming what is wrong, empty when ok). Given a Signal, two more fields — rate and duration (Nums) — and a rate that is zero, negative or non-finite becomes an issue, since every frequency axis derived from it would be meaningless. Named verify_signal rather than verify because a bare verify says nothing about what it verifies.
find_triggerfind_trigger(x, level, [edge="rising"])x: a length-N real vector or Signal; level: a number, the trigger level — positional and required (defaulting it would let find_trigger(x) answer confidently about a level the caller never chose), though level= is accepted as a keyword too. edge (optional string): "rising" (default), "falling", or "both"; "rise"/"fall"/"up"/"down"/"positive"/"negative"/"any"/"either" are accepted spellings. Returns a vector of 0-indexed integer sample indices, one per crossing, each being the first sample of the new state — a rising crossing at i means x[i-1] < level <= x[i]. A transition involving a NaN is skipped rather than reported, so a dropout does not manufacture a pair of edges.
find_zero_crossingsfind_zero_crossings(x, [edge="both"])x: a length-N real vector or Signal; edge (optional string) as above. find_trigger at level zero. The default is both directions, unlike find_trigger's own default: the zero-crossing rate is a count of every sign change, so len(find_zero_crossings(x)) has to be that count to be worth anything, and a "rising" default would silently halve it. Returns a vector of 0-indexed integer sample indices.
find_edgesfind_edges(x, [level=], [threshold=], [hysteresis=0])x: a length-N real vector or Signal; level=/threshold= (optional number, same thing under two names) defaults to the signal's own midpoint (min+max)/2; hysteresis (optional number, default 0): with 0 this is a plain single-threshold detector, i.e. find_trigger run in both directions; with a positive value it is a Schmitt trigger requiring level + hysteresis/2 to call high and level - hysteresis/2 to call low, so noise on a slow edge yields one edge rather than a burst. The reported positions are taken at level either way, so switching hysteresis on to reject glitches does not move the measurements it protects. Returns a Model (kind "edges") with fields indices (a vector of integer sample indices), directions (a vector, +1 rising / -1 falling, parallel to indices), positions (a vector of interpolated sub-sample crossing points), rising and falling (the two index splits), and count (a number).
find_pulsesfind_pulses(x, [level=], [hysteresis=0], [polarity="positive"])x: a length-N real vector or Signal; level/hysteresis as for find_edges; polarity (optional string): "positive" (default) pairs each rising edge with the next falling one, "negative" the reverse. Returns a Model (kind "pulses") with fields starts, stops (vectors of integer sample indices — stops, not ends, because end is a Qu keyword), widths (a vector of times: seconds for a Signal, samples otherwise, measured between the interpolated crossings so that mean(p.widths) equals pulse_width(x) exactly), and count (a number). A partial pulse at either end of the record — already high when capture started, or still high when it stopped — has only one of its two edges and is not reported; its width is genuinely unknown.
rise_time, fall_timerise_time(x, [low=0.1], [high=0.9], [base=], [top=])x: a length-N real vector or Signal. low/high (optional numbers, defaults 0.1/0.9) are fractions of the step, not levels, so the 20%–80% convention is low=0.2, high=0.8. base/top (optional numbers) are the levels the step runs between, defaulting to x's own min and max. Returns a single number: the transition time of the first complete rising (resp. falling) transition, in seconds for a Signal and samples otherwise, with both endpoints linearly interpolated between samples. Errors rather than guessing when the record holds no complete transition. Caveat, and it is a common case: on a step that *rings*, the automatic top is the overshoot peak rather than the settled value, which drags the 90% level up and reports a rise time that is too long — pass top= explicitly when the step overshoots.
pulse_widthpulse_width(x, [level=], [hysteresis=0], [polarity="positive"])x: a length-N real vector or Signal; keywords as for find_pulses. Returns a single number: the mean width of the complete pulses, in seconds for a Signal and samples otherwise. Equal by construction to mean(find_pulses(x, ...).widths).
duty_cycleduty_cycle(x, [level=], [hysteresis=0])x: a length-N real vector or Signal; keywords as for find_edges. Returns a single number: mean high time over mean period, as a fraction in [0, 1], not a percentage — multiply by 100 for the figure a scope's front panel shows. The fraction is the composable form: duty_cycle(x) * pulse_period(x) is the high time.
pulse_period, pulse_frequencypulse_period(x, [level=], [hysteresis=0])x: a length-N real vector or Signal; keywords as for find_edges. Returns a single number: the mean interval between successive rising crossings (pulse_period) or its reciprocal (pulse_frequency) — seconds and Hz for a Signal, samples and cycles/sample otherwise. Errors when the record holds fewer than two rising crossings, i.e. not a full cycle. These are edge-counting measurements; dominant_frequency/estimate_frequency above are spectral estimators answering a different question — see the note before this table.
overshoot, undershootovershoot(x, [settle_level=], [initial_level=], [settle_frac=0.1])x: a length-N real vector or Signal. settle_level/initial_level (optional numbers) default to the mean of the last and first settle_frac of the record (10%, at least one sample each — a mean rather than the single end samples, so one noisy point cannot carry the whole measurement). Returns a single number, a percent of the step's own size abs(final - initial): overshoot is how far the response travels *past its settled value* in the direction the step was going, undershoot how far it backs up *past where it started* (the pre-shoot), which is MATLAB stepinfo's convention. Both clamp at zero. A falling step works the same way with min and max exchanged. Errors when the record contains no step to be a percentage of.
reflection_coefficientreflection_coefficient(z, [z0=50])z: an impedance — real or complex, scalar or vector (ohms); z0 (optional number, default 50): the real reference impedance. Returns Γ = (z - z0)/(z + z0), complex. Errors at z = -z0, where Γ is genuinely undefined rather than merely large (impossible for a passive load).
impedance_from_reflectionimpedance_from_reflection(g, [z0=50])g: a reflection coefficient, scalar or vector; z0 (optional number, default 50). Returns z = z0(1 + Γ)/(1 - Γ), the exact inverse. Errors at Γ = 1, an ideal open.
vswrvswr(g)g: a reflection coefficient. Returns (1 + |Γ|)/(1 - |Γ|). A perfect match is exactly 1; total reflection is inf, which is the true value rather than a large stand-in. |Γ| >= 1 (an active or mismeasured load) returns inf rather than the negative number the unguarded formula produces.
return_lossreturn_loss(g)g: a reflection coefficient. Returns -20 log10 |Γ| in dB, positive for a passive load — the engineering convention in which "20 dB return loss" means well matched. A perfect match is inf.
mismatch_lossmismatch_loss(g)g: a reflection coefficient. Returns -10 log10(1 - |Γ|²) in dB: the incident power not delivered to the load. Zero for a perfect match.

Compressed sensing chapter → 28

AMat, m × nThe sensing matrix: m measurements of n unknowns, with m usually far smaller than n.
yVec, length mThe measurements, y = A·x.
methodstring, default "omp"Which solver to run: greedy ("omp", "cosamp", "sp"/"subspace_pursuit", "iht", "niht") or convex ("fista", "ista", "bp"/"basis_pursuit").
sparsitynumber (an integer count k), no defaultThe target number of non-zeros, 1 ≤ k ≤ n. Required by every greedy method — omitting it is an error; the convex methods infer the support instead and silently ignore sparsity= if it is passed anyway.
lambdanumber, default 1e-3The l1 penalty weight, used only by "ista"/"fista".
itersnumber (an integer count), default 200The iteration cap. "ista", "fista", and "bp" silently raise this to at least 1000, and "niht" to at least 500, regardless of a smaller value passed here.
tolnumber, default 1e-9The residual norm at which the solver declares convergence and stops early. "bp" never accepts a value tighter than 1e-8.
debiasbool, default falseWhen true, re-fits the recovered support by plain least squares after the chosen method finishes, removing the l1 shrinkage bias (see below).
stepnumber, default 0.5The gradient step size, used only by "iht". Must stay under 1/‖A‖₂² or the iteration diverges; "niht" computes its own step every iteration and ignores this parameter.
rhonumber, default 1.0The ADMM penalty parameter, used only by "bp".
method=What it doesWhen
"omp"Orthogonal matching pursuit, using sparsity=k and tol=. Add the column most correlated with the residual, re-solve least squares on the whole support, repeat until k columns are chosen or the residual falls below tol.The baseline. Hard to beat when A is well conditioned and k is genuinely small.
"cosamp"Compressive sampling matching pursuit, using sparsity=k, iters=, tol=. Takes the 2k best candidates at once, solves least squares on the union with the current support, prunes back to the best k, and repeats up to iters times or until tol is met.When OMP stalls. The prune lets it *undo* a bad early choice, which OMP structurally cannot.
"sp" / "subspace_pursuit"Subspace pursuit, using the same sparsity=k, iters=, tol= as CoSaMP: the same structure with a k-sized (rather than 2k-sized) working set each round.Cheaper than CoSaMP, comparable robustness.
"iht"Iterative hard thresholding, using sparsity=k, step= (default 0.5), iters=, tol=. Gradient step, keep the k largest entries, repeat. No least-squares solve at all.A problem too large to factorise. Needs step= below 1/‖A‖₂² or it diverges.
"niht"Normalised IHT, same sparsity=k, iters=, tol= as "iht", but the step is recomputed from the gradient every iteration, so step= is ignored, and at least 500 iterations always run.Almost always in preference to iht. It does not diverge.
method=What it doesWhen
"fista"Proximal gradient with Nesterov momentum, using lambda= (default 1e-3), iters= (floored at 1000), tol=, on ½‖Ax-y‖² + λ‖x‖₁ — the LASSO / basis-pursuit-denoising problem.The default convex choice. Noisy measurements, or k only estimated.
"ista"The same objective, and the same lambda=/iters=/tol=, without the momentum term.Only to see the difference: same cost per iteration, O(1/t) convergence against FISTA's O(1/t²).
"bp" / "basis_pursuit"Basis pursuit by ADMM, using rho= (default 1.0), iters= (floored at 1000), tol= (floored at 1e-8): min ‖x‖₁ subject to Ax = y.Clean measurements, when you want the constraint satisfied rather than penalised.
.xVec, length nThe recovered signal.
.supportVec of indices, length ≤ nIndices where .x is non-zero, ascending.
.residualnumber‖A·x - y‖₂ at the answer.
.iterationsnumber (an integer count)How many the solver actually ran.
.convergedboolWhether the tolerance was met, or the iteration cap hit.
.methodstringThe method= value that was used, echoed back exactly as passed (or "omp" if method= was omitted) — useful when a script loops over several methods and prints results together.
Clean, k known, A well conditioned"omp"
Noisy, or k only estimated"fista", with debias = true

Noise & distortion chapter → 54

gaussian, whiteThermal (Johnson–Nyquist) noise; the sum of many small independent causesFlat
pink, flickerFlicker noise in semiconductors, sensor drift1/f
brown, redA random walk — baseline wander1/f²
blueWhat dithering and noise shaping producef
uniformA bounded error source; matched in *power* to a Gaussian of the same level, so the two are comparableFlat
shot, poissonDiscrete quanta arriving — photons, electrons across a junction. Variance equals mean, so it grows *with* the signal—
salt_pepperDead and stuck pixels, bit errors—
impulse, spikeSwitching transients, ESD events—
quantize, adcThe error an ADC makes—
.xlength-N number vectorThe quantised signal, same length as the input x
.lsbnumberOne least-significant bit, (vmax - vmin) / 2^bits, in the signal's own units
.clippedinteger countHow many input samples fell outside [vmin, vmax] and were clamped to it
.snr_idealnumber, dB6.02·bits + 1.76 dB — what an ideal converter of this word length would give on a full-scale sine
.vmin, .vmaxnumbersThe reference range actually used — the given values, or the signal's own full scale when left to default
.bitsintegerThe word length actually used, echoed back for convenience
humhum(x, fs, [freq=50], [harmonics=3], [snr=20], [amplitude=], [seed=])Adds simulated mains pickup to x, a length-N signal vector, given the sample rate fs in Hz. freq (number, Hz) is the mains fundamental, default 50. harmonics (integer count) is how many odd harmonics to include — 3 means the 1st, 3rd and 5th, i.e. 50, 150 and 250 Hz — default 3. snr (number, dB, default 20) or amplitude (number, raw units) sets the interference level, one or the other, not both. seed (integer, optional) fixes the phase/noise draw for a reproducible run. Returns a length-N vector, x plus the interference.
emfemf(x, fs, [carrier=], [bursts=], [snr=20], [amplitude=], [seed=])Adds simulated switching/EMI interference to x, a length-N signal vector, given the sample rate fs in Hz: an amplitude-modulated carrier plus damped bursts at each switching edge. carrier (number, Hz) is the switching frequency, default fs / 20. bursts (number, burst events per second) sets how often a ringing transient fires, default carrier / 50. snr (number, dB, default 20) or amplitude (number, raw units) sets the interference level, one or the other, not both. seed (integer, optional) fixes the random draw. Returns a length-N vector, x plus the interference.
clip, hardThe amplifier ran out of rail. Odd harmonics, abruptly
soft, saturateA tanh curve — a transformer, a valve. The same harmonics, arriving gradually
crossoverA dead zone at zero, from a class-B stage whose halves do not meet. Worst on small signals, the opposite of clipping
harmonic, cubicA weakly nonlinear amplifier; a cubic term
quantizeWord length, 16 bits down to 2
medfiltmedfilt(x, [window=3])Replaces each sample by the median of window samples centred on it. x is a length-N number vector or an Image (filtered channel by channel); window is a positional integer, odd, default 3. Returns a value the same shape as x: salt-and-pepper, spikes.
smoothsmooth(x, [window=5], [method="savgol"], [order=2])One word for the smoothers. x is a length-N number vector; window is a named/positional odd integer, default 5; method is a named string, one of "savgol" (default), "moving", "median"; order is a named integer, the polynomial order, used only by "savgol", default 2. Returns a length-N vector.
savgolsavgol(x, window, [order=2])Savitzky-Golay: fits a degree-order polynomial over each window-wide neighbourhood and keeps its centre value, preserving peak height/width that a moving average would flatten. x is a length-N number vector; window is a required positional odd integer; order is an optional positional integer, default 2. Returns a length-N vector. When the *shape* matters.
hampelhampel(x, [window=7], [n_sigma=3])Outlier removal: replaces a sample by the local median only when it is more than n_sigma robust deviations (1.4826 × MAD) from it. x is a length-N number vector; window is an optional positional odd integer, default 7; n_sigma is an optional positional number, default 3. Returns a record {x, replaced} — the cleaned length-N vector and the integer count of samples actually changed.
detrenddetrend(x, [order=1])Subtracts a least-squares polynomial trend from x, a length-N number vector. order is an optional positional integer: 0 removes the mean, 1 (default) a linear drift, 2 a quadratic bow. Returns a length-N vector. For baseline wander.
measure_snrmeasure_snr(clean, noisy)Computes the achieved signal-to-noise ratio by treating noisy - clean as the noise. clean and noisy are two length-N number vectors of equal length. Returns a single number, in dB. Closing the loop.
rolling_meanrolling_mean(x, [window=5])Mean over a window centred on each sample. x is a length-N number vector or a Signal; window is an odd integer, positional or named, default 5. Returns the same length and the same type — a Signal keeps its Fs.
rolling_rmsrolling_rms(x, [window=5])Root-mean-square over a centred window — a moving level, e.g. for an RMS trigger threshold. This is the RMS of the samples themselves, DC included, not of their deviation from the local mean; detrend first if the AC part is what you want, or use rolling_std, which is the already-centred counterpart. Same shape/type rules as rolling_mean.
rolling_stdrolling_std(x, [window=5])Sample (N-1, unbiased) standard deviation over a centred window, matching std/var exactly, so rolling_std(x, w)[i] equals std of that window — a property you can check. A window covering a single sample yields 0, as std of one sample already does. Same shape/type rules as rolling_mean.
rolling_minrolling_min(x, [window=5])Minimum over a centred window. Same shape/type rules as rolling_mean.
rolling_maxrolling_max(x, [window=5])Maximum over a centred window. Same shape/type rules as rolling_mean.
find_outliersfind_outliers(x, [method="zscore"], [threshold=], [window=7])The indices of the samples a criterion flags, as a number vector (same shape of answer as find_peaks). x is a length-N number vector or Signal. method is a named string: "zscore", "modified_zscore", "iqr", "hampel". threshold (alias n_sigma) is a named number, defaulting per method — see below. window is a named odd integer, default 7, read only by method="hampel"; passing it to the others is an unread-keyword error rather than silently ignored.
remove_outliersremove_outliers(x, [method=], [threshold=], [window=])The same criterion, with the flagged samples dropped. Returns a plain vector, shorter than the input, even from a Signal — the surviving samples are no longer evenly spaced, so the old Fs would be a lie (the same call interpolate_at makes, for the same reason). Use replace_outliers when the rate must survive.
replace_outliersreplace_outliers(x, [method=], [threshold=], [window=], [fill_method="linear"], [value=])The same criterion, with the flagged samples patched in place. Length-preserving, so a Signal keeps its Fs. fill_method is a named string taking fill_missing's own method set plus "nan" (mark them missing and stop, leaving the decision to you); value is a named number that overrides it with a constant. Samples that were *already* missing stay missing — this replaces outliers, not dropouts. The keyword is fill_method=, not fill=: fill is a plotting colour keyword engine-wide, so fill="median" would be rejected as a colour name.
methodTestDefault threshold
"zscore"|x - mean| / std > threshold3
"modified_zscore"0.6745 · |x - median| / MAD > threshold (Iglewicz & Hoaglin)3.5
"iqr"outside [Q1 - threshold·IQR, Q3 + threshold·IQR] (Tukey's fences)1.5
"hampel"|x - local median| > threshold · 1.4826 · local MAD over window3
find_missingfind_missing(x)The indices of the missing samples, as a number vector. x is a length-N number vector or Signal.
remove_nanremove_nan(x)x with the missing samples dropped. Returns a plain vector even from a Signal, same reasoning as remove_outliers: what is left is no longer uniformly sampled.
fill_missingfill_missing(x, [method="linear"], [value=])x with the missing samples patched, same length, so a Signal keeps its Fs. method is a named string: "linear" (default), "previous"/"ffill", "next"/"bfill", "nearest", "mean", "median". value is a named number overriding all of them with a constant.
interpolate_naninterpolate_nan(x)Exactly fill_missing(x, method="linear") — the same engine, not a second implementation — kept under its own name because that is the operation people go looking for by name.
adcadc(x, [bits=12], [full_scale=]|[vmin=], [vmax=], [dither=false], [seed=])Quantises x (a length-N number vector) the way a converter does — with a reference range, not just a step size, so a signal outside [vmin, vmax] clips instead of being quantised as if the range were infinite. This is also the engine's quantization *simulator*: the design doc's quantize(bits:) and simulateADC(bits:, fullScale:) are this one function, not two more. bits (positional or named integer, at least 1, default 12) fixes the code count 2^bits; vmin/vmax (named numbers) default to -peak/+peak of x itself; full_scale= (named positive number) is the symmetric shorthand for vmin=-full_scale, vmax=+full_scale, sharing the word dbfs/is_clipped/detect_saturation use for the same quantity — giving it *together with* vmin= or vmax= is an error, not a precedence rule, the same way add_noise refuses snr= and amplitude= together. dither (named boolean, default false) adds two-LSB peak-to-peak TPDF noise before quantising, with seed (named integer) the RNG seed it uses. See the section above for the full field-by-field discussion. Returns a Record with fields x (a length-N Vec, the quantised signal), lsb (a Num, (vmax - vmin) / 2^bits), clipped (a Num, how many samples fell outside the range), snr_ideal (a Num, dB), vmin (a Num, the low end of the range actually used), vmax (a Num, the high end) and bits (a Num, the word length actually used).
add_noiseadd_noise(x, kind, [snr=], [amplitude=], [seed=])Adds noise of the named kind (a string — see the kinds table near the top of this chapter) to x, a length-N number vector or an Image (noise is added per-pixel, per-channel). snr (named number, dB) or amplitude (named number, raw units) sets the level — give one or the other, never both; with neither, defaults to 20 dB. seed is a named integer for a reproducible draw, default 1. Returns a value the same shape as x.
remove_noiseremove_noise(x, [method="wiener"], [window=5], [noise_var=])x is a length-N number vector or Signal. method="wiener" (default): a local adaptive Wiener filter — for each sample, compares the local variance in a window-wide neighborhood (shrinking at the edges rather than padding) to the estimated noise variance (noise_var=, or the mean of every local variance across the record if not given); where local variance is at or below the noise floor the sample is fully smoothed to its local mean, where it is well above the original value is mostly kept. method="median": delegates to the existing medfilt(x, window), for outlier-shaped (impulsive/salt-pepper) corruption a Wiener filter would blur into a smear rather than remove — see tv_denoise above for a third option shaped for step-like signals instead of Gaussian-like noise. A Signal keeps its Fs.
distortdistort(x, kind, [amount=0.3])Put the signal through a nonlinearity: clip, soft, crossover, harmonic, quantize. See the dedicated table and signature above for the full parameter breakdown. Returns a plain length-N Vec — a Signal argument comes back as a bare vector, so re-wrap it with signal(...) if you need the sample rate.
medfilt2, median_filtermedfilt2(x, [window=3])Synonyms for medfilt at the Qu level: x is a length-N number vector or an Image, window an optional positional/named odd integer, default 3. On a plain vector the result is identical to medfilt(x, window) (a 1-D median); the two-dimensional median — over a window×window square, channel by channel, not separable, so the median of medians is never substituted for the real thing — only happens when x is an Image, since the image itself carries its own width and height. Returns a value the same shape as x.
tv_denoisetv_denoise(y, [lambda=1.0])Total-variation denoising: y is a length-N number vector; lambda is an optional positional number, the smoothing penalty, default 1.0 — larger values remove more variation. Assumes few CHANGES rather than few non-zeros, so a step survives where an l1 method would flatten it. Condat's direct algorithm, one pass. Returns a length-N vector.
coherencecoherence(A)A is an M×N sensing matrix. Returns a single number: the largest inner product between any two different normalised columns of A. Small is good. Unrelated to spectral_coherence (magnitude-squared spectral coherence of two signals) in the Signal Processing chapter's Spectral Analysis section — two different functions, two different names.
cs_recovercs_recover(A, y, [method="omp"], [sparsity=], [lambda=], [iters=200], [tol=1e-9], [step=], [rho=1.0], [debias=false])Compressed-sensing reconstruction of a sparse vector x from an M×N sensing matrix A and a length-M measurement vector y. method (named string) selects the algorithm: the greedy family omp, cosamp, sp and iht/niht need sparsity= (named integer, the assumed number of non-zeros); the convex family fista, ista and bp need lambda= (named number, the penalty) instead. iters (named integer) caps the iteration count, tol (named number) the convergence tolerance, step (named number) the IHT step size, rho (named number) the ADMM penalty for bp; debias=true re-fits the recovered support by plain least squares afterwards. Returns a record {x, support, residual, iterations, converged, method}: the recovered length-N vector, the integer indices of its non-zero support, the final residual norm, the iteration count, whether it converged, and the method name used.
cs_guaranteecs_guarantee(A)A is an M×N sensing matrix. Returns a single number: the largest sparsity level that the matrix's coherence alone can *prove* recoverable. Badly pessimistic, and the only certificate that is computable at all.

Statistics & machine learning chapter → 140

corrcorr(x, y)Pearson correlation between two length-N numeric vectors x and y. Returns one number in [-1, 1]. xcorr is the lag-by-lag version.
covcov(x, y)Sample covariance between two length-N numeric vectors x and y, N-1 denominator — the same convention var and std use. Returns a single number.
modemode(x)The most frequent value in a numeric or categorical vector x of length N. Returns one scalar; ties go to the smallest, matching MATLAB.
skewnessskewness(x)Third standardized moment, population form, of a length-N numeric vector x. Returns a single number: zero if symmetric, positive for a long upper tail.
kurtosiskurtosis(x)Fourth standardized moment, population form, of a length-N numeric vector x. Returns a single number — not excess kurtosis, so a normal distribution scores 3.
polyfitpolyfit(x, y, degree)Fits a least-squares polynomial of the given integer degree to a length-N vector x and a length-N vector y. Returns a length-degree + 1 coefficient vector, highest-degree term first, ready for polyval.
polyvalpolyval(coeffs, x)Evaluates a coefficient vector coeffs (as returned by polyfit, highest-degree first) at x, either a single number or a length-N vector, by Horner's method. Returns a number or a length-N vector matching the shape of x.
ridgeridge(X, y, alpha)Tikhonov-regularized (L2) least squares on an N-row, D-column feature matrix X and a length-N target vector y, with regularization strength alpha (a non-negative number; plain OLS at alpha = 0). Returns only the length-D coefficient vector, with no intercept term.
ar_modelar_model(x, order)Fits an autoregressive AR(p) model by Yule-Walker to a length-N numeric vector x, using the integer lag order order (this is p). Returns a fitted model Record with fields coef (a length-p vector of AR coefficients), order (p back), mean (the scalar series mean subtracted before fitting), history (the last p values of x, used to seed forecasting), fitted (a length-N vector of in-sample fitted values), and residuals (a length-N vector, x minus fitted).
predict (AR)ar.predict(n_ahead)Forecasts n_ahead (a positive integer) values beyond the end of the series the model was fitted on, by recursively applying the AR coefficients. Returns a length-n_ahead vector.
kmeanskmeans(X, k, [seed=])Lloyd's algorithm on an N-row, D-column data matrix X, partitioning it into the integer number of clusters k, starting from randomly chosen initial centroids (an optional integer seed= fixes the draw). Returns a length-N vector of integer cluster labels in 0..k-1, one per row of X.
kmeans_centerskmeans_centers(X, k, [seed=])The same Lloyd's-algorithm run as kmeans on X/k/seed=, returning the (k, D) centroid matrix instead of the labels. Passing the same seed= as a kmeans call on the same X/k reproduces the matching run. Returns a (k, D) Mat, one centroid per row.
dbscandbscan(X, eps, min_samples)Density-based clustering on an N-row, D-column data matrix X: a number eps (the neighbourhood radius, in X's own units) and an integer min_samples (the minimum neighbourhood size to count as a dense core point). Returns a length-N vector of integer cluster labels; points that fall in no dense cluster get label -1.
pcapca(X, k)Projects an N-row, D-column matrix X onto its top k principal components (columns mean-centered first). Returns the (N, k) projected coordinate matrix.
pca_componentspca_components(X, k)Fits the same PCA as pca on X and k, returning the (k, D) loading matrix instead — each row is a unit-length direction in the original D-dimensional feature space. Returns a (k, D) Mat.
pca_explained_variancepca_explained_variance(X, k)Fits the same PCA as pca on X and k, returning a length-k vector giving the fraction of the total variance in X that each kept component carries, in decreasing order. Returns a length-k Vec.
tsnetsne(X, [n_components=2], [perplexity=], [seed=], [max_iter=300])t-SNE embedding of an N-row, D-column matrix X into n_components dimensions (an integer, default 2), controlled by perplexity (a number balancing local vs. global structure; unset uses the implementation's default), an optional integer seed=, and max_iter (an integer iteration budget, default 300). Returns the (N, n_components) embedded coordinate matrix — for looking at structure rather than measuring it.
ols_modelols_model(X, y)Fits ordinary least squares with an automatic intercept on an N-row, D-column feature matrix X and a length-N target vector y. Returns a fitted model Record with fields coef (length-D slope vector), intercept (a number), fitted (length-N in-sample predictions), residuals (length-N), and r2 (a number, the in-sample R²).
ridge_modelridge_model(X, y, alpha)The same fit as ols_model on an N-row, D-column X and a length-N y, but with L2 regularization strength alpha (a non-negative number) shrinking the coefficients toward zero; ols_model is this at alpha = 0. Returns a fitted model Record with the same fields as ols_model.
kmeans_modelkmeans_model(X, k, [seed=])k-means as a reusable handle: fits on an N-row, D-column matrix X into k clusters (optional integer seed=), so .predict(Xnew) later assigns new rows to the nearest centroid rather than only labelling the fitting data. Returns a fitted model Record whose .predict gives a length-M integer label vector for an M-row Xnew.
kmedians_modelkmedians_model(X, k, [seed=])The outlier-resistant sibling of kmeans_model, same X/k/seed= shape: clusters by L1 distance around coordinate-wise median centres instead of means. Returns a fitted model Record with a .predict of the same shape as kmeans_model.
kmedoids_modelkmedoids_model(X, k, [seed=])PAM clustering on the same X/k/seed= shape as kmeans_model — every one of the k centres is an actual row of X, never an average. Returns a fitted model Record whose .predict gives a length-M integer label vector for an M-row input.
gmm_modelgmm_model(X, k, [seed=], [max_iter=100])Gaussian mixture model with k components fitted by EM on an N-row, D-column matrix X, warm-started from a k-means run (optional integer seed=, and max_iter capping the EM iterations, default 100). Returns a fitted model Record with fields means ((k, D)), covariances (one (D, D) matrix per component), weights (length-k mixing proportions), and log_likelihood (a number, the total training log-likelihood).
pca_modelpca_model(X, k)PCA as a reusable handle: fits the top k principal components on an N-row, D-column matrix X, so .predict(Xnew) projects new rows onto the same fitted components instead of refitting. Returns a fitted model Record whose .predict gives an (M, k) matrix for an M-row Xnew.
tree_modeltree_model(X, y, [max_depth=20], [min_samples_split=2], [kind=])One CART decision tree on an N-row, D-column matrix X and a length-N target y, with max_depth (integer, default 20) limiting tree depth, min_samples_split (integer, default 2) the minimum node size to keep splitting, and kind a string, "regression" or "classification" (never inferred — must be given explicitly when it matters). Splits by variance reduction for regression, Gini impurity for classification. Returns a fitted model Record with a .predict/.score.
random_forest_modelrandom_forest_model(X, y, n_trees, [max_depth=20], [seed=], [kind=])Bagged ensemble of n_trees (a positive integer) CART trees on an N-row, D-column X and length-N y, each tree grown on its own bootstrap resample of the rows and a ceil(sqrt(D))-column feature subsample at each split, max_depth per tree (default 20), an optional integer seed= that reproducibly seeds every tree's own draw, and kind ("regression" or "classification", never inferred). Returns a fitted model Record with .predict/.score.
gradient_boosting_modelgradient_boosting_model(X, y, n_trees, [learning_rate=0.1], [max_depth=3])Regression-only boosted ensemble on an N-row, D-column X and length-N y: n_trees (positive integer) shallow trees fitted in sequence, each to the running residual, scaled by learning_rate (a number, default 0.1) and capped at max_depth (default 3, shallower than tree_model's 20 because a boosting weak learner is supposed to be weak). Returns a fitted model Record with .predict/.score.
svm_modelsvm_model(X, y, [kernel=], [C=1.0], [gamma=], [degree=3], [coef0=1])Binary-classification support-vector machine by simplified SMO on an N-row, D-column X and a length-N target y that must take exactly two distinct values (no one-vs-rest wrapper). kernel is a string, one of "linear", "rbf", "poly"; C (number, default 1.0) is the regularization strength; gamma (number) scales the "rbf"/"poly" kernels; degree (integer, default 3) and coef0 (number, default 1) apply to "poly". Returns a fitted model Record with .predict/.score.
knn_modelknn_model(X, y, k, [metric=], [kind=])k-nearest-neighbours on an N-row, D-column X and a length-N target y, with integer neighbour count k, an optional metric string (distance function name), and kind ("regression" or "classification", never inferred). Fitting only stores X/y; all the work happens inside .predict, which returns a length-M vector for an M-row query matrix. Returns a fitted Model of kind "knn" — the handle .predict/.score are called on.
naive_bayes_modelnaive_bayes_model(X, y)Gaussian naive Bayes classifier on an N-row, D-column X and a length-N categorical/integer target y, scored in log space so a product of small per-feature densities cannot underflow. Returns a fitted model Record whose .predict(Xnew) gives a length-M label vector; it defines predict but not score.
logistic_modellogistic_model(X, y)Binary logistic regression on an N-row, D-column X and a length-N 0/1 target y. Returns a fitted model Record with .predict/.score, .score giving classification accuracy.
svr_modelsvr_model(X, y)Support-vector regression on an N-row, D-column X and a length-N numeric target y. Returns a fitted model Record with .predict/.score, .score giving R².
predictmodel.predict(Xnew)Applies a fitted model Record model to a new M-row (same D columns as it was fitted on) matrix or vector Xnew. Returns a length-M prediction vector for a supervised or clustering model. For a Kalman or particle filter, called instead as state.predict(...) with filter-specific arguments, this is the time-update step, returning a new filter state Record rather than a prediction vector.
scoremodel.score(X, [y])Scores a fitted model Record model against an N-row feature matrix X and, for a supervised kind, the matching length-N target vector y. Returns a single number: R² for a regression, accuracy for a classifier, negative inertia (within-cluster sum of squared distances) for k-means, an explained-variance sum for PCA, or total log-likelihood for a GMM; y is required for a supervised kind and refused for a clustering one.
estimatestate.estimate()Estimation-family only: reads a point estimate off a filter state Record state with no arguments. Returns the particle filter's weighted-mean particle vector, or a Kalman/EKF/UKF filter's state.x vector directly.
updatestate.update(...)Estimation-family only: the measurement-update half of a filter, called on a state Record state with filter-specific arguments (an observation matrix/function, a measurement vector, and a noise covariance, see the Estimation section below). Returns a new filter state Record; nothing is mutated in place.
pipelinepipeline(stage1, ..., finalStage)Composes one or more stage names (strings naming functions already defined in the program) into a single unfitted pipeline spec — every stage but the last must be a function (X) -> X; the last must be (X, y) -> Model. Returns an unfitted pipeline Record ready for .fit.
fitpipe.fit(X, y)Runs a pipeline Record pipe (from pipeline(...)) on an N-row feature matrix X and a length-N target vector y: applies every transform stage in order, then calls the final estimator stage. Returns a fitted pipeline Record whose .predict/.score replay the same transform stages before delegating to the fitted model inside.
lstm_initlstm_init(input_size, hidden_size, [seed=])Builds fresh LSTM weights for an input of size input_size (integer, number of features per timestep) and a hidden state of size hidden_size (integer): Xavier-scaled weight matrices and zero biases for all four gates (forget, input, output, candidate), plus an optional integer seed=. Returns a plain, untracked Record with fields wf, uf, bf, wi, ui, bi, wo, uo, bo, wg, ug, bg — wrap the ones you want trained in param(...) before use.
lstm_celllstm_cell(x_t, h_prev, c_prev, weights)One LSTM timestep: x_t (length-input_size input vector), h_prev/c_prev (length-hidden_size previous hidden/cell state vectors), and weights (a Record with the twelve gate fields lstm_init produces, param-wrapped where you want gradients). Returns a Record {h, c} — two length-hidden_size states thread through an LSTM, unlike GRU's single h.
lstm_forwardlstm_forward(x_sequence, h0, c0, weights)Unrolls lstm_cell over a whole sequence: x_sequence an (input_size, seq_len) matrix (one column per timestep), h0/c0 length-hidden_size initial states, weights the same gate-weights Record as lstm_cell. Returns a length-seq_len list of length-hidden_size hidden-state vectors, one per timestep; the cell state threads through internally and is not returned.
gru_initgru_init(input_size, hidden_size, [seed=])Builds fresh GRU weights for an input of size input_size (integer) and a hidden state of size hidden_size (integer): Xavier-scaled weight matrices and zero biases for the update, reset and candidate gates, plus an optional integer seed=. Returns a plain, untracked Record with fields wz, uz, bz, wr, ur, br, wh, uh, bh — wrap the ones you want trained in param(...).
gru_cellgru_cell(x_t, h_prev, weights)One GRU timestep: x_t (length-input_size input vector), h_prev (length-hidden_size previous hidden state), weights (a Record with the nine gate fields gru_init produces). Returns the length-hidden_size new hidden state vector h directly, not a record — a GRU has no separate cell state to carry alongside it.
gru_forwardgru_forward(x_sequence, h0, weights)Unrolls gru_cell over a whole sequence: x_sequence an (input_size, seq_len) matrix, h0 a length-hidden_size initial hidden state, weights the same Record gru_cell takes. Returns a length-seq_len list of length-hidden_size hidden-state vectors, one per timestep.
llm_loadllm_load(name)Loads a chat model, identified by name: a string, either a bundled name like "tinyllama" or a local filesystem path to a .gguf weights file with a tokenizer.json beside it. Returns a model handle Record with a .generate method; loading is eager, so the call blocks until the whole model is read into memory.
generatemodel.generate(prompt, [max_tokens=64])Runs greedy (argmax, no sampling knobs, no temperature) text completion on a model handle model from llm_load, given a string prompt and an integer cap max_tokens (default 64) on how many tokens to generate. Returns the completion as a plain string. There is no streaming and no hidden conversation state — each call is independent, so a multi-turn chat has to concatenate prior turns into prompt itself.
param, trackparam(v) / track(v)Wraps a plain number, vector, or matrix v as a fresh, differentiable Tensor — a new leaf node on the autodiff tape with no inputs of its own, so grad treats it as something to differentiate *with respect to* rather than something computed. param and track do exactly the same thing; the two names exist so a program can say which values are trainable weights (param) versus intermediate values you also want a gradient through (track) — a note to the reader, not a mechanical difference. Returns a Tensor of the same shape as v (a bare vector is promoted to a column matrix, matching to_matrix's convention).
densedense(x, w, b)One fully-connected layer on an N-row, D-column input matrix x, a (D, H) weight matrix w, and a length-H bias vector b: computes x * w + b, broadcasting b over every row. Returns an (N, H) matrix.
relu, sigmoidrelu(x)Elementwise activation applied to a number, vector, or matrix x of any shape — relu clips negative values to zero, sigmoid squashes to (0, 1). Returns a value of the same shape as x, differentiable through the tape.
softmax_rowssoftmax_rows(M)Softmax along each row of an N-row, D-column matrix M of scores, shifted by the row maximum first so a large score cannot overflow the exponential. Returns an (N, D) matrix where each row sums to 1.
dropoutdropout(x, rate)Zeroes a random share of the entries of x (a vector or matrix of any shape) at probability rate (a number in [0, 1)), and scales the surviving entries up by 1 / (1 - rate), so the expected value of the output equals x. Returns a value the same shape as x, freshly randomized on every call.
tape_resettape_reset()Discards every entry recorded so far on the autodiff tape, freeing the memory a chain of param/grad calls has built up. Takes no arguments; call it between independent computations, since a program that never calls it keeps every tracked operation alive for as long as it runs. Returns Nothing.
conv1dconv1d(x, kernel, [stride=], [padding=])Slides a length-K learnable kernel vector over a length-N signal x, moving stride positions at a time (integer, default 1) with padding ("valid" — no padding, output shrinks — or "same" — zero-padded to keep the output length equal to N; default "valid"). Returns the length-M convolved output vector, M depending on N, K, stride, and padding.
conv2dconv2d(x, kernel, [stride], [padding])Slides a (Kh, Kw) learnable kernel matrix over an (H, W) image matrix x, moving stride positions at a time (integer, default 1) with padding — "valid" (no padding) or "same" (output keeps x's (H, W) shape); default "valid". Returns an (H', W') convolved output matrix.
maxpool2dmaxpool2d(x, size, [stride=])Downsamples an (H, W) matrix x by taking the largest value in each size x size window (integer size), moving stride positions at a time (integer, defaults to size — non-overlapping windows). Returns a smaller (H', W') matrix.
avgpool2davgpool2d(x, size, [stride=])Downsamples an (H, W) matrix x the same way as maxpool2d — size x size windows, stride defaulting to size — but takes the mean of each window instead of the max. Returns a smaller (H', W') matrix.
layer_normlayer_norm(x, gamma, beta, [eps=])Normalizes each row of an N-row, D-column matrix x independently to zero mean and unit variance, then applies a learned length-D per-feature scale gamma and shift beta, with eps (a small positive number, default a tiny constant) added inside the variance's square root for numerical stability. Returns an (N, D) matrix, the same shape as x.
scaled_dot_product_attentionscaled_dot_product_attention(q, k, v, [mask=])Core attention computation: an (Nq, D) query matrix q, an (Nk, D) key matrix k, and an (Nk, Dv) value matrix v (k and v share the same row count Nk). Scores are q * kᵀ scaled by 1/sqrt(D) before the softmax, so the softmax does not saturate as D grows; an optional mask matrix (same shape as the score matrix, (Nq, Nk)) adds large negative values to positions that should not be attended to before the softmax. Returns an (Nq, Dv) matrix.
multi_head_attentionmulti_head_attention(x, heads, n_heads)Runs several attention heads over the same (N, D) input x in parallel: heads is a tuple of n_heads (integer) Records, each with fields wq, wk, wv (per-head projection matrices) and wo (the head's output projection), and self-attention (q = k = v = x projected through each head's own weights) is computed per head, then the results are combined through each head's wo and summed. Returns an (N, D) matrix.
transformer_blocktransformer_block(x, weights)One transformer block on an (N, D) input x: multi-head self-attention plus a two-layer feed-forward network, each wrapped in a residual connection and a layer_norm. weights is a Record with fields heads (the tuple multi_head_attention expects), ln1_gamma/ln1_beta and ln2_gamma/ln2_beta (length-D layer-norm parameters for the two sublayers), and w1/b1/w2/b2 (the feed-forward layer's weights and biases). Returns an (N, D) matrix, the same shape as x.
compilecompile(pipeline, [optimizer=], [loss=])Attaches an optimizer Record (from sgd/adam/etc., default adam()) and a loss name string ("mse" or "cross_entropy", default "mse") to an input(n) |> dense(...) |> ... pipeline Record (built by piping through input/dense, see the layer-spec subsection below). Returns a fitted-model-ready kind="sequential" Model whose weights are already initialized (but not yet trained) — the same Model sequential(...) itself returns. Returns a Model of kind "sequential".
train_looptrain_loop(loss_fn_name, params, epochs, optimizer=)Runs the fit loop inside the engine rather than stepping it from Qu: loss_fn_name a string naming an in-scope function (params) -> number, params the Tensor (from param(...)) or Record of Tensors to optimize, epochs an integer number of iterations, and optimizer= an optimizer Record (from sgd/adam/etc., referenced here by the string name of the variable holding it). Returns a length-epochs vector of the loss value after each epoch.
optimizer_stepoptimizer_step(opt, grads)One optimizer update, for when you are writing the training loop yourself instead of calling train_loop: opt an optimizer Record (from sgd/adam/etc.), grads the gradient value (same shape as the parameter being optimized) from grad(...). Returns a new optimizer Record with the updated parameter value in its ._params field and any internal state (momentum, running averages) advanced by one step.
sgd, nesterov_sgdsgd(params, [lr=0.01])Plain stochastic gradient descent (sgd) and its look-ahead variant (nesterov_sgd, which evaluates the gradient after applying the momentum step rather than before it), given params (a Tensor to optimize) and a learning rate lr (a number, default 0.01; nesterov_sgd also takes a momentum= number). Returns an optimizer Record ready for optimizer_step or optimizer=. Called with no positional argument at all (e.g. adam(lr=0.01)) any of these instead returns a spec-only "recipe" Record for passing as optimizer= to compile/train_loop, without binding to a specific parameter yet.
adam, adamw, nadam, adamaxadam(params, [lr=0.001])The Adam family of per-parameter adaptive-learning-rate optimizers, given params (a Tensor to optimize) and a learning rate lr (a number, default 0.001). adamw decouples weight decay from the gradient update; nadam folds in Nesterov-style look-ahead momentum; adamax swaps Adam's second-moment estimate for an infinity norm. Returns an optimizer Record, or (with no params) a recipe Record for optimizer=.
rmsprop, adagrad, adadeltarmsprop(params, [lr=0.001])Per-parameter learning rates derived from the running gradient history, given params (a Tensor to optimize) and lr (a number, default 0.001). adagrad accumulates the full gradient history and so its effective rate only shrinks over time; rmsprop and adadelta use a decaying average instead, so they keep adapting late in training. Returns an optimizer Record, or a recipe Record when called with no params.
lr_adaptive, lr_plateaulr_plateau([lr=], [patience=], [factor=], [base=])Learning-rate controllers that wrap a base optimizer rather than replacing it: lr= the starting learning rate (number), patience an integer number of epochs to wait for improvement before shrinking the rate, factor the multiplicative shrink (a number in (0, 1)), and base a string naming the wrapped optimizer (e.g. "adam"). Passed as optimizer= wherever a plain optimizer recipe would go. Returns an optimizer-recipe Record.
quick_mlpquick_mlp(X, y, [seed=], [epochs=])Fits a single-hidden-layer multilayer perceptron in one call on an N-row, D-column feature matrix X and a length-N target vector y (or an (N, n_classes) one-hot matrix for multi-class y), with an optional integer seed=, epochs (integer, default 200), and an implied hidden width of clamp(2*D, 8, 64). Returns an already-fitted kind="sequential" Model with a loss_history field (a length-epochs vector) plus .predict.
sgd(params, [lr=])An optimizer Record bound to params, with _params holding the tensor's current value -- ready for optimizer_step.
sgd([lr=]) (no positional argument)An unbound "recipe" Record with no _params -- for passing as optimizer= to compile/train_loop, to be bound to a parameter later.
inputinput(n)Starts the pipeline sugar: n (a positive integer) is the number of input features. Returns a pipeline_input Record tracking the running output width and an (initially empty) layer list, ready to be piped into dense(...) stages and finished with compile(...).
dense_layerdense_layer(in_dim, out_dim, [activation=])Builds one unfitted dense-layer spec: in_dim/out_dim (positive integers) the layer's input and output widths, activation a string, "relu" or "none" (default "none", a bare affine layer). Returns a layer-spec Record with no weights yet — sequential does the actual initialization. Piping several calls together (dense_layer(2, 8, activation = "relu") |> dense_layer(8, 1)) accumulates them into a single list, ready for sequential.
dropout_layerdropout_layer(rate)Builds one unfitted dropout-layer spec for use inside a sequential stack: rate a number in [0, 1), the fraction of activations to zero during training. Returns a layer-spec Record with no weights (dropout has none) — sequential_forward turns it into a dropout(...) call during training and a no-op passthrough during .predict.
sequentialsequential(layers, [seed=])Initializes a stack of layer specs (a list of dense_layer/dropout_layer Records, or a single one) into a trainable model: weights use He initialization (sqrt(2/in_dim)) on a layer whose activation is "relu", Xavier-style (sqrt(1/in_dim)) otherwise, biases start at zero, and an optional integer seed= makes the draw reproducible. Returns an initialized, not-yet-fitted kind="sequential" Model with .fit/.predict.
mlp_classifiermlp_classifier(in_dim, hidden_dims, n_classes, [seed=])Shortcut that builds a dense_layer(..., activation="relu") for every size in hidden_dims (a vector of positive integers, e.g. [64, 32]) followed by a final dense_layer(..., activation="none") down to n_classes (a positive integer) raw logits, then initializes them with sequential (optional integer seed=). Returns an initialized, not-yet-fitted kind="sequential" Model; pair .fit(X, Y, loss = "cross_entropy") (one-hot Y) with softmax_rows/argmax on .predict's output yourself.
simple_cnnsimple_cnn([height, width], n_classes, [seed=])Builds an untrained conv → relu → maxpool → dense image classifier: [height, width] a 2-element vector giving the image size, n_classes a positive integer, and an optional integer seed=. Returns a kind="simple_cnn" Model with .fit(images, labels, [epochs=], [lr=]), where images is a tuple of height x width matrices (one per sample) and labels a length-M integer vector, epochs an integer and lr a number (learning rate); .fit returns the trained Model, and .predict(images) on it returns a length-M vector of predicted classes.
simple_rnn_classifiersimple_rnn_classifier(input_size, hidden_size, n_classes, [seed=])Builds an untrained GRU-backed sequence classifier: input_size/hidden_size/n_classes positive integers (features per timestep, hidden width, and number of classes), plus an optional integer seed=. Returns a kind="simple_rnn_classifier" Model with .fit(sequences, labels, [epochs=], [lr=]), where sequences is a tuple of (input_size, seq_len) matrices and labels a length-M integer vector; .predict(sequences) returns a length-M vector of predicted classes.
gridworld_envgridworld_env(n, [start=], [goal=], [step_reward=-1], [goal_reward=10])Builds an n x n grid environment (integer n), with start/goal (optional integer state indices, defaulting to opposite corners), step_reward (number, default -1, given on every non-terminal move) and goal_reward (number, default 10, given on reaching the goal). Actions are the integers 0 to 3: up, right, down, left; walking into an edge leaves the agent where it was. Returns a kind="gridworld_env" Model (an environment handle, not a fitted model) with .reset()/.step(state, action).
resetreset(env) or env.reset()Returns the environment env's starting state — a plain integer state index. The environment holds no live position of its own to reset; the returned index is the one to thread through your own loop.
stepenv.step(state, action)Applies one action (an integer 0-3) from the current integer state index in environment env. Returns a Record with next_state (integer), reward (a number, step_reward or goal_reward), and done (a boolean, true once the goal is reached).
q_learning, sarsaq_learning(env, episodes, [alpha=0.1], [gamma=0.9], [epsilon=0.1], [seed=])Tabular temporal-difference learning on a gridworld_env env for an integer number of episodes, with learning rate alpha, discount factor gamma, and epsilon-greedy exploration rate epsilon (all numbers), plus an optional integer seed=. q_learning is off-policy (bootstraps off the greedy next action); sarsa is on-policy (bootstraps off the action actually taken next). Both return a fitted model Record with .q_table (an (n_states, n_actions) matrix) and .rewards (a length-episodes vector, one total reward per episode — it should trend upward as training progresses), plus .predict(state) giving the greedy action (an integer) for a given state index. Returns that fitted Model.
kalman_initkalman_init(x0, P0)Initial linear-Kalman state: x0 a length-D initial state estimate vector, P0 a (D, D) initial covariance matrix. Returns a kind="kalman" state Record with fields x (length-D) and P ((D, D)). No control input.
particle_filter_initparticle_filter_init(x0, n, [spread=1.0], [seed=])Generic particle filter state: x0 a length-D centre vector, n (integer) the particle count scattered around it with spread spread (a number, default 1.0), and an optional integer seed=. Returns a kind="particle_filter" state Record with (n, D) particles and a length-n uniform weights vector; you supply the transition and likelihood functions by name on predict/update.
particle_filterparticle_filter(n_particles, initial_state, [process_noise=0.05], [obs_noise=1.0], [spread=1.0], [seed=])The specialized constant-velocity tracker: n_particles (integer), initial_state (a length-D position/velocity vector), process_noise/obs_noise (numbers, the built-in noise levels — no Q/R argument needed at predict/update time), spread (number, initial scatter), and an optional integer seed=. Returns a kind="particle_tracker" state Record whose predict step is a single matmul across all particles, so it can go to the GPU.
predict (linear)state.predict(F, Q)On a kind="kalman" state, F a (D, D) transition matrix and Q a (D, D) process-noise covariance. Computes x' = F·x, P' = F·P·Fᵀ + Q. Returns a new state Record.
predict (EKF/UKF)state.predict("process_fn", Q, [jac=], [method=])On a kind="kalman" state, "process_fn" a string naming an in-scope function (x) -> x', Q a (D, D) process-noise covariance, jac= an optional string naming the process function's Jacobian (x) -> (D, D) matrix (EKF only), and method= "ekf" (default) or "ukf". The function itself is evaluated exactly; only the covariance propagation linearizes for EKF. "ukf" pushes sigma points through instead and rejects jac= outright, since a UKF has no Jacobian to take. Returns a new state Record.
predict (particle)state.predict("process_fn")On a kind="particle_filter" state, "process_fn" a string naming an in-scope function (particle) -> particle' applied to every one of the n particles; the function is expected to inject its own noise — there is no Q argument here. Returns a new state Record with updated particles.
predict/move (tracker)state.predict(dt) / state.move(dt)On a kind="particle_tracker" state, dt a number (the timestep). Advances every particle by one constant-velocity step (one matmul across all of them) then adds process noise scaled by dt. move is an alias for the same call — it exists because for this state a "predict" really is a concrete motion update. Returns a new state Record.
movestate.move(dt)Exactly predict(dt) on a kind="particle_tracker" state — the row above — under a verb that says what the step is: for this filter the predict step really is a concrete constant-velocity motion update, not the estimation family's generic predict(transition, Q). dt is a number, the timestep. Calling it on any other kind of state errors rather than silently falling back to predict. Returns a new kind="particle_tracker" state Record; the original state is left untouched.
update (linear)state.update(H, z, R)On a kind="kalman" state, H a (M, D) observation matrix, z a length-M measurement vector, R an (M, M) measurement-noise covariance. Applies the standard Kalman gain, state, and covariance correction. Returns a new state Record.
update (EKF/UKF)state.update("obs_fn", z, R, [jac=], [method=])On a kind="kalman" state, "obs_fn" a string naming an in-scope observation function (x) -> z, z a length-M measurement vector, R an (M, M) measurement-noise covariance, jac=/method= the same EKF/UKF choice predict takes, applied here to the observation model instead. Returns a new state Record.
update (particle)state.update("likelihood_fn", z, [resample_threshold=0.5], [seed=])On a kind="particle_filter" state, "likelihood_fn" a string naming an in-scope function (particle, z) -> weight, z the measurement (shape matching what likelihood_fn expects), resample_threshold a number in (0, 1] (fraction of n below which resampling triggers, default 0.5), and an optional integer seed=. Reweights every particle, renormalizes, and resamples once the effective sample size falls below the threshold. Returns a new state Record with neff (a number) and resampled (a boolean) added.
update (tracker)state.update(observation, [resample_threshold=0.5], [seed=])On a kind="particle_tracker" state, observation a position-only measurement (velocity is unobserved), using the obs_noise stored on the state rather than a fresh R argument; resample_threshold/seed= as above. Returns a new state Record.
estimatestate.estimate()Reads a point estimate off any estimation-family state with no arguments. Returns the particle weighted-mean vector (length-D) for a particle filter/tracker, or a Kalman/EKF/UKF state's x vector directly.
markov_chainmarkov_chain(P, [initial_state=0])Builds a discrete Markov chain from an (S, S) row-stochastic transition matrix P (every row must sum to 1 — rows that don't are rejected outright, never quietly renormalized) and an integer initial_state (default 0, a state index in 0..S-1). Returns a kind="markov_chain" Record with field transition (the (S, S) matrix P itself) and methods .simulate/.stationary.
simulatechain.simulate(n_steps, [seed=])Draws one random trajectory from a markov_chain chain, starting at its initial_state, for an integer n_steps transitions (with an optional integer seed=). Returns a length-n_steps + 1 vector of integer state indices.
stationarychain.stationary()Computes the long-run state distribution of a markov_chain chain by power iteration; converges for any irreducible, aperiodic chain. Returns a length-S probability vector.
hmmhmm(transition, emission, initial)Builds a discrete hidden Markov model from an (S, S) row-stochastic hidden-state transition matrix transition, an (S, O) row-stochastic emission matrix emission (O the number of observable symbols), and a length-S initial-state distribution initial. Returns a kind="hmm" Record with methods .forward/.viterbi. Parameter fitting (Baum-Welch) is not implemented — the transition/emission matrices must already be known.
forwardhmm.forward(obs)Runs the forward algorithm on an hmm model hmm for a length-T integer observation-symbol sequence obs (each entry a 0-based column index into emission). Returns a single number: the total probability of that observation sequence, summed over every possible hidden-state path.
viterbihmm.viterbi(obs)Runs the Viterbi algorithm on an hmm model hmm for a length-T integer observation sequence obs (same encoding as forward). Returns a length-T vector of integer hidden-state indices: the single most likely path, not a distribution over paths.
voronoivoronoi(points)Computes the Voronoi diagram of an (N, 2) point matrix points, built on a real Delaunay triangulation. Returns a Record with fields points (the input (N, 2) matrix, unchanged), cells (a length-N list, one entry per input point, each a list of (x, y) vertex coordinates outlining that point's Voronoi cell), and bounded (a length-N vector of 0/1 flags, one per point).
normalizenormalize(X)Min-max scaling of X (a vector, an N-row/D-column matrix scaled column-wise, or a table scaled per numeric column) to [0, 1]: (x - min) / (max - min). Returns a value the same shape as X.
standardizestandardize(X)z-score scaling of X (vector, matrix column-wise, or table per numeric column): (x - mean) / std. Returns a value the same shape as X, mean 0 and unit variance per column/vector.
robust_scalerobust_scale(X)Outlier-resistant scaling of X (vector, matrix column-wise, or table per numeric column): (x - median) / IQR. Neither the median nor the interquartile range moves much when one extreme value arrives, unlike standardize's mean/std. Returns a value the same shape as X.
quantile_normalizequantile_normalize(X)Rank-based scaling of X (vector, matrix column-wise, or table per numeric column): each value is replaced by its rank against its own column, rescaled uniform onto [0, 1]. Returns a value the same shape as X; tied input values land on the same output rank.
fit_scalerfit_scaler(X, [method=])Fits and stores scaling parameters from an N-row, D-column matrix (or vector, or table) X, for reuse on new data — the fit-once path, as opposed to the four one-shot verbs above. method is a string, one of "standard", "minmax", "robust", "quantile" (default "standard"). Returns a fitted scaler Record carrying the per-column parameters (e.g. mean/std for "standard") plus .transform/.inverse_transform.
transformscaler.transform(newX)Applies a fitted scaler Record scaler's stored parameters to a new matrix/vector/table newX with the same columns it was fitted on. Never refits, even if newX's own statistics differ. Returns a value the same shape as newX.
inverse_transformscaler.inverse_transform(newX)Undoes a fitted scaler Record scaler's transform on an already-scaled matrix/vector/table newX, returning it to the original units. Returns a value the same shape as newX; lossy for a "quantile"-method scaler when the originally-fitted data had ties.
train_test_splittrain_test_split(X, y, [test_size=0.2], [seed=], [shuffle=true])Splits an N-row feature matrix X and a length-N target vector y into training and test sets, X and y permuted together by the same random order (unless shuffle=false). test_size is a number in (0, 1) giving the test fraction (default 0.2), and seed= an optional integer. Returns a Record with X_train, X_test (matrices), y_train, y_test (vectors).
sequential_splitsequential_split(X, y, [test_size=0.2])The same shape as train_test_split on X/y/test_size, but never shuffles: the first rows become the training set, the last rows the test set, in their original order. Returns a Record with X_train, X_test, y_train, y_test.
stratified_splitstratified_split(X, y, [test_size=0.2], [seed=])The same shape as train_test_split on X/y/test_size/seed=, but splits each class of y separately before combining, so a rare class keeps its proportion in both sets every time rather than only on average. Returns a Record with X_train, X_test, y_train, y_test.
train_val_test_splittrain_val_test_split(X, y, [val_size=0.2], [test_size=0.2], [seed=], [shuffle=true])Three-way split of X/y into training, validation, and test sets: val_size/test_size are numbers in (0, 1) (both default 0.2); val_size is rescaled against the remainder left after removing the test set, so the final validation share really is what you asked for rather than a share of a share. Returns a Record with X_train/X_val/X_test (matrices) and y_train/y_val/y_test (vectors).
confusion_matrixconfusion_matrix(actual, predicted, [n_classes])Draws a confusion-matrix heatmap comparing a length-N vector of true labels actual against a length-N vector of predicted labels predicted, over an optional integer n_classes (inferred from the data if omitted). This is a plotting side effect, not a computed matrix handed back to the caller. Returns Nothing.
randrand([rows], [cols], [seed=])Draws from the uniform distribution on [0, 1). rows/cols are integers, both defaulting to 1, giving the output shape (a number if both are 1, otherwise a vector or (rows, cols) matrix); an optional integer seed= starts a fresh reproducible stream, otherwise the shared stream advances. Returns a scalar Num when rows and cols are both 1, a Vec when one of them is, and a (rows, cols) Mat otherwise.
randnrandn([rows], [cols], [seed=])Draws from the standard normal distribution (mean 0, std 1), same rows/cols/seed= shape as rand. Returns a number, vector, or (rows, cols) matrix.
seedseed(n)Reseeds the shared random stream with integer n, so subsequent calls to rand/randn/etc. without their own seed= become reproducible from this point on. Returns nothing.
uniformuniform(a, b, [rows], [cols], [seed=])Draws from the uniform distribution on [a, b), two numbers a < b, with the same rows/cols/seed= shape as rand. Returns a number, vector, or (rows, cols) matrix.
normalnormal(mu, sigma, [rows], [cols], [seed=])Draws from a Gaussian. mu (number) is the mean; sigma (number) is the standard deviation; rows and cols (numbers, optional) give the shape of the draw, one number for a vector and two for a matrix; seed= (number, optional) makes the draw repeatable. Returns a number, vector, or (rows, cols) matrix.
randirandi(lo, hi, [rows], [cols], [seed=])Draws random integers. lo (number) is the smallest value that can come out; hi (number) is the largest, inclusive at both ends (MATLAB's convention, not NumPy's half-open one, so randi(1, 6) really can return 6); rows and cols (numbers, optional) give the shape of the draw, one number for a vector and two for a matrix; seed= (number, optional) makes the draw repeatable. Returns a number, vector, or (rows, cols) matrix.
poissonpoisson(lambda, [rows], [cols], [seed=])Exact Poisson draws. lambda (a positive number) is the rate, which is also the mean and the variance of the result; rows and cols (numbers, optional) give the shape of the draw, one number for a vector and two for a matrix; seed= (number, optional) makes the draw repeatable. Slow, not wrong, for very large lambda. Returns a number, vector, or (rows, cols) matrix of non-negative integers.
exponentialexponential(rate, [rows], [cols], [seed=])Exponential draws. rate (a positive number) is the rate, not the scale: the mean is 1/rate, and NumPy instead takes scale = 1/rate directly, so a value copied from NumPy needs inverting; rows and cols (numbers, optional) give the shape of the draw, one number for a vector and two for a matrix; seed= (number, optional) makes the draw repeatable. Returns a number, vector, or (rows, cols) matrix.
binomialbinomial(n_trials, p, [rows], [cols], [seed=])Exact binomial draws. n_trials (a positive integer) is how many trials each draw counts successes over; p (a number in [0, 1]) is the success probability of one trial; rows and cols (numbers, optional) give the shape of the draw, one number for a vector and two for a matrix; seed= (number, optional) makes the draw repeatable. Returns a number, vector, or (rows, cols) matrix of non-negative integers.
chisquarechisquare(k, [rows], [cols], [seed=])Draws from the chi-square distribution with k degrees of freedom (a positive integer), same rows/cols/seed= shape as rand. Returns a number, vector, or (rows, cols) matrix.
chi2pdfchi2pdf(x, k)Chi-square probability density at x (a number or vector, elementwise) with k degrees of freedom (a positive number), computed in log space so it survives modest k without overflowing. Returns a number or vector the same shape as x.
chi2cdfchi2cdf(x, k)Chi-square cumulative distribution P(X <= x) at x (a number or vector, elementwise) with k degrees of freedom. Returns a number or vector in [0, 1], the same shape as x.
normpdfnormpdf(x, [mu=0], [sigma=1])Gaussian probability density at x (a number or vector, elementwise) with mean mu (default 0) and standard deviation sigma (default 1). Returns a number or vector the same shape as x.
mvnpdfmvnpdf(x, mu, Sigma)Multivariate Gaussian density at a length-D point x, with a length-D mean vector mu and a (D, D) covariance matrix Sigma, evaluated through Sigma's Cholesky factor rather than an explicit matrix inverse (faster, and numerically stabler for a near-singular covariance). Returns a single number.
random_walkrandom_walk(n_steps, [drift=0], [volatility=1], [seed=])Generates a discretized Wiener-process path: n_steps (a positive integer) increments, each drawn ~ Normal(drift, volatility), cumulatively summed, with an optional integer seed=. Returns a length-n_steps + 1 vector starting at 0, where Var(x[n]) = n * volatility^2.
corrcoefcorrcoef(M)Called on an N-row, D-column matrix or table M, returns the full (D, D) matrix of pairwise Pearson correlations between its columns. For two length-N vectors x/y, use corr(x, y) instead, which returns their correlation as a single number. corr_heatmap draws the same corrcoef numbers as a plot. Returns a (D, D) Mat, symmetric with ones down the diagonal.
mae, mse, rmsermse(actual, predicted)The regression-error trio, each taking a length-N vector of true values actual and a length-N vector of predictions predicted, and returning a single number: mae the mean absolute error, mse the mean squared error, rmse its square root. .score(X, y) on a model already gives R-squared; these three give the plain error numbers instead, in the target's own units for mae and rmse (mse is in squared units). Returns a scalar Num.
precision, recall, f1f1(actual, predicted)Classification metrics on a length-N vector of true labels actual and a length-N vector of predicted labels predicted, each returning a single number macro-averaged over every class present (the per-class score averaged with equal weight, regardless of how many examples that class has), so the same call works on binary and multi-class labels alike. Returns a scalar Num in [0, 1].
k_foldk_fold(X, y, folds)Splits an N-row feature matrix X and a length-N target vector y into an integer number of folds cross-validation folds. Returns a length-folds list, each entry a Record with X_train/X_test/y_train/y_test for that fold; the loop over them (fitting a model per fold and averaging the score) is yours to write.
cv_stabilitycv_stability(X, y, [n_repeats=10], [cv_folds=5])Repeats cross-validation n_repeats times (integer, default 10) with cv_folds folds each (integer, default 5) on an N-row X and length-N y, reshuffling between repeats. Returns a length-n_repeats vector of the raw per-repeat scores (not just their average): mean and std of the result give the usual score-plus-variability summary, and a wide spread means the single number you were about to quote was luck.
ablation_studyablation_study(X, y, [cv_folds=3])Computes one importance score per feature column of an N-row, D-column X and length-N y, using cv_folds folds (integer, default 3): the full model's cross-validated score minus the score of the same model refit without that column. Returns a length-D vector of importance scores — a report on each feature's contribution, not a selection of which to keep.
rferfe(X, y, n_features)Recursive feature elimination on an N-row, D-column X and length-N y, down to an integer target n_features: repeatedly drops the weakest-scoring remaining column and refits. Returns a vector of the kept column indices, zero-based, length n_features.
mutual_info_classifmutual_info_classif(X, y, [k=3])k-nearest-neighbour mutual information between each column of an N-row, D-column X and a length-N discrete label vector y, using k neighbours (integer, default 3). Returns a length-D vector of non-negative scores, one per feature; catches a relationship that is real but not linear, which corr/corrcoef misses.
astar_mrmrastar_mrmr(X, y, n_features, ...)A guided (A*) search on an N-row, D-column X and length-N y for a feature subset of size n_features (integer) that is relevant to the target and not redundant with itself (minimum-redundancy-maximum-relevance). Returns a vector of the selected column indices, zero-based, length n_features, the same convention as rfe.
permutation_importancepermutation_importance(model, X, y, [n_repeats=])Shuffles one column of an N-row, D-column X at a time and re-scores an already-fitted model Record model against the matching length-N target y, over n_repeats shuffles per column (integer). Returns a length-D vector of importance scores (drop in score caused by shuffling that column); works on any fitted model because it perturbs the input rather than reaching inside the model itself.
save_modelsave_model(m, path)Writes a fitted kind="sequential" model Record m (from sequential/compile/quick_mlp/mlp_classifier/etc.) to an HDF5 file at the string path, weights and all, in a Keras-compatible layout. Returns nothing. Only sequential models are supported — calling it on an ols_model/kmeans_model/etc. is rejected with a clear error.
load_modelload_model(path)Reads a model previously written by save_model back from the HDF5 file at the string path. Returns a fitted kind="sequential" model Record with .predict ready to use immediately, so a fit does not have to be repeated.

Plotting chapter → 128

circlecircle(cx, cy, r, [segments=128])Draws a circle centered at (cx, cy) (numbers, data units) with radius r (number, data units). segments= (integer, default 128) is how many straight edges approximate the curve — raise it for a very large circle, lower it for a deliberately faceted look. Returns nothing; adds a shape to the current panel.
ellipseellipse(cx, cy, rx, ry, [rotate=])Draws an ellipse centered at (cx, cy) (numbers) with semi-axis radii rx and ry (numbers, data units along x and y respectively). rotate= (number, degrees, anticlockwise, default 0) tilts the whole ellipse about its center. Returns nothing.
arcarc(cx, cy, r, from, to)Draws part of a circle, as an open stroke. cx and cy (numbers) are the centre, in data coordinates; r (number, positive — a zero or negative radius is an error) is the radius, applied as the same figure to both axes, so a panel whose x and y scales differ draws an ellipse rather than a round arc — a square canvas is what makes it round, not axis equal, which only equalises the ranges; from (number, degrees) is the angle the sweep starts at, measured counterclockwise from the positive x axis, so 0 is the three-o'clock position; to (number, degrees) is the angle it ends at, and a to smaller than from sweeps clockwise instead. Optional segments= (number, default 128) is how many straight pieces approximate the curve, and rotate= (number, degrees) turns the whole arc about its centre. Unlike circle, an arc is open — it renders as a stroke (color=/width=/dash=), not a fillable shape. Returns nothing.
rectangle, rectrectangle(x0, y0, x1, y1)Draws an axis-aligned rectangle. x0 and y0 (numbers, data units) are one corner; x1 and y1 (numbers, data units) are the corner diagonally opposite it, and which of the two you give first does not matter. rect is a plain alias. Returns nothing.
polygonpolygon(xs, ys)Draws a closed shape connecting the points (xs[i], ys[i]) in order and back to the first. xs and ys are equal-length Vecs of numbers (data units). Returns nothing.
pointpoint(x, y)Marks a single position (x, y) (numbers, data units) with a dot. Returns nothing. Note: in the Annotations table below, point additionally auto-labels itself with its own coordinates — same builtin, described twice because it serves both roles.
hsvhsv(h, s, v)Builds a colour from hue h (number, degrees, 0–360), saturation s (number, 0–1) and value/brightness v (number, 0–1). Returns a "#rrggbb" string usable anywhere a colour is taken.
hslhsl(h, s, l)Builds a colour from hue h (number, degrees, 0–360), saturation s (number, 0–1) and lightness l (number, 0–1, symmetric about 0.5 — "the same colour, lighter" is one number going up). Returns a "#rrggbb" string.
lablab(L, a, b)Builds a colour from CIE L\*a\*b\* coordinates: L (number, lightness, 0–100), a and b (numbers, roughly -128..127, green–red and blue–yellow axes). This is the only space here that is perceptually uniform. Returns a "#rrggbb" string.
cmykcmyk(c, m, y, k)Builds a colour from the printer's subtractive space: cyan c, magenta m, yellow y, key/black k, each a number 0–1. Returns a "#rrggbb" string.
to_hsvto_hsv(color)Takes color (any string/value the language accepts as a colour — name, hex, rgb(...), etc.) and returns its (h, s, v) triple as a Vec of numbers. Also to_hsl, to_lab, to_cmyk, to_rgb, each returning that space's own coordinate tuple as a Vec. Returns a 3-element Vec of numbers, [h, s, v].
delta_edelta_e(a, b)Compares colours a and b (each any accepted colour string) in CIE76 Lab space and returns a single number: the perceptual distance. Under 1 is invisible, 2–3 is where people start to notice, over 10 is plainly a different colour. Returns a scalar Num.
palettepalette(n, [saturation=, value=, start=])Generates n (integer) categorical colours of equal perceptual weight by walking hue at fixed saturation/value. saturation= (default 0.62) and value= (default 0.78) are numbers 0–1; start= (default 215, degrees) is the first colour's hue. Returns a List of n "#rrggbb" strings.
text, annotatecolor, text, x, y, size, italic
vline, hlinecolor, width, dash, dot, at
holdhold on / hold off (bare command)Toggles overlay mode: on (default) overlays successive plot calls on the current panel, off gives each call a fresh panel.
nextnext plot [vertical|horizontal] (bare command)Starts a new panel unconditionally (ignores hold), stacked below (vertical, default) or beside (horizontal) the previous one. next layer / next layer N instead stays in the same cell and moves through the deck a split plot grid gave it.
split (command)split plot R C [L] (bare command)Lays the whole figure out as an R×C grid up front and puts the cursor on the first cell, so the plots that follow read as a sequence instead of as separate calls that happen to agree about the shape — the same grid panel(R, C, i) builds, said once. A third number is a LAYER count, not a starting cell: split plot 3 2 2 is that grid two decks deep, twelve panels in six rectangles. panel, subplot and figure are accepted in place of plot.
pan, zoompan / zoom (bare command)Accepted and ignored. Both parse and do nothing, so a script written for a live GUI still runs headless — there is no viewport to move when the output is a static file. Documented so that a reader porting such a script learns it here rather than from a pan that silently does not pan. zoom_inset(x0, x1, y0, y1) is a different, static-friendly feature and a real function call, not this command.
clearclear / clear figure / clear panel / clear panel N / clear panel R, C, I (bare command)Resets figure/panel state: everything, the current panel, a panel by creation index, or a panel by grid coordinate (even before that cell has been visited). subplot is an accepted alias of panel in this form too.
axisaxis equal / axis tight / axis auto / axis origin / axis edge / axis scale x|y log|linear (bare command)equal: equal data units per pixel on both axes. tight: fit exactly to the data (no 5% padding); auto restores the default padding. origin: axis spines cross through data (0,0) (clamped to the nearest edge if 0 is out of range) instead of framing a box; edge restores the box. scale x/y log: sets that axis's scale (z is accepted as a no-op, reserved for a future 3-D milestone).
legend (command)legend / legend off / legend top|bottom|left|right|best [outside] (bare command)Bare form toggles visibility and/or sets position; outside is an order-independent modifier reserving margin outside the plot. best scores the four corners by how many plotted points fall in each quadrant and picks the emptiest.
legend (function)legend("label1", "label2", ...)Labels the trailing N series of the current panel (N = number of arguments given, in call order) and turns the legend on.
gridgrid on|off / grid minor [off] (bare command)on/off toggles major gridlines. minor/minor off independently toggles dotted minor gridlines (MATLAB allows minor grid without major grid too, so this never forces major grid on). Calling grid(...) as a function is accepted but is a no-op — only the bare command form actually changes anything. Returns Nothing, in both the command and the (no-op) function form.
boxbox on|off (bare command)Toggles the panel's bounding box. As a function call, box(...) is accepted but is a no-op. Returns Nothing, in both the command and the (no-op) function form.
yyaxisyyaxis left|right (bare command)Every series plotted from this point on (until the next switch) targets that y-axis; recorded as a switch-point list, not a per-series flag.
xxaxisxxaxis top|bottom (bare command)Qu's own name (not a MATLAB spelling) for a secondary, independently-scaled x-axis, mirroring yyaxis.
showshow plot (bare command)Marks a figure as rendered/finalized (increments the figure counter); headless bookkeeping today, not a live GUI pop-up.
close (command)close (bare command)Accepted as a no-op for figures (so scripts written for a live GUI still parse and run). Note: close(handle) as a *function call* is unrelated — it closes a file handle opened by fopen, not a figure. Returns Nothing either way — the figure command does nothing at all, and close(f) releases the handle.
subplot / panelpanel(rows, cols, index)Selects grid cell index (integer, 1-based, row-major) of a rows-by-cols (integers) grid on the current figure as the panel further drawing targets. MATLAB-subplot-style. subplot(...) is a plain alias of panel(...), same arguments. Returns nothing.
figurefigure()Clears/resets the whole figure (all panels), starting a fresh one. Takes no arguments. Must be called with parentheses — bare figure (no parens) is not a recognized command verb. Returns Nothing.
xlabelxlabel(text, [align=])Labels the current panel's x-axis with text (string). align= (string, one of "left"/"center"/"right", default "center") sets the label's horizontal alignment. While xxaxis top is active, labels the *top* axis instead of the bottom one. Returns nothing.
ylabelylabel(text, [align=])Labels the current panel's y-axis with text (string). align= (string, "left"/"center"/"right", plus "bottom"/"top" for the rotated text, default "center") sets alignment. While yyaxis right is active, labels the *right* axis instead of the left one. Returns nothing.
titletitle(text, [align=])Sets the current panel's title to text (string). align= (string, "left"/"center"/"right", default "center") sets its horizontal alignment. Returns nothing.
fontfamilyfontfamily(name)Sets the figure-wide font (string name, inherited by every title/label/tick/legend). "default"/"sans" and "print"/"serif" are curated stacks (screen sans, paper/journal serif); any other string passes through verbatim as a literal CSS font-family. Every curated stack falls back to Latin Modern Math for Greek letters and mathematical operators, because none of the text faces covers them — Latin Modern has no μ at all — and savefig(embed_fonts=true) embeds that fallback too, but only for the symbols a given figure actually paints. Returns nothing.
fontsizefontsize(n) / fontsize(tick=, label=, title=)A bare number n scales tick/label/title text together (in points); named arguments tick=, label=, title= (each a number, points) override each independently (and win over the positional value if both are given). Returns nothing.
figure_backgroundfigure_background(color)Sets the current figure's SVG background fill to color (string: "#rrggbb" hex or a CSS named colour; default "#ffffff"), passed straight through, unparsed. Figure-wide, like fontfamily/fontsize. Does not auto-invert axis/gridline/text colors for a dark background — that's a bigger "themeable plot" feature, not built here. Returns nothing.
xticksxticks(positions)Sets explicit x tick positions from positions (Vec of numbers, data units), paired in order with xticklabels(...) when both are set. xticks(()) (empty) removes ticks entirely. Returns nothing.
xticklabelsxticklabels("a", "b", ...)Sets categorical x tick labels from the given strings (variadic positional arguments); without an xticks(...) call, spread evenly across the current x-extent. Returns nothing.
ylim / xlimylim(lo, hi) / ylim()Sets explicit axis limits lo and hi (numbers, data units); calling with no arguments clears them and restores auto-scaling. Returns nothing.
colormapcolormap(name)Sets the current panel's categorical/sequential palette to name (string — see the Markers & Styling reference below for the full list). An unknown name silently resolves to "default" rather than erroring. Returns nothing.
colorbarcolorbar (bare command) or colorbar() (function)Accepted, with or without a [extend=]-style argument in the function form (so MATLAB-style scripts parse) but currently a documented no-op in both forms — no colorbar is actually drawn. Returns nothing.
plotplot(y) / plot(x, y) / plot(x, y, "o")Draws a basic line (or, with a positional or marker= marker string such as "o", a scatter-style) plot of y versus x. x and y are equal-length Vecs (or scalars broadcast to match) of numbers, data units; omitting x uses 0, 1, 2, .... Returns nothing; adds one series to the current panel.
scatterscatter(x, y)Same machinery as plot — x, y are equal-length Vecs of numbers — but defaults its marker to "o" (dots) instead of "line". Returns nothing.
stemstem(x, y)Discrete stem plot: x, y are equal-length Vecs of numbers; draws a vertical line plus a dot from the baseline up to each (x[i], y[i]) (marker "stem"). Returns nothing.
barbar(x, y, [values=true], [hatch=true])Bar chart: x (Vec of numbers or strings, category positions/labels) and y (Vec of numbers, bar heights) must be equal length. values=true (bool, default false) prints each bar's height above it; hatch=true (bool, default false) fills bars with a diagonal hatch instead of solid colour. Returns nothing.
stackbarstackbar(x, y)Stacked bar chart: x (Vec, category positions) and y (Mat or list of Vecs, one row/series per stack segment) with the same values=/hatch= options as bar. Returns nothing.
groupbargroupbar(x, y)Grouped (side-by-side) bar chart: x (Vec, category positions) and y (Mat or list of Vecs, one series per group of bars). Returns nothing.
stairstair(x, y)Step (staircase) plot of equal-length numeric Vecs x, y. stair is the only callable spelling — step is a reserved keyword (to ... step ... ranges) so it can't be a function name; the series is still internally marked marker "step". Returns nothing.
hist / histogramhist(samples, [bins]) or hist(samples, bins=)Bins raw samples (Vec of numbers) into equal-width buckets and renders as bars. bins (integer, positional or bins= keyword) sets the bucket count; defaults to ceil(sqrt(n)) where n = len(samples). Distinct from bar, which takes already-aggregated (x, height) pairs. Returns nothing.
boxplotboxplot(data) / boxplot(data1, data2, ...)One group per argument (each a Vec of numbers), placed at x = 0, 1, 2, ...; draws a Tukey five-number summary (min/Q1/median/Q3/max plus outliers) per group as a box-and-whisker. Returns nothing.
waterfallwaterfall(x, Z)x is a Vec of numbers (shared horizontal axis); Z is a Mat where each row becomes its own line, each successive row offset up-and-right so traces read back-to-front. A 2-D approximation of the stacked-trace look — no true 3-D projection yet. Returns nothing.
scatterfitscatterfit(x, y, [degree])Draws a scatter of equal-length numeric Vecs x, y plus a polyfit trend line. degree (integer, positional, default 1) is the polynomial degree, sampled densely over x's range. Returns nothing.
splineplotsplineplot(x, y)Natural cubic spline through the control points (x[i], y[i]) (equal-length numeric Vecs), resampled onto 200 points for a smooth line. Returns nothing.
pwlpwl(x, y, [n_segments])Continuous piecewise-linear least-squares fit through equal-length numeric Vecs x, y. n_segments (integer, positional, default 4) sets how many straight segments approximate the data; plotted through its own fitted breakpoints. Returns nothing.
spiderplotspiderplot(values) / spiderplot(v1, v2, ...)Radar chart; each argument (a Vec of numbers, one value per spoke/category) becomes its own series, layered onto the current panel's spider chart (repeated calls add more series). Category axis labels aren't wired up yet — spokes are unlabeled. Returns nothing.
polarplotpolarplot(theta, r)Converts polar coordinates theta (Vec of numbers, radians) and r (Vec of numbers, radius) to Cartesian (x=r·cos θ, y=r·sin θ) and draws an ordinary line/scatter series. Not a native polar-axis renderer — no circular gridlines, angular ticks, or radial axis; it's a correctly-shaped curve on Cartesian-looking axes. Returns nothing.
raincloudraincloud(data) / raincloud(data1, ...)Allen et al. (2019) raincloud plot: one group per argument (each a Vec of numbers) at x = 0, 1, 2, ..., each rendered as a Gaussian KDE "cloud" + boxplot + jittered raw points ("rain"). Returns nothing.
violinviolin(data) / violin(data1, ...)The same Gaussian KDE and Tukey summary as raincloud, arranged the other way: the density is MIRRORED about the category into the closed symmetric shape, with the box inside it and the raw points omitted. rain=true puts them back. One group per argument at x = 0, 1, 2, .... Shares raincloud's code path, so the two can never disagree about the density of a given sample. Returns nothing.
beeswarmbeeswarm(data, ...), [spread=], [ms=], [marker=], [fill=]Every sample drawn, nudged sideways only as far as it must be to clear its neighbours, so the WIDTH is the count. The middle ground between a box (hides the sample) and a raincloud (shows it, but scattered at random). Best below a few hundred points per group. Returns nothing.
ecdfecdf(data) / ecdf(data1, ...)Empirical cumulative distribution, one staircase per argument. The honest two-distribution comparison: a density estimate's shape is partly its bandwidth's, and an ECDF has no such parameter. The step rises AT the observation (i/n), so the curve reaches 1 at the largest value. Returns nothing.
hexbinhexbin(x, y, [bins=], [colormap=], [mincount=])The plane tiled with hexagons, each shaded by how many points fell in it — for the case a scatter cannot do, where past a few thousand marks the picture saturates into a blob. x and y are equal-length numeric Vecs giving the point coordinates; bins= (number, default 30, minimum 2) is how many hexagons span the x range; the row count follows from it at three quarters of that, which is the spacing that makes the offset rows interlock rather than overlap; colormap= (string) names the shading ramp; mincount= (number) leaves a cell unpainted until at least that many points land in it, which is what keeps a sparse tail from covering the plane in near-empty hexagons. Hexagons rather than squares because a hexagon's centre is equidistant from all six neighbours, so a cell's count does not depend on which way the data runs. Returns nothing.
smithsmith(Z, [z0=], [grid=], [color=], [lw=], [ms=])Impedance on the reflection-coefficient plane: z = Z/z0, Γ = (z−1)/(z+1), drawn on the unit disc ruled by constant-resistance circles and constant-reactance arcs. Both families are exact — the Möbius map takes circles to circles. z0= defaults to 50 Ω; grid=false draws the locus alone. Sets equal aspect, because on unequal axes the circles become ellipses and every angle on the chart is wrong. Returns nothing.
errorbarerrorbar(x, y, yerr)Draws one capped whisker plus a marker per sample: x, y, yerr are equal-length numeric Vecs, yerr the (symmetric) half-height of each whisker in data units. For uncertainty bars on top of a scatter/bar/line plot. Returns nothing.
areaarea(x, y)Filled area under the curve (x, y) (equal-length numeric Vecs) down to y=0; the zero-baseline special case of fill_between. Returns nothing.
fill_betweenfill_between(x, y_lo, y_hi)A filled band between two curves: x, y_lo, y_hi are equal-length numeric Vecs giving the lower and upper boundary at each x, e.g. a confidence interval. It's the general form area calls into. Returns nothing.
bubblebubble(x, y, sizes)Scatter where marker radius encodes a third variable: x, y, sizes are equal-length numeric Vecs; the drawn radius is scaled from sizes's own min/max. Returns nothing.
donutdonut(values, [label1, label2, ...])Pie chart with a hollow center. values is a Vec of numbers (slice magnitudes); trailing string arguments (variadic, optional) label the slices in order. Returns nothing.
piepie(values, [label1, label2, ...])Ordinary pie chart — same call shape as donut (values a Vec of numbers, trailing strings optional slice labels) with donut=false. Returns nothing.
heatmapheatmap(matrix, [colormap=])Grid of colored cells: matrix is a Mat, each cell coloured by its own value scaled to the matrix's own min/max. colormap= (string, default "blues") picks the palette. Returns nothing.
semilogysemilogy(x, y)Plots equal-length numeric Vecs x, y like plot and additionally sets the y-axis to log scale. Returns nothing.
semilogxsemilogx(x, y)Plots equal-length numeric Vecs x, y like plot and additionally sets the x-axis to log scale. Returns nothing.
loglogloglog(x, y)Plots equal-length numeric Vecs x, y like plot and additionally sets both axes to log scale. (semilogx/semilogy/loglog share one implementation, differing only in which axis/axes get Scale::Log). Returns Nothing — this call is made for what it draws.
corrplot / corr_heatmapcorrplot(table)table is a Table (record of equal-length numeric columns). Computes the pairwise Pearson correlation of its numeric columns and renders the resulting square matrix as a heatmap. Both spellings call the same code. Returns nothing.
edaeda(table)table is a Table. One-call exploratory overview: a correlation heatmap in the first grid cell, plus one histogram per numeric column in the remaining cells, auto-gridded (ceil(sqrt(n)) columns for n numeric columns). Returns nothing.
sns_scattersns_scatter(df, xcol, ycol, [huecol])Seaborn-style scatter pulling columns from Table df: xcol, ycol (strings, column names) give the coordinates; optional huecol (string, column name) draws one series per distinct hue value (first-seen order) and turns the legend on. Returns nothing.
sns_boxsns_box(df, groupcol, valuecol)One boxplot group per distinct value of column groupcol (string, first-seen order) in Table df, each group's values drawn from column valuecol (string) and labeled with the group's name. Returns nothing.
sns_barsns_bar(df, groupcol, valuecol, [agg])Aggregates column valuecol (string, column name) within each distinct value of groupcol (string, column name) of Table df, using aggregator agg (string, positional, default "mean"; also accepts things like "sum"/"median" depending on what the underlying aggregation supports), and plots the one resulting number per group as bars. Returns nothing.
vlinevline(x, [color=])Draws a vertical reference line spanning the whole panel at x (number, data units). color= (string, colour, default the theme's rule colour). Returns a handle (see "Handles" above) whose color/width/dash/dot/at properties can be read or reassigned.
hlinehline(y, [color=])Draws a horizontal reference line spanning the whole panel at y (number, data units). color= (string, colour). Returns a handle, same properties as vline.
rectanglerectangle(x0, y0, x1, y1, [color=])Draws a translucent highlighted box from corner (x0, y0) to (x1, y1) (numbers, data units). color= (string, colour) tints the fill. Returns nothing.
xspanxspan(x0, x1, [color=])Draws a translucent vertical band covering x in [x0, x1] (numbers, data units) across the panel's full height. color= (string, colour). Returns nothing.
yspanyspan(y0, y1, [color=])Draws a translucent horizontal band covering y in [y0, y1] (numbers, data units) across the panel's full width. color= (string, colour). Returns nothing.
zoom_insetzoom_inset(x0, x1, y0, y1, [position=], [outside=], [clip=])Magnifies the data region x in [x0, x1], y in [y0, y1] (numbers, data units) into an auto-placed inset panel, with a dashed zoom-box drawn over the source region and connector lines back to it. position= (string, reuses the legend's keyword vocabulary: "top right", "best", ...) chooses where the inset sits; outside=true (bool, default false) reserves margin and places the inset entirely outside the plot area instead of overlapping it; clip= (bool) controls whether the inset's own contents are clipped to its box. Returns nothing.
xbreakxbreak(lo, hi)Reshapes the *main* x-axis's coordinate mapping with a fixed-width "//" jag that squeezes out the skipped range [lo, hi] (numbers, data units) — linear-scale axes only. Not a sub-panel (unlike zoom_inset). Returns nothing.
ybreakybreak(lo, hi)Same as xbreak, on the y-axis: squeezes out [lo, hi] (numbers, data units). Returns nothing.
blur_backdropblur_backdrop(x0, y0, x1, y1, [radius=])Figure-level (not per-panel) depth-of-field effect: (x0,y0)–(x1,y1) (numbers, fractions 0..1 of the whole rendered canvas) name the rectangle that stays sharp; everything else is Gaussian-blurred. radius= (number, blur strength). SVG-native (<feGaussianBlur>); the TikZ export has no filter-primitive equivalent so it degrades to an unblurred render plus an explanatory comment. Returns nothing.
texttext(x, y, text)Plain text label text (string) placed at (x, y) (numbers, data units), no marker dot. Returns a handle with color/text/x/y/size/italic properties.
annotateannotate(x, y, text)Same as text — label text (string) at (x, y) (numbers, data units) — but also draws a marker dot at that point. Returns a handle with the same properties as text.
arrowarrow(x0, y0, x1, y1)Draws an arrow from (x0, y0) to (x1, y1) (numbers, data units), no label. Returns nothing.
arrowtextarrowtext(x0, y0, x1, y1, text)Same as arrow — from (x0, y0) to (x1, y1) (numbers, data units) — but the arrowhead ends in a point labeled with text (string). Returns nothing.
pointpoint(x, y)Draws a highlighted "radioactive" callout marker at (x, y) (numbers, data units), auto-labeled with its own coordinates, e.g. "(3, 4)" — for calling out one sample without a separate text(...) call. Returns nothing.
interp1interp1(x, y, xq, [method])Interpolates (and freely extrapolates — there's no opt-in flag, a query point outside x's range is always answered) y at query point(s) xq. x, y are equal-length Vecs of numbers (the known samples); xq is a number or a Vec of numbers (the query point(s)), and the return type matches: a number for a scalar xq, a Vec for a vector one. method (string, positional, default "linear") is "linear" (extrapolates via the boundary segment's slope), "spline" (natural cubic, shares splineplot's solver), or "nearest" — these are string arguments to interp1, not separate functions.
savefigsavefig(path, [embed_fonts=])Exports the current figure to path (string, a filesystem path); format is chosen by the file extension. .svg, .html/.htm (an SVG embedded in a minimal page), .tikz/.tex (LaTeX/TikZ source) and .pdf are implemented and share one draw-command list so they never visually disagree. .png is not implemented for a whole figure (it needs a real 2-D rasterizer) and raises a clear error saying so; save_image(path, img) does write a PNG of raster Value::Image content. embed_fonts= (bool) inlines the actual font bytes (only possible for the curated fontfamily(...) presets), subset to the glyphs the figure actually draws so a journal-theme figure costs tens of kilobytes rather than the whole font file; it defaults to on under a print-ready theme and off otherwise. A .pdf always embeds its faces, and subsets them the same way. Returns Nothing; the file on disk is the result.
save / save_allsave(path, "name1", "name2", ...) / save_all(path)Not figure-specific: serializes named top-level variables — path (string) plus variadic string variable names for save, or every top-level variable for save_all(path) — to a human-readable JSON file. Operates on the base workspace only, like MATLAB's own save. Included here because it's the companion of savefig for round-tripping plotted *data* rather than the rendered figure; load(path) restores it. Returns nothing.
textex(x)Not figure export — converts a single Qu value x (number, Vec, Mat, or complex) to a LaTeX math-mode string (e.g. a matrix becomes a bmatrix environment) and returns it as a string. Pairs with str the way printtex pairs with print. Returns a Str.
printtexprinttex(x)Same conversion as tex(x) on value x (number, Vec, Mat, or complex), but prints it directly instead of returning a string. Returns nothing.
edge= (or mec=)Outlines the marker in place, in the colour given. edge = "#ffffff" is the usual choice on a saturated field.
shadow=trueCasts an offset, translucent copy of the marker underneath it. Scales with the marker's own size, so a 2pt dot and a 9pt star are shadowed in proportion.
panel, subplotpanel(rows, cols, k)Selects cell k (integer, 1-based, row-major) of a rows-by-cols (integers) grid as the target for further drawing. subplot is the same call under MATLAB's name. Returns nothing.
legendlegend() or legend offShows or hides the key for the current panel. With no argument it turns on and places itself where it overlaps least; legend outside (bare command) reserves margin instead. See also the function form legend("label1", ...) in the Figure & Axes Control table above, which labels series rather than toggling visibility. Returns nothing.
themetheme(name)Sets the whole-figure visual theme from name (string): one of "default", "publication", "bw", "minimal", "grey", "classic". "publication" also embeds fonts, because a figure asked to be print-ready has to look the same wherever it lands. Returns nothing.
figure_sizefigure_size(w, h) or figure_size("ieee1")Sets canvas size either from w, h (numbers, raw units) or from a named journal-column preset string (e.g. "ieee1"). Type sizes scale with the square root of the area, so a figure shrunk to a column keeps its proportions. Returns nothing.
xlim, ylimxlim(lo, hi)Fixes an axis range from lo, hi (numbers, data units). After yyaxis right these apply to the right-hand axis. Returns nothing.
xscale, yscalexscale("log")Sets that axis's scale from a string, "linear" or "log". A log axis draws minor ticks per decade without being asked. Returns nothing.
yticks, yticklabelsyticks([0, 1, 2])yticks takes a Vec of numbers (tick positions, data units); yticklabels takes variadic strings to relabel them in order. yticks(()) (empty) removes ticks entirely; axis off removes the whole frame instead. Returns nothing.
hist, histogramhist(samples, [bins])Bins samples (Vec of numbers) into equal-width buckets and renders as bars; bins (integer, positional or bins= keyword) defaults to ceil(sqrt(n)) for n = len(samples). Returns nothing. (Same builtin as the hist/histogram row in the Chart Types table above.)
meshgridmeshgrid(x, y)Builds the pair of coordinate matrices a scalar-field plot needs from axis vectors x (Vec of numbers, length nx) and y (Vec of numbers, length ny): every (x[i], y[j]) combination, laid out as two ny-by-nx matrices. Returns a single Record with fields .x and .y (each a Mat) — not two separate values, so g = meshgrid(xs, ys) then g.x, g.y is the pattern, never a multi-assignment like [X, Y] = meshgrid(...) (Qu has no destructuring assignment). Typically consumed directly by contour/contourf.
contour, contourfcontour(x, y, Z)Iso-lines through scalar field Z (a Mat with len(y) rows and len(x) columns) over axis vectors x, y (Vecs of numbers); contourf fills the bands between levels instead of only outlining them. All three arguments are always required — contour(Z) alone is a runtime error (contour(x, y, Z) needs three arguments), even though Z alone is enough information for some other libraries' contour calls. levels= (integer count, or a Vec of explicit level values) controls how many iso-lines are drawn or exactly which. Returns nothing.
corr_heatmap, corrplot, corrmatcorr_heatmap(t)Computes the pairwise Pearson correlation of Table t's numeric columns. corr_heatmap/corrplot render it directly as a heatmap and return nothing; corrmat(t) instead returns a tagged Model (.matrix, an n-by-n Mat of correlation values, plus .labels, a List of the n column names) for when you want the numbers rather than a picture — calling .plot() on that Model also renders the labeled heatmap. Returns a tagged Model from corrmat — .matrix, an n-by-n Mat of correlations, plus .labels, a List of the n column names; corr_heatmap/corrplot draw instead and hand back no value.
capturecapture("fn", [args...])Runs the named drawing function "fn" (string, a function you defined) into a scratch panel, passing along any further positional args..., and keeps what it drew as a value (a "layer"). See Layers, near the top of this chapter. Returns a layer value.
stampstamp(layer, x, y, [scale=], [rotate=])Places a transformed copy of a captured layer (the value capture returned) at position (x, y) (numbers, data units). scale= (number, default 1) and rotate= (number, degrees, default 0) transform the copy: translate, then scale, then rotate about the layer's own origin. Returns nothing.
animateanimate("fn", frames, path, [fps=])Calls function "fn" (string) once per frame index from 0 to frames - 1 (integer) and writes the sequence to path (string) as one animated SVG, no JavaScript. fps= (number, default 24) sets playback speed. Returns nothing.
exploreexplore("fn", path, names=, from=, to=, steps=)Writes a self-contained HTML page to path (string) with one slider per parameter of function "fn" (string). names= (List of strings, slider labels), from=/to= (Lists/tuples of numbers, per-parameter ranges), steps= (List of integers, per-parameter step counts) are parallel, one entry per parameter. Every combination is rendered up front (capped at 400 total), because a browser cannot run Qu. Returns nothing.
rgb, rgbargb(r, g, b)Builds a colour from channel numbers: r, g, b (and, for rgba, a fourth channel a) — a fractional 0–1 fourth channel is an opacity, a whole number 0–255 is a byte value like the other three. For channels that are computed rather than typed literally. Returns a "#rrggbb" (or with-alpha) string.
to_rgb, to_hsl, to_lab, to_cmykto_rgb(color)Takes apart any colour the language accepts (color, a string) into that space's own coordinates, returned as a Vec of numbers — to_rgb gives (r,g,b), to_hsl gives (h,s,l), to_lab gives (L,a,b), to_cmyk gives (c,m,y,k). See also to_hsv in the Colour spaces table above, which is the same idea. Returns a Vec of numbers — 3 elements for to_rgb/to_hsl/to_lab, 4 for to_cmyk.
sweepsweep(f0, f1, fs, n, [method=])Generates a linear (or, with method="logarithmic", log) frequency sweep from f0 to f1 (numbers, Hz) sampled at rate fs (number, Hz) for n (integer) samples. chirp is the exact same call under a second name — both share one implementation. Returns a Signal (a tagged Vec carrying its own sample rate) of length n.
chirpchirp(f0, f1, fs, n, [method=])Identical to sweep above — same four positional arguments (start frequency, end frequency, sample rate, sample count) and the same method= (string, "linear" default or "logarithmic"/"log"/"exponential"). Returns a Signal of length n.
triangle, sawtoothtriangle(freq, fs, n) / sawtooth(freq, fs, n)Each generates one period-repeating waveform: freq (number, Hz), fs (number, sample rate in Hz), n (integer, sample count) are all scalars, in that order. sawtooth ramps linearly from -1 up to (but not including) +1 each period then drops back to -1; triangle rises and falls symmetrically. Both are band-unlimited — they carry every harmonic, which is the point when testing a filter. Returns a Signal of length n.
squaresquare(freq, fs, n, [duty=])A bipolar (±1) periodic pulse train. freq (number, Hz) is the repetition rate; fs (number, Hz) is the sample rate the train is generated at; n (number) is how many samples to produce; duty= (number, 0–1, default 0.5) is the fraction of each period spent at +1 rather than -1. Returns a Signal of length n.
pwmpwm(modulator, carrier_freq, fs, [carrier=])Natural-sampling pulse-width modulation: modulator is a Vec of numbers (any signal, conventionally in [-1, 1]), carrier_freq and fs are numbers (Hz). Emits +1 where the modulator exceeds a carrier wave oscillating in [-1, 1] at carrier_freq, else -1. carrier= (string, "triangle" default or "sawtooth"/"saw") picks the carrier shape. Returns a Signal the same length as modulator.
signalsignal(x, fs)Tags Vec x (numbers) with sample rate fs (number, Hz), so later calls (like rfft) do not have to be told it again. Returns a Signal.
ui_sliderui_slider(label, min, max, [default], [step=], [id=])Declares a slider control (for a value you sweep) in an explore page or Qu Studio, labeled label (string) with range min..max (numbers). default (number, positional, default min) is the starting value; step= (number) sets the increment; id= (string, default label) is the identifier the host uses to persist/report a value, useful when two sliders would otherwise share a label. Outside a host, returns the current (or default) value as a number — arguments are positional, not steps=-style keywords, and min/max (not from/to) are the names that matter. Returns a scalar Num — the host's current value for this control, or default outside one.
ui_numberui_number(label, [default], [id=])Declares a free-entry number box (for a value you type exactly rather than sweep), labeled label (string). default (number, positional, default 0) is the starting value; id= (string) as with ui_slider. Returns the current (or default) value as a number.
ui_selectui_select(label, options, [default], [id=])Declares a dropdown, labeled label (string), choosing among options (a List of strings — or of any values, displayed via their string form). default (positional, default options's first entry) and id= (string) as above. Returns the current (or default) choice as a string.
ui_checkboxui_checkbox(label, [default], [id=])Declares an on/off toggle, labeled label (string). default (bool, positional, default false) and id= (string) as above. Returns the current (or default) value as a bool. These two (ui_select/ui_checkbox) are for a parameter that is a mode rather than a magnitude.
ui_buttonui_button(label, [id=])Declares a push-button, labeled label (string); id= (string) as above. Returns true only on the run the host reports it as pressed, false otherwise — it does not stay true on later re-runs, so if ui_button("Reset") ... end reads naturally. Unlike the other UI widgets, it takes no default=.
ui_textui_text(label, [default], [id=])Declares a free-text field, labeled label (string). default (string, positional, default "") and id= (string) as above. Returns the current (or default) text as a string.

Images chapter → 46

image_newimage_new(width, height, [r=0, g=0, b=0])Creates a blank solid-color canvas. width and height are positive integers giving the canvas size in pixels. r, g, b are optional named numbers 0–255 giving the fill color's channel values (default 0, i.e. solid black). Returns a new Image of exactly width x height pixels. The only way to build a synthetic image with no file on disk.
image_from_matriximage_from_matrix(matrix)Builds a grayscale Image directly from matrix, a 2-D Mat of numbers; each value is rounded and clamped to 0–255 and written to R=G=B for that pixel (matrix rows become image rows, columns become image columns). Returns a new Image sized cols x rows to match the matrix's own shape. For a real pixel buffer you can further process/save, as opposed to imagesc's colormap display.
load_imageload_image(path)path is a string file path. Reads the file from disk and decodes it — PNG and BMP. The format is sniffed from the file's first bytes rather than its extension, because a .png that is really a BMP is a thing that happens and the bytes are never wrong. PNG: bit depths 1/2/4/8/16, colour types grey, truecolour, palette, grey+alpha and RGBA; alpha composites onto white, since Image is three channels. Adam7 interlacing is refused by name rather than decoded wrongly. Returns a new Image sized to the file's own dimensions.
save_imagesave_image(path, img)path is a string destination; img is the Image to write. Encodes img and writes it to path, dispatching on the path's own extension: a .png extension writes a real (if uncompressed) PNG; any other extension, or none, writes a BMP. Returns nothing.
imagescimagesc(matrix, [colormap="viridis"])matrix is a 2-D Mat of arbitrary real-valued numbers (no 0–255 requirement). colormap is an optional named string (default "viridis") selecting the palette, same set as heatmap's. False-color raster display of the plain numeric matrix (no pixel buffer produced) — pushes a dense Heatmap onto the current plot panel, reusing the same renderer as heatmap, just without per-cell value labels or gridlines. Defaults to viridis rather than heatmap's blues. Returns nothing; it is a plotting side effect.
imshowimshow(img)img is an Image value (e.g. from load_image/grayscale/any transform below), of any size. Places it inline in the current plot panel as a native SVG <image> element at its own resolution. Takes an actual Image, not a scalar matrix — use imagesc for that. Returns nothing.
grayscalegrayscale(img)img is an Image of any size. Converts RGB → luma via ITU-R BT.601 weights (matches plotting.rs's contrast_text_color). Returns a new Image, same width/height as img, with R=G=B at every pixel — still a full 3-channel RGB image, not a separate 1-channel type.
resizeresize(img, width, height, [method="nearest"])img is an Image; width/height are positive integers giving the absolute target size in pixels (not a scale factor — see imscale for that). method is an optional named string: "nearest" (default, cheap nearest-neighbor) or "bilinear" (smoother). Returns a new Image of exactly width x height pixels. Also overloaded for Vec (resize(vec, new_length, [fill=0.0]), a ReDim Preserve-style grow/shrink to new_length elements, padding new slots with the number fill when growing, truncating when shrinking, and returning a new Vec) — unrelated to images but the same builtin name.
cropcrop(img, x0, y0, width, height)img is an Image; x0, y0 are integers giving the top-left pixel coordinate of the sub-rectangle; width/height are positive integers giving its size in pixels. Extracts that sub-rectangle. Returns a new Image of exactly width x height pixels.
imrotateimrotate(img, angle_degrees, [method="bilinear"], [bbox="loose"])Rotates an image about its own center. img is an Image; angle_degrees is a number, the rotation angle about the image center — positive = counterclockwise (MATLAB's convention). method is an optional named string, "nearest" or "bilinear" (default), controlling resampling. bbox is an optional named string: "loose" (default) expands the canvas to fit the rotated content; "crop" keeps the original width/height, clipping content that rotates outside the frame. Returns a new Image.
imtranslateimtranslate(img, dx, dy, [method=], [bbox="crop"], [fill=0])img is an Image; dx/dy are numbers, the horizontal/vertical pixel shift (positive = right/down). method is an optional named string ("nearest"/"bilinear") controlling resampling. bbox is an optional named string, defaulting to "crop" (output stays the same size as the input, matching MATLAB imtranslate's 'OutputView','same') — the opposite default from imwarp/imscale. fill is an optional named number 0–255 (default 0), the byte value used on all 3 channels for pixels that map outside the source. Implemented as imwarp + affine_translate. Returns a new Image.
imscaleimscale(img, sx, [sy], [method=], [bbox="loose"], [fill=0])img is an Image; sx is a number, the scale factor (imscale(img, 2) doubles both dimensions); sy is an optional number, the vertical scale factor, defaulting to sx (uniform scale) when omitted. method/fill as in imtranslate. bbox is an optional named string, defaulting to "loose" so the output canvas grows/shrinks to fit the scaled content — the opposite default from imtranslate. Implemented as imwarp + affine_scale. Different from resize, which takes absolute output dimensions rather than a factor. Returns a new Image.
affine_identityaffine_identity()Takes no arguments. Returns the 3x3 identity Mat — a no-op transform, useful as a composition base case.
affine_translateaffine_translate(dx, dy)dx/dy are numbers, the horizontal/vertical shift amount. Returns a new 3x3 homogeneous-coordinate Mat encoding that translation.
affine_scaleaffine_scale(sx, [sy])Builds a scaling transform for imwarp. sx is a number, the scale factor along x; sy is an optional number, the scale factor along y, defaulting to sx (uniform scale) when omitted — matching MATLAB imresize(img, scale)'s single-factor convention. Returns a new 3x3 Mat.
affine_rotateaffine_rotate(angle_degrees)angle_degrees is a number. Returns a new 3x3 Mat encoding a CCW rotation matrix in standard math convention (see the clockwise-on-screen note above for the visual difference from imrotate).
affine_shearaffine_shear(shx, shy)shx/shy are numbers, the shear factors along x and y. Returns a new 3x3 Mat encoding that shear.
imwarpimwarp(img, M, [method="bilinear"], [bbox="loose"], [fill=0])img is an Image; M is a 3x3 (or 2x3, auto-padded with [0,0,1]) affine Mat — from the affine_* builders above, a literal matrix, or any composition of the two via */matmul. method is an optional named string ("nearest"/"bilinear", default "bilinear"). bbox is an optional named string, "loose" (default, grows the canvas to fit) or "crop" (keeps the input's size). fill is an optional named number 0–255 (default 0) applied to all 3 channels for pixels that map outside the source image. Applies M to img in one resampling pass via inverse mapping. Returns a new Image.
blurblur(img)img is an Image of any size. Applies a fixed 3x3 box-average blur kernel. Returns a new Image, the same dimensions as img.
sharpensharpen(img)img is an Image. Applies a fixed 3x3 unsharp-mask sharpen kernel. Returns a new Image, same dimensions as img.
edge_detectedge_detect(img)img is an Image. Applies a fixed 3x3 discrete Laplacian edge filter, highlighting intensity discontinuities. Returns a new Image, same dimensions as img.
imfilterimfilter(img, kernel)img is an Image; kernel is an arbitrary odd-sized (e.g. 3x3, 5x5) square Mat of numeric weights. Generic 2-D convolution with edge-clamped borders — the escape hatch when blur/sharpen/edge_detect's fixed kernels aren't enough. Returns a new Image, same dimensions as img.
imdilateimdilate(img, radius)img is a binary (0/255 mask-style) Image; radius is a positive integer, the half-width of a square structuring element of side 2*radius+1 (a documented choice over a disk element). Performs binary morphological dilation, growing foreground regions. Returns a new Image, same dimensions as img.
imcloseimclose(img, radius)img is a binary Image; radius is a positive integer (same square structuring-element convention as imdilate). Morphological closing (dilate then erode) — fills small background holes without enlarging the overall shape. Returns a new Image, same dimensions. (imopen/imerode, erosion and opening, also exist alongside it in the same match arm pair but aren't in this chapter's requested scope — see the "More functions" table below.)
imbothatimbothat(img, radius)img is a binary Image; radius is a positive integer. Bottom-hat: imclose(img, radius) - img, extracts small dark features / corrects a slowly-varying dark background. Returns a new Image, same dimensions. (imtophat, the bright-feature dual, is its sibling arm, documented below.)
histeqhisteq(img) (alias of imequalize)img is an Image of any size, color or grayscale. Global histogram equalization: builds a BT.601-luma cumulative distribution and remaps intensities to spread across the full range. RGB-preserving via luma-ratio remapping — not a grayscale-only fallback. Returns a new Image, same dimensions as img.
imadjustimadjust(img, [in_low=], [in_high=], [out_low=0.0], [out_high=1.0], [gamma=1.0])img is an Image. in_low/in_high are optional named numbers in [0,1], the input intensity range to stretch from; when both are omitted they auto-default to the image's own 1st/99th percentile (all channel bytes pooled) — robust to outlier pixels, like MATLAB's stretchlim. out_low/out_high are optional named numbers in [0,1] (default 0.0/1.0), the output range to stretch to. gamma is an optional named number (default 1.0) applying a power-law curve after the linear stretch. MATLAB-style contrast stretch, applied identically and independently to each of R/G/B. Returns a new Image, same dimensions as img.
imhistimhist(img, [n_bins=256])img is an Image; n_bins is an optional positive integer (default 256; may be given positionally or as a named argument), the number of histogram bins. Computes raw per-bin BT.601-luma intensity counts. Returns a Vec of length n_bins — data, not a rendered plot. Pipe the result into hist/bar to actually draw it.
imnoiseimnoise(img, type, [mean=0.0], [sigma=0.05], [density=0.05], [seed=])img is an Image; type is a required string, "gaussian" or "salt_pepper". For "gaussian": mean/sigma are optional named numbers (defaults 0.0/0.05), the additive per-channel Gaussian noise's mean/standard-deviation in normalized [0,1] intensity units. For "salt_pepper": density is an optional named number (default 0.05), the fraction of pixels (not channel samples) flipped to pure black/white. seed is an optional named integer for reproducibility (same convention as randn/uniform); omitted, a fresh random seed is used. Adds synthetic noise for testing other CV algorithms. Returns a new Image, same dimensions as img.
thresholdthreshold(x, level)x is an Image, Signal, Vec, or scalar; level is a number, the cutoff. Elementwise binary threshold, general-purpose (not image-specific). Image → binary black/white image of the same dimensions (per-pixel BT.601 luma vs level); Signal → same-Fs Signal of 0.0/1.0; Vec/scalar → identical to x >= level (a Mask/Bool via the shared compare path). Returns the same kind of value x was: an Image from an Image, a same-Fs Signal from a Signal, a Mask from a Vec, a Bool from a scalar.
multithresholdmultithreshold(x, levels)x is an Image, Signal, Vec, or scalar; levels is a Vec/matrix or tuple List of cut-point numbers (sorted ascending regardless of input order). Quantizes into len(levels)+1 bands at the given cut points. Image → posterized image of the same dimensions with evenly-spaced gray levels per band; Signal/plain numeric → raw 0-based band index. Returns the same kind of value x was: an Image from an Image, a same-Fs Signal from a Signal, and otherwise a Vec/Num of 0-based band indices.
otsu_thresholdotsu_threshold(x)x is an Image, Vec, or Signal. Computes (does not apply) the classic Otsu optimal threshold from x's histogram (Image reads per-pixel luma; Vec/Signal read their own values). Returns a single number, the threshold level. Compose with threshold(x, otsu_threshold(x)) to segment.
otsuotsu(x)x is an Image, Vec, or Signal. Compute-and-apply convenience: otsu_threshold followed immediately by threshold in one call. Returns the same type/shape threshold(x, level) would (e.g. a new binary Image of the same dimensions for an Image input).
multi_otsumulti_otsu(x, n_classes)x is an Image, Vec, or Signal; n_classes is a positive integer, the desired number of intensity classes. The n_classes - 1-threshold generalization of otsu_threshold. Returns a Vec of n_classes - 1 cut points in ascending order. Compose with multithreshold(x, multi_otsu(x, n)) to segment into n classes.
kapur_thresholdkapur_threshold(x)x is an Image, Vec, or Signal. Same "compute, don't apply" shape as otsu_threshold, but using Kapur's entropy-maximizing criterion instead of Otsu's between-class variance — tends to handle unequal class sizes better. Returns a single threshold number.
bwlabelbwlabel(binary_img, [connectivity=8]) (alias of label_blobs)binary_img is a binary (0/255) Image. connectivity is an optional named number, 4 or 8 (default 8), the neighbor rule used for flood-fill labeling. Connected-component labeling. Returns a Model (kind "blobs") with fields .labels (a Mat of the same height/width as binary_img, integer label ids, background = 0), .count (a number, the blob count), .width, .height (the source image's own dimensions).
regionpropsregionprops(labeled) (alias of blob_stats)labeled is a Model produced by bwlabel/label_blobs. Takes that result and returns a List of one Record per blob, in label-id order, each with fields: label (integer id), area (pixel count), centroid_x, centroid_y (real pixel-coordinate means, not bbox-center approximations), bbox_x, bbox_y, bbox_width, bbox_height (tightest axis-aligned rectangle) — all numbers. Returns a List with one Record per blob, in label-id order — empty when labeled found none.
bwareaopenbwareaopen(binary_img, min_area) (alias of remove_small_blobs)binary_img is a binary Image; min_area is a number, the minimum pixel count a blob must have to survive. Labels internally (8-connectivity, matching MATLAB's default) and zeroes out every blob whose pixel count is below min_area. Returns a new binary Image, same dimensions as binary_img, with small blobs removed.
foreground_maskforeground_mask(img, level, [radius=1])img is an Image, color or grayscale (BT.601 luma either way); level is a required number, the threshold cutoff 0–255; radius is an optional named positive integer (default 1), the structuring-element radius for the cleanup step. Thresholds img at level, then applies imopen(radius) to remove noise specks. level is a required argument by design — pair with otsu_threshold for auto-thresholding: foreground_mask(img, otsu_threshold(img)). Returns a new binary Image, same dimensions as img.
imerodeimerode(img, radius)img is a binary Image; radius is a positive integer, the half-width of a square structuring element of side 2*radius+1. Binary morphological erosion — shrinks foreground regions and removes specks smaller than the element. Returns a new Image, same dimensions as img.
imopenimopen(img, radius)img is a binary Image; radius is a positive integer (same structuring-element convention as imerode). Morphological opening (erode then dilate) — removes specks smaller than the structuring element while leaving larger shapes their size. Returns a new Image, same dimensions as img.
imtophatimtophat(img, radius)img is a binary/grayscale Image; radius is a positive integer. The image minus its opening: what the opening removed. The standard way to pull small bright features off an uneven background. Returns a new Image, same dimensions as img.
imequalizeimequalize(img)img is an Image of any size. Histogram equalisation, spreading the intensities to fill the range (identical operation to histeq above). Reveals detail in a flat image and exaggerates noise in a clean one. Returns a new Image, same dimensions as img.
remove_small_blobsremove_small_blobs(img, min_area)img is a binary Image; min_area is a number, the minimum pixel area a connected component must have to survive. Drop connected components below that area, after labelling internally (identical operation to bwareaopen above). The cheap alternative to tuning a filter. Returns a new binary Image, same dimensions as img.
label_blobslabel_blobs(img)img is a binary Image. Connected-component labelling: every separate region gets its own integer (identical operation to bwlabel above). Returns a Model (kind "blobs") with .labels, .count, .width, .height fields.
blob_statsblob_stats(img)img is a Model produced by label_blobs/bwlabel. Per-region area, centroid and bounding box, from a labelled image (identical operation to regionprops above). Returns a List of Records, one per blob.

Collections & strings chapter → 161

strstr(x)Renders x (any value/type) the same way print/disp would. Returns a Str.
substr, midsubstr(s, start, [length])s is a Str; start (number, 0-based character index, must lie in [0, char_count]) is where the slice begins; optional length (number of characters, default: to the end) is clamped rather than erroring if it runs past what's left. Plain aliases of the same implementation (mid exists purely for BASIC/Excel discoverability). Returns a Str.
leftleft(s, n)The first n characters of a string. s is a Str; n (number of characters) selects the first n of them, clamped to the whole string if n exceeds its length. Returns a Str.
rightright(s, n)The last n characters of a string. s is a Str; n (number of characters) selects the last n of them, with the same clamping as left. Returns a Str.
reversereverse(x)x is a Str, List, Vec, or Mask. Unicode-aware character reversal for a Str (same type back); element-order reversal for a List/Vec/Mask (same type and shape back). Returns exactly the same type and length as x.
upperupper(s)s is a Str. Unicode-aware uppercase conversion. Returns a Str the same length (in characters).
lowerlower(s)s is a Str. Unicode-aware lowercase conversion. Returns a Str the same length (in characters).
replacereplace(s, old, new)s is the Str to search; old and new are Strs. Every literal (non-regex) occurrence of old in s is replaced by new. Returns a Str.
starts_withstarts_with(s, prefix)s and prefix are Strs. Returns a bool: true if s starts with prefix.
ends_withends_with(s, suffix)s and suffix are Strs. Returns a bool: true if s ends with suffix.
flipflip(s)s is a Str. The same as reverse on a string — the word a BASIC hand reaches for. Returns a Str.
insertinsert(s, i, text)s and text are Strs; i (number, 0-based character position) is where text is spliced in. Returns a new Str; s itself is untouched.
removeremove(s, text) or remove(s, start, [count])s is a Str. Two overloads, picked by the type of the second argument: text (Str) deletes every occurrence of it; start (number, 0-based index) with optional count (number of characters, default: to the end) deletes that run instead. Returns a Str.
countcount(s, sub)s and sub are Strs. Returns a number: how many non-overlapping times sub occurs in s (non-overlapping so it agrees with replace).
index_ofindex_of(s, sub)s and sub are Strs. Returns a number (0-based character position of the first occurrence) or none if sub is absent.
last_index_oflast_index_of(s, sub)s and sub are Strs. Returns a number (0-based character position of the last occurrence, searching from the end) or none if absent — so a miss cannot be mistaken for a position.
pad_leftpad_left(s, width, [fill=" "])s is a Str; width (number, target character count); optional fill (single-character Str, default " "). Pads on the left to width characters; a string already that wide is returned unchanged, never truncated. Returns a Str.
pad_rightpad_right(s, width, [fill=" "])Same parameters and return as pad_left, padding on the right instead. Returns a Str of at least width characters — s unchanged when it is already that long.
capitalizecapitalize(s)s is a Str. Uppercases the first character, leaves the rest untouched. Returns a Str.
properproper(s)s is a Str. Uppercases every word's first character, lowercases the rest — VB's StrConv(s, vbProperCase). Returns a Str.
lineslines(s)s is a Str. Splits on either line ending, with no spurious empty last element when the text ends in a newline. Returns a List of Str.
charschars(s)s is a Str. Returns a List of one-character Strs.
repeat_strrepeat_str(s, n)s is a Str; n (number of copies). s * n is the shorter spelling for the same thing; the function is not called repeat because that is a loop keyword. Returns a Str.
chr, ordchr(n), ord(s)chr(n): n is a numeric Unicode code point — not a byte, so chr(9731) is a snowman, not an error. ord(s): s is a Str; a longer string is not an error, only its FIRST character is read, so ord("Abc") is 65. asc is a second name for ord. Returns a one-character Str from chr, and a number — the code point — from ord.
trimtrim(s, [chars])Strips characters from both ends of a string. s is a Str; optional chars (Str, default: whitespace) is a SET of characters to strip, not a substring — trim(field, "\"' ") strips quotes and spaces in any order from both ends. Returns a Str.
ltrim, rtrimltrim(s, [chars])Same parameters as trim, restricted to one end only (ltrim the left, rtrim the right). Returns a Str.
splitsplit(s, delim, [limit])s and delim are Strs; optional limit (number of pieces, default: unlimited) stops after that many pieces and leaves the remainder undivided as the last one — split(line, ": ", 2) takes key: value with: colons apart that way. Returns a List of Str.
comparecompare(a, b, [ignore_case])a and b are Strs; optional ignore_case (bool, default false). Returns a number: −1, 0 or 1, so it can drive a sort directly.
sortsort(list, [descending])list is a List of Str or a numeric Vec; optional descending (bool, default false). A list of strings sorts lexicographically, a numeric vector sorts numerically. Returns the same type as list.
ucase, lcaseucase(s)s is a Str. BASIC's names for upper/lower; toupper/tolower are C's names for the same thing. Returns a Str.
write_textwrite_text(path, s)path and s are Strs (file path, content to write). Writes the whole string to a file, overwriting it. Returns a number (bytes written). append_text adds to the end instead; the counterpart of read_all_text.
after, beforeafter(s, mark)s and mark are Strs. after returns the piece of s past the first mark; before returns the piece up to it. after_last/before_last search from the other end. A mark that is not present leaves s whole (returned unchanged), never empty. Returns a Str.
head, tailhead(s, n)s is a Str, List, Vec, or Table; n (number, default 5 when used on a table). Returns the first (head) or last (tail) n elements/rows, same type as s.
grepgrep(s, pattern, [invert=])s is a Str (often multi-line) or List of lines; pattern is a regex Str; optional named invert (bool, default false) selects non-matching lines instead. Returns a List of the matching (or non-matching) LINES — regex_find_all returns the matched substrings themselves, a different thing.
parse_as, scanparse_as(s, template, [must_match=])s and template are Strs. scanf backwards: "hello world 12".parse_as("hello world %d") gives 12. %d a whole number, %f any number, %s a run of non-space, %* anything. The template understands \t, \n, \r and \\ in its literal parts, so "%d\thello" and r"%d\thello" mean the same thing; a literal backslash is doubled. Returns the extracted value (a number, Str, or a List/tuple of them when template has more than one placeholder), or none if the line doesn't have the shape described — never numbers pulled from a different sentence. Optional named must_match (bool, default false) raises an error naming the missing part of the shape instead of returning none — see the limit noted below.
formatformat(x, pattern)x is a number; pattern is a Str picture: "0.00", "#,##0.0", "0.0%", "0.00e0". Interpolation ({x:.2f}) reads better inline; format is for a pattern held in a variable. Returns a Str.
as_textas_text(v)v is a Vec, List, or Signal. Returns a List of Str (each element formatted the way print would), so [1, 2, 3].as_text().join(", ") works. str renders the whole value as one string in one shot — a different question.
md2htmlmd2html(s)s is a Str of Markdown source. Converts headings, paragraphs, lists, fenced code with its language, blockquotes, pipe tables, rules, and inline code/bold/italic/links/images. Returns a Str of HTML.
html2mdhtml2md(s)s is a Str of HTML. Converts the same subset back to Markdown; malformed HTML degrades to its text rather than erroring. Returns a Str.
substr(s, start)Everything from start to the end of s — the 2-argument form.
substr(s, start, length)Exactly length characters starting at start, clamped (not an error) if length runs past what's left — the 3-argument form.
remove(s, text)text is a Str. Deletes every occurrence of it from s.
remove(s, start)start is a number (0-based character index). Deletes from start to the end of s.
remove(s, start, count)count is a number of characters. Deletes exactly that many, starting at start, clamped rather than erroring if count runs past what's left.
regex_matchregex_match(s, pattern)s and pattern are Strs (pattern a regular expression). Returns a bool: whether the pattern occurs anywhere in s. Anchor it with ^/$ to test the whole string.
regex_findregex_find(s, pattern)s and pattern are Strs. Returns a Str (the first match) or none — not an empty string, so "matched empty" and "did not match" stay apart.
regex_find_allregex_find_all(s, pattern)s and pattern are Strs. Returns a List of Str — every match, in order.
regex_groupsregex_groups(s, pattern)s and pattern are Strs (pattern containing (...) capture groups). Returns a List of Str — the capture groups of the first match, group 1 onward; a group that did not participate is an empty string. Returns none if nothing matched.
regex_replaceregex_replace(s, pattern, repl, [count])s, pattern and repl are Strs; optional count (number, default: all occurrences) caps how many replacements are made. $1 and ${name} in repl refer to capture groups. Returns a Str.
regex_splitregex_split(s, pattern)s and pattern are Strs. Returns a List of Str, split on every match of the pattern.
regex_countregex_count(s, pattern)s and pattern are Strs. Returns a number: how many non-overlapping matches occur.
likelike(s, pattern)s and pattern are Strs. BASIC's wildcard match, anchored at both ends: * any run, ? any one character, # any digit, [abc]/[!abc] a set. Returns a bool.
bitandbitand(a, b)a and b are numbers holding integer values. Returns a number: the bitwise AND of a and b as 64-bit integers.
bitorbitor(a, b)a and b are numbers holding integer values. Returns a number: the bitwise OR.
bitxorbitxor(a, b)a and b are numbers holding integer values. Returns a number: the bitwise XOR.
bitcmpbitcmp(a)a is a number holding an integer value. Returns a number: the bitwise complement (!a) as a 64-bit integer.
bitshiftbitshift(x, n)Shifts an integer's bits left or right. x is a number holding an integer value; n is a number holding an integer shift amount — positive shifts left, negative shifts right (MATLAB's single-function convention rather than separate <</>> operators). Returns a number.
xorxor(a, b)a and b are any values, read by whole-value truthiness. Returns a bool: logical XOR, non-short-circuit like and/or.
nandnand(a, b)a and b are any values, read by whole-value truthiness. Returns a bool: logical NAND.
nornor(a, b)a and b are any values, read by whole-value truthiness. Returns a bool: logical NOR.
hex2dechex2dec(s)Reads a hexadecimal digit string as a number. s is a Str (a hex digit string, optional 0x/0X prefix). Returns a number.
dec2hexdec2hex(n)n is a number holding an integer value. Returns a Str: uppercase hex digits, no prefix.
bin2decbin2dec(s)Reads a binary digit string as a number. s is a Str of 0/1 digits. Returns a number.
dec2bindec2bin(n)n is a number holding an integer value. Returns a Str of 0/1 digits, no prefix.
removeremove(collection, index)collection is a Vec or List; index is a number (0-based position). Returns a NEW Vec/List (same type as collection) with the element at index dropped. (remove(timer) is a distinct, unrelated overload for deregistering a simulated-event timer.)
insertinsert(collection, index, value)collection is a Vec or List; index is a number (0-based position, index == length appends at the end); value is the element to insert — a Vec insert requires value to be numeric, a List insert accepts anything. Returns a NEW Vec/List.
appendappend(collection, value)collection is a Vec or List; value is the element to add. Returns a NEW Vec/List with value added at the end.
containscontains(collection, value)collection is a Vec or List; value is any comparable element. Returns a bool: membership test via structural equality.
indexofindexof(collection, value)collection is a Vec or List; value is any comparable element. Returns a number (0-based index of the first match) or Nothing if absent (composes with ??: indexof(xs, v) ?? -1).
uniqueunique(x)x is a numeric Vec. Returns a Vec: a sorted, de-duplicated copy.
sortsort(x, [descending])x is a numeric Vec or List of Str; optional descending (bool, default false). Returns the same type as x, ascending by default; uses a proper total order (f64::total_cmp) so a stray NaN cannot corrupt the ordering of the other elements around it.
argsortargsort(x, [descending])x is a numeric Vec; optional descending (bool, default false). Returns a Vec of number (0-based indices): the permutation that would sort x — the index-returning sibling of sort, same convention as argmin/argmax.
cumsumcumsum(x)x is a numeric Vec or Signal. Returns the running sum, same type/length as x; a Signal input stays a Signal with the same Fs.
diffdiff(x)x is a numeric Vec or Signal of length N. Returns the first difference (x[i+1] - x[i]), length N-1, same base type as x; a Signal input stays a Signal with the same Fs.
sort(list_of_str, [descending])list_of_str is a List in which every element is a Str. Sorts lexicographically. Returns a List.
sort(vec, [descending])vec is (or coerces to) a numeric Vec. Sorts numerically via f64::total_cmp, immune to a stray NaN. Returns a Vec.
enum_valuesenum_values(EnumType)EnumType is a type declared with enum ... end (not a string — the bare type name). Returns a List of EnumVals: every variant of the declared type, in declaration order — makes the type a real enumeration rather than just a handful of named constants, and lets code iterate "all seasons" without hardcoding the list a second time.
table, DataFrameDataFrame(name=values, ...)Each named argument is a column: values is either a numeric Vec / List of Str (a real column) or a scalar number/Str (broadcast to every row). Builds a Table from the named columns, in the order the arguments were written; a scalar/string column broadcasts to the row count set by whichever columns are actual vectors, and vector columns must all agree in length. Returns a Table.
table, DataFrametable(csv_text, [sep=","], [headers=true])csv_text is a Str (a header line and a line per row); optional sep (single-character Str, default ",") sets the delimiter; optional headers (bool, default true) — when false, columns are auto-named col1, col2, etc. Cells are trimmed and blank lines ignored, so the source can be aligned. Returns a Table. See below.
nrownrow(df)df is a Table. Returns a number: the row count. df.nrows is property-style sugar for this — see below.
ncolncol(df)df is a Table. Returns a number: the column count. df.ncols is property-style sugar for this — see below.
headhead(df, [n=5])df is a Table; optional n (number of rows, default 5). Returns a Table: the first n rows.
selectselect(df, "col", ...)df is a Table; each remaining argument is a Str column name. Returns a Table containing only the named columns, in the order given.
filterfilter(df, mask)df is a Table; mask is a boolean Vec/Mask the same length as df's rows (typically built from a comparison, e.g. df.x > 0). Returns a Table containing only the rows where mask is true.
sort_bysort_by(df, "col", [descending])df is a Table; "col" is a Str column name; optional descending (bool, default false). Returns a Table sorted by that one column.
group_by_agggroup_by_agg(df, "group_col", "value_col", "agg")df is a Table; "group_col"/"value_col" are Str column names; agg is a Str naming the aggregate ("mean" by default, plus "sum", "min", "max", "count", etc.). Returns a Table: one row per distinct value of group_col, with value_col aggregated.
describedescribe(df)df is a Table. Pandas-style describe(): returns a Table with one row per summary statistic (count, mean, std, min, 25%, 50%, 75%, max) and one column per NUMERIC column of df (text columns are skipped). Returns a Table, 8 rows by however many numeric columns df has.
cast(list_of_strings, "num")list_of_strings is a List of Str. Returns a Vec of parsed numbers, same length; errors clearly naming the first element that doesn't parse.
cast(str, "num")str is a Str. Returns a single parsed number, same parse-or-error rule.
cast(vec_or_signal, "str")vec_or_signal is a numeric Vec or Signal. Returns a List of formatted number-strings (fmt_num, the same formatter print/disp already use), same length.
cast(num, "str") / cast(bool, "str")num/bool is a single number/bool. Returns a single formatted Str.
cast(x, "bool")x is any value. Returns a bool: truthy conversion — the exact same rule if/and/or/the ternary already use.
cast(vec, "list") / cast(list_of_numbers, "vec")Converts between a homogeneous numeric Vec and a List of boxed numbers, same length, elementwise.
cast(vec, "signal") / cast(signal, "vec")vec is a numeric Vec; signal is a Signal. Wraps a plain Vec as a Signal (default Fs=1.0, matching signal(data)'s own default) or drops a Signal's Fs back to a plain Vec, same length either way.
cast(vec_or_signal, "mask") / cast(mask, "vec")vec_or_signal is numeric, mask is boolean; both are the same length in and out. Elementwise nonzero-is-true, or the numeric 0.0/1.0 inverse.
fifofifo(capacity)capacity is a number (positive integer, the buffer's fixed size, set once with no resize). Returns a fifo handle: a new, empty ring buffer.
.pushf.push(value)f is a fifo handle; value is any value to store. Appends at the back; evicts the OLDEST element first if f is already full. Returns Nothing.
.popf.pop()f is a fifo handle. Removes and returns the oldest element (same type as whatever was stored). Errors clearly on an empty fifo.
.peekf.peek()f is a fifo handle. Returns the oldest element without removing it. Errors clearly on an empty fifo.
.is_fullf.is_full()f is a fifo handle. Returns a bool: true iff the next .push would evict.
.is_emptyf.is_empty()f is a fifo handle. Returns a bool: true iff .pop/.peek would error right now.
len, length, numellen(f)f is a fifo handle. Returns a number: the current element count (via the same generic length dispatch every collection uses).
double_bufferdouble_buffer(initial)initial is any value. Returns a double_buffer handle; front AND back both start equal to initial.
.writeb.write(value)b is a double_buffer handle; value is any value. Writes ONLY the back buffer. Returns Nothing.
.readb.read()b is a double_buffer handle. Returns the current FRONT buffer's value (same type as whatever was last swapped in).
.swapb.swap()b is a double_buffer handle. Atomically exchanges front and back. Returns Nothing.
linked_listlinked_list()Takes no arguments. Returns a linked_list handle: a new, empty double-ended list.
.push_frontl.push_front(v)l is a linked_list handle; v is any value. Prepends v in O(1). Returns Nothing.
.push_backl.push_back(v)l is a linked_list handle; v is any value. Appends v in O(1). Returns Nothing.
.pop_frontl.pop_front()l is a linked_list handle. Removes and returns the front element in O(1). Errors clearly if empty.
.pop_backl.pop_back()l is a linked_list handle. Removes and returns the back element in O(1). Errors clearly if empty.
.to_vecl.to_vec()l is a linked_list handle. Returns a plain List: the elements materialized front to back, for interop with the rest of Qu (indexing, length, print, ...).
len, length, numellen(l)l is a linked_list handle. Returns a number: the current element count.
graphgraph([directed=false])Optional named directed (bool, default false). Returns a graph handle: a new, empty node+edge graph.
.add_nodeg.add_node(id)g is a graph handle; id is a Str or number node identifier (canonicalized like dict keys, so 1 and 1.0 name the same node). Adds a node; idempotent — adding an existing node is a no-op. Returns Nothing.
.add_edgeg.add_edge(a, b, [weight=1.0])g is a graph handle; a/b are node ids (Str/number); optional named weight (number, default 1.0). Adds an edge, auto-creating either endpoint if missing. Undirected (the default) stores the edge in both directions. Returns Nothing.
.neighborsg.neighbors(id)g is a graph handle; id is a node id. Returns a List of Str neighbor ids, in the order their edges were added (always strings regardless of what kind of id was originally passed in). Errors if id isn't a node.
.has_edgeg.has_edge(a, b)g is a graph handle; a/b are node ids. Returns a bool — false (not an error) if either endpoint isn't even a node.
.shortest_pathg.shortest_path(source, target)g is a graph handle; source/target are node ids. Returns a number (the shortest total edge weight from source to target, via Dijkstra's algorithm) or Nothing if unreachable. Errors on a negative edge weight or an unknown node.
len, length, numellen(g)g is a graph handle. Returns a number: the node count.
and, ora and ba and b are any values, read by whole-value truthiness. Returns a bool. Both short-circuit: the right side is not evaluated when the left already decides the answer, so i < len(xs) and xs[i] > 0 is a safe guard.
notnot aa is any value. Returns a bool: logical negation. Anything falsy — false, 0, none, an empty string, an empty collection — negates to true.
moda mod ba/b are numbers. Returns a number: the remainder with the sign of the divisor, so -1 mod 3 is 2 rather than -1. A keyword, not a function.
print, disp, echo, writelineprint(x, ...)Each x is any value. Writes its arguments, space-separated, and a newline, to stdout. Returns Nothing. All four names are the same function. Strings interpolate: print("n = {n}").
inputinput(n)Not a stdin reader despite the name — Qu has no line-reading builtin today. n (number, a positive integer — 0 or a non-integer errors) is the input dimension of a new neural-network pipeline. Returns a Record shaped {kind: "pipeline_input" (string), out_dim: n (number), layers: [] (empty List)}, meant to be piped into dense(out_dim, [activation=]) stages and finished with compile(optimizer=, loss=) or sequential(...) — see [Statistics & ML](statistics-ml.md) for the full training example.
typetype(x)x is any value. Returns a Str: the value's type, e.g. "number", "string", "vector", "matrix", "table", "layer".
sizeofsizeof(x)Deprecated — use shape. The same function under a name that means a byte count in every language it could have come from. Still works, and warns once per run. Returns a 2-element Vec, [rows, cols] — the same value shape gives.
castcast(x, type)x is any value; type is a Str naming the target: num, bool, str, vec, mat, complex, cvec, cmat, signal, mask, table, model, list, record, image, timer, file, worker, mutex, semaphore, none. Returns a value of that kind. A conversion that is not defined is an error, not a best effort.
to_intto_int(x)x is a number, or a Str that parses as one. Rounds to the nearest whole number, ties away from zero — the same primitive round uses, so the two agree by construction rather than by coincidence. MATLAB's int32 rounds; C's cast truncates; this rounds, and says so. A string that is not a number is a clear error, never a silent 0. Returns a Num.
to_floatto_float(x)x is a number, a Bool (giving 1/0), or a Str that parses as one. The parsing half of to_int without the rounding — mostly for turning text read from a file or an instrument into a number. A string that is not a number, or a value of any other type, is a clear error rather than a 0. Returns a Num.
to_boolto_bool(x)For a Str, x is parsed, not weighed: "true"/"false" (any case) and any number spelling work, and anything else errors — because a config file holding "false" means false, and truthiness would call that non-empty string true. For every other type this is exactly Qu's own truthiness, the same rule if and while use. Returns a Bool.
complexcomplex(re, im)re/im are numbers (real and imaginary parts). Returns a Complex. 3 + 4i is the literal form; this is for computed components.
all, anyall(xs, predicate)xs is a Vec/List; predicate is a one-argument function returning a bool — the function itself (is_even, sqrt, (x) := x > 2), or a Str naming one you defined. Returns a bool: whether every (all) or at least one (any) element satisfies it. As a quoted name a builtin is refused, because a string is indistinguishable from a typo; passed as a value, without quotes, it is allowed.
first, lastfirst(xs)xs is a Vec/List. Returns the first (first) or last (last) element (same element type as xs holds), or none when xs is empty. Check for none if an empty input is possible; nothing further down will do it for you.
take, droptake(xs, n)xs is a Vec/List; n is a number of elements. Returns the same type as xs: the first n elements (take) or everything after them (drop). n beyond the length is clamped, not an error.
distinctdistinct(xs)xs is a Vec/List. Returns the same type: the unique values, in the order they first appear — which unique does not promise, since it sorts.
flattenflatten(xs)xs is a List of Lists (one level of nesting). Returns a flat List: one level of nesting removed.
fold, reducefold(xs, f, initial)xs is a Vec/List; f is a two-argument function — the function itself, or a Str naming one you defined; initial is the starting accumulator value (fold only — reduce has no initial and instead starts from xs's first element). Returns the final accumulated value (whatever type f produces).
map, pmapmap(xs, f)xs is a Vec/List; f is a one-argument function — the function itself (double, sqrt, (x) := x * 2), or a Str naming one you defined. Returns a List: f applied to every element. The collection comes first, like every other higher-order builtin, which is what makes xs.map(f) and xs
zipzip(a, b, ...)Each of a, b, ... is a Vec/List. Returns a List of tuples, pairing up the collections element by element, stopping at the shortest.
dictdict() or dict(k, v, ...)With no arguments: an empty store. Otherwise k/v are parallel Vec/List of keys and values (Str or number keys). Returns a Dict, insertion-ordered. Keys are compared as given, so a number and the string of that number are different keys.
get, setget(d, key) / set(d, key, value)d is a Dict; key is a Str/number; value (for set) is any value. get returns the stored value (any type) or none if key is absent. set returns a new Dict with that entry written — it does not modify d in place, so assign the result. Returns the stored value (any type) or none from get, and a new Dict from set.
keys, values, itemskeys(d)d is a Dict. Returns a List: its keys (keys), its values (values), or (key, value) tuples (items) — insertion order, not sorted.
has_keyhas_key(d, key)d is a Dict; key is a Str/number. Returns a bool: whether the dict has that key, without reading it.
atat(t, i) or t.at(i)t is a Table; i is a number (0-based row position). Returns a Record: one row of the table by position, always positional even when the table carries a string index.
indexindex(t, "col")t is a Table; "col" is a Str column name. Returns a Table: t with its row index set to that column, so rows can afterwards be looked up by label.
insert_columninsert_column(t, name, values, [pos=])t is a Table; name is a Str; values is a numeric Vec/List of Str (or a scalar to broadcast) the same length as t's rows; optional named pos (number, default: append at the end) sets the column's position. Returns a NEW Table; the original is untouched.
drop_rowdrop_row(t, i) or drop_row(t, [i, j])t is a Table; i/j are numbers (0-based row positions), or a Vec of them. Returns a Table without those rows, by position.
insert_rowinsert_row(t, i, record)Inserts one row into a table at a chosen position. t is a Table; i is a number (0-based row position, i equal to the row count appends); record is a Record supplying one value per existing column, matched by field name. Returns a NEW Table.
swap, readswap(b) / read(b)b is a double_buffer handle. swap atomically exchanges front and back (returns Nothing); read returns the stable front value. Writers fill the spare half and swap when the frame is whole; a reader never sees a partly-written frame. Returns the stable front value from read — whatever type was written into the buffer; swap hands back no value.
append_text, append_allappend_text(path, s) / append_all(path, s)path/s are Strs. Appends s to the end of the file at path, creating it if absent. write_text replaces the whole file instead. append_all is the same builtin under the name that pairs with read_all_text — whole file in, whole string out, no handle in either direction — and both spellings stay, since append_text is already in scripts. Returns a number: the bytes written.
after_last, before_lastafter_last(s, mark)s/mark are Strs. Returns a Str: like after/before but searching from the end — the pair to reach for on a path or a dotted name.
ascasc(s)s is a Str. Returns a number: the code point of its first character. A second name for ord, because it is what a BASIC hand types.
toupper, tolowertoupper(s)s is a Str. Returns a Str: C's names for upper/lower, accepted so a ported line does not have to be edited.
to_vecto_vec(ll)ll is a linked_list handle. Returns a List: the linked list's elements, front to back.
push, pop, peekpush(q, x) / pop(q) / peek(q)On a fifo handle q: push(q, x) adds x at the back (returns Nothing); pop(q) removes and returns the front element; peek(q) looks at it without removing. pop on an empty FIFO is an error. On a queue() — the job queue — push(q, "fname") enqueues a function you defined instead (a Str naming it, not a value). Returns the front element itself from pop/peek, whatever type was pushed; push hands back no value.
push_back, push_frontpush_back(l, x)l is a linked_list handle; x is any value. Grows l at the back (push_back) or front (push_front) in O(1). Returns Nothing.
pop_back, pop_frontpop_front(l)l is a linked_list handle. Removes and returns the element from the front (pop_front) or back (pop_back) in O(1). to_vec turns the result back into an ordinary List. Returns the removed element itself, whatever type was pushed; the list is one shorter afterwards.
add_node, add_edgeadd_node(g, name)g is a graph handle; name is a Str/number node id; add_edge(g, a, b, [weight=1.0]) also takes a second node id and an optional weight (number, default 1.0). Nodes are named; an edge carries an optional weight, defaulting to 1. Returns Nothing from both — the graph handle g is what changed.
has_edge, neighborsneighbors(g, name)g is a graph handle; name/a/b are node ids. has_edge(g, a, b) returns a bool; neighbors(g, name) returns a List of Str node ids. Ask about the graph: whether two nodes are joined, and what one node is joined to. Returns a Bool from has_edge, and a List of node ids from neighbors.
shortest_pathshortest_path(g, from, to)g is a graph handle; from/to are node ids. Returns a number (the shortest total edge weight, via Dijkstra) or none if to is unreachable from from — disconnected is an answer, not an error. Errors instead if from/to isn't even a node in g. Same free-function form as .shortest_path, not the sequence of node names along the route.

File I/O chapter → 121

fopenfopen(path, mode)Opens a file for reading, writing, or appending. path (string) is the filesystem path. mode (string) is one of "r" (read, errors if the file doesn't exist), "w" (write, truncate-or-create), "a" (append, create-if-missing), or the same three with a "b" suffix ("rb"/"wb"/"ab") for binary — text and binary modes behave identically at the byte level. Returns an opaque Value::File handle to pass to every other builtin in this chapter.
closeclose(f)Flushes and releases a file handle. f (file handle, from fopen/StreamFile) is the handle to release. Returns Nothing. Reading/writing a closed handle errors clearly afterward rather than silently no-op'ing or panicking. Any pending partial write_bit byte is flushed, zero-padded. Calling close again on an already-closed handle is a harmless no-op.
touchtouch(path)Unix touch semantics. path (string) is the filesystem path: creates an empty file if it doesn't exist; if it already exists, updates its modification time WITHOUT altering its content. Returns Nothing. Uses a real mtime-set syscall (via the filetime crate) rather than the unreliable "open for append, write nothing" trick, which does not reliably bump mtime on every platform/filesystem.
read_lineread_line(f)Reads one line from f (file handle, opened readable). Returns a string holding the line's content without its trailing newline (\r\n or \n), or Nothing once there is no more content to read.
read_allread_all(f)Reads every remaining byte from f (file handle, opened readable). Returns the remaining content as one string — possibly the empty string "" if called right at EOF, which is a legitimate result here, not the Nothing sentinel every other read in this section returns.
read_untilread_until(f, delimiter)Reads from f (file handle, opened readable) up to and including the next occurrence of delimiter (string), consuming it. Returns a string of everything read, with delimiter stripped off the end. If delimiter never appears again before EOF, returns everything remaining instead of erroring.
read_charsread_chars(f, n)Reads exactly n (number, count of Unicode characters, UTF-8 aware) characters from f (file handle, opened readable). Returns a string of up to n characters — fewer than n if the file ends first — or Nothing if already at EOF.
read_charread_char(f)Reads one character from f (file handle, opened readable), UTF-8 aware. Returns a one-character string, or Nothing at EOF.
write_linewrite_line(f, s)Writes s (string) to f (file handle, opened writable/appendable) plus a trailing \n. Returns Nothing.
write_charwrite_char(f, s)Writes s (string) to f (file handle, opened writable/appendable) with no newline added. Returns Nothing.
seekseek(f, offset, [whence="start"])Moves f's (file handle, opened readable) read cursor. offset (number, byte count) is the distance to move. whence (string, optional, default "start") is "start", "current", or "end", matching C's fseek — the point offset is measured from. Returns Nothing; errors if the resulting position falls outside [0, file length].
telltell(f)Reports f's (file handle, opened readable) current read position. Returns a number: the current byte-aligned offset from the start of the file.
rewindrewind(f)Resets f's (file handle, opened readable) read cursor to the beginning — exactly seek(f, 0). Returns Nothing.
eofeof(f)Checks whether f (file handle, opened readable) has any bytes left to read from the current position. Returns a boolean: true iff none remain.
peek_linepeek_line(f)Looks at the next line of f (file handle, opened readable) without consuming it. Returns exactly what read_line(f) would return (a string, or Nothing at EOF), but leaves the read cursor exactly where it was.
peek_charpeek_char(f)Looks at the next character of f (file handle, opened readable) without consuming it. Returns exactly what read_char(f) would return (a one-character string, or Nothing at EOF), cursor restored.
peek_bytepeek_byte(f)Looks at the next raw byte of f (file handle, opened readable) without consuming it. Returns exactly what read_byte(f) would return (a number 0-255, or Nothing at EOF), cursor restored.
read_byteread_byte(f)Reads one raw byte from f (file handle, opened readable). Returns a number in 0..=255, or Nothing at EOF.
read_bitread_bit(f)Reads one bit from f (file handle, opened readable), MSB-first, advancing a sub-byte cursor that only moves to the next byte once all 8 bits of it are consumed. Returns a number, 0 or 1, or Nothing at EOF.
read_int16read_int16(f, [endian=])Reads a signed 16-bit integer from f (file handle, opened readable). endian (string, optional, default "little", or "big") selects byte order. Returns a number, or Nothing if fewer than 2 bytes remain.
read_uint16read_uint16(f, [endian=])Reads an unsigned 16-bit integer from f (file handle, opened readable). endian (string, optional, default "little", or "big") selects byte order. Returns a number, or Nothing if fewer than 2 bytes remain.
read_int32read_int32(f, [endian=])Reads a signed 32-bit integer from f (file handle, opened readable). endian (string, optional, default "little", or "big") selects byte order. Returns a number, or Nothing if fewer than 4 bytes remain.
read_uint32read_uint32(f, [endian=])Reads an unsigned 32-bit integer from f (file handle, opened readable). endian (string, optional, default "little", or "big") selects byte order. Returns a number, or Nothing if fewer than 4 bytes remain.
read_int64read_int64(f, [endian=])Reads a signed 64-bit integer from f (file handle, opened readable). endian (string, optional, default "little", or "big") selects byte order. Returns a number, or Nothing if fewer than 8 bytes remain. Every Value here is an f64, exact only up to 2^53 — a value outside -2^53..=2^53 (about 9 quadrillion) comes back rounded to the nearest representable double, silently losing its low bits, the same limitation any language whose only numeric type is a double has (JavaScript's Number, for one).
read_uint64read_uint64(f, [endian=])Reads an unsigned 64-bit integer from f (file handle, opened readable). endian (string, optional, default "little", or "big") selects byte order. Returns a number, or Nothing if fewer than 8 bytes remain. Same 2^53 exact-precision ceiling as read_int64.
read_floatread_float(f, [endian=])Reads a 32-bit IEEE-754 float from f (file handle, opened readable). endian (string, optional, default "little", or "big") selects byte order. Returns a number, or Nothing if fewer than 4 bytes remain.
read_doubleread_double(f, [endian=])Reads a 64-bit IEEE-754 float from f (file handle, opened readable). endian (string, optional, default "little", or "big") selects byte order. Returns a number, or Nothing if fewer than 8 bytes remain.
write_bytewrite_byte(f, b)Writes one raw byte to f (file handle, opened writable/appendable). b (number) must be in 0..=255, or the call errors. Returns Nothing.
write_bitwrite_bit(f, b)Writes one bit to f (file handle, opened writable/appendable). b (number) must be 0 or 1, accumulated MSB-first into a pending byte and flushed to disk every 8 bits (close(f) flushes any final partial byte, zero-padded). Returns Nothing.
write_int16write_int16(f, n, [endian=])Writes n (number) to f (file handle, opened writable/appendable) as a signed 16-bit integer. endian (string, optional, default "little", or "big") selects byte order. Returns Nothing.
write_uint16write_uint16(f, n, [endian=])Writes n (number) to f (file handle, opened writable/appendable) as an unsigned 16-bit integer. endian (string, optional, default "little", or "big") selects byte order. Returns Nothing.
write_int32write_int32(f, n, [endian=])Writes n (number) to f (file handle, opened writable/appendable) as a signed 32-bit integer. endian (string, optional, default "little", or "big") selects byte order. Returns Nothing.
write_uint32write_uint32(f, n, [endian=])Writes n (number) to f (file handle, opened writable/appendable) as an unsigned 32-bit integer. endian (string, optional, default "little", or "big") selects byte order. Returns Nothing.
write_int64write_int64(f, n, [endian=])Writes n (number) to f (file handle, opened writable/appendable) as a signed 64-bit integer. endian (string, optional, default "little", or "big") selects byte order. Returns Nothing. Same 2^53 exact-precision ceiling on n as read_int64.
write_uint64write_uint64(f, n, [endian=])Writes n (number) to f (file handle, opened writable/appendable) as an unsigned 64-bit integer. endian (string, optional, default "little", or "big") selects byte order. Returns Nothing. Same 2^53 exact-precision ceiling on n as read_int64.
write_floatwrite_float(f, n, [endian=])Writes n (number) to f (file handle, opened writable/appendable) as a 32-bit IEEE-754 float. endian (string, optional, default "little", or "big") selects byte order. Returns Nothing.
write_doublewrite_double(f, n, [endian=])Writes n (number) to f (file handle, opened writable/appendable) as a 64-bit IEEE-754 float. endian (string, optional, default "little", or "big") selects byte order. Returns Nothing.
read_intread_int(f, [bytes=4], [signed=true], [endian="little"])The width-as-a-value counterpart of the fixed-width family above: reads bytes (a number, 1/2/4/8 only) from f (file handle, opened readable) and decodes them as an integer, with signed (boolean) and endian (string) chosen at runtime rather than by which function you called. Reach for it when a format declares its field width in a header instead of in its spec. Returns a number, or Nothing if fewer than bytes bytes remain. Every number here is an f64, so an 8-byte value above 2^53 comes back rounded — the same ceiling read_int64 documents.
write_intwrite_int(f, value, [bytes=4], [signed=true], [endian="little"])The mirror of read_int, writing value (a number) to f (file handle, opened writable/appendable) in the given width and byte order. Unlike write_int16/write_int32, this checks that value fits and errors if it does not, rather than silently wrapping: bytes=/signed= are runtime values that can come from a variable, so a wrapped result here would be far harder to notice than picking the wrong fixed-width function. Returns Nothing.
read_binread_bin(f, n)Reads up to n (a number) raw bytes from f (file handle, opened readable). A partial read is not an error — hitting the end partway gives however many bytes were there, which is what makes a "drain this file in chunks" loop composable without an eof check each time round. Returns a Vec of numbers 0-255, or Nothing only when no bytes remain at all.
write_binwrite_bin(f, bytes)The inverse of read_bin: writes raw bytes to f (file handle, opened writable/appendable). bytes is a Vec/List of numbers, every one of them a whole number in 0..=255 — anything else errors rather than being truncated into range. Returns Nothing.
huffman_encodehuffman_encode(data)Canonical Huffman coding of data (a Str, or a Vec of 0-255 byte values). Stores the code as one byte of code length per symbol, so the decoder rebuilds the tree rather than carrying it. Returns a Record with fields lengths (a length-256 Vec, the code length of each byte value, 0 for a value that never occurs), bits (a Vec of 0-255 packed code bytes), bit_len (a Num, how many of those bits are real) and symbol_count (a Num, the input length). Empty input gives none rather than a record: there is no data to encode, and none to decode back.
huffman_decodehuffman_decode(enc, [as_str=false])Inverse of huffman_encode: enc is the whole Record that call returned, passed back unchanged; as_str (named boolean, default false) asks for text instead of bytes. Returns a Vec of 0-255 numbers, or the decoded text as a Str when as_str = true.
range_encoderange_encode(data)Byte-oriented adaptive range coding of data (a Str, or a Vec of 0-255 byte values). The model adapts as it goes, so nothing but the symbol count travels alongside the payload. Returns a Record with fields bytes (a Vec of 0-255 coded bytes) and symbol_count (a Num, the input length). Empty input gives none rather than a record.
range_decoderange_decode(enc, [as_str=false])Inverse of range_encode: enc is the Record that call returned; as_str (named boolean, default false) asks for text instead of bytes. Returns a Vec of 0-255 numbers, or the decoded text as a Str when as_str = true.
rans_encoderans_encode(data)rANS entropy coding of data (a Str, or a Vec of 0-255 byte values) — a static frequency table, unlike range_encode's adaptive model, so the table travels with the payload. Returns a Record with fields freq (a length-256 Vec, the symbol frequency table), bytes (a Vec of 0-255 coded bytes) and symbol_count (a Num, the input length). Empty input gives none rather than a record.
rans_decoderans_decode(enc, [as_str=false])Inverse of rans_encode: enc is the Record that call returned; as_str (named boolean, default false) asks for text instead of bytes. Returns a Vec of 0-255 numbers, or the decoded text as a Str when as_str = true.
zlib_decompresszlib_decompress(data, [as_str=false])Inflates a zlib stream (RFC 1950 wrapper around RFC 1951 DEFLATE): data is a Str or a Vec of 0-255 byte values; as_str (named boolean, default false) asks for text instead of bytes. Errors clearly on a stream it cannot parse rather than returning partial output. Returns a Vec of 0-255 numbers, or the decompressed text as a Str when as_str = true.
cur_dir, pwdcur_dir() / pwd()Takes no arguments. cur_dir says what it gives back and pwd is what anyone who has used a shell types first, so both spellings exist rather than one being renamed out from under existing scripts. Returns a Str: the process's current working directory, using the platform's own separator.
cdcd(path)Changes the working directory to path (a Str) for the whole process, so every later relative path in the script resolves from there. Errors if path does not exist or is not a directory, rather than leaving you somewhere you did not expect. To run one command elsewhere without moving the script, use exec's cwd= instead. Returns Nothing.
list_dir, listdir, dirlist_dir(path, [pattern])The bare names inside path (a Str), sorted — "a.qu", not "tools/a.qu". Files and subdirectories both; filter them apart with file_exists/dir_exists per entry. pattern (an optional Str) keeps only the names matching a */? wildcard, e.g. "*.csv". listdir and dir are the same builtin under the names other languages and shells use. Returns a List of Str.
list_files, globlist_files([dir], [pattern], [filter=], [contains=], [size=], [recursive=])Every file matching a whole-path wildcard, as full paths, sorted — never a directory, which is what makes the content and size filters mean something on every entry. dir is a directory to search and pattern a wildcard to match (* and ? stay inside one path segment, ** crosses them); a single argument is read as a pattern when it holds a wildcard and as a directory when it does not. filter= is the keyword spelling of the pattern; contains= keeps only files whose bytes hold that text; size= compares against the byte size (">2MB", "<=100KB", "=0", with 1024-based units); recursive= searches subdirectories without writing ** yourself. glob is the same search with no filters, under the name most other languages give it. Returns a List of Str, empty when nothing matched.
file_exists, dir_existsfile_exists(path) / dir_exists(path)Whether path (a Str) exists and is a regular file / a directory. A path that is not there at all is false, not an error — its absence is the answer you asked for. Returns a Bool.
mkdirmkdir(path)Creates the directory path (a Str), including any missing parents — mkdir -p, not bare mkdir. Idempotent: a directory that already exists is success, not an error, because "make sure this exists" is what callers actually want. Returns Nothing.
make_filemake_file(path)Creates an empty file at path (a Str), truncating it if it is already there — the same promise fopen(path, "w") makes, so the two agree. Returns Nothing.
tmp_filetmp_file()Takes no arguments. Creates a new empty file under the OS temp directory with a name nothing else will collide with (process id, nanosecond clock, and a counter — any one alone has a plausible collision window). Returns a Str: its path, not an open handle, so it composes with fopen like any other path.
remove_fileremove_file(path, [recycle_bin=false])Deletes path (a Str). Errors if it does not exist or is not a regular file, rather than silently doing nothing. recycle_bin=true sends it to the OS Recycle Bin/Trash instead of deleting it permanently — default false keeps a script's existing behavior unchanged. Returns Nothing.
remove_dirremove_dir(path, [recursive=false], [recycle_bin=false])Deletes the directory path. Refuses a non-empty directory unless recursive=true — this check applies whether or not recycle_bin is set, since "may I remove a whole tree" and "should this be recoverable" are different questions. Returns Nothing.
rename_filerename_file(old, new, [on_exists="error"])Renames old to new (both Str), generally within the same filesystem. on_exists controls what happens if new already exists: "error" (default) refuses; "overwrite" replaces it; "skip" does nothing and returns false instead of erroring. Returns true if the rename happened, false if skipped. Unlike move_file, does not fall back to copy+delete across drives — a cross-drive rename_file fails with a clear error instead of silently becoming a slower, different operation.
move_filemove_file(src, dst, [on_exists="error"])Moves src to dst, falling back to copy-then-remove-the-original when a plain rename fails (e.g. across drives) — the on_exists collision check happens first either way, so the fallback can never overwrite something the fast path would have refused. Same on_exists values and return convention as rename_file.
copy_filecopy_file(src, dst, [on_exists="error"])Copies src to dst, leaving the original in place. Same on_exists values and return convention as rename_file/move_file.
create_filecreate_file(path, [on_exists="error"])make_file with a collision policy: "error" (default) refuses if path already exists, "overwrite" truncates it like make_file does unconditionally, "skip" does nothing and returns false. make_file itself is unchanged — this is the builtin for callers who need to say what should happen on collision, not a replacement for it.
*any run of characters, within one path segment
?exactly one character, within one path segment
**zero or more whole segments, so a/**/b.txt finds a/b.txt, a/x/b.txt and a/x/y/b.txt alike
contains=files whose bytes contain this text — matched against raw bytes, so it works on any file and never fails on one that is not valid UTF-8. Case-sensitive.
size=files whose byte size satisfies a comparison written as a string: ">2MB", "<=100KB", "=0", "!=0". Operators are >, >=, <, <=, =, ==, !=; with no operator at all it means equality, which is what makes size="0" read as "the empty ones".
recursive=search subdirectories too, without writing ** yourself — list_files(d, "*.html", recursive = true) is exactly list_files(d, "**/*.html").
execexec(program, [args], [shell=], [cwd=], [stdin=])Runs program (a Str) and waits, capturing what it printed. args is an optional List of arguments passed to the OS as separate items — not joined into a command line and re-split — so a path with a space in it needs no quoting rule. shell=true instead reads program as a whole command line for cmd /C (Windows) or sh -c, so pipes and && work. cwd= (a Str) runs it in that directory without moving the caller. stdin= (a Str) is written to the program's input, which is then closed, so a program reading to EOF gets exactly that and does not hang. Returns a Record with stdout (a Str), stderr (a Str), success (a Bool) and exit_code (a Num) — the same four fields python_exec/js_exec/matlab_exec already give back.
shellshell(command, [style])Hands command (a Str) to the OS shell and returns immediately, without waiting — Visual Basic's Shell, which is where the window styles come from too. style (an optional Str, positional or style=) is one of "normal" (the default), "hidden" (also spelled "ghost"), "minimized" or "maximized". Returns a Num: the process id.
mmap_openmmap_open(path)Memory-maps path (string, filesystem path) read-only. Returns an opaque mmap handle. Errors if the file doesn't exist or is empty (mapping a zero-length file is unsupported).
mmap_lenmmap_len(m)Reports the mapped file's size. m (mmap handle, from mmap_open) is the mapping to inspect. Returns a number: the total length in bytes.
mmap_readmmap_read(m, start, len)Reads a byte range out of a mapping without moving any cursor. m (mmap handle, from mmap_open) is the mapping to read from. start (number, byte offset from the beginning of the file) and len (number, byte count) select the range. Returns a Vec of len numbers, each 0-255 — the same representation read_bin uses. A range that runs past the end of the file is a clear error, not a silent truncation (unlike read_bin's "graceful partial read" — an mmap handle always knows its own length up front via mmap_len, so a past-EOF range is far more likely a caller bug than an intentional "give me whatever's left").
StreamFileStreamFile(path, [mode])A second name for exactly fopen's own machinery. path (string, filesystem path) is the file to open. mode (string, optional, default "r") accepts the same mode strings fopen does. Returns a Value::File handle — the same concrete type fopen returns — so every existing real-streaming fopen builtin (read_line, read_all, seek, eof, read_bin, ...) already works on it, not just the four listed here.
StreamURLStreamURL(url)url (string, an HTTP or HTTPS URL) is fetched eagerly with a GET request (same request http_get makes: GET only, 30s timeout, clear errors on an unreachable host or non-2xx status — see [Networking (HTTP)](concurrency.md#networking-http)). Returns an opaque stream handle wrapping the whole response body in a read-only, in-memory cursor exposing read_line/read_all/eof/close.
.read_line() / read_line(s)—s is a StreamFile/StreamURL handle. Returns one line as a string, without its trailing newline, or Nothing at EOF — identical contract on both stream kinds.
.read_all() / read_all(s)—s is a StreamFile/StreamURL handle. Returns the remaining content as one string (possibly empty at EOF).
.eof() / eof(s)—s is a StreamFile/StreamURL handle. Returns a boolean: true iff no bytes remain to read from the current position.
.close() / close(s)—s is a StreamFile/StreamURL handle. Releases it and returns Nothing. Idempotent on both kinds — closing an already-closed stream is a no-op, not an error. Reading or checking eof after close is a clear error naming the handle.
read_csvread_csv(path, [headers=true], [sep=","], [decimal="."])Reads a CSV file into a Table. path (string) is the file to read. headers (boolean, optional, default true) — false treats the first line as data instead of column names (columns are then auto-named col1, col2, ...). sep (string, optional, default ",") is the field delimiter. decimal (string, optional, default ".") is the decimal-point marker (e.g. sep=";", decimal="," for the European convention). Returns a Table with one row per data line and one column per field. table.load(path) is sugar for this (no keyword-argument forwarding — use read_csv directly for headers=/sep=/decimal=).
write_csvwrite_csv(df, path)Writes a Table to a CSV file. df (Table) is the data to write. path (string) is the destination file. Returns Nothing. table.write(df, path) is sugar for this — same argument order.
xlsx.sheetsxlsx.sheets(path)Names a workbook's worksheets without reading any of them, so a program can find out what it is holding before deciding what to load. path (string) is the .xlsx file. Returns a List of Str, the worksheet names in workbook order.
xlsx.readxlsx.read(path, [sheet], [headers=true])Reads one worksheet of a workbook into a Table, the same type read_csv produces, so everything that consumes a CSV consumes a spreadsheet unchanged. path (string) is the .xlsx file. sheet (string, optional, positional or sheet=) picks it by name; omitting it takes the first. headers (boolean, optional, default true) — false treats the first row as data and names the columns by position (A, B, C) instead. Returns a Table, one column per spreadsheet column, each column numeric or text according to what the cells hold.
xlsx.writexlsx.write(path, df, [sheet="Sheet1"])Writes a Table out as a one-worksheet workbook. path (string) is the destination, overwritten if it exists. df (Table) is the data. sheet (string, optional, positional or sheet=, default "Sheet1") names the worksheet inside the file. Returns Nothing.
codec.flac_infocodec.flac_info(src)Reads a FLAC file's header without decoding any audio, which is how to check a file is what you expect before paying for the samples. src (string path, or Vec of bytes) is the stream. Returns a Record with fields: fs (Num, the sample rate in Hz), channels (Num, how many channels the stream carries), bits (Num, bits per sample), frames (Num, or none — a FLAC stream is allowed not to declare its length, and none says so where 0 would read as an empty file).
codec.decode_flaccodec.decode_flac(src, [channel=])Decodes a FLAC file to samples. src (string path, or Vec of bytes) is the stream. channel (number, optional, named only) picks one channel out of a multi-channel file, numbered from 0. Returns a Signal when the result is a single series, and a Record of Signals when it is not — see the two forms below.
codec.decode_wavcodec.decode_wav(src, [channel=])Decodes a WAV file. Same arguments and same two return forms as codec.decode_flac. Integer WAV is normalised by 2^(bits-1), exactly as FLAC is, so the same recording in either container gives the same numbers. Float WAV passes through untouched — it is already in -1.0 ..= 1.0, and rescaling it would be the one case where normalising changes the data — and reports bits as none, because a float format has a width but no quantisation step. Returns a Signal for a single series — a mono file, or any file with channel= — and otherwise a Record with fs, bits, frames and channels, exactly as codec.decode_flac does.
codec.decode_mp3codec.decode_mp3(src, [channel=])Decodes an MP3 file. Same arguments and same two return forms as codec.decode_flac. bits is always none: MP3 is lossy, its output is real numbers rather than a quantised grid, and a plausible 16 there would invite arithmetic that means nothing. MP3 has no header — only a run of frames — so a file that is not MP3 fails by finding no frames rather than by rejecting a magic number, and the error says so. Returns a Signal for a single series — a mono file, or any file with channel= — and otherwise a Record with fs, bits, frames and channels, exactly as codec.decode_flac does.
jsonifyjsonify(value)Converts any value (any Value — number, string, Vec, Table, Record, ...) to a JSON string — exactly the save/load on-disk shape (see the link above: a {"type": ..., ...} envelope), just returned as a string instead of written to a file. Returns a string.
parse_jsonparse_json(str)jsonify's inverse. str (string) is JSON text — either a jsonify/save-style {"type": ...} envelope, or ordinary JSON from anywhere else (e.g. an HTTP API response), which is mapped in generically. Returns the reconstructed Value.
csvifycsvify(table)Converts table (Table) to CSV text — exactly write_csv's own formatting (Table::to_csv), just returned as a string instead of written to a file. Returns a string. Errors clearly on anything that isn't a Table (a bare scalar/vector has no tabular shape).
parse_csvparse_csv(str)Converts str (string, CSV text) to a Table — exactly read_csv's own parsing (Table::from_csv, the headers=true, sep=",", decimal="." defaults; use read_csv on a real file for the headers=/sep=/decimal= keyword arguments). Returns a Table.
xmlifyxmlify(value)Converts any value (any Value) to an XML string — see "The Value<->XML mapping" below. Returns a string.
parse_xmlparse_xml(str)xmlify's inverse. str (string) is XML text in xmlify's own element-naming convention. Returns the reconstructed Value.
json2csvjson2csv(str)str (string, JSON text) is converted to CSV text: exactly csvify(parse_json(str)). Returns a string.
csv2jsoncsv2json(str)str (string, CSV text) is converted to JSON. Not jsonify(parse_csv(str)) — it emits a plain JSON array of one flat {"col": value, ...} object per row (the natural shape for feeding to another JSON-consuming tool), rather than jsonify's own {"type":"table", ...} envelope. json2csv accepts either shape back, since parse_json understands both. Returns a string.
xml2jsonxml2json(str)str (string, XML text in xmlify's convention) is converted to JSON. Like csv2json, this produces the same plain array-of-row-objects shape, not jsonify(parse_xml(str))'s type-tagged envelope. Returns a string.
json2xmljson2xml(str)str (string, JSON text) is converted to XML: exactly xmlify(parse_json(str)). Returns a string.
xml2csvxml2csv(str)str (string, XML text) is converted to CSV text: exactly csvify(parse_xml(str)). Returns a string.
csv2xmlcsv2xml(str)str (string, CSV text) is converted to XML: exactly xmlify(parse_csv(str)). Returns a string.
savesave(path, name1, [name2, ...])Writes the named variables — path (string, destination file) plus one or more variable names (strings) given explicitly as extra arguments — to a JSON file, each tagged with its own type. Returns Nothing. Unlike save_all, save only ever writes the variables it is explicitly told to; there is no implicit "the whole workspace" behavior.
loadload(path)Restores every variable a save/save_all call wrote. path (string) is the file to read. Returns Nothing; each saved variable is written back into the current workspace under its original name, overwriting any existing variable of the same name (the same "load replaces" semantics MATLAB's own load has).
save_allsave_all(path)Saves literally every current binding — every user variable plus Qu's own built-in constants (pi, e, tau, none, the Qu* escape-character constants, ...) — to path (string). Returns Nothing. There is no "scratch" filtering; use save with an explicit name list to save only specific variables.
read_all_textread_all_text(path)Reads path (string) in full. Returns the whole file's content as one string. For splitting it into lines, open a handle with fopen and loop over read_line; for a file that isn't text, read it as raw bytes instead — read_bin(f, n) on a handle opened in binary mode, or read_array/mmap_read for typed/binary data.
read_valuesread_values(f, type, n)Reads n (number, count) typed values from an already-open handle. f (file handle, opened readable, positioned wherever the caller left it) is the source. type (string, one of f64/f32/i64/u64/i32/u32/i16/u16/i8/u8/byte, with the aliases double, float, int64, uint64, int32, uint32, int16, uint16 for the first eight respectively) is the element type. Returns a Vec of up to n numbers (fewer if the file runs out first). Useful mid-stream, interleaved with other reads on the same handle; for a whole file in one call, use read_array instead.
read_arrayread_array(path, [type="f64"], [endian="little"])Reads a whole binary file as one typed array, without an explicit fopen. path (string) is the file. type (string, optional, default "f64", same type names as read_values) is the element type. endian (string, optional, default "little", or "big") is the byte order. Returns a Vec of numbers — one per element in the file. Errors if the file's byte length isn't a whole multiple of the element width, rather than silently truncating a partial trailing element.
write_arraywrite_array(path, data, [type="f64"], [endian="little"])Writes a whole Vec/Mat/Signal (or a bare number/bool) to a binary file in one call, without an explicit fopen — the write-side counterpart read_array never had. path (string) is the destination, overwritten if it exists. data is the value to write; a Mat is flattened in its own column-major storage order (the same order A -> (r, c) fills), not row-major — reading it back with read_array and reshaping recovers the original matrix, since a flat binary file carries no shape of its own. type/endian as in read_array. Returns Nothing.
read_matread_mat(path)Reads a MATLAB .mat file (via the matfile crate) without needing a MATLAB installation. path (string) is the file. Returns a record with one field per saved variable, named after the variable, each holding that variable's data (a scalar, vector, or matrix depending on what was saved).
read_structread_struct(f, fields)Reads one fixed-width binary record from f (file handle, opened readable). fields (list of [name, type] pairs, e.g. [["t", "f64"], ["ch", "u16"]]) describes the record's layout in byte order, using the same type names as read_values. Returns a record with one field per entry in fields, or Nothing if fewer bytes remain than a full record needs.
read_structsread_structs(f, fields, n)Reads up to n (number) fixed-width binary records from f (file handle, opened readable), using the same fields layout read_struct takes. Returns a Table with one column per field (not one row-record per call) — the more useful shape once there are enough records to work on column-wise, stopping early (with however many complete records were read) if the file runs out.
file_sizefile_size(path)Reports a file's size without opening it. path (string) is the file to stat. Returns a number: the size in bytes on disk. Worth asking before you read something you did not write.
argvargv()Takes no arguments. Returns a list of strings: the command-line arguments given after a literal -- in the invocation (e.g. qu run analyse.qu -- data.csv 1000 gives ("data.csv", "1000")).
getenvgetenv(name)Reads one environment variable. name (string) is the variable's name. Returns its value as a string, or none if it isn't set — so getenv("HOME") ?? "/tmp" is the idiom for a default.
write_reportwrite_report(path)Writes a standalone HTML report to path (string) — every figure, table, and printed line the script has produced up to this point in execution, bundled into one file with nothing linked from outside it. Returns Nothing.
json2csvjson2csv(text)Converts text (string, JSON) to CSV text. Returns a string. Exactly csvify(parse_json(text)); accepts both jsonify's type-tagged JSON and the plain row-object JSON csv2json produces.
csv2jsoncsv2json(text)Converts text (string, CSV) to JSON. Returns a string: a plain JSON array of one flat {"col": value, ...} object per row — not jsonify's type-tagged envelope. The round trip through json2csv is lossy in one direction: CSV carries no type tags, so a value that comes back is a number or string by looking at it, not by a recorded type.
csv2xml, xml2csvcsv2xml(text) / xml2csv(text)The same conversion pair for XML, and exact compositions of the primitives above: csv2xml(text) is xmlify(parse_csv(text)); xml2csv(text) is csvify(parse_xml(text)). Both take/return a string.
json2xmljson2xml(text)Converts text (string, JSON) to XML text. Returns a string. Exactly xmlify(parse_json(text)).
xml2jsonxml2json(text)Converts text (string, XML in xmlify's own tag convention) to JSON. Returns a string: the same plain array-of-row-objects shape csv2json produces, not jsonify(parse_xml(text))'s type-tagged envelope. parse_xml (and so this function) only understands the specific element/attribute conventions xmlify itself produces — arbitrary hand-written XML with its own attributes is not a supported input and errors clearly rather than being guessed at.
python_exec, js_execpython_exec(code, [vars=]) / js_exec(code, [vars=])Runs code (string, source in the guest language) as a subprocess. vars (optional, a Record) is injected into the guest as ordinary variables. The guest writes its result as JSON to an injected output-path variable (_qu_output_path), which this call reads back. Returns a record {stdout, stderr, success, exit_code, result}: captured output streams, whether the process exited cleanly, its exit code, and the parsed JSON result. For a library with no Qu equivalent yet — and a dependency to be honest about in anything published using it.
matlab_execmatlab_exec(code, [vars=])The same contract as python_exec/js_exec, run through a local MATLAB installation instead: code's result is written to an injected qu_output_path variable (no leading underscore — MATLAB identifiers can't start with one) and the call returns the same {stdout, stderr, success, exit_code, result} record. Requires a working, licensed local MATLAB install; a failure (e.g. an expired license) does not panic — it comes back as success = false with MATLAB's own error text in stderr. Returns a Record with fields stdout (a Str), stderr (a Str), success (a Bool), exit_code (a Num) and result (whatever the parsed JSON held, or none if MATLAB wrote no result).

Concurrency chapter → 49

run_forrun_for(duration)Drives every registered every/after/at timer across a simulated virtual timeline, not a real wall-clock sleep. duration (number — seconds, same convention as every/after/at's own interval arguments) is how far along that virtual timeline to advance. Timers interleave by scheduled fire time, the way a real event loop would. Requires at least one timer to already be registered, or it errors. Returns an integer: the total number of timer firings that occurred while advancing.
pump_watchespump_watches()Takes no arguments. Checks every registered watch ... end (§ Watches, below) exactly ONCE, right now, against its real current external state, firing the body of any whose state has genuinely changed since the last check. Unlike run_for, this is real-time, not simulated — a file's mtime, a variable's value, and an HTTP response body have no "virtual" equivalent to fast-forward through. Requires at least one watch to already be registered, or it errors. Returns an integer: the number of watches that fired on this call.
spawnspawn("fnName", arg1, arg2, ...)Runs an already-defined user function on rayon's global thread pool (the Worker abstraction). "fnName" (string) names a function already defined in this script; arg1, arg2, ... (any number of values of any type, zero or more) are forwarded to it positionally, exactly as if calling it directly. The worker gets an ISOLATED snapshot of the current globals and function table plus a freshly-drawn RNG seed — never the live shared environment — so nothing a worker does can race with the caller or another worker. Only a user-defined function can be spawned, never a builtin (builtins like plot/savefig mutate state with no meaning off the main thread). Returns a Worker handle (a lightweight opaque token, type(w) == "worker") immediately, before the function has necessarily finished; join/worker_done observe completion via a Mutex+Condvar under the hood, since the pool's own dispatch is fire-and-forget.
joinjoin(w) or join(list[, delimiter])Two unrelated forms selected by the argument's type. On a Worker handle w (from spawn): blocks the calling thread until that worker finishes, then returns its function's return value (whatever type that function produces), or re-raises whatever error the worker's body raised as an ordinary runtime error here on the caller. Consumes the handle — joining the same worker twice is an error. On a List of strings list (with an optional string delimiter, default ""): the unrelated collection form, concatenating every element into one string with delimiter inserted between each pair — the inverse of split. Returns a string in this form.
worker_doneworker_done(w)Non-blocking check of whether worker w (a Worker handle from spawn) has finished. Returns a boolean (true/false). The handle stays valid either way — still needs a later join(w) to actually retrieve the result or error.
pmappmap(xs, f)Applies a named user function to every element of xs (a List/vector of any length, elements of any type) across a work-stealing thread pool (rayon), same share-nothing isolation model as spawn/parallel for (each element gets its own env/funcs snapshot and an RNG stream drawn up front from the parent's stream, for reproducibility). f is a one-argument function applied to each element — the function itself (including a lambda, which is carried to the workers), or a Str naming one you defined; a builtin is accepted as a value but refused as a quoted name. Returns a new List/vector of the same length, holding each call's return value in the original order. xs comes first so
mutexmutex(initial)Creates a shared mutable cell holding initial (any value, of any type — the mutex has no fixed element type). Returns a Mutex handle (type(m) == "mutex"); cloning that handle (assigning it, capturing it into a worker's snapshot) shares the same underlying cell rather than copying the value inside it.
mutex_getmutex_get(m)Reads the current value out of mutex handle m. Locked only for the instant it takes to clone the value out. Returns whatever value is currently stored (same type as the last mutex_set/mutex/mutex_add/mutex_update put there).
mutex_setmutex_set(m, v)Overwrites the value stored in mutex handle m with v (any value, any type), discarding the old one unconditionally — no read of the previous value is involved. Returns none.
mutex_addmutex_add(m, delta)Atomic read-modify-write in a single lock acquisition (unlike mutex_set(m, mutex_get(m) + delta), which would race). m is a Mutex handle whose current stored value must be numeric; delta (number, may be negative) is added to it in place. The one operation you want for a shared counter/accumulator across parallel for iterations. Returns the new value (number) after the addition.
mutex_updatemutex_update(m, "fnName")Atomic read-modify-write via an arbitrary user function called with the current value as its one argument — for accumulations mutex_add can't express (a running max, an append-only log). m is a Mutex handle; "fnName" (string) names a one-argument user-defined function whose return value becomes the mutex's new stored value. The lock is held for the whole call, so fnName's body must not touch this same mutex itself, directly or indirectly — that deadlocks. Returns the new value (whatever fnName returned).
semaphoresemaphore(n)Creates a counting semaphore with n (integer, must be non-negative) initial permits. Returns a Semaphore handle (type(s) == "semaphore"); cloning it shares the same counter, the same convention Mutex/Channel use.
semaphore_acquiresemaphore_acquire(s)Blocks the calling thread until a permit is free on semaphore handle s, then takes it (decrementing the available count by one). Returns none. There is no RAII/finally in Qu, so releasing on an error path (e.g. inside a try/catch) is the caller's own responsibility.
semaphore_releasesemaphore_release(s)Returns one permit to semaphore handle s (incrementing the available count by one). Returns none. Releasing more times than acquired just grows the available count past its starting size — not checked, since a semaphore used purely as a signal (more releases than acquires) is a legitimate pattern.
semaphore_availablesemaphore_available(s)Non-blocking snapshot of how many permits are free right now on semaphore handle s. Returns an integer — a diagnostic, not a guarantee, since it can change the instant after it's read.
channelchannel()Takes no arguments. Creates a new, empty channel. Returns a Channel handle (type(ch) == "channel"); cloning it shares the same underlying queue, not a separate copy.
channel_sendchannel_send(ch, value)Pushes value (any value, any type) onto channel ch's queue and wakes one waiting channel_recv. Returns none. Never blocks — the queue is unbounded, so a fast producer can run arbitrarily far ahead of a slow consumer.
channel_recvchannel_recv(ch)Blocks the calling thread until a value is available on channel ch, then pops and returns it (FIFO — oldest channel_sendd value first). Returns the sent value itself — whatever type the matching channel_send put in.
channel_try_recvchannel_try_recv(ch)Non-blocking counterpart to channel_recv: returns none (Nothing) immediately if nothing is queued on channel ch right now, instead of waiting; otherwise pops and returns the next value the same way channel_recv would. Returns the sent value itself, whatever type it is, or none when the channel is empty.
channel_lenchannel_len(ch)How many messages are queued right now on channel ch, without consuming any of them. Returns an integer — a diagnostic/backpressure-aware-producer helper, not needed for ordinary send/recv.
queuequeue()Takes no arguments. Creates an empty deferred-job list. Returns a Queue handle (type(q) == "queue"); cloning it shares the same underlying list of pending jobs, not a separate copy.
.pushq.push("fnName", arg1, arg2, ..., on="any")Enqueues a call onto queue q, to run later when run drains it. "fnName" (string) names an already-defined user function — never a builtin; arg1, arg2, ... (zero or more values of any type) are the arguments to call it with, evaluated and captured right now, not when the job later runs. on= is an optional string kwarg, one of "cpu", "gpu", or "any" (default "any") — a resource tag consulted only by run q on any's auto-routing across every registered pool; a run q on <namedPool> ignores it, since the caller already said exactly where the job runs. Returns none; mutates q in place.
pool (named)pool <name> with cpu=N[, gpu=N][, remote=(...)] [policy=round_robin] [on full=queue] end poolA statement, not an expression — builds a persistent, resource-limited worker pool and registers it under the bare identifier name (so run ... on any can find it too, and any later run ... on name can reference it by that same identifier). cpu=N (integer) is the number of local worker threads. gpu=N (integer) parses but is not implemented — a nonzero value errors clearly. policy= only implements round_robin. on full= only implements queue. remote=(...) (a list of "host:port" strings) is covered under Distributed pools below. Produces no value of its own.
pool (anonymous)pool(n)n (integer) local cpu workers, fixed round_robin policy and on full=queue behavior, never registered under any name — scoped to whichever single run ... on pool(n) call uses it. Returns a Pool handle (type(p) == "pool").
run ... onrun <queue> on <pool> / run <queue> on anyDrains queue <queue> (a Queue handle) and runs every job on <pool> (a Pool handle, a registered pool name, or the bare keyword any), blocking the caller until all finish. Returns a List of each job's return value in submission order (never completion order) — element i is the result of the i-th .push call. on any auto-routes each job to whichever registered pool matching its on= tag currently has the most free capacity. A job's error is never swallowed — the first one, in submission order, propagates out of run as an ordinary runtime error.
listen_poollisten_pool(port, allow=(...))port (integer, 0-65535) is the TCP port to bind. allow=(...) (a list of strings, required and non-empty) names exactly which already-defined functions this listener may run for a remote caller — a hard security requirement, not an option. Binds port and blocks forever (this call never returns under normal operation), accepting job requests over TCP and running only functions named in allow. A request for anything else is rejected cleanly (never a crash, never executed anyway). Each accepted job runs on a fresh, isolated interpreter seeded from a snapshot of the listening script's own globals/functions, taken once when listen_pool is called. Returns nothing, because it never returns: the call blocks for the life of the listener.
pool ... remote=pool <name> with cpu=N, remote=("host:port", ...) ... end poolAdds one or more remote listeners as additional workers alongside cpu. remote= is a list of strings, each a "host:port" address of another process running listen_pool. cpu (integer) is optional when remote names at least one address (a remote-only pool, pool p with remote=(...) end pool, is valid). A single address may be written bare (remote = "host:port") — Qu's list literal is a parenthesized tuple, and a single-element (x) without a trailing comma is just grouping, not a one-element list, so the bare-string form sidesteps that trap. Produces no value of its own (a statement, like the plain named pool form).
http_gethttp_get(url)url (string, must include the scheme, e.g. "https://example.com/") is the address to fetch. Issues an HTTP(S) GET request and returns the response body as a string (UTF-8, decoded lossily — the same convention read_all_text/text-mode read_all already use). GET-only in this v1: no custom headers, auth, or POST. A 30-second timeout applies to the whole request (connect + read) — an unreachable host errors clearly rather than hanging forever. A non-2xx response is a clear error naming the actual status code. Returns a Str: the response body. No status code and no headers come back with it — a call that returns at all succeeded, and everything else raised.
watch filewatch file(path) [do] ... endpath (string, a filesystem path). Fires when path's modification time differs from the last check (polled via the same filetime crate touch uses — not the notify crate's OS-level filesystem events, a deliberate v1 scope cut: wiring an async filesystem watcher into this single-threaded, cooperatively-pumped interpreter is a separate concurrency design question). A path that doesn't exist yet at registration also fires once it's later created. A statement — registers the watch and its body, produces no value.
watch <name>watch <name> [do] ... end<name> (a bare variable identifier, not a string). Fires when that variable's current value differs from its value as of the last check (same equality == uses) — reassigning the identical value never fires. Checked by reading the named variable fresh at each pump_watches() call, not by hooking every assignment in the interpreter, so scripts that never use watch pay zero extra cost on ordinary variable writes. A statement, no value.
watch urlwatch url(url, [interval_seconds=]) [do] ... endurl (string, must include the scheme). interval_seconds (optional number, default 5, real wall-clock seconds) bounds how often this actually fetches over the network. Fires when a fresh http_get-equivalent fetch of url's response body differs from the last fetch; a pump_watches() call landing before the interval has elapsed is a cheap no-op that doesn't touch the network. The baseline is one real fetch performed at registration time. A statement, no value.
serial_openserial_open(port, baud_rate, [data_bits=8, stop_bits=1, parity="none", timeout_ms=1000])Opens a real OS serial port. port (string) is the OS device name, e.g. "COM3" on Windows or "/dev/ttyUSB0" on Linux/macOS. baud_rate (integer, must be positive) is the line speed. data_bits (optional integer, default 8) accepts 5/6/7/8. stop_bits (optional integer, default 1) accepts 1 or 2 (the underlying crate has no 1.5-stop-bit option). parity (optional string, default "none") accepts "none"/"even"/"odd". timeout_ms (optional number, default 1000, milliseconds) bounds every blocking read below — see the note on timeouts vs. EOF further down. Returns a Serial handle. Errors clearly (naming the port) if the port doesn't exist, is already open elsewhere, or the OS refuses it.
serial_portsserial_ports()Takes no arguments. Lists the short names of every serial device the OS currently reports (e.g. "COM3" on Windows, "/dev/ttyUSB0" on Linux/macOS). Returns a List of strings. An empty list on a machine with no serial hardware attached is a correct, honest result, not an error.
.read_line()read_line(conn)conn (a Serial handle from serial_open). Reads one line without its trailing newline, same contract as Value::File's own read_line — except at end of data: a serial device has no natural EOF, so a read that times out with nothing at all collected yet returns Nothing (a string otherwise; composes with ??, same as EOF elsewhere), while a timeout after some bytes already arrived returns that partial line as-is (a string).
.read_bytes(n)read_bytes(conn, n)conn (a Serial handle); n (integer, the maximum number of bytes to collect). Blocks (bounded by the handle's own timeout_ms) collecting up to n bytes; may return FEWER than n if the timeout elapses first — an honest short read, not an error or a hang. Returns a Vec of 0-255 integer values (length between 0 and n), the same representation read_bin uses.
.available()available(conn)conn (a Serial handle). Returns an integer: how many bytes are currently waiting in the OS's input buffer, without blocking.
.write()write(conn, data)conn (a Serial handle); data may be a string (written as UTF-8 bytes) or a Vec of byte values 0-255. Writes straight through to the wire, no added newline. Returns none.
.close()close(conn)conn (a Serial handle). Releases the OS handle. Returns none. Idempotent, like Value::File's own close — calling it again on an already-closed handle is a harmless no-op.
nownow()Takes no arguments. Returns the current time (UTC) as a Record with integer fields .year, .month, .day, .hour, .minute, .second, plus .unix (number, Unix epoch seconds, for arithmetic) and .iso (string, an ISO-8601 timestamp you can print or store).
sleepsleep(seconds)seconds (number, fractional values honoured, e.g. 0.5 for half a second). Pauses the calling thread for that long. Returns none.
sysinfosysinfo()Takes no arguments. Returns a Record describing this machine: .os/.arch/.hostname/.cpu/.qu_version/.build (strings), .logical_cores (integer), .physical_cores and .total_memory (number, or none when the platform doesn't report them), and .gpu/.gpu_reason (string, or none/an explanatory string when this build has no GPU support). What to branch on before sizing a pool.
mem_usagemem_usage()Takes no arguments. Returns this process's resident-set size right now, in bytes (a Num) — what THIS run has actually mapped in, not the machine's total memory (sysinfo()'s job). none on a platform this isn't implemented for (anything but Windows and Linux today). Call it before and after the code being compared and take the difference: the question "which of these two ways of computing the same result used more memory" that timing alone can't answer. See also profile_start/profile_end (repl-diagnostics chapter) for the same reading bundled with elapsed time into one clean before/after window, instead of two bare mem_usage() calls.
poolpool(n)n (integer, number of local cpu workers). Returns a Pool handle, unregistered and scoped to wherever it's used. pmap makes one of these implicitly under the hood; make it explicit (or use the named pool ... end pool form above) when several stages should share workers rather than each starting their own.
tcp_listen, tcp_accepttcp_listen(port), tcp_accept(listener)tcp_listen(port): port (integer 0-65535, 0 asks the OS for a free ephemeral port) binds and returns a TcpListener handle immediately (does not block). tcp_accept(listener): takes that handle and blocks the calling thread until a client connects, then returns a TcpConn handle for the new connection — call it in a loop to accept multiple clients, one call per connection. Returns a TcpListener handle from tcp_listen, and a TcpConn handle from tcp_accept.
tcp_connect, tcp_porttcp_connect(host, port), tcp_port(listener)tcp_connect(host, port): host (string, hostname or IP) and port (integer 0-65535) — blocks until connected (or the OS gives up and errors), returning a TcpConn handle, the client-side mirror of tcp_accept. tcp_port(listener): takes a TcpListener handle and returns an integer, the port it actually bound — which matters when you asked for 0 and let the system choose. Returns a TcpConn handle from tcp_connect, and the bound port as a scalar Num from tcp_port.
tcp_send, tcp_recvtcp_send(sock, data), tcp_recv(sock, [max_bytes=4096])tcp_send: sock (a TcpConn handle) and data (string, written as UTF-8 bytes) — returns none. tcp_recv: sock (a TcpConn handle) and an optional integer kwarg max_bytes (default 4096) — blocks until at least one byte arrives, reads up to max_bytes, and returns it as a string (UTF-8, decoded lossily), or none if the peer closed the connection (a zero-byte read). Neither call frames the message for you — TCP is a stream, so a length prefix or delimiter is yours to add if you need distinct messages. Returns a Str of the bytes read from tcp_recv, or none once the peer has closed; tcp_send hands back no value.
tcp_closetcp_close(sock)sock must be a TcpConn handle (from tcp_accept/tcp_connect) — not a TcpListener; calling it on a listener errors, since a listener has no explicit close and simply releases its OS socket when the handle is dropped. Shuts the connection down and marks it closed; returns none. Idempotent — closing an already-closed connection is a harmless no-op, not an error. Returns Nothing.
availableavailable(conn)conn (a Serial handle from serial_open). Returns an integer: bytes waiting on the OS's serial input buffer right now, without blocking. Check it before a read you do not want to block on.
read_bytesread_bytes(conn, n)conn (a Serial handle); n (integer, maximum bytes to collect). Blocks up to the handle's timeout_ms, returning a Vec of 0-255 integer values — possibly fewer than n if the timeout elapses first. Use read_line instead when the data is text with a line terminator. Returns a Vec of 0-255 integer values, at most n long and possibly shorter.

REPL & diagnostics chapter → 74

echoecho(v1, v2, ...)Alias of print/disp/writeline. Takes any number of positional arguments v1, v2, ... of any printable type (number, string, matrix, struct, ...) and prints each argument's display form space-joined on one line, followed by a newline. Returns none.
writewrite(v1, v2, ...) or write(fileHandle, s)Dispatches on the type of the first argument. With ordinary values v1, v2, ... (any printable type): prints them space-joined, without a trailing newline (unlike print/echo). With a fileHandle (the handle object returned by fopen) as the first argument and a string s as the second: instead writes the raw string s to that open file, with no newline added and no console output. Returns none in both forms.
errorerror(msg)Takes one argument, msg (a string, typically built with {...} interpolation), and raises an EvalError carrying that message. Never returns normally — control passes to the nearest enclosing try/catch, where the caught exception object exposes the string as .message; uncaught, it aborts the script. Returns nothing, ever — there is no value to receive, because control leaves the call.
warnwarn(msg)Takes one argument, msg (a string), and prints warning: {msg} to the console. Non-fatal — execution continues on the next line, unlike error. Returns Nothing.
explainexplain("fnName")Takes one argument, fnName (a string naming a user-defined function), and returns a string report — it does not print by itself, so wrap it in print(...) to see it. The report says whether that function is running the fast register-only ("soft-compiled") tier or falls back to the ordinary tree-walking interpreter, and — when interpreted — which construct disqualified it (a call to another user function, a loop, indexing, or a non-numeric value). This is the M4 "Phase 0" diagnostic surface: calling explain triggers the same lazy eligibility check an actual call would, so it works even before the function has ever been called, letting a script author ask "why is this function still slow" and get a real answer instead of a black box. Returns a Str, the report itself — the call prints none of it for you.
write(v1, v2, ...)Prints the values space-joined to the console, with no trailing newline — the ordinary-value form.
write(fileHandle, s)Writes the string s verbatim to the already-open file fileHandle; no console output, no newline added.
tictic()Takes no arguments. Starts (or restarts) the single global stopwatch. timer.start() is sugar for this — see below. Returns Nothing.
toctoc()Takes no arguments. Returns a number: elapsed seconds (float, fractional) since the last tic(). Does not clear the start, so repeated toc() calls measure from the same tic() — useful for lap-timing a loop. Errors if called before any tic(). timer.elapsed() and timer.stop() are both sugar for this (see below) — toc() was already a non-resetting peek, so both aliases inherit that for free.
progressprogress(i, n)A tqdm-style progress bar, called once per loop iteration: i is the 0-based index (0 through n - 1), n is the total count. Draws [####------] 42% (420/1000) 123.4/s eta 4.7s and redraws in place with a carriage return, throttled to at most once per 100ms (the first and last frame always draw regardless). Resets its own clock whenever i is 0, so a second loop in the same script gets its own rate and ETA. Errors if i is out of 0..n-1 — the common mistake is calling it from for i = 1 to n instead of for i = 0 to n - 1. Returns Nothing.
timer / preciseTimertimer([interval]) / preciseTimer([interval])Takes one optional positional argument, interval (a number, in seconds; irrelevant for plain profiling use) — the tick period on elapsed(t)/on elapsedOnce(t) fire at. Returns a standalone, controllable timer object (a handle, conventionally bound to a variable t) — the fix for tic/toc's single-global-slot limitation. Starts not running; start(t) begins counting. preciseTimer sets an internal precise marker on the returned object but is otherwise identical to timer — both use the same monotonic clock today; the distinct name is for intent-signaling and forward compatibility. Not the same feature as the bare timer.start()/timer.elapsed()/timer.stop() sugar below — this row produces a real, independent, per-variable object (t = timer(), t.start(), t.pause(), ...); the sugar is the single-global-slot tic/toc MATLAB-style convenience wearing nicer verbs. Pick the object form for nested/concurrent/pausable timing, the bare sugar for quick single-shot profiling.
startstart(t)Takes one argument, t (a timer object from timer()/preciseTimer()). Begins counting, or resumes from pause. Returns none; idempotent on an already-running timer.
pausepause(t)Takes one argument, t (a timer object). Freezes the count, keeping the accumulated total so start resumes from where it left off. Returns none; idempotent on an already-paused timer.
elapsedelapsed(t)Takes one argument, t (a timer object). Returns a number: elapsed seconds so far. A pure read — never stops or resets the timer, callable regardless of running state.
restartrestart(t)Takes one argument, t (a timer object). Returns a number: the elapsed time up to this call (the completed "lap"), then resets the object to zero and immediately starts it running again — a one-call lap/checkpoint pattern for timing each iteration of a loop.
stopstop(t)Takes one argument, t (a timer object). Freezes the timer and resets the count to zero (unlike pause, which keeps it); returns none. Also stops any on elapsed(t)/on elapsedOnce(t) registration from firing until started again. The handle remains valid and reusable. Returns Nothing.
profile_startprofile_start()Takes no arguments. Starts a named profiling window and returns a Record handle -- t0 (wall-clock seconds) and mem0 (RSS bytes, NaN if unsupported) -- to pass unmodified to profile_end. t0/mem0 are semi-internal (read by profile_end, not meant to be inspected directly); mem0 is NaN on a platform current_rss_bytes doesn't support (anything but Windows/Linux). Because the handle is an ordinary value rather than mutated global state (unlike tic), multiple windows — p1 = profile_start(), p2 = profile_start() — can overlap or nest without clobbering each other. Uses SystemTime rather than a monotonic clock, trading tic/toc's clock-step immunity for a value that can round-trip through a Record field — prefer tic/toc for sub-millisecond or clock-step-sensitive timing. See also timer/preciseTimer above for a controllable object, and profiling_mode/profile_stats below for per-builtin call-count and time attribution (no memory) across a whole recording window instead of one region's time and memory.
profile_endprofile_end(handle)Takes one argument, handle (the Record returned by profile_start(), unmodified). Closes the window and returns a Record with fields time (elapsed seconds) and mem (RSS delta in bytes, NaN if either sample was NaN, e.g. on an unsupported platform). mem is mem_now - mem0, sampled once at each end rather than polled, so a large allocation that also frees before profile_end runs is invisible to it — the same coarse-sampling trade-off qu-cli's own --profile/--max-memory watchdog documents for itself. Errors if handle is missing t0/mem0 or either field isn't a number, naming which field and why. See also tic/toc above for simpler lap timing with no memory tracking, and profiling_mode/profile_stats below for call-count/time attribution across many builtin calls instead of one region.
estimate_complexityestimate_complexity(sizes, times)Takes two same-length numeric vectors/lists: sizes (the problem sizes swept over) and times (the matching elapsed times in seconds, e.g. from toc() at each size) — at least 3 matching points are required in both. Fits several candidate growth models (O(1), O(log n), O(n), O(n log n), O(n^2), O(n^3)) to the data by least squares and picks whichever has the best R², rather than a naive log-log slope (which misclassifies O(log n)/O(n log n)). As a side effect it prints the fit (label, R², coefficient); it also returns the label as a string (e.g. "O(n)"). Meant to pair with tic/toc: sweep over increasing problem sizes, record elapsed time at each, then call this on the two vectors. Returns a Str, the winning model's label (e.g. "O(n)").
track (alias param)track(v)Takes one argument, v — a plain number or a matrix (a bare [...] list literal is promoted to a column, matching to_matrix's convention). Returns a tracked value: internally a fresh leaf node on the gradient tape with no inputs, so grad treats it as a differentiation root, while remaining numerically transparent (a tracked scalar still reports type(...) as number; a tracked matrix prints as tensor([...], node #N)). Calling track on an already-tracked value is a no-op.
stop_gradstop_grad(v)Takes one argument, v — a tracked value produced by track/param. Returns the plain, untracked inner value (same numeric content and shape) detached from the tape, so gradients don't flow through it — e.g. holding a target/label steady, or truncating backprop through time.
gradgrad(loss, wrt=X) or grad(loss, X, Y, ...)Takes loss — a tracked scalar that is the result of a computation built from tracked inputs — plus either a keyword argument wrt=X (one tracked tensor X) or one or more positional tracked tensors X, Y, .... Runs the backprop walk over the tape. The keyword form wrt=X returns a single gradient value with the same shape as X (a number for a scalar X, a matrix for a matrix X); the positional form grad(loss, X, Y, ...) returns a List of such gradients, one per argument, in the same order (positional rather than wrt=[X, Y], because Qu's [...] bracket literal is numeric-matrix syntax and would silently flatten a list of tensors down to plain numbers, losing the node identity grad needs).
grad(loss, wrt=X)A single gradient value shaped like X — a number for a scalar X, a matrix for a matrix X.
grad(loss, X, Y, ...)A List of gradient values, one per positional argument, in the same order.
rand / randnrand(rows[, cols]) / randn(rows[, cols])Takes rows (a number, the row count) and an optional cols (a number, the column count; when omitted, defaults to 1, giving a rows×1 column vector). Draws rows*cols samples — uniform on [0, 1) for rand, standard-normal (mean 0, variance 1) for randn — and returns them as a rows×cols numeric matrix, drawn from the persistent RNG stream. An optional seed= keyword argument (a number) switches to a fresh, independent, reproducible local stream instead of the persistent one, without disturbing the persistent stream's state.
seedseed(n)Takes one argument, n (a number, the seed value). Reseeds the interpreter's persistent random stream and returns none, so subsequent unseeded rand/randn calls (and anything downstream that draws from self.rng, including spawn/pmap worker seeds) become reproducible — two calls to seed(n) with the same n are followed by identical draws.
rand(rows) / randn(rows)cols defaults to 1 — returns a rows×1 column vector, drawn from the persistent stream.
rand(rows, cols) / randn(rows, cols)Returns a rows×cols matrix, drawn from the persistent stream.
rand(rows, cols, seed=n)Draws from a fresh, independent, local stream seeded with n instead — the persistent stream's position is left completely untouched, which is the surprising part.
HzHertz, base unit (×1)
kHzKilohertz (×1e3)
MHzMegahertz (×1e6)
GHzGigahertz (×1e9)
sSeconds, base unit (×1)
msMilliseconds (×1e-3)
usMicroseconds (×1e-6)
nsNanoseconds (×1e-9)
VVolts, base unit (×1)
mVMillivolts (×1e-3)
kVKilovolts (×1e3)
AAmperes, base unit (×1)
mAMilliamperes (×1e-3)
uAMicroamperes (×1e-6)
OhmOhms, base unit (×1)
mOhmMilliohms (×1e-3)
kOhmKiloohms (×1e3)
MOhmMegaohms (×1e6)
FFarads, base unit (×1)
uFMicrofarads (×1e-6)
nFNanofarads (×1e-9)
pFPicofarads (×1e-12)
HHenries, base unit (×1)
mHMillihenries (×1e-3)
uHMicrohenries (×1e-6)
WWatts, base unit (×1)
mWMilliwatts (×1e-3)
kWKilowatts (×1e3)
kBare SI prefix, no base unit (×1e3)
MBare SI prefix, no base unit (×1e6)
GBare SI prefix, no base unit (×1e9)
mBare SI prefix, no base unit (×1e-3)
uBare SI prefix, no base unit (×1e-6)
pBare SI prefix, no base unit (×1e-12)
aBare SI prefix, no base unit (×1e-18)
unit_scaleunit_scale(name)name: a string. Returns the scale factor a unit name = ... declaration registered, or errors naming name if nothing was ever declared under it.
textex(x)Takes one argument, x — any value (number, complex number, vector, or matrix). Returns a string: a complete LaTeX math-mode snippet wrapped in $...$ delimiters. Numbers/complex values reuse the same scientific-notation splitting as ordinary display formatting but rendered as \times 10^{n} (e.g. 4.7e-8 becomes $4.7 \times 10^{-8}$); vectors and matrices become a bmatrix environment (e.g. [1, 2, 3] becomes $\begin{bmatrix} 1 & 2 & 3 \end{bmatrix}$).
printtexprinttex(x)Takes one argument, x — any value, same acceptance as tex. Same rendering as tex(x), printed directly to the console (with a trailing newline) instead of returned. Returns none.
builtinsbuiltins()Takes no arguments. Returns a List of strings: every name the engine answers to (hundreds of entries; the exact count grows as builtins are added). The builtin index is this list joined against the chapters.
aproposapropos("filter")Takes one argument, a search substring (a string, e.g. "filter"). Returns a List of strings: every builtin name containing that substring, in engine-registration order. Returns a list rather than printing, so a script can count (len(...)) or loop over the hits.
helphelp("curve_fit")Takes one argument, a builtin name (a string, e.g. "curve_fit"). Prints what is known about that name directly to the console and returns none — that it exists, near matches when it does not (e.g. help("not_a_real_fn") suggests close spellings), and where the worked examples live. Honest about its limits — the engine carries no per-builtin prose. Returns Nothing; the report goes straight to the console.
sandbox_modesandbox_mode(on)Takes one argument, on (a boolean). Refuses file and network access for the rest of the session and returns none. One way only — passing sandbox_mode(false) does not turn it back off, which is the point; e.g. after sandbox_mode(true), a subsequent fopen(path, "w") raises a catchable error instead of opening the file. Returns Nothing.
profiling_mode, profile_statsprofiling_mode(true)profiling_mode takes one argument, a boolean (true to start recording, false to stop), and returns none. profile_stats() takes no arguments and returns a Table value with columns function, calls, and seconds, one row per builtin called while recording was on. Record per-builtin time and call counts, then read them back; off by default, because the recording itself costs something. Returns a Table from profile_stats, with columns function, calls and seconds; profiling_mode hands back no value. See also the Timers section above, which lays out all four of Qu's profiling/timing mechanisms side by side (tic/toc, timer/preciseTimer, profile_start/profile_end, and this one) and says when to reach for which.
device_useddevice_used()Takes no arguments. Returns a struct-like value with two fields: .device (a string, e.g. "cpu" or a GPU device name) and .gpu_dispatches (a number, the count of operations actually dispatched to the GPU). Reports where the accelerated work actually went — a GPU that quietly fell back to the CPU is the failure this catches.
gpu_probe_infogpu_probe_info()Takes no arguments. Returns a struct-like value with three fields: .available (a boolean, whether a GPU backend was found), .crossover (a number, the measured matrix/problem size above which the GPU wins over the CPU — inf on a build without GPU support), and .samples (a list of the timed sample points used to compute the crossover). Reports what the GPU probe found at startup.

Not in a chapter table 4

These names are in the engine and answer to a call, but no chapter table describes them yet. The list is computed by comparing the interpreter's own name table against the chapters, so it is the documentation backlog rather than a claim about the language. apropos("filter") finds them from inside a running program.

circuit_impedance image preciseTimer timer