Expand description
Β§SymbAnaFis: Fast Symbolic Differentiation for Rust
SymbAnaFis is a high-performance symbolic mathematics library focused on differentiation,
simplification, and fast numeric evaluation. It provides both string-based and type-safe APIs
with extensive optimization for real-world mathematical computing.
Β§Quick Start
use symb_anafis::{diff, simplify, symb, Diff};
// String-based API - quick and familiar
let result = diff("x^3 + sin(x)", "x", &[], None).unwrap();
assert_eq!(result, "3*x^2 + cos(x)");
// Type-safe API - powerful and composable
let x = symb("x");
let expr = x.pow(3.0) + x.sin();
let derivative = Diff::new().differentiate(&expr, &x).unwrap();
assert_eq!(derivative.to_string(), "3*x^2 + cos(x)");Β§Key Features
Β§π High Performance
- Compiled evaluation: Expressions compile to optimized bytecode
- SIMD vectorization: Batch evaluation with f64x4 operations
- Parallel evaluation: Multi-threaded computation with Rayon
- Smart simplification: Rule-based engine with memoization
Β§π§ Developer Experience
- Type-safe expressions: Rustβs type system prevents runtime errors
- Operator overloading: Natural mathematical syntax (
x.pow(2) + x.sin()) - Copy symbols: No
.clone()needed for symbol reuse - Builder patterns: Fluent APIs for differentiation and simplification
Β§π Mathematical Features
- Symbolic differentiation: Automatic derivatives with simplification
- Vector calculus: Gradients, Jacobians, and Hessian matrices
- Custom functions: User-defined functions with partial derivatives
- Uncertainty propagation: Error analysis with covariance matrices
Β§Core APIs
Different API styles for the same operations, choose based on your use case:
| Operation | String API | Type-safe API | Builder API |
|---|---|---|---|
| Differentiation | diff("x^2 + sin(x)", "x", &[], None) | Diff::new().differentiate(&expr, &x) | Diff::new().domain_safe(true).differentiate(&expr, &x) |
| Simplification | simplify("x + x + x", &[], None) | Use Simplify::new().simplify(&expr) | Simplify::new().max_iterations(100).simplify(&expr) |
| Evaluation | evaluate_str("x^2", &[("x", 2.0)]) | expr.evaluate(&vars, &custom_evals) | CompiledEvaluator::compile(&expr, &["x"], None) |
Β§Examples by Use Case
Β§Basic Differentiation
// String API
let result = diff("x^2 + 3*x + 1", "x", &[], None).unwrap();
assert_eq!(result, "3 + 2*x"); // Order may vary
// Type-safe API
let x = symb("x");
let poly = x.pow(2.0) + 3.0 * x + 1.0;
let derivative = Diff::new().differentiate(&poly, &x).unwrap();
assert_eq!(derivative.to_string(), "3 + 2*x"); // Order may varyΒ§Vector Calculus
let x = symb("x");
let y = symb("y");
let f = x.pow(2.0) + y.pow(2.0); // f(x,y) = xΒ² + yΒ²
let grad = gradient(&f, &[&x, &y]).unwrap();
// Returns [2*x, 2*y]Β§High-Performance Evaluation
let x = symb("x");
let expr = x.sin() * x.cos() + x.pow(2.0);
// Compile once, evaluate many times
let evaluator = CompiledEvaluator::compile(&expr, &[&x], None).unwrap();
// Fast numerical evaluation
let result = evaluator.evaluate(&[0.5]); // ~0.479...Β§Custom Functions
let x = symb("x");
// Define f(x) with derivative f'(x) = 2x
let ctx = Context::new().with_function("f", UserFunction::new(1..=1)
.partial(0, |args| 2.0 * (*args[0]).clone()).unwrap());
let expr = parse("f(x^2)", &HashSet::new(), &HashSet::new(), Some(&ctx)).unwrap();
let derivative = Diff::new().with_context(&ctx)
.differentiate(&expr, &x).unwrap(); // Chain rule: f'(xΒ²) * 2xΒ§Output Formatting
let x = symb("x");
let expr = x.pow(2.0) / (x + 1.0);
println!("{}", expr); // x^2/(x + 1)
println!("{}", expr.to_latex()); // \\frac{x^{2}}{x + 1}
println!("{}", expr.to_unicode()); // xΒ²/(x + 1)Β§Feature Flags
SymbAnaFis supports optional features for specialized use cases:
[dependencies]
symb_anafis = { version = "0.7", features = ["parallel"] }-
parallel: Enables parallel evaluation with Rayon- Adds
eval_f64()for SIMD+parallel evaluation - Enables
evaluate_parallel()for batch operations - Required for high-performance numerical workloads
- Adds
-
python: Python bindings viaPyO3(separate crate)- Type-safe integration with
NumPyarrays - Automatic GIL management for performance
- See
symb-anafis-pythoncrate for usage
- Type-safe integration with
Β§Architecture Overview
SymbAnaFis is built with a layered architecture for performance and maintainability:
ββ PUBLIC APIs ββββββββββββββββββββββββββββββββββββββββββββββ
β β
β String API Type-safe API Builder API β
β ----------- -------------- ----------- β
β diff() x.pow(2) Diff::new() β
β simplify() expr + expr Simplify::new() β
β β
ββ CORE ENGINE ββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β Parser Differentiator Simplifier β
β ------- -------------- ---------- β
β "x^2" β AST AST β AST AST β AST β
β β
ββ EVALUATION βββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β Interpreter Compiler SIMD Evaluator β
β ----------- -------- --------------- β
β AST β f64 AST β Bytecode Bytecode β [f64; N] β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββΒ§Module Organization
The crate is organized into logical layers:
- Core:
Expr,Symbol, error types, visitor pattern - Parsing: String β AST conversion with error reporting
- Computation: Differentiation, simplification, evaluation engines
- Functions: Built-in function registry and mathematical implementations
- APIs: User-facing builders and utility functions
- Bindings: Python integration and parallel evaluation
Β§Getting Started
- Add dependency:
cargo add symb_anafis - Import symbols:
use symb_anafis::{diff, symb, Diff}; - Create expressions:
let x = symb("x"); let expr = x.pow(2); - Compute derivatives:
let result = diff("x^2", "x", &[], None)?;
Β§Performance Notes
- Compilation: Use
CompiledEvaluatorfor repeated numeric evaluation - Batch operations: Enable
parallelfeature for SIMD and multi-threading - Memory efficiency: Expressions use
Arcsharing for common subexpressions - Simplification: Automatic during differentiation, manual via
simplify()
Β§Safety and Limits
- Stack safety: Compile-time validation prevents stack overflow in evaluation
- Memory limits: Default max 10,000 nodes and depth 100 prevent resource exhaustion
- Error handling: All operations return
Resultwith descriptive error messages - Thread safety: All public types are
Send + Syncfor parallel usage
ModulesΒ§
- visitor
- Advanced APIs for extending functionality.
StructsΒ§
- Compiled
Evaluator - Compiled expression evaluator - thread-safe, reusable.
- Context
- Context system for custom functions and parsing.
- Covariance
Matrix - Uncertainty propagation and error analysis for experimental data.
- Diff
- Fluent APIs for differentiation and simplification.
- Dual
- Dual number type for automatic differentiation. Dual number for automatic differentiation
- Expr
- The main expression type for building and manipulating mathematical expressions.
- Simplify
- Fluent APIs for differentiation and simplification.
- Span
- The main expression type for building and manipulating mathematical expressions.
- Symbol
- The main expression type for building and manipulating mathematical expressions.
- User
Function - Context system for custom functions and parsing.
EnumsΒ§
- CovEntry
- Uncertainty propagation and error analysis for experimental data.
- Diff
Error - The main expression type for building and manipulating mathematical expressions.
- Symbol
Error - The main expression type for building and manipulating mathematical expressions.
TraitsΒ§
- ArcExpr
Ext - Functions for creating and managing symbols in the global registry.
- Math
Scalar - Mathematical scalar trait and compiled evaluator for high-performance computation.
A trait comprising all operations required for mathematical scalars
in the
SymbAnaFislibrary. - ToParam
Name - Trait for types that can be used as parameter names in compile methods.
FunctionsΒ§
- clear_
symbols - Functions for creating and managing symbols in the global registry.
- diff
- Main API function for symbolic differentiation
- evaluate_
str - Vector calculus operations for computing gradients, Jacobians, and Hessians.
- gradient
- Vector calculus operations for computing gradients, Jacobians, and Hessians.
- gradient_
str - Vector calculus operations for computing gradients, Jacobians, and Hessians.
- hessian
- Vector calculus operations for computing gradients, Jacobians, and Hessians.
- hessian_
str - Vector calculus operations for computing gradients, Jacobians, and Hessians.
- jacobian
- Vector calculus operations for computing gradients, Jacobians, and Hessians.
- jacobian_
str - Vector calculus operations for computing gradients, Jacobians, and Hessians.
- parse
- Parse a formula string into an expression AST
- relative_
uncertainty - Uncertainty propagation and error analysis for experimental data.
- remove_
symbol - Functions for creating and managing symbols in the global registry.
- simplify
- Simplify a mathematical expression
- symb
- Functions for creating and managing symbols in the global registry.
- symb_
get - Functions for creating and managing symbols in the global registry.
- symb_
new - Functions for creating and managing symbols in the global registry.
- symbol_
count - Functions for creating and managing symbols in the global registry.
- symbol_
exists - Functions for creating and managing symbols in the global registry.
- symbol_
names - Functions for creating and managing symbols in the global registry.
- uncertainty_
propagation - Uncertainty propagation and error analysis for experimental data.