FrankenNumPy

Docs/Architecture

Algorithm Catalog

On this page 13 sections

FFT

Hybrid approach supporting arbitrary input lengths:

  • Power-of-two lengths: Cooley–Tukey decimation-in-time (DIT). Recursively splits into even/odd subsequences, applies butterfly operations with twiddle factors exp(-2πi·k/N).
  • Non-power-of-two lengths: Bluestein's chirp-Z transform. Rewrites the DFT as a convolution, zero-pads to the next power of two, uses Cooley–Tukey for the convolution, then extracts the result.

All 18 transforms (fft, ifft, fft2, ifft2, fftn, ifftn, rfft, irfft, rfft2, irfft2, rfftn, irfftn, hfft, ihfft, plus fftfreq, rfftfreq, fftshift, ifftshift) build on these two primitives in the Rust API (fnp-ufunc). Multi-dimensional transforms apply 1-D FFTs sequentially along each axis. From Python, 17 of the 18 fnp_python.fft entry points call numpy.fft; only fftfreq is native.

Signal Processing

  • convolve(a, v, mode): Direct O(n·m) convolution; supports full (default, length n+m−1), same, and valid modes. Flips the kernel and slides it across the input.
  • correlate(a, v): Cross-correlation implemented as convolve(a, v[::-1]).
  • convolve2d / correlate2d: Full 2-D convolution with output shape (h1+h2−1, w1+w2−1). correlate2d is implemented as convolve2d with the kernel reversed along both axes, the same flip-then-convolve relationship as the 1-D pair.

Numerical Differentiation and Interpolation

gradient(f, *varargs) computes numerical derivatives with configurable edge handling:

Position edge_order=1 edge_order=2
Interior (f[k+1] − f[k−1]) / 2h same (central difference)
First element (f[1] − f[0]) / h (−3f[0] + 4f[1] − f[2]) / 2h
Last element (f[n−1] − f[n−2]) / h (3f[n−1] − 4f[n−2] + f[n−3]) / 2h

Non-uniform spacing uses Lagrange polynomial coefficients (3-point at edges, 2-point for edge_order=1).

diff(a, n) computes n-th discrete difference: diff[i] = a[i+1] − a[i], applied n times. Output length decreases by n.

interp(x, xp, fp) does 1-D piecewise linear interpolation: binary search to find the enclosing interval in xp, then fp[lo]·(1−t) + fp[hi]·t with t = (x − xp[lo]) / (xp[hi] − xp[lo]). Values outside xp are clamped to the boundary values.

Windowing Functions

Five window types for spectral analysis (all returning [1.0] for M ≤ 1):

