simple_equation_inversion 1.0.1

A Rust library for solving linear equations and invertible function chains.
Documentation
use alloc::rc::Rc;
use alloc::string::String;
use core::fmt;

use crate::element::Element;

/// A mathematical or domain-specific invertible transformation.
pub trait Transform: fmt::Debug {
    /// Applies the transformation in the forward direction: y = f(x)
    fn apply(&self, x: f64) -> Result<f64, String>;

    /// Inverts the transformation to solve for x: x = f⁻¹(y)
    fn invert(&self, y: f64) -> Result<f64, String>;

    /// Human-readable name of the transformation for error reports and compute logging.
    fn name(&self) -> &str {
        "transform"
    }

    /// Applies this transformation to an [`Element`].
    fn apply_to(&self, element: impl Into<Element>) -> Element
    where
        Self: 'static + Sized + Clone,
    {
        let elem = element.into();
        elem.apply(Rc::new(self.clone()))
    }
}

/// A function/closure-based [`Transform`].
#[derive(Clone)]
pub struct FnTransform {
    name: String,
    forward_fn: Rc<dyn Fn(f64) -> Result<f64, String>>,
    inverse_fn: Rc<dyn Fn(f64) -> Result<f64, String>>,
}

impl FnTransform {
    /// Creates a new `FnTransform` from fallible forward and inverse closures returning `Result<f64, String>`.
    pub fn new<F, I>(name: impl Into<String>, forward: F, inverse: I) -> Self
    where
        F: Fn(f64) -> Result<f64, String> + 'static,
        I: Fn(f64) -> Result<f64, String> + 'static,
    {
        Self {
            name: name.into(),
            forward_fn: Rc::new(forward),
            inverse_fn: Rc::new(inverse),
        }
    }

    /// Creates a new `FnTransform` from infallible mathematical functions `f64 -> f64`.
    pub fn from_fn<F, I>(name: impl Into<String>, forward: F, inverse: I) -> Self
    where
        F: Fn(f64) -> f64 + 'static,
        I: Fn(f64) -> f64 + 'static,
    {
        Self::new(name, move |x| Ok(forward(x)), move |y| Ok(inverse(y)))
    }

    /// Applies this transformation to an [`Element`].
    pub fn apply_to(&self, element: impl Into<Element>) -> Element {
        let elem = element.into();
        elem.apply(Rc::new(self.clone()))
    }
}

impl fmt::Debug for FnTransform {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "FnTransform({})", self.name)
    }
}

impl Transform for FnTransform {
    fn apply(&self, x: f64) -> Result<f64, String> {
        (self.forward_fn)(x)
    }

    fn invert(&self, y: f64) -> Result<f64, String> {
        (self.inverse_fn)(y)
    }

    fn name(&self) -> &str {
        &self.name
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[allow(unused_imports)]
    use alloc::format;
    #[allow(unused_imports)]
    use alloc::string::ToString;

    #[test]
    fn test_fn_transform_infallible() {
        let double = FnTransform::from_fn("double", |x| x * 2.0, |y| y / 2.0);
        assert_eq!(double.name(), "double");
        assert_eq!(double.apply(5.0), Ok(10.0));
        assert_eq!(double.invert(10.0), Ok(5.0));

        // Applied to known element
        let elem = double.apply_to(5.0);
        assert_eq!(elem.value(), Some(10.0));
        assert!(!elem.is_unknown());
    }

    #[test]
    fn test_fn_transform_fallible_success() {
        let sqrt = FnTransform::new(
            "sqrt",
            |x| {
                if x < 0.0 {
                    Err("negative input".to_string())
                } else {
                    Ok(x.sqrt())
                }
            },
            |y| {
                if y < 0.0 {
                    Err("negative inverse input".to_string())
                } else {
                    Ok(y * y)
                }
            },
        );

        assert_eq!(sqrt.apply(25.0), Ok(5.0));
        assert_eq!(sqrt.invert(5.0), Ok(25.0));

        let elem = sqrt.apply_to(16.0);
        assert_eq!(elem.value(), Some(4.0));
    }

    #[test]
    fn test_fn_transform_fallible_error_propagation() {
        let sqrt = FnTransform::new(
            "sqrt",
            |x| {
                if x < 0.0 {
                    Err("negative input".to_string())
                } else {
                    Ok(x.sqrt())
                }
            },
            |y| {
                if y < 0.0 {
                    Err("negative inverse input".to_string())
                } else {
                    Ok(y * y)
                }
            },
        );

        assert!(sqrt.apply(-4.0).is_err());
        assert!(sqrt.invert(-4.0).is_err());

        // Applied to known negative element
        let elem = sqrt.apply_to(-4.0);
        assert!(elem.error().is_err());
    }

    #[test]
    fn test_custom_struct_transform() {
        #[derive(Clone, Debug)]
        struct LinearScaling {
            factor: f64,
        }

        impl Transform for LinearScaling {
            fn apply(&self, x: f64) -> Result<f64, String> {
                Ok(x * self.factor)
            }
            fn invert(&self, y: f64) -> Result<f64, String> {
                if self.factor == 0.0 {
                    return Err("factor cannot be zero".to_string());
                }
                Ok(y / self.factor)
            }
            fn name(&self) -> &str {
                "LinearScaling"
            }
        }

        let scaler = LinearScaling { factor: 3.0 };
        assert_eq!(scaler.name(), "LinearScaling");
        assert_eq!(scaler.apply(4.0), Ok(12.0));
        assert_eq!(scaler.invert(12.0), Ok(4.0));

        let zero_scaler = LinearScaling { factor: 0.0 };
        assert!(zero_scaler.invert(12.0).is_err());
    }
}