numerics 0.1.0
Loading...
Searching...
No Matches
Numerics Library

A C++ scientific computing library: linear algebra, ODE/PDE solvers, spectral methods, statistical mechanics, and gnuplot-based plotting – all under a single #include "numerics.hpp".


Example: Lorenz attractor

The Lorenz system is integrated with num::solve + num::RK45 (adaptive Dormand-Prince) and the trajectory is plotted with num::plt – the full program is ~30 lines (examples/lorenz.cpp):

#include "numerics.hpp"
int main() {
const double sigma = 10.0, rho = 28.0, beta = 8.0 / 3.0;
auto lorenz = [&](double, const num::Vector& s, num::Vector& ds) {
ds[0] = sigma * (s[1] - s[0]);
ds[1] = s[0] * (rho - s[2]) - s[1];
ds[2] = s[0] * s[1] - beta * s[2];
};
auto observer = [&](double, const num::Vector& y) {
xz.emplace_back(y[0], y[2]);
};
num::ODEProblem{lorenz, {1.0, 0.0, 0.0}, 0.0, 50.0},
num::RK45{.rtol = 1e-8, .atol = 1e-10, .max_steps = 2000000},
observer);
num::plt::plot(xz);
num::plt::title("Lorenz attractor (sigma=10, rho=28, beta=8/3)");
num::plt::xlabel("x");
num::plt::ylabel("z");
num::plt::savefig("lorenz.png");
}
ODEResult solve(const P &prob, const RK45 &alg, ObserverFn obs=nullptr)
Definition solve.hpp:59
constexpr real e
Definition math.hpp:43
Explicit ODE: du/dt = f(t, u)
Definition problems.hpp:18
double rtol
Ordered (x, y) series.
Definition plot.hpp:42
Lorenz attractor phase portrait (x vs z)

Example: 2D heat equation

2D Heat Equation

Implicit backward Euler via sparse CG. Grid2D carries geometry; ScalarField2D carries data. The sparse system A = I - coeff*L is assembled once and reused at every step:

num::Grid2D grid{N, h};
num::LinearSolver solver = num::make_cg_solver(A);
num::ScalarField2D u(grid, [=](double x, double y) {
return num::gaussian2d(x, y, 0.5, 0.5, sigma);
});
num::solve(u, num::BackwardEuler{.solver=solver, .dt=dt, .nstep=nstep});
Sparse matrix in Compressed Sparse Row (CSR) format.
Definition sparse.hpp:15
SparseMatrix backward_euler_matrix(int N, double coeff)
Definition diffusion.hpp:90
real gaussian2d(real x, real y, real cx, real cy, real sigma)
2D isotropic Gaussian centred at with width :
Definition math.hpp:310
std::function< SolverResult(const Vector &rhs, Vector &x)> LinearSolver
LinearSolver solver
Initial Gaussian and diffused distribution at t=T_end.

Library Modules

kernel – Performance substrate

The inner-loop layer shared by all solvers. Three tiers:

  • Tier 1 (kernel::raw): always-inline dot/axpy/scale, BLAS-dispatched
  • Tier 2 (kernel::array, kernel::reduce): tag-dispatched ops with seq_t/par_t compile-time policy tags; zero runtime overhead
  • Tier 3 (kernel::subspace): LinearOp interface, mgs_orthogonalize, arnoldi_step — the shared inner loops for GMRES, Lanczos, and expv

core – Vectors, matrices, and high-level dispatch

factorization – Direct linear solvers

solvers – Iterative solvers

eigen – Eigenvalue methods

svd – Singular value decomposition

spectral – Fourier transforms

analysis – Quadrature and root finding

stats – Simulation observables

markov – Markov chain Monte Carlo

fields – Grid geometry and field storage

solve – Unified solver dispatcher

sparse and banded – Structured sparse formats

meshfree – Particle-based spatial structures


plot – Gnuplot pipe wrapper

  • num::Gnuplot – popen wrapper: operator<< for commands, send1d() for inline data
  • num::Seriesstd::vector<std::pair<double,double>> for (x, y) data
  • num::apply_siam_style(gp) – clean SIAM-style theme
  • num::save_png(gp, file, w, h) – redirect output to PNG
  • num::set_loglog(gp), num::set_logx(gp) – axis scaling helpers

