simple_equation_inversion 1.0.1

A Rust library for solving linear equations and invertible function chains.
Documentation
use alloc::boxed::Box;
use alloc::rc::Rc;
use alloc::string::ToString;

use crate::element::Element;
use crate::element::element_kind::ElementKind;
use crate::error::Error;
use crate::transform::Transform;

impl Element {
    /// Applies a transformation to this element.
    ///
    /// If the element is a known constant, the transformation is evaluated immediately.
    /// If the element is an unknown or transformed expression, it wraps the element into a new [`ElementKind::Transformed`].
    pub fn apply(self, transform: Rc<dyn Transform>) -> Self {
        if self.error.is_err() {
            return self;
        }

        match self.kind {
            ElementKind::Known(val) => match transform.apply(val) {
                Ok(res) => Self::new_known(res),
                Err(msg) => Self {
                    kind: ElementKind::Known(val),
                    error: Err(Error::TransformError {
                        transform: transform.name().to_string(),
                        stage: "forward".to_string(),
                        value: val,
                        message: msg,
                    }),
                },
            },
            ElementKind::Variable { .. } | ElementKind::Transformed { .. } => Self {
                kind: ElementKind::Transformed {
                    factor: 1.0,
                    transform,
                    inner: Box::new(self),
                    offset: 0.0,
                },
                error: Ok(()),
            },
        }
    }

    /// Applies a concrete transformation implementing [`Transform`].
    pub fn transform(self, transform: impl Transform + 'static + Clone) -> Self {
        self.apply(Rc::new(transform))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::transform::FnTransform;
    #[allow(unused_imports)]
    use alloc::format;
    #[allow(unused_imports)]
    use alloc::string::ToString;
    use core::cell::RefCell;

    #[test]
    fn test_apply_transform_to_known() {
        let double = FnTransform::from_fn("double", |x| x * 2.0, |y| y / 2.0);
        let k = Element::known(10.0);
        let res = double.apply_to(k);
        assert_eq!(res.value(), Some(20.0));
        assert!(!res.is_unknown());
    }

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

        let k = Element::known(-4.0);
        let res = sqrt.apply_to(k);
        assert_eq!(
            res.error(),
            Err(Error::TransformError {
                transform: "sqrt".to_string(),
                stage: "forward".to_string(),
                value: -4.0,
                message: "negative".to_string(),
            })
        );
    }

    #[test]
    fn test_chained_transforms_tree() {
        let double = FnTransform::from_fn("double", |x| x * 2.0, |y| y / 2.0);
        let add_ten = FnTransform::from_fn("add_ten", |x| x + 10.0, |y| y - 10.0);

        let rc = Rc::new(RefCell::new(0.0));
        let x = Element::new_unknown(rc.clone());

        // add_ten(double(x)) == 30 => double(x) = 20 => x = 10
        let transformed = add_ten.apply_to(double.apply_to(x));
        assert_eq!(format!("{transformed}"), "add_ten(double(x))");

        let res = crate::Equation::new(transformed, 30.0).solve();
        assert_eq!(res, Ok(10.0));
        assert_eq!(*rc.borrow(), 10.0);
    }

    #[test]
    fn test_transformed_nested_expression() {
        let double = FnTransform::from_fn("double", |x| x * 2.0, |y| y / 2.0);

        let rc = Rc::new(RefCell::new(0.0));
        let x = Element::new_unknown(rc.clone());

        // double(x + 5.0) == 24 => x + 5 = 12 => x = 7
        let transformed = double.apply_to(x + 5.0);
        assert_eq!(format!("{transformed}"), "double(x + 5)");

        let res = crate::Equation::new(transformed, 24.0).solve();
        assert_eq!(res, Ok(7.0));
        assert_eq!(*rc.borrow(), 7.0);
    }
}