docs

You are reading the docs for v0.1.2. Nabi 0.1.2 is no longer supported. Latest release: v0.1.3 →

#Science with Nabi

On this page

Nabi's numeric core is in the standard library: Array<T, N>, the dot operators, reductions, Complex and random numbers (chapter 21). Everything a scientist builds on top of that, linear algebra, statistics, signals, data frames, plots, lives in packages: one package per field, each versioned on its own, all written in Nabi with no C or Fortran underneath, so they build for every target Nabi has, WebAssembly included.

This chapter maps the packages, shows the one rule they share for input data, works one small problem from a CSV file to a plot, points to each package's tutorial, and ends with a table for readers coming from NumPy, SciPy and pandas.

#The packages

PackageWhat it doesPython counterpart
linalgdense matrices: products, LU, Cholesky, QR, SVD, eigen, solvers, expmnumpy.linalg, scipy.linalg
sparseCSR / CSC / COO matrices, CG, GMRES, BiCGSTAB, sparse Cholesky and LUscipy.sparse, scipy.sparse.linalg
spatialsmall fixed-size vectors, quaternions, matrices, transforms and shapes for games and graphics; #[repr(C)], SIMD Mat4pyglm, scipy.spatial.transform
autodiffderivatives of your own functions: dual numbers, a reverse-mode tape, Hessians, Taylor seriesjax.grad, autograd
statsdescriptive statistics, 19 distributions, tests, regressionscipy.stats, statsmodels (basics)
signalFFT of any length, windows, FIR / IIR filters, spectra, peaksnumpy.fft, scipy.signal
interpolatesplines, polynomials, grids, scattered data, quadraturescipy.interpolate, scipy.integrate.quad
optimizeminimization, least squares, root finding, linear programmingscipy.optimize
odeinitial and boundary value problems, stiff solvers, symplectic integratorsscipy.integrate.solve_ivp
specialgamma, Bessel, erf, zeta, elliptic functions; complex elementary functionsscipy.special
tablecolumnar data frames, CSV, JSONL, Arrow and Parquet files, lazy queriespandas, polars, pyarrow
unitsquantities with units, checked when you compilepint
plotSVG, PNG and terminal plots, notebook displaymatplotlib

Add the ones you use to nabi.nabion with nabi add (or, for a single-file script, nabi add <package> file.nabi):

sh
nabi add linalg
nabi add table

Each package's docs, a tutorial and its API, are under Package docs: follow the package's name in the table. The code on this page needs those packages, so unlike the rest of this guide it is not run when the site is built; every block was checked with the packages' current versions.

#One way in: array-like input

Every package takes a sequence of numbers the same way. A function that wants a vector of f64 takes anything linalg::AsVector<f64> covers: a Vector, a List, a fixed array, of f64, f32 or integers, and an integer range. A Vector<f64> or a List<f64> is read in place; anything else is converted once.

nabi
use core::array::Vector;

let xs: List<f64> = [0.0, 1.0, 2.0, 3.0];
let ys: List<i64> = [0, 1, 8, 27];
let s = try interpolate::cubic_spline(xs, ys);       // lists of different types
let same = try interpolate::cubic_spline(0..4, [0f32, 1f32, 8f32, 27f32]);
assert(s(1.5) == same(1.5));

let r = try ode::solve_ivp(|t: f64, y: Vector<f64>| -> Vector<f64> { -y }, 0.0..1.0, [1, 2]);
println(stats::mean(1..5));                            // 2.5

stats also reads arrays of any rank (in row-major order), and plot the same forms plus nested lists for grids. Your own functions can take the same trait:

nabi
use linalg::AsVector;
use core::array::Vector;

fn rms<X: AsVector<f64>>(x: X) -> f64 {
    let v: Vector<f64> = x.as_vector();
    (v .* v).mean().sqrt()
}

println(rms([3, 4]));        // 3.5355339059327378

Write the element type of a mixed literal first: [0.0, 0.5, 1] is a list of floats, while [0, 0.5, 1] starts as a list of integers and the 0.5 is an error.

