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:
-
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. -
Never silently wrong. Operations return
Result::Err, an unevaluated node, orNoneinstead of a guess:∫₋₁¹ dx/x²isErr(Divergent),solve(x − x)isErr(InfiniteSolutions),re(z)staysre(z)untilzis known to be real. Structural substitution by default. -
One representation per concept. One assumption system. One polynomial type. One number type. One solve function.
-
Thread-safe from day one. Expression handles are
Send + Sync. -
No recursive tree walks. All traversals use explicit stacks.
-
The compiler is the API contract.
pub= stable.pub(crate)= internal.Ex,BoolExandSetExare distinct types. -
Extensible without inheritance. Custom functions via registered rules (
Rule,RuleSet).
§API model
- Operations for which “unevaluated” is a valid answer return
Exand have atry_twin returningResult(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) returnResult. - Queries (
is_positive,equals,SetEx::contains,Matrix::is_symmetric) returnOption<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::extended::Extended;pub use base::interval::Bounds;pub use base::interval::Interval;pub use base::interval::IntervalKind;pub use base::numeric;pub use num_bigint;pub use num_complex;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
Contextis 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.
- decompositions
- Named results of matrix decompositions (
Qr,Lu,HermiteNormalForm, …) shared byMatrix,ZMatrixandQMatrix. Named results of matrix decompositions and normal forms. - 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, Pellx² − Dy² = 1, sums of two squares, and Pythagorean triples. - discrete
- Discrete transforms on exact sequences (convolution, NTT, Walsh–Hadamard, Möbius).
Discrete transforms on exact sequences (SymPy’s
sympy.discrete): linear, cyclic and subset convolutions, the number-theoretic transform, the Walsh–Hadamard transform and the Möbius (subset/superset-sum) transform. (0.9) - 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 onEx: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 forExpr/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 onEx. - 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.
- mathml
- Presentation MathML rendering.
Presentation MathML rendering of expressions (
Ex::to_mathml). (0.9) - 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 onEx: 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 onEx. - series_
api - Summation, products, series and formal-power-series methods on
Ex. Summation, products, and series extension methods onEx. - 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 onSetEx/BoolEx/Ex. - solvers
- Solver entry points beyond
Ex::solve:linsolve,LinearSolution,GeneralSolution, Newton systems. Extended solving methods onEx: general solutions, systems, recurrences, IVPs. - stats
- Symbolic probability and statistics: random variables, exact moments, probabilities, densities.
Symbolic probability and statistics (SymPy’s
stats): random variables with named distributions, exact moments, probabilities of events, densities and distribution functions — all as expressions — plus conditioning, transformations and mixtures of distributions. - 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 onEx. - 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!).