Skip to main content

Crate simple_equation_inversion

Crate simple_equation_inversion 

Source
Expand description

§simple_equation_inversion

Rust Edition License

Define an equation once, solve it for any variable — fully no_std.

simple_equation_inversion is a Rust library for solving linear equations and invertible function chains. Given an equation with one unknown variable, it isolates and computes the value of the unknown.

§Usage

The crate provides three ways to express equations, plus support for custom invertible transformations.

§1. Inline Expressions (solve!)

For direct computations without declaring a struct:

use simple_equation_inversion::solve;

// Specify target variable with `for <var> in ...`
let x = solve!(for x in 3.0 * x + 7.0 = 22.0)?;
assert_eq!(x, 5.0);

// Or with prefix syntax `<var>: ...`
let voltage = solve!(u: u = 220.0 * 0.5)?;
assert_eq!(voltage, 110.0);

// Fractions and parentheses
let current = solve!(i: 230.0 = (100.0 * i) / 2.0 + 30.0)?;
assert_eq!(current, 4.0);

§2. Struct Model (#[derive(Equation)])

For domain structs where fields represent equation variables. Define the relationship directly with #[equation(...)]:

use simple_equation_inversion::element::Element;
use simple_equation_inversion::equation::EquationAutoCompute;
use simple_equation_inversion::equation::EquationElement;
use simple_equation_inversion::Equation;

#[derive(Equation)]
#[equation(voltage = resistance * current)]
pub struct OhmsLaw {
    #[variable]
    pub voltage: EquationElement,
    #[variable]
    pub resistance: EquationElement,
    #[variable]
    pub current: EquationElement,
}

// Leave the variable to solve for as `Element::unknown()`:
let circuit = OhmsLaw {
    voltage: Element::known(230.0),
    resistance: Element::known(46.0),
    current: Element::unknown(),
};

let i = circuit.solve()?;
assert_eq!(i, 5.0);

You can also omit #[equation(...)] and implement EquationAutoCompute manually if needed:

use simple_equation_inversion::equation::EquationAutoCompute;
use simple_equation_inversion::solve;

impl EquationAutoCompute for OhmsLaw {
    fn simple_equation_inversion(&self) -> Result<f64, simple_equation_inversion::Error> {
        let Self { voltage, resistance, current } = self;
        solve!(voltage = resistance * current)
    }
}

§3. Declarative Formula (declare_equation!)

Generates a struct with builder setters from a formula string. Free variables are detected at compile time, and whichever variable is omitted (None) is solved for:

use simple_equation_inversion::declare_equation;

declare_equation! {
    pub struct KineticEnergy {
        formula: "energy = factor * mass * v_squared",
        constants: {
            factor: 0.5,
        }
    }
}

// Solve for energy (energy is omitted):
let e = KineticEnergy::new()
    .mass(10.0)
    .v_squared(16.0)
    .solve()?;

assert_eq!(e, 80.0);

// Solve for mass (mass is omitted):
let m = KineticEnergy::new()
    .energy(80.0)
    .v_squared(16.0)
    .solve()?;

assert_eq!(m, 10.0);

An attribute macro is also available for empty structs:

use simple_equation_inversion::equation;

#[equation("force = mass * acceleration")]
pub struct NewtonSecondLaw;

let a = NewtonSecondLaw::new()
    .force(50.0)
    .mass(10.0)
    .solve()?;

assert_eq!(a, 5.0);

§4. Invertible Transformations

Equations can include custom transformations as long as an inverse is provided. Functions can be called directly in equations (f(x)).

§Closure-based (FnTransform)
use simple_equation_inversion::solve;
use simple_equation_inversion::transform::FnTransform;

// A 20% haircut: forward = x * 0.8, inverse = y / 0.8
let haircut = FnTransform::from_fn("haircut_20", |v| v * 0.8, |c| c / 0.8);

let position = solve!(for pos in haircut(pos * 100.0) = 4000.0)?;
assert_eq!(position, 50.0);
§In declare_equation!
use simple_equation_inversion::declare_equation;
use simple_equation_inversion::transform::FnTransform;

declare_equation! {
    pub struct Collateral {
        formula: "collateral = h(position * price)",
        transforms: {
            h: FnTransform::from_fn("haircut_15", |v| v * 0.85, |c| c / 0.85),
        }
    }
}

let required = Collateral::new()
    .position(50.0)
    .price(100.0)
    .solve()?;
§Custom Transform Implementation

For stateful or fallible transformations, implement the Transform trait:

use simple_equation_inversion::{solve, Transform};

#[derive(Clone, Debug)]
pub struct Haircut {
    pub rate: f64,
}

impl Transform for Haircut {
    fn apply(&self, x: f64) -> Result<f64, String> {
        if x < 0.0 {
            return Err("Asset value cannot be negative".into());
        }
        Ok(x * (1.0 - self.rate))
    }

    fn invert(&self, y: f64) -> Result<f64, String> {
        if y < 0.0 {
            return Err("Collateral cannot be negative".into());
        }
        Ok(y / (1.0 - self.rate))
    }

    fn name(&self) -> &str {
        "Haircut"
    }
}

let haircut = Haircut { rate: 0.20 };

// Forward calculation:
let collateral = solve!(for col in col = haircut(5000.0))?;
assert_eq!(collateral, 4000.0);

// Inverse calculation:
let position = solve!(for pos in haircut(pos * 100.0) = 4000.0)?;
assert_eq!(position, 50.0);

§How It Works

Expressions are represented as an ElementKind tree:

  • Known(f64): A known scalar constant.
  • Variable { factor, unknown, offset }: An unknown in affine form (factor * x + offset).
  • Transformed { factor, transform, inner, offset }: A transformation applied to an expression (factor * T(inner) + offset).

When Equation::new(lhs, rhs).solve() or solve!(lhs = rhs) is called, the solver reduces the expression to lhs - rhs = 0 and isolates x:

  1. If the node is Variable, $x = -\text{offset} / \text{factor}$.
  2. If the node is Transformed, the solver inverts the transform and recurses on inner.
  3. If the node is Known, returns Error::NoUnknown.

§Error Handling

All solvers return Result<f64, simple_equation_inversion::Error>.

Error VariantCause
NoUnknownNo unknown variable found in the equation
SeveralUnknownMore than one distinct unknown variable found
DivisionByZeroDivision by a constant evaluating to 0
UnknownInDenominatorVariable appears in a denominator
SquareForbiddenMultiplication of two variable terms ($x \cdot x$)
TransformErrorA Transform’s apply or invert returned an error

Errors are latched during expression evaluation and returned on .solve() rather than panicking.

§Diagnostics

Logging can be enabled via Cargo features:

  • debug-structure: Prints struct field analysis at macro expansion time.
  • debug-setup: Logs field values and unknown detection at runtime.
  • debug-compute: Traces equation reduction and solving steps.
  • debug-all: Enables all of the above.

§Benchmarks

Run benchmarks with Criterion:

cargo bench --bench solving_benchmark

Measurements (Intel / AMD x86_64, Linux):

ImplementationTime
Direct analytical formula (c - b) / a~1.5 ns
solve! macro~129 ns
declare_equation! struct~145 ns
#[derive(Equation)] struct~200 ns
FnTransform inversion~227 ns

§Examples

Run the examples in examples/:

cargo run --example electrical_ohms_law
cargo run --example physics_ideal_gas
cargo run --example financial_haircut

§Running Tests

./test.sh

§License

Dual-licensed under either of:

  • Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
  • MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)

at your option.

Re-exports§

pub use element::Element;
pub use equation::Equation;
pub use equation::EquationAutoCompute;
pub use equation::EquationElement;
pub use error::Error;
pub use transform::FnTransform;
pub use transform::Transform;

Modules§

element
equation
error
logger
Zero-cost conditional logging infrastructure for simple_equation_inversion.
transform
unknown

Macros§

declare_equation
solve

Attribute Macros§

equation

Derive Macros§

Equation