thales
A comprehensive Computer Algebra System (CAS) library for symbolic mathematics, equation solving, calculus, and linear algebra. Named after Thales of Miletus, the first mathematician in the Greek tradition.
Designed for cross-platform use with first-class iOS support via FFI bindings.
Features
Parsing & Expression Handling
- Expression Parsing: Parse mathematical expressions and equations with full operator precedence using chumsky parser combinators
- LaTeX Parsing: Parse LaTeX mathematical notation (
\frac,\sqrt, Greek letters, etc.) - LaTeX Rendering: Convert expressions to LaTeX output for display
- Pattern Matching: Rule-based expression rewriting with wildcard matching and commutativity awareness
Equation Solving
- Symbolic Solving: Solve linear, quadratic, polynomial, and transcendental equations using algebraic manipulation
- Multi-Equation Systems: Solve systems of arbitrary equations with automatic dependency analysis and solving order determination
- Inequality Solving: Solve inequalities and systems of inequalities with interval solutions
- Numerical Methods: Newton-Raphson, secant method, bisection, Brent's method, Levenberg-Marquardt for equations that cannot be solved symbolically
Calculus
- Differentiation: Symbolic differentiation with support for all elementary functions
- Integration: Indefinite and definite integration, integration by parts, substitution, tabular method
- Limits: Limit evaluation with L'Hôpital's rule for indeterminate forms (0/0, ∞/∞)
- ODEs: First-order ODE solving (separable and linear equations)
Advanced Features
- Partial Fractions: Decompose rational functions into partial fractions
- Trigonometric Simplification: Apply Pythagorean identities, double angle formulas, and more
- Matrix Operations: Matrix expressions with LaTeX rendering
Coordinate Systems
- Coordinate Transformations: Convert between Cartesian, polar, spherical, and cylindrical coordinate systems with full precision
- Complex Numbers: Complete support for complex arithmetic, polar form operations, and De Moivre's theorem
Infrastructure
- Resolution Paths: Track step-by-step solution processes for educational applications
- Unit System: Dimensional analysis and automatic unit conversion for physics calculations
- FFI Support: Swift bindings for seamless iOS/macOS integration via swift-bridge
- Memory Safety: Zero unsafe code in core logic, all abstractions are zero-cost
- Performance: Link-time optimization, single codegen unit, aggressive compiler optimizations
Table of Contents
- Installation
- Quick Start
- API Reference
- Building from Source
- Testing
- iOS Cross-Compilation
- Contributing
- License
- Dependencies
- Version History
- References
Installation
Add to your Cargo.toml:
[]
= "0.2.0"
Or install from GitHub:
[]
= { = "https://github.com/ChrisGVE/thales", = "main" }
Quick Start
Example 1: Coordinate Transformations
Convert between 2D Cartesian and polar coordinate systems:
use ;
Example 2: 3D Coordinate Transformations
Convert between Cartesian and spherical coordinates:
use ;
Example 3: Complex Number Operations
Work with complex numbers using polar form and De Moivre's theorem:
use ComplexOps;
use Complex64;
Example 4: Expression Parsing and Solving (In Progress)
Build mathematical expressions using the AST:
use ;
For complete parsing and solving capabilities (parser implementation in progress):
use ;
Example 5: Cylindrical Coordinates
Convert between Cartesian and cylindrical coordinates:
use ;
Example 6: Multi-Equation System Solver
Solve systems of equations with automatic dependency analysis:
use ;
Example 7: Calculus Operations
Differentiation, integration, and limits:
use ;
use Variable;
use ;
API Reference
The library is organized into focused modules. See the full documentation on docs.rs or build locally:
Core Modules
ast- Abstract syntax tree definitions for mathematical expressions, equations, variables, operators, and functionsparser- String to AST conversion using chumsky parser combinator librarylatex- LaTeX parsing and rendering for mathematical expressionssolver- Symbolic equation solving with specialized solvers for linear, quadratic, polynomial, and transcendental equationsequation_system- Multi-equation system solver with dependency analysis and automatic solving ordernumerical- Numerical root-finding methods (Newton-Raphson, bisection, Brent's method) with symbolic differentiationlimits- Limit evaluation with L'Hôpital's rule for indeterminate formsintegration- Symbolic integration with multiple methods (by parts, substitution, tabular)ode- Ordinary differential equation solving (separable and linear first-order)inequality- Inequality solving with interval solutionspartial_fractions- Rational function decomposition into partial fractionspattern- Pattern matching and rule-based expression rewritingtrigonometric- Trigonometric identity simplificationresolution_path- Solution step tracking for educational applicationsprecision- High-precision evaluation with configurable rounding modesmatrix- Matrix expressions with LaTeX renderingdimensions- Dimensional analysis and unit conversion systemtransforms- Coordinate system conversions (Cartesian, Polar, Spherical, Cylindrical) and complex number operationsffi- Foreign function interface for Swift via swift-bridge (requiresffifeature flag)
Key Types
Commonly used types re-exported at crate root:
use ;
Feature Flags
default- Standard features (currently none)ffi- Enable Swift bindings for iOS/macOS integration
Enable FFI in your Cargo.toml:
[]
= { = "0.2.0", = ["ffi"] }
Building from Source
Standard Build
# Clone repository
# Build library
# Build with FFI support
# Run tests
# Generate documentation
# Run benchmarks
Build Profiles
The project uses aggressive optimization in release mode:
[]
= 3 # Maximum optimization
= true # Link-time optimization
= 1 # Single codegen unit for maximum optimization
Clean Build
# Remove all build artifacts
# Rebuild from scratch
Testing
Comprehensive test suite with unit tests, integration tests, property-based tests, and numerical accuracy validation.
Run All Tests
# Run standard test suite
# Run with verbose output
# Run documentation tests
# Run specific test
# Run ignored tests (requires full implementation)
Property-Based Testing
The library uses proptest for property-based testing:
# Run property tests with verbose output
Test Organization
- Unit tests: Embedded in source files (
#[cfg(test)]modules) - Integration tests: Located in
tests/directory - Documentation tests: Code examples in doc comments
- Property tests: Randomized test generation with proptest
Test Coverage
Current implementation status (verify with tests):
# Run all tests and display pass/fail status
# Run only implemented features
iOS Cross-Compilation
Build for iOS devices and simulators with full ARM64 and x86_64 support.
Prerequisites
Install iOS targets (one-time setup):
Build for iOS Device
Output: target/aarch64-apple-ios/release/libthales.a
Build for iOS Simulator
Build for both Apple Silicon and Intel simulators:
# iOS simulator (Apple Silicon)
# iOS simulator (Intel)
Create Universal Simulator Library
Combine Intel and ARM simulator builds into a universal library:
Verify Library Architectures
# Check device library (should show arm64)
# Check simulator library (should show x86_64 and arm64)
Automated Build Script
Use the provided build script for convenience:
This script:
- Builds for all three iOS targets
- Creates universal simulator library
- Verifies architectures
- Copies generated Swift files to Xcode project
See IOS_BUILD.md for complete iOS integration guide including:
- Swift-Bridge code generation
- Xcode project configuration
- Library search paths
- Bridging header setup
- Xcode build phase integration
Swift-Bridge FFI
Build with FFI support for Swift bindings:
Generated files:
target/SwiftBridgeCore.swift- Core Swift bridge codetarget/thales.swift- Generated Swift APItarget/thales-Bridging-Header.h- Objective-C bridging header
Contributing
This is a private project for use with the SlipStick iOS app. Contributions are welcome via pull requests.
Code Standards
All contributions must adhere to these standards:
- Rust Idioms: Follow Rust 2021 edition idioms and best practices
- Zero Unsafe Code: No
unsafeblocks outside FFI boundary (core abstractions must be safe) - Clippy Compliance: Pass
clippy::pedanticlint checks: - Documentation: Comprehensive documentation with examples for all public APIs
- Test Coverage: Complete test coverage including:
- Unit tests for all functions
- Integration tests for complete workflows
- Documentation tests (code examples in doc comments)
- Property-based tests for numerical functions
- Performance: Benchmark performance-critical code paths:
- Formatting: Use
rustfmtfor consistent code style:
Development Workflow
- Fork the repository
- Create a feature branch:
git checkout -b feature/my-feature - Make changes following code standards
- Run tests:
cargo test - Run clippy:
cargo clippy -- -D warnings - Format code:
cargo fmt --all - Commit with conventional format (see below)
- Push and create pull request
Commit Format
Use conventional commits format:
<type>(<scope>): <subject>
<body>
<footer>
Types:
feat- New featurefix- Bug fixdocs- Documentation onlystyle- Code formatting (no logic change)refactor- Code change (neither fix nor feature)test- Adding or updating testschore- Auxiliary tools/librariesperf- Performance improvementci- CI configuration changesbuild- Build system/script changesrevert- Reverts previous commit
Scope: Optional, location of change (e.g., parser, solver, transforms)
Breaking Changes: Add ! after type/scope and include BREAKING CHANGE: in footer
Examples:
feat(transforms): add homogeneous transformation matrices
fix(parser): handle negative exponents correctly
Previous implementation failed to parse expressions like 10^-3
due to precedence issues with unary minus.
feat(solver)!: change solution return type to Result
BREAKING CHANGE: solve() now returns Result<Solution, Error>
instead of Option<Solution> for better error reporting.
Semantic Versioning
This project follows Semantic Versioning:
- Breaking changes → increment major version (1.0.0 → 2.0.0)
- New features (
feat) → increment minor version (1.0.0 → 1.1.0) - Bug fixes (
fix) → increment patch version (1.0.0 → 1.0.1)
Testing Requirements
Before submitting a pull request:
# Run full test suite
# Run clippy
# Format code
# Build documentation
# Run benchmarks (if touching performance-critical code)
Code Review Process
All pull requests require:
- Passing CI checks (tests, clippy, formatting)
- Code review approval
- Updated documentation
- Updated CHANGELOG.md
License
MIT License
Copyright (c) 2026 Christian C. Berclaz
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Dependencies
Core Dependencies
| Dependency | Version | Purpose |
|---|---|---|
| chumsky | 1.0.0-alpha.8 | Parser combinator library for expression and equation parsing with full operator precedence |
| num | 0.4 | Generic numeric types providing unified interface for all numeric operations |
| num-bigint | 0.4 | Arbitrary-precision integer arithmetic for exact symbolic computation |
| num-complex | 0.4 | Complex number types and operations (Complex64, polar form) |
| num-rational | 0.4 | Rational number types for exact fraction arithmetic |
| argmin | 0.10 | Numerical optimization framework for root-finding and minimization algorithms |
| nalgebra | 0.33 | Linear algebra library for matrix operations and coordinate transformations |
| fasteval | 0.2 | Fast expression evaluation engine for numerical computation |
| swift-bridge | 0.1 | Swift FFI bindings generator for iOS/macOS integration |
| serde | 1.0 | Serialization framework for data persistence and interchange |
| serde_json | 1.0 | JSON serialization support for equation and expression data |
Development Dependencies
| Dependency | Version | Purpose |
|---|---|---|
| proptest | 1.9 | Property-based testing framework for randomized test generation |
| criterion | 0.5 | Benchmarking framework with statistical analysis and regression detection |
Dependency Rationale
- chumsky: Modern parser combinator with excellent error reporting and composability
- num ecosystem: Industry-standard numeric types with comprehensive trait implementations
- argmin: Mature optimization library with multiple numerical methods
- nalgebra: High-performance linear algebra with extensive coordinate system support
- swift-bridge: Zero-overhead Swift FFI with automatic binding generation
- proptest: Gold standard for property-based testing in Rust
- criterion: Statistical benchmarking with visualization and regression detection
Version History
0.2.0 (2026-01-01) - Multi-Equation System Solver & Calculus
New Features:
-
Multi-Equation System Solver (
equation_systemmodule):- Solve systems of arbitrary equations (algebraic, ODE, differential, integral)
- Automatic dependency graph construction
- Topological sorting for optimal solving order
- Chained solution propagation between equations
- Unified
SystemResolutionPathfor step-by-step tracking - FFI bindings via
solve_equation_system_ffi()
-
Limits with L'Hôpital's Rule (
limitsmodule):- Direct substitution for continuous functions
- Limits at positive/negative infinity
- One-sided limits (left and right)
- Automatic L'Hôpital's rule for 0/0 and ∞/∞ indeterminate forms
- Detection of all indeterminate forms (0·∞, ∞-∞, 0⁰, 1^∞, ∞⁰)
- Special limits (sin(x)/x, tan(x)/x, (1-cos(x))/x²)
-
Partial Fraction Decomposition (
partial_fractionsmodule):- Decompose rational functions into partial fractions
- Support for linear and repeated linear factors
- Symbolic integration of decomposed forms
-
Pattern Matching (
patternmodule):- Rule-based expression rewriting
- Wildcard patterns with binding
- Commutativity-aware matching for + and *
- Common algebraic rules (identity, zero, double negation, etc.)
- Apply rules recursively to fixpoint
-
LaTeX Support (
latexmodule):- Parse LaTeX mathematical notation
- Support for
\frac,\sqrt,\sin,\cos, Greek letters, etc. - Render expressions to LaTeX output
- Display and inline math modes
-
Integration Enhancements (
integrationmodule):- Integration by parts with step tracking
- Integration by substitution
- Tabular integration method
- Improper integrals to infinity
-
ODE Solving (
odemodule):- First-order separable ODEs
- First-order linear ODEs
- Initial value problems
-
Trigonometric Simplification (
trigonometricmodule):- Pythagorean identities
- Double angle formulas
- Product-to-sum rules
- Quotient identities
- Step-by-step simplification
-
Inequality Solving (
inequalitymodule):- Linear and polynomial inequalities
- Interval solution representation
- Systems of inequalities
-
Matrix Expressions (
matrixmodule):- Matrix AST representation
- LaTeX rendering with bracket styles
-
Precision Control (
precisionmodule):- Configurable evaluation context
- Multiple rounding modes
- High-precision computation
Improvements:
- Extended FFI bindings for all new features
- 276+ unit tests with comprehensive coverage
- Enhanced resolution path tracking
0.1.0 (2025-12-17) - Initial Release
Implemented:
- Core AST definitions (
Expression,Equation,Variable,BinaryOp,UnaryOp,Function) - Complete coordinate transformation system:
- 2D: Cartesian ↔ Polar
- 3D: Cartesian ↔ Spherical
- 3D: Cartesian ↔ Cylindrical
- Full test coverage with round-trip verification
- Complex number operations:
- De Moivre's theorem implementation
- Polar form conversion
- Conjugate and modulus operations
- Expression parser using chumsky with full operator precedence
- Linear equation solver (ax + b = c form)
- Quadratic equation solver (ax² + bx + c = 0 with discriminant)
- Polynomial solver (companion matrix method)
- Transcendental equation solver (trig/exp/log functions)
- Smart solver with automatic method dispatch
- Numerical methods:
- Newton-Raphson with symbolic differentiation
- Bisection method
- Brent's hybrid method
- Secant method
- Levenberg-Marquardt
- Resolution path generation for step-by-step solutions
- Symbolic differentiation engine
- Basic symbolic integration
- iOS cross-compilation support:
- aarch64-apple-ios (device)
- aarch64-apple-ios-sim (ARM simulator)
- x86_64-apple-ios (Intel simulator)
- Universal library creation
- FFI bindings infrastructure with swift-bridge
- Test framework with proptest integration
- Benchmark infrastructure with criterion
- Documentation with comprehensive examples
- Build optimization (LTO, single codegen unit)
Future Roadmap
0.3.0 - Advanced Calculus
- Higher-order ODEs
- Systems of ODEs
- Partial derivatives and gradients
- Series expansions (Taylor, Fourier)
0.4.0 - Units and Dimensions
- Complete unit system
- Automatic conversions
- Dimensional analysis
1.0.0 - Stable Release
- API stabilization
- Performance optimization
- Comprehensive documentation
- Production-ready for iOS integration
References
Rust Language and Ecosystem
- The Rust Programming Language - Official Rust book
- Rust by Example - Learn Rust through examples
- Rust API Guidelines - API design best practices
- Cargo Book - Cargo package manager documentation
Core Libraries
- Chumsky Parser Tutorial - Parser combinator library
- Argmin Documentation - Numerical optimization framework
- Nalgebra User Guide - Linear algebra library
- num Crate Documentation - Generic numeric types
FFI and Mobile
- Swift-Bridge Guide - Swift FFI bindings
- Rust on iOS - Mozilla Blog - iOS integration guide
- Apple Developer: Using Swift with C and Objective-C - Bridging documentation
Testing and Benchmarking
- Proptest Book - Property-based testing
- Criterion.rs Guide - Benchmarking framework
- Rust Testing Guide - Official testing documentation
Mathematical Algorithms
- Numerical Recipes - Numerical algorithms reference
- Wolfram MathWorld - Mathematical encyclopedia
- Wikipedia: Coordinate Systems - Transformation formulas
Performance Optimization
- The Rust Performance Book - Performance optimization guide
- Rust Compiler Optimization - Compiler optimization flags
- Profile-Guided Optimization - PGO guide
Crate: crates.io/crates/thales Documentation: docs.rs/thales Repository: github.com/ChrisGVE/thales Issues: Report bugs and request features Author: Christian C. Berclaz Status: Active Development (v0.2.0)