Skip to main content

Crate symplex

Crate symplex 

Source
Expand description

symplex — a fast, correct symbolic mathematics library for Rust.

Expressions are exact (Ratio<BigInt> arithmetic, hash-consed in a Context arena) and the library can differentiate, integrate (indefinite, definite, improper, numeric), sum, take limits and series, solve equations, systems, ODEs and recurrences, simplify with a public rewrite-rule engine, work with sets and boolean logic, do exact linear algebra, view expressions as polynomials with symbolic coefficients (Poly), put rational functions into normal form (ratsimp), solve linear programs exactly with dual values and Farkas certificates, compute Hermite and Smith normal forms of integer matrices, run numerical root finding and minimisation, apply Laplace/Fourier/Mellin/Z transforms, and generate optimized Rust or C99 code. See the README and The Symplex Book for a guided tour, and CHANGELOG.md for the 0.1 → 0.2 breaking changes and the 0.2 → 0.3 behaviour changes.

Symplex is designed around seven principles:

  1. Construction is cheap, evaluation is explicit. Constructors only canonicalize (flatten, sort, combine). No expansion, no function evaluation, no identity application. Call .eval(), .expand(), or .simplify() when you choose.

  2. Never silently wrong. Operations return Result::Err, an unevaluated node, or None instead of a guess: ∫₋₁¹ dx/x² is Err(Divergent), solve(x − x) is Err(InfiniteSolutions), re(z) stays re(z) until z is known to be real. Structural substitution by default.

  3. One representation per concept. One assumption system. One polynomial type. One number type. One solve function.

  4. Thread-safe from day one. Expression handles are Send + Sync.

  5. No recursive tree walks. All traversals use explicit stacks.

  6. The compiler is the API contract. pub = stable. pub(crate) = internal. Ex, BoolEx and SetEx are distinct types.

  7. Extensible without inheritance. Custom functions via registered rules (Rule, RuleSet).

§API model

  • Operations for which “unevaluated” is a valid answer return Ex and have a try_ twin returning Result (integrate / try_integrate, integrate_definite / try_integrate_definite, summation / try_summation, …).
  • Numeric boundaries (eval_f64, compile, to_rust_fn, to_c_fn, integrate_numeric) and structural preconditions (Matrix::inv, cholesky) return Result.
  • Queries (is_positive, equals, SetEx::contains, Matrix::is_symmetric) return Option<bool>: yes, no, or unknown.

§Quick Start

use symplex::prelude::*;
use symplex::syms;

let ctx = Context::new();
syms!(ctx; x, y);
let expr = &x * &x + &x * 2 + 1;
assert_eq!(format!("{expr}"), "x^2 + 2*x + 1");

// Differentiate, integrate over an infinite range, solve, compile.
assert_eq!(format!("{}", expr.diff(&x)), "2*x + 2");
let gauss = (-x.powi(2)).exp().integrate_definite(&x, &ctx.neg_infinity(), &ctx.infinity());
assert_eq!(format!("{gauss}"), "sqrt(pi)");
let roots = (&x.powi(2) - 4).solve(&x).unwrap();
assert_eq!(roots.len(), 2);
let f = expr.compile(&["x"]).unwrap();
assert_eq!(f(&[2.0]), 9.0);

§Module map

The prelude re-exports everything most programs need. Domain modules are re-exported at the crate root: ntheory, diophantine, combinatorics, matrix, matrix_decomp, normalforms, linprog, optimize, vector, quaternion, control, robotics, dynamics, poly_ex, multipoly, polysys, groebner, factor_zassenhaus, definite, summation, formal_series, finite_diff, fourier_transform, mellin, z_transform, ode, rsolve, sets, logic, parse, tree, codegen, lambdify, units, assumptions, numeric, errors, config.

New in 0.3: poly_ex (the Poly view of an expression), linprog (exact simplex), normalforms (Hermite / Smith normal forms, integer kernels) and optimize (Brent, Nelder–Mead, differential evolution, least-squares fitting).

Re-exports§

pub use base::assumptions;
pub use base::config;
pub use base::errors;
pub use base::numeric;
pub use num_bigint;
pub use num_integer;
pub use num_rational;
pub use num_traits;

