nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
Documentation
//! Closed motion/energy goals reuse the shared typed formulas and report formatter.
use super::{Domain, Mechanics};
use crate::{Context, Error, re};
use num_rational::BigRational;
use num_traits::{Signed, Zero};

impl Mechanics {
    fn inelastic_report(
        &self,
        first_input: &str,
        velocity_input: &str,
        second_input: &str,
        signed_change: bool,
        context: &Context,
    ) -> Result<String, Error> {
        let first = self.supplied_role(first_input, "kg", Domain::Positive, context)?;
        let velocity = self.supplied_role(velocity_input, "m/s", Domain::Signed, context)?;
        let second = self.supplied_role(second_input, "kg", Domain::Positive, context)?;
        self.supplied_role(
            &format!("{first}+{second}"),
            "kg",
            Domain::Positive,
            context,
        )?;
        let common = format!("{first}*{velocity}/({first}+{second})");
        // Reduced mass avoids subtracting nearly equal kinetic energies.
        let lost = format!("{first}*{second}/({first}+{second})*square({velocity})/2");
        let (velocity_label, energy_label, energy) = if signed_change {
            (
                "common velocity",
                "kinetic energy change",
                format!("-({lost})"),
            )
        } else {
            ("shared velocity", "kinetic energy lost", lost)
        };
        self.report(
            &[(velocity_label, "m/s", common), (energy_label, "J", energy)],
            context,
        )
    }