Window Formula
Hamming 0.54 − 0.46·cos(2π·i / (M−1))
Hanning 0.5 − 0.5·cos(2π·i / (M−1))
Blackman 0.42 − 0.5·cos(2π·i / (M−1)) + 0.08·cos(4π·i / (M−1))
Bartlett `1 −
Kaiser I0(β·sqrt(1 − r²)) / I0(β) (modified Bessel I0 via piecewise rational approx)

Histogram and Binning

histogram(a, bins) supports three automatic bin-count strategies:

Strategy Formula
"sturges" ceil(log2(n)) + 1
"sqrt" ceil(sqrt(n))
"auto" max(sturges, sqrt)

Bin edges are uniformly spaced. Element-to-bin assignment uses O(log bins) binary search per element. histogram_bin_edges returns just the edges without counting. histogramdd generalizes to N dimensions.

Padding

11 pad modes matching NumPy's np.pad:

Mode Behavior
constant Fill with a specified value (default 0)
edge Replicate the edge value
wrap Modular wrapping via rem_euclid
reflect Mirror at edge, not duplicating the edge element
symmetric Mirror at edge, duplicating the edge element
linear_ramp Linear interpolation from edge to a ramp endpoint
maximum Fill with the maximum of a window of the array edge
minimum Fill with the minimum of a window
mean Fill with the mean of a window
median Fill with the median of a window
empty Leave padded values uninitialized (filled with 0.0)

Financial Mathematics

Ten time-value-of-money functions using closed-form annuity algebra where possible:

Function Method
fv, pv, pmt Closed-form annuity factor (1+rate)^nper
nper Logarithmic inversion of annuity formula
npv Discounted cashflow sum Σ cf[i] / (1+rate)^i
irr Newton's method (max 100 iterations, tol 1e-12, initial guess 0.1)
mirr Separates positive/negative cashflows, applies reinvestment/finance rates
rate Newton's method on the annuity equation
ipmt, ppmt Interest and principal portions derived from fv and pmt

Polynomial Systems

Five polynomial families (Power series, Chebyshev, Legendre, Hermite, Laguerre), with Hermite represented in both physicist and probabilist normalizations as separate submodules. Counting Hermite's two normalizations as distinct submodules, the table below has six rows, matching NumPy's own numpy.polynomial.{polynomial, chebyshev, legendre, hermite, hermite_e, laguerre} enumeration. Each row carries the full evaluation, arithmetic, calculus, fitting, and basis-conversion suite in the Rust API (fnp-ufunc). From Python, fnp_python.polynomial.<family> is NumPy's namespace with two functions replaced by native, bit-identical ones for float64 input: the series evaluator (polyval, chebval, legval, hermval, hermeval, lagval) and the least-squares fit (polyfit, chebfit, legfit, hermfit, hermefit, lagfit; the fit builds NumPy's design matrix and column norms natively and solves with NumPy's own linalg.lstsq, as does the legacy top-level polyfit):

Family Basis Key operations
Power series x^n polyval, polyder, polyint, polyfit, polymul, polyadd, polysub, polydiv, polyroots
Chebyshev T_n(x) chebval, chebadd, chebsub, chebmul, chebdiv, chebder, chebint, chebroots, chebfromroots, chebfit, cheb2poly, poly2cheb
Legendre P_n(x) legval, legadd, legsub, legmul, legdiv, legder, legint, legroots, legfromroots, legfit, leg2poly, poly2leg
Hermite (physicist) H_n(x) hermval, hermadd, hermsub, hermmul, hermdiv, hermder, hermint, hermroots, hermfromroots, hermfit, herm2poly, poly2herm
Hermite (probabilist) He_n(x) hermeval, hermeadd, hermesub, hermemul, hermediv, hermeroots, hermefromroots, hermefit, herme2poly, poly2herme
Laguerre L_n(x) lagval, lagadd, lagsub, lagmul, lagdiv, lagder, lagint, lagroots, lagfromroots, lagfit, lag2poly, poly2lag

Masked Arrays

MaskedArray wraps a UFuncArray with an optional boolean mask and fill value:

MaskedArray { data: UFuncArray, mask: Option<UFuncArray>, fill_value: f64, hard_mask: bool }

Mask convention: 1.0 = masked (excluded), 0.0 = valid. Matches numpy.ma. Operations that reduce masked arrays (sum, mean, min, max, var, std, median, ptp, argmin, argmax, cumsum, cumprod, count) skip masked values. Comparison and arithmetic operations propagate masks through mask_or. compressed() returns a 1-D array of only the unmasked values. filled(fill_value) replaces masked values with a fill value.

Datetime and Timedelta

Datetime and timedelta arrays are not separate struct types; they are UFuncArray instances with DType::DateTime64 or DType::TimeDelta64, backed by ArrayStorage::I64. The time unit (one of ns, us, ms, s, min, h, D, W, M, Y) is carried on the dtype via the DateTimeUnit enum. Construct them via UFuncArray::from_datetime_strings(values, unit) or from_timedelta_strings(values, unit).

Full temporal arithmetic is supported through dispatch on the dtype:

  • Datetime − Datetime = Timedelta
  • Datetime + Timedelta = Datetime
  • Timedelta + Timedelta = Timedelta
  • Scalar multiplication of Timedelta

Business-day helpers: busday_count(start, end), busday_offset(date, offset), is_busday(date) with Monday–Friday weekday mask.

String Operations

33 numpy.char functions operate elementwise on string arrays: upper, lower, capitalize, title, center, ljust, rjust, zfill, strip, lstrip, rstrip, replace, find, rfind, count, startswith, endswith, isnumeric, isalpha, isdigit, isdecimal, str_len, encode, decode, translate, maketrans, partition, rpartition, split, rsplit, join, expandtabs, swapcase. String add concatenates elementwise; string multiply repeats.

Bit Packing

  • packbits(axis): Packs 8 boolean elements into 1 byte, MSB first. Output length = ceil(axis_len / 8).
  • unpackbits(axis, count): Unpacks bytes into boolean bits, MSB to LSB. Output length = axis_len * 8 (or count if specified).

Scimath (Complex-Domain Extensions)

8 numpy.lib.scimath functions extend real-valued math to the complex domain for inputs outside the real function's natural domain. Useful in signal processing and physics where negative square roots or out-of-range inverse trig naturally arise.

Function Real domain Extension
scimath_sqrt(x) x ≥ 0 Complex sqrt for x < 0
scimath_log(x) x > 0 Complex log for x ≤ 0
scimath_log2(x) x > 0 Complex base-2 logarithm
scimath_log10(x) x > 0 Complex base-10 logarithm
scimath_power(x, p) x ≥ 0 (non-integer p) Complex result for negative base
scimath_arccos(x) −1 ≤ x ≤ 1 Complex arccos for |x| > 1
scimath_arcsin(x) −1 ≤ x ≤ 1 Complex arcsin for |x| > 1
scimath_arctanh(x) −1 < x < 1 Complex arctanh for |x| ≥ 1

This section in the README on GitHub