Modules§

base
Foundation layer: expression nodes, arena, tree traversal, canonicalization, and core types.
certificates
Exact, machine-checkable non-negativity certificates: Handelman (boxes), half-lines, parametric polyhedra and sums of squares, with Lean export. Exact, machine-checkable certificates that a polynomial is non-negative on a box, on a half-line, or on a polyhedron whose facets depend on a parameter — each exportable as a Lean 4 / Mathlib proof.
codegen
Code-generation options and compiled numeric functions. Rust source code generation from symbolic expressions.
combinatorics
Combinatorics: Stirling numbers, multinomial coefficients, partition counting. Combinatorial functions: binomial and multinomial coefficients, Stirling, Bell and Catalan numbers, derangements, and integer partitions (counting and enumeration).
context
Expression context — arena, symbol table, configuration. The Context is the user-facing entry point for symplex.
control
Control systems: state-space models, transfer functions, stability analysis. Control systems analysis: state-space models, transfer functions, stability analysis, and controller design utilities.
data_export
Data export utilities: CSV, TSV, JSON, Markdown, HTML, LaTeX table output. Data export utilities for exporting tabular data in multiple formats.
definite
Definite and improper integration. Definite and improper integration: singularity checks, limits at endpoints, known-value tables.
diophantine
Diophantine equations. Diophantine equations: linear ax + by = c, Pell x² − Dy² = 1, sums of two squares, and Pythagorean triples.
dynamics
Lagrangian dynamics: equations of motion, mass matrix, Coriolis, gravity. Lagrangian dynamics for robotic systems.
eq
Symbolic equation type (lhs = rhs). Symbolic equation type.
expr
The core expression handle and types. User-facing expression handle.
expr_complex
Complex-analysis methods on Ex (re, im, conjugate, arg, polar, …). Complex-analysis methods on Ex: re, im, conjugate, arg, polar form — plus the 0.2 special-function constructors (si, ci, ei, li, zeta, polygamma, kronecker_delta).
expr_ops
Operator overloads and scalar-conversion traits (ToEx, Scalar). Operator overloads, standard-library trait implementations, and numeric-ingestion helpers for Expr / Context.
expr_view
A non-locking, read-only view of an expression node for use in replace(). A non-locking, read-only view of an expression node.
factor_zassenhaus
Univariate factorization over ℤ via Berlekamp–Zassenhaus. Univariate factorization over ℤ via Berlekamp–Zassenhaus (mod-p factoring, Hensel lifting, recombination).
finite_diff
Finite difference methods: weights, application, and differentiation. Finite difference methods: weights, application, and differentiation.
formal_series
Formal power series representations and algorithms. Formal power series with exact, lazily computed coefficients.
fourier_transform
Symbolic Fourier transform. Symbolic Fourier transform and inverse Fourier transform (table + rules).
groebner
Gröbner basis computation via Buchberger’s algorithm with FGLM order conversion. Gröbner basis computation via Buchberger’s algorithm with Gebauer-Möller criteria.
integrate_api
Definite / improper / numeric integration methods on Ex. Definite / improper / numeric integration methods on Ex.
lambdify
Compiled numeric closures (CompiledFn, CompiledFnVec). Compile symbolic expressions to callable numerical functions.
lean
Lean 4 / Mathlib rendering (Ex::to_lean, LeanOpts). Lean 4 / Mathlib rendering of expressions (Ex::to_lean).
linprog
Exact linear programming over ℚ (two-phase simplex, duals, Farkas certificates). Exact linear programming over ℚ: two-phase simplex with Bland’s rule, dual values and Farkas infeasibility certificates.
logic
Boolean-logic simplification, normal forms, satisfiability. Boolean-logic simplification: flatten/absorb, CNF/DNF, satisfiability.
macros
Convenience macros for building expressions. Convenience macros for creating symbolic variables, plus the public rewrite-engine and simplification option types.
matrix
Symbolic matrix type and operations. Symbolic matrix type.
matrix_decomp
Additional matrix decompositions (QR, Gram–Schmidt) and structure tests. Additional matrix decompositions and structure tests.
mellin
Mellin transform. Mellin transform (table-based) and its inverse.
multipoly
Sparse multivariate polynomials over ℚ. Sparse multivariate polynomials over ℚ.
normalforms
Integer matrix normal forms: Hermite, Smith, unimodular transforms, integer kernels. Integer matrix normal forms: Hermite normal form, Smith normal form, unimodular transforms and integer kernels.
ntheory
Number theory: primality, factorization, divisors, modular arithmetic. Number theory: primality testing, integer factorization, divisors, modular arithmetic, quadratic residues, discrete logarithms, prime counting, continued fractions and classical integer sequences.
ode
Ordinary differential equation solver. Ordinary Differential Equation (ODE) solver.
optimize
Numerical optimisation and root bracketing (Brent, Nelder–Mead, polynomial fitting). Numerical optimisation and root bracketing.
parse
Runtime expression parser — convert strings to symbolic expressions. Runtime expression parser.
poly_api
Polynomial-algebra methods on Ex (resultant, discriminant, division, numeric roots, …). Polynomial-algebra methods on Ex: resultant, discriminant, square-free, division, numeric roots.
poly_ex
Public sparse polynomial view (Poly) over explicit generators. Public polynomial view: Poly — an expression seen as a sparse polynomial in an explicit list of generators, with symbolic or exact rational coefficients.
polysys
Polynomial system solving via Gröbner bases. Polynomial system solving via Gröbner bases.
polytope
Exact convex polyhedra in ℚⁿ from half-spaces: vertices, volume, containment, cutting. Exact convex polyhedra in ℚⁿ given by half-spaces.
prelude
The symplex prelude — one import to get started.
quaternion
Symbolic quaternion algebra for attitude representation. Symbolic quaternion algebra for attitude representation.
robotics
Robotics kinematics: DH parameters, forward kinematics, rotations. Robotics kinematics helpers: DH parameters, forward kinematics, Jacobian, and algebraic inverse kinematics.
rsolve
Recurrence-relation solver. Recurrence-relation solver (linear, constant-coefficient, with forcing).
rules
Public rewrite-rule engine: Rule, RuleSet, Bindings, RewriteOpts, Step. Public rewrite-rule engine and simplification extensions on Ex.
series_api
Summation, products, series and formal-power-series methods on Ex. Summation, products, and series extension methods on Ex.
sets
Set algebra on intervals, finite sets, unions. Set algebra: interval arithmetic, membership, subset tests, inf/sup, measure.
sets_api
Set-algebra and boolean-logic helpers (reduce_inequalities). Set-algebra, boolean-logic, and piecewise methods on SetEx / BoolEx / Ex.
solvers
Solver entry points beyond Ex::solve: linsolve, LinearSolution, GeneralSolution, Newton systems. Extended solving methods on Ex: general solutions, systems, recurrences, IVPs.
summation
Symbolic summation and products. Symbolic summation and products: Faulhaber, telescoping, hypergeometric, infinite sums, and closed-form products.
transforms_api
Integral transforms (Fourier, Mellin, Laplace helpers) and directional limits on Ex. Integral transforms (Fourier, Mellin) and directional limits on Ex.
tree
Serializable expression tree for interchange (JSON, etc.). Serializable expression tree for interchange.
units
Compile-time dimensional analysis for physical quantities. Compile-time dimensional analysis for physical quantities.
vector
Vector calculus: gradient, divergence, curl, laplacian. Vector calculus: gradient, divergence, curl, Laplacian (in Cartesian, cylindrical and spherical coordinates), directional derivatives, line integrals and scalar potentials.
z_transform
Z-transform for discrete-time signal analysis. Z-transform and inverse z-transform for discrete-time signal analysis.

Macros§

assert_dim
Compile-time dimension checkpoint.
const_assert_dim
Compile-time formula dimension verification with custom error messages.
dim
Build a dimension-checked physical quantity using natural math syntax.
eq
Build a symbolic equation using natural math syntax.
expr
Build a symbolic expression using natural math syntax.
matrix
Build a symbolic matrix using natural math syntax.
rule
Define a rewrite rule with pattern/template syntax.
sym
Declare a symbol with mathematical assumptions.
syms
Declare multiple symbolic variables at once.
vars
Declare multiple symbolic variables at once (alias of syms!).