    fn spring_report(
        &self,
        stiffness_input: &str,
        compression_input: &str,
        context: &Context,
    ) -> Result<String, Error> {
        let stiffness = self.supplied_role(stiffness_input, "N/m", Domain::Positive, context)?;
        let compression =
            self.supplied_role(compression_input, "m", Domain::Nonnegative, context)?;
        let k = crate::plugins::model_coordinates::read(
            stiffness_input,
            "N/m",
            &self.compositions,
            context,
        )?;
        let x = crate::plugins::model_coordinates::read(
            compression_input,
            "m",
            &self.compositions,
            context,
        )?;
        if k.authored && x.authored {
            let force = crate::plugins::model_coordinates::bounded(&k.value * &x.value)?;
            let energy = crate::plugins::model_coordinates::bounded(
                force.clone() * &x.value / BigRational::from_integer(2.into()),
            )?;
            let typed = |value: &BigRational, unit: &str| {
                format!("(rational({},{}) {unit})", value.numer(), value.denom())
            };
            self.report(
                &[
                    ("force magnitude", "N", typed(&force, "N")),
                    ("elastic potential energy", "J", typed(&energy, "J")),
                ],
                context,
            )
        } else {
            self.report(
                &[
                    ("force magnitude", "N", format!("{stiffness}*{compression}")),
                    (
                        "elastic potential energy",
                        "J",
                        format!("{stiffness}*square({compression})/2"),
                    ),
                ],
                context,
            )
        }
    }
    fn supplied_role(
        &self,
        input: &str,
        reference: &str,
        domain: Domain,
        context: &Context,
    ) -> Result<String, Error> {
        let coordinate =
            crate::plugins::model_coordinates::read(input, reference, &self.compositions, context)?;
        if (!matches!(domain, Domain::Signed) && coordinate.value.is_negative())
            || (matches!(domain, Domain::Positive) && coordinate.value.is_zero())
        {
            return Err(Error("invalid_physical_quantity".into()));
        }
        // Retaining the original typed role also retains computed-call provenance.
        Ok(format!("({input})"))
    }
    pub(super) fn supplied_reports(
        &self,
        input: &str,
        context: &Context,
    ) -> Result<Option<String>, Error> {
        if input.len() > 4096 {
            return Ok(None);
        }
        macro_rules! q {
            ($c:ident,$n:literal,$unit:literal,$domain:ident) => {
                self.supplied_role(&$c[$n], $unit, Domain::$domain, context)?
            };
        }
        if let Some(c) = re!(r"(?i)^a (.+?) [a-z]+ moving at (.+?) couples in a perfectly inelastic collision with a stationary (.+?) [a-z]+[.] report their common velocity and the signed kinetic energy change, using momentum conservation$").captures(input) {
            return self.inelastic_report(&c[1], &c[2], &c[3], true, context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a (.+?) [a-z]+ at (.+?) sticks to a (.+?) [a-z]+ at (.+?)\. give (final signed velocity and the momentum before impact|the momentum before impact and final signed velocity)$").captures(input) {
            let first = crate::plugins::model_coordinates::read(&c[1], "kg", &self.compositions, context)?;
            let second = crate::plugins::model_coordinates::read(&c[3], "kg", &self.compositions, context)?;
            if first.value.is_negative() || second.value.is_negative()
                || crate::plugins::model_coordinates::bounded(&first.value + &second.value)?.is_zero() {
                return Err(Error("invalid_physical_quantity".into()));
            }
            let first_mass = format!("({})", &c[1]);
            let second_mass = format!("({})", &c[3]);
            let first_velocity = self.supplied_role(&c[2].replace('−', "-"), "m/s", Domain::Signed, context)?;
            let second_velocity = self.supplied_role(&c[4].replace('−', "-"), "m/s", Domain::Signed, context)?;
            let momentum = format!("{first_mass}*{first_velocity}+{second_mass}*{second_velocity}");
            let final_velocity = format!("({momentum})/({first_mass}+{second_mass})");
            let fields = if c[5].eq_ignore_ascii_case("final signed velocity and the momentum before impact") {
                vec![
                    ("final signed velocity", "m/s", final_velocity),
                    ("momentum before impact", "kg·m/s", momentum),
                ]
            } else {
                vec![
                    ("momentum before impact", "kg·m/s", momentum),
                    ("final signed velocity", "m/s", final_velocity),
                ]
            };
            return self.report(&fields, context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^an? (.+) [a-z]+ changes velocity from (.+?) to (.+?); report signed momentum change and kinetic energy change$").captures(input) {
            let mass = q!(c, 1, "kg", Nonnegative);
            let initial = self.supplied_role(&c[2].replace('−', "-"), "m/s", Domain::Signed, context)?;
            let final_velocity = self.supplied_role(&c[3].replace('−', "-"), "m/s", Domain::Signed, context)?;
            return self.report(&[
                ("momentum change", "kg·m/s", format!("{mass}*({final_velocity}-{initial})")),
                ("kinetic energy change", "J", format!("{mass}*(square({final_velocity})-square({initial}))/2")),
            ], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a (.+?) load is shared by supports ([A-Za-z][A-Za-z0-9_]*) and ([A-Za-z][A-Za-z0-9_]*), with support ([A-Za-z][A-Za-z0-9_]*) carrying (.+?) the load of ([A-Za-z][A-Za-z0-9_]*)[.] report each signed upward reaction and verify their sum balances the load$").captures(input) {
            if c[2].eq_ignore_ascii_case(&c[3])
                || !c[2].eq_ignore_ascii_case(&c[4])
                || !c[3].eq_ignore_ascii_case(&c[6]) {
                return Err(Error("invalid_expression".into()));
            }
            let ratio_input = if c[5].eq_ignore_ascii_case("twice") {
                "2".to_string()
            } else {
                re!(r"(?i)^(.+?) times?$").captures(&c[5])
                    .map(|part| part[1].to_string())
                    .ok_or_else(|| Error("invalid_expression".into()))?
            };
            let load = crate::plugins::model_coordinates::read(
                &c[1], "N", &self.compositions, context)?;
            let ratio = crate::plugins::model_coordinates::read(
                &ratio_input, "1", &self.compositions, context)?;
            if load.value.is_negative() || ratio.value.is_negative() {
                return Err(Error("invalid_physical_quantity".into()));
            }
            let bounded = crate::plugins::model_coordinates::bounded;
            let second = bounded(&load.value / (&ratio.value + BigRational::from_integer(1.into())))?;
            let first = bounded(&ratio.value * &second)?;
            if bounded(first + second)? != load.value {
                return Err(Error("invalid_expression".into()));
            }
            let report = format!("mechanics_support_report({};{};{};{})",
                super::encode_support(&c[2]), super::encode_support(&c[3]),
                super::typed_coordinate(&load, "N")?, super::typed_coordinate(&ratio, "1")?);
            if report.len() > 4096 {
                return Err(Error("invalid_expression".into()));
            }
            return Ok(Some(report));
        }
        if let Some(c) = re!(r"(?i)^an? [a-z][a-z '-]* starts from rest and accelerates uniformly at (.+?) for (.+?); (?:find|calculate) its final speed and displacement$").captures(input) {
            let acceleration = q!(c, 1, "m/s²", Signed);
            let time = q!(c, 2, "seconds", Nonnegative);
            return self.report(&[
                ("final speed", "m/s", format!("abs({acceleration}*{time})")),
                ("displacement", "m", format!("{acceleration}*square({time})/2")),
            ], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a (.+?) [a-z]+ moving at (.+?) receives a constant (.+?) forward force for (.+?) on a frictionless level track\. use a\s*=\s*F/m and constant-acceleration kinematics; report acceleration, final speed, displacement during the (.+?), and final kinetic energy using KE\s*=\s*mv(?:\^2|²)/2$").captures(input) {
            let mass = q!(c, 1, "kg", Positive);
            let initial = q!(c, 2, "m/s", Nonnegative);
            let force = q!(c, 3, "N", Nonnegative);
            let time = q!(c, 4, "seconds", Nonnegative);
            let repeated = crate::plugins::model_coordinates::read(&c[5], "seconds", &self.compositions, context)?;
            let original = crate::plugins::model_coordinates::read(&c[4], "seconds", &self.compositions, context)?;
            if repeated.value != original.value {
                return Err(Error("invalid_physical_quantity".into()));
            }
            let acceleration = format!("{force}/{mass}");
            let final_speed = format!("{initial}+({acceleration})*{time}");
            return self.report(&[
                ("acceleration", "m/s²", acceleration.clone()),
                ("final speed", "m/s", final_speed.clone()),
                ("displacement", "m", format!("{initial}*{time}+({acceleration})*square({time})/2")),
                ("final kinetic energy", "J", format!("{mass}*square({final_speed})/2")),
            ], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a (.+?) [a-z]+ moving at (.+?) stops uniformly over (.+?); using v(?:²|\^2)\s*=\s*u(?:²|\^2)\s*\+\s*2as and F\s*=\s*ma, report acceleration and signed net force$").captures(input) {
            let mass = q!(c, 1, "kg", Positive);
            let speed = q!(c, 2, "m/s", Positive);
            let distance = q!(c, 3, "m", Positive);
            let acceleration = format!("-square({speed})/(2*{distance})");
            return self.report(&[
                ("acceleration", "m/s²", acceleration.clone()),
                ("net force", "N", format!("{mass}*({acceleration})")),
            ], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a spring obeys F\s*=\s*kx and E\s*=\s*kx\^2/2; with k\s*=\s*(.+?) and compression x\s*=\s*(.+?), report force and stored energy$").captures(input) {
            return self.spring_report(&c[1], &c[2], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a (.+?) [a-z]+ accelerates at (.+?) under the supplied F\s*=\s*ma model; find net force and momentum at (.+)$").captures(input) {
            let mass = q!(c, 1, "kg", Positive);
            let acceleration = q!(c, 2, "m/s²", Signed);
            let speed = q!(c, 3, "m/s", Signed);
            return self.report(&[
                ("net force", "N", format!("{mass}*{acceleration}")),
                ("momentum", "kg·m/s", format!("{mass}*{speed}")),
            ], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a (.+?) [a-z]+ moving at (.+?) brakes uniformly to rest in (.+?); what is its acceleration and the magnitude of the average braking force$").captures(input) {
            let mass = q!(c, 1, "kg", Positive);
            let speed = q!(c, 2, "m/s", Nonnegative);
            let duration = q!(c, 3, "seconds", Positive);
            // Initial travel defines the positive axis; braking acceleration is signed.
            let acceleration = format!("-{speed}/{duration}");
            return self.report(&[("acceleration", "m/s²", acceleration.clone()),
                ("braking force magnitude", "N", format!("abs({mass}*({acceleration}))"))], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a spring with (?:stiffness|constant) (.+?) is compressed by (.+?); what force magnitude does it exert and how much elastic potential energy is stored$").captures(input) {
            return self.spring_report(&c[1], &c[2], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a (.+?) [a-z]+ is pushed with (.+?) against (.+?) friction; (?:find|calculate) net force and acceleration$").captures(input) {
            let mass = q!(c,1,"kg",Positive);
            let force = q!(c,2,"N",Nonnegative);
            let friction = q!(c,3,"N",Nonnegative);
            let net = format!("{force}-{friction}");
            return self.report(&[("net force","N",net.clone()),("acceleration","m/s²",format!("({net})/{mass}"))], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a (.+?) [a-z]+ moves at (.+?) and rebounds at (.+?) in the opposite direction; (?:calculate|find) momentum change$").captures(input) {
            let mass = q!(c,1,"kg",Nonnegative);
            let initial = q!(c,2,"m/s",Nonnegative);
            let rebound = q!(c,3,"m/s",Nonnegative);
            // Standard one-axis convention: initial motion is positive; delta is final minus initial.
            return Ok(Some(format!("{mass}*(-{rebound}-{initial}) in kg·m/s")));
        }
        if let Some(c) = re!(r"(?i)^a (.+?) [a-z]+ rises (.+?) in (.+?); (?:calculate|find) work against gravity and average power using g\s*=\s*(.+)$").captures(input) {
            let mass = q!(c,1,"kg",Positive);
            let height = q!(c,2,"m",Nonnegative);
            let time = q!(c,3,"seconds",Positive);
            let gravity = q!(c,4,"m/s²",Positive);
            let work = format!("{mass}*{gravity}*{height}");
            return self.report(&[("work","J",work.clone()),("average power","W",format!("({work})/{time}"))],context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a force of (.+?) points (.+?) from a (.+?) displacement; (?:calculate|find) work using W\s*=\s*Fd\s+cos\(theta\)$").captures(input) {
            let force = q!(c,1,"N",Nonnegative);
            let angle = q!(c,2,"radians",Signed);
            let displacement = q!(c,3,"m",Nonnegative);
            return Ok(Some(format!("{force}*{displacement}*cos({angle}) in J")));
        }
        if let Some(c) = re!(r"(?i)^a spring with constant (.+?) is compressed by (.+?); (?:calculate|find) stored energy using one half kx squared$").captures(input) {
            let spring = q!(c,1,"N/m",Positive);
            let displacement = q!(c,2,"m",Nonnegative);
            return Ok(Some(format!("{spring}*square({displacement})/2 in J")));
        }
        if let Some(c) = re!(r"(?i)^a (.+?) [a-z]+ rests on a horizontal floor with coefficient of static friction (.+?); (?:calculate|find) maximum static friction using g\s*=\s*(.+)$").captures(input) {
            let mass = q!(c,1,"kg",Positive);
            let coefficient = q!(c,2,"1",Nonnegative);
            let gravity = q!(c,3,"m/s²",Positive);
            return Ok(Some(format!("{coefficient}*{mass}*{gravity} in N")));
        }
        if let Some(c) =
            re!(r"(?i)^a (.+?) mass occupies (.+?); (?:calculate|find) density in (.+?) and (.+)$")
                .captures(input)
        {
            let mass = q!(c, 1, "kg", Nonnegative);
            let volume = q!(c, 2, "m³", Positive);
            let density = format!("{mass}/{volume}");
            return self
                .report(
                    &[
                        ("density", &c[3], density.clone()),
                        ("density", &c[4], density),
                    ],
                    context,
                )
                .map(Some);
        }
        if let Some(c) = re!(r"(?i)^a (.+?) long train passes a pole in (.+?); (?:calculate|find) its speed in (.+?) and (.+)$").captures(input) {
            let length = q!(c,1,"m",Positive);
            let time = q!(c,2,"seconds",Positive);
            let speed = format!("{length}/{time}");
            return self.report(&[("speed",&c[3],speed.clone()),("speed",&c[4],speed)],context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a cyclist rides (.+?) in (.+?); (?:find|calculate) average speed in (.+?) and (.+)$").captures(input) {
            let distance = q!(c,1,"m",Nonnegative);
            let time = q!(c,2,"seconds",Positive);
            let speed = format!("{distance}/{time}");
            return self.report(&[("average speed",&c[3],speed.clone()),("average speed",&c[4],speed)],context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a (.+?) hiker gains (.+?) elevation; using g\s*=\s*(.+?), (?:calculate|find) the increase in gravitational potential energy in (.+)$").captures(input) {
            let mass = q!(c,1,"kg",Positive);
            let height = q!(c,2,"m",Nonnegative);
            let gravity = q!(c,3,"m/s²",Positive);
            self.compositions.quantity_value(&format!("1 {}",&c[4]),"J",context)?;
            return Ok(Some(format!("{mass}*{gravity}*{height} in {}",&c[4])));
        }
        if let Some(c) = re!(r"(?i)^a (.+?) ball moves at (.+?); (?:find|calculate) momentum and kinetic energy, then find the speed that would give twice its kinetic energy$").captures(input) {
            let mass = q!(c,1,"kg",Positive);
            let speed = q!(c,2,"m/s",Nonnegative);
            return self.report(&[("momentum","kg·m/s",format!("{mass}*{speed}")),
                ("kinetic energy","J",format!("{mass}*square({speed})/2")),
                ("speed for twice kinetic energy","m/s",format!("{speed}*sqrt(2)"))],context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a (.+?) object moving at (.+?) collides and sticks to a (.+?) object at rest; (?:calculate|find) the shared velocity and kinetic energy lost$").captures(input) {
            return self.inelastic_report(&c[1], &c[2], &c[3], false, context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a (.+?) object is dropped from (.+?) with no air resistance; using g\s*=\s*(.+?), (?:find|calculate) fall time and impact speed$").captures(input) {
            let _mass = q!(c,1,"kg",Positive);
            let height = q!(c,2,"m",Nonnegative);
            let gravity = q!(c,3,"m/s²",Positive);
            return self.report(&[("fall time","s",format!("sqrt(2*{height}/{gravity})")),
                ("impact speed","m/s",format!("sqrt(2*{gravity}*{height})"))],context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a (.+?) force acts on a (.+?) object on a frictionless surface for (.+?) from rest; (?:calculate|find) acceleration, final speed, and distance$").captures(input) {
            let force = q!(c,1,"N",Signed);
            let mass = q!(c,2,"kg",Positive);
            let time = q!(c,3,"seconds",Nonnegative);
            let acceleration = format!("{force}/{mass}");
            return self.report(&[("acceleration","m/s²",acceleration.clone()),
                ("final speed","m/s",format!("abs(({acceleration})*{time})")),
                ("distance","m",format!("abs({acceleration})*square({time})/2"))],context).map(Some);
        }
        Ok(None)
    }
}