#A worked example

A cup of tea cools from 90 degrees. The readings are in a CSV file; Newton's law of cooling says the temperature falls toward the room's at a rate proportional to the difference, T' = k (room - T). We fit room and k to the data, solve the law as an ODE, check the fit and plot it.

Each step is one call into one package, and the values between them are plain Vector<f64>s: no conversion layer, no copies beyond the CSV parse.

#The tutorials

Each package's docs start with a tutorial: a small problem worked step by step, with code that its tests run.

TutorialPackageWhat it does
A first data analysistable, stats, plotread a CSV file, clean, group, test a difference, plot
Linear algebralinalgsolve systems, least squares, eigenvalues
Sparse systemssparsea 10 000-unknown sparse system, iterative and direct solvers
Statisticsstatsdistributions, random samples, tests, regression, the bootstrap
Signals and spectrasignalFFT, power spectra in noise, filters, peaks, convolution
Fitting and optimizationoptimizeroots, minima, curve fitting, linear programming
Differential equationsodeinitial value problems, events, stiff systems, boundary value problems
Derivativesautodiffexact gradients, Jacobians and Taylor series of your own functions

#From NumPy, SciPy and pandas

PythonNabi
np.array([[1, 2], [3, 4]])let m: Matrix<f64> = [[1, 2], [3, 4]];
np.linspace(0, 1, 5), np.arangearray::linspace(0.0, 1.0, 5), array::arange(0.0, 1.0, 0.25)
a.sum(axis=0), a.argmax(), np.allclose(a, b)a.sum_along(0), a.argmax(), a.all_close(b)
a @ b, np.linalg.solve(a, b)a @ b, linalg::solve(a, b) or a \ b
np.linalg.eigh, svd, cholesky, lstsqlinalg::eigh, svd, cholesky, lstsq
scipy.sparse.csr_matrix, spsolve, cgsparse::Csr, sparse::lu(a).solve(b), sparse::cg
jax.grad(f)(x)autodiff::grad(f, x) or ∇(f)(x)
scipy.stats.norm(0, 1).cdf(x)stats::Normal::new(0.0, 1.0).cdf(x)
np.mean, np.std(x, ddof=1), np.quantilestats::mean, stats::std(x, ddof: 1), stats::quantile
scipy.stats.ttest_ind, linregressstats::ttest_ind, stats::ols
np.fft.fft, rfft, scipy.signal.welchsignal::fft, signal::rfft, signal::welch
scipy.signal.butter(..., output="sos"), sosfiltfiltsignal::filter::butter, sosfiltfilt
scipy.interpolate.CubicSpline, make_interp_splineinterpolate::cubic_spline, make_interp_spline
scipy.integrate.quad, solve_ivpinterpolate::quad (or ∫(f, a..b)), ode::solve_ivp
scipy.optimize.minimize, curve_fit, brentqoptimize::minimize, curve_fit, brentq
scipy.special.gamma, jv, erfspecial::gamma, jv, erf
pd.read_csv, df[df.x > 2], df.groupby("k").agg(...)table::read_csv, t.filter(col("x") .> 2), t.group_by(["k"]).agg([...])
pd.read_parquet, pl.scan_parquet(...).filter(...).collect()table::read_parquet, table::scan_parquet(..).filter(..).collect()
plt.plot(x, y); plt.savefig("a.svg")plot::axes().line(x, y).save("a.svg")

#Speed

The packages are pure Nabi and use every core when the input is large: dense matrix products run at about 30 GFLOP/s on one Apple M-series core and above 100 GFLOP/s on all of them, FFTs of any length are O(n log n), and a sparse matrix-vector product reads several hundred million nonzeros a second. Each package's README has a "Speed" section with its numbers and how they compare with NumPy, SciPy and the reference libraries. Two habits keep code fast: build arrays with Array::from_fn or the dot operators instead of pushing to a list in a loop, and pass Vector<f64>s between calls rather than converting back and forth.

Found a mistake? Edit this page on GitHub. Last updated