Skip to main content

Crate symb_anafis

Crate symb_anafis 

Source
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:

OperationString APIType-safe APIBuilder API
Differentiationdiff("x^2 + sin(x)", "x", &[], None)Diff::new().differentiate(&expr, &x)Diff::new().domain_safe(true).differentiate(&expr, &x)
Simplificationsimplify("x + x + x", &[], None)Use Simplify::new().simplify(&expr)Simplify::new().max_iterations(100).simplify(&expr)
Evaluationevaluate_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
  • python: Python bindings via PyO3 (separate crate)

    • Type-safe integration with NumPy arrays
    • Automatic GIL management for performance
    • See symb-anafis-python crate for usage

Β§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

  1. Add dependency: cargo add symb_anafis
  2. Import symbols: use symb_anafis::{diff, symb, Diff};
  3. Create expressions: let x = symb("x"); let expr = x.pow(2);
  4. Compute derivatives: let result = diff("x^2", "x", &[], None)?;

Β§Performance Notes

  • Compilation: Use CompiledEvaluator for repeated numeric evaluation
  • Batch operations: Enable parallel feature for SIMD and multi-threading
  • Memory efficiency: Expressions use Arc sharing 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 Result with descriptive error messages
  • Thread safety: All public types are Send + Sync for parallel usage

ModulesΒ§

visitor
Advanced APIs for extending functionality.

StructsΒ§

CompiledEvaluator
Compiled expression evaluator - thread-safe, reusable.
Context
Context system for custom functions and parsing.
CovarianceMatrix
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.
UserFunction
Context system for custom functions and parsing.

EnumsΒ§

CovEntry
Uncertainty propagation and error analysis for experimental data.
DiffError
The main expression type for building and manipulating mathematical expressions.
SymbolError
The main expression type for building and manipulating mathematical expressions.

TraitsΒ§

ArcExprExt
Functions for creating and managing symbols in the global registry.
MathScalar
Mathematical scalar trait and compiled evaluator for high-performance computation. A trait comprising all operations required for mathematical scalars in the SymbAnaFis library.
ToParamName
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.