Physics Simulations

Raylib-rendered simulations built on numerics. Each runs as a batch renderer: simulate all frames, export PNGs, composite with make_video.sh.

Monte Carlo

2D Ising Model

page_app_ising

Metropolis dynamics and umbrella-sampled nucleation on a 300x300 lattice. Reproduces Brendel et al. (2005) nucleation experiments.

Library feature Role
num::markov::metropolis_sweep_prob Sweep hot path with precomputed Boltzmann table
num::markov::umbrella_sweep_prob Per-sweep rejection / save-restore for window sampling
num::SparseMatrix + sparse_matvec Neighbour-sum matrix for energy observable (SIMD path)
num::RunningStats, num::Histogram Online mean, variance, nucleus-size distribution per window
num::newton Mean-field self-consistency equation solver

Fluid Dynamics

2D SPH Fluid Simulation

page_app_fluid

Weakly compressible SPH with heat transport, rigid bodies, and particle injection. Tait EOS, cubic-spline kernel, Morris viscosity Laplacian.

Library feature Role
num::CellList2D O(1) neighbour queries; Newton-3rd-law pair traversal
num::Backend dispatch seq (pair loop) <-> omp (per-particle) selectable at runtime
num::Vector Flat particle attribute arrays

3D SPH Fluid Simulation

page_app_fluid3d

3D WCSPH with opposing hose jets, heat transport, and a free-orbit camera whose orientation rotates the gravity vector.

Library feature Role
num::CellList3D 3D counting-sort spatial hash; 13-stencil Newton-3rd-law pairs
num::Backend dispatch seq (pair traversal) <-> omp (per-particle)
num::Vector Flat particle attribute arrays

2D Incompressible Navier-Stokes

page_app_ns

Chorin projection on a staggered MAC grid; semi-Lagrangian advection; matrix-free CG pressure solve. Kelvin-Helmholtz double shear layer initial condition.

Library feature Role
num::cg_matfree Matrix-free CG for -grad^2p = r; warm-start from previous pressure field
num::dot Inner products inside CG (dispatched to best available backend)
num::Vector Velocity faces u, v; pressure p; intermediates u*, v*, rhs

Quantum Mechanics

2D Time-Dependent Schrodinger Equation

page_app_tdse

Strang operator splitting with Crank-Nicolson kinetic sweeps; Thomas algorithm for O(N) tridiagonal solves; Lanczos eigendecomposition; five interchangeable potentials.

Library feature Role
num::thomas O(N) complex tridiagonal solve per row/column (kinetic sweeps)
num::lanczos Krylov subspace for lowest eigenmodes
num::brent Bessel zero-finding for exact circular-well energies
num::gauss_legendre Norm and energy quadrature

Electromagnetism

Electromagnetic Field Demo

page_app_em

DC current flow + magnetostatics on a 32^3 voxel grid. Four Poisson problems (one electric, three magnetic) solved with matrix-free CG; interactive magnetic dipole.

Library feature Role
num::cg_matfree All four Poisson solves (variable-coefficient electric + 3x magnetic)
num::Grid3D 3D scalar field storage for phi, A, J, B components
num::Vector Flattened field arrays passed to the solver

Status Report

Run cmake --build build --target report to generate output/REPORT.md – a full snapshot of the current build:

  • Build environment – compiler, flags, detected backends (BLAS, FFTW3, OpenMP, CUDA, MPI)
  • Test summary – pass/fail counts per suite
  • Benchmark tables – throughput and timing for every module (linalg, FFT, banded, analysis)
  • Plots – PNG throughput curves (seq vs fftw, size scaling) in output/plots/

Sections whose backend was not found at configure time are left as placeholders, so the report always reflects exactly what is installed.


Performance Notes

Notes on hardware-aware implementation: cache blocking, register tiling, and SIMD vectorization applied to the matrix operations in this library.


Algorithm Theory

For derivations, error bounds, and proofs of the algorithms implemented here (LU/QR factorization, CG, GMRES, Lanczos, eigenvalue methods, quadrature, root finding, ODE integrators), see the companion notes:

Scientific Computing — adityadendukuri.github.io/cs111-scientific-computing-notes