nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
Documentation
//! Supplied electrical roles lower to the existing typed evaluator.
//! Battery answers use only the explicitly requested rated/ideal model; AC roles require RMS/PF.
use super::compositions::Compositions;
use crate::{Context, Error, ModelPosition, Outcome, Plugin, re};

mod models;

#[derive(Default)]
pub struct ElectricalQueries {
    compositions: Compositions,
}

#[derive(Clone, Copy)]
enum Domain {
    Signed,
    Nonnegative,
    Positive,
    PowerFactor,
    PositivePowerFactor,
}

/// Explicit goal words within the complete supplied electrical-relation model.
pub(super) fn supplied_formula_target(role: &str) -> Option<&'static str> {
    match role.trim().to_ascii_lowercase().as_str() {
        "current" => Some("A"),
        "voltage" => Some("V"),
        "resistance" => Some("Ω"),
        _ => None,
    }
}

/// Authored equations preserve signed coordinates, unlike passive magnitude models.
pub(super) fn supplied_formula_role(
    role: &str,
    value: &str,
    engine: &Compositions,
    context: &Context,
) -> Result<String, Error> {
    let reference =
        supplied_formula_target(role).ok_or_else(|| Error("invalid_expression".into()))?;
    if value.len() > 4096 {
        return Err(Error("expression_too_complex".into()));
    }
    typed_role(engine, value, reference, Domain::Signed, context)
}

fn typed_role(
    engine: &Compositions,
    input: &str,
    reference: &str,
    domain: Domain,
    context: &Context,
) -> Result<String, Error> {
    let value = engine.quantity_value(input, reference, context)?;
    let positive = matches!(domain, Domain::Positive | Domain::PositivePowerFactor);
    let factor = matches!(domain, Domain::PowerFactor | Domain::PositivePowerFactor);
    if (value < 0.0 && !matches!(domain, Domain::Signed))
        || (positive && value == 0.0)
        || (factor && value > 1.0)
    {
        return Err(Error("invalid_physical_value".into()));
    }
    Ok(format!("({input})"))
}

impl Plugin for ElectricalQueries {
    fn rewrite_model(&self, input: &str, context: &Context, _: ModelPosition) -> Outcome {
        self.lower(input, context).transpose()
    }
    fn rewrite(&self, input: &str, context: &Context) -> Outcome {
        super::syntax::rewrite_groups(input, |part| self.lower(part, context).transpose())
    }

    fn evaluate(&self, input: &str, context: &Context) -> Outcome {
        let input = super::syntax::ungroup(input);
        let Some(inner) = input
            .strip_prefix("electrical_power_pair(")
            .and_then(|s| s.strip_suffix(')'))
        else {
            return self.evaluate_models(input, context);
        };
        Some((|| {
            let args = super::named_quantities::function_arguments(inner, false)?;
            if args.len() != 3 {
                return Err(Error("invalid_expression".into()));
            }
            let v = self.role(args[0], "V", Domain::Nonnegative, context)?;
            let i = self.role(args[1], "A", Domain::Nonnegative, context)?;
            let pf = self.role(args[2], "1", Domain::PowerFactor, context)?;
            let real = self.calculate(&format!("({v} * {i} * {pf}) in W"), context)?;
            let apparent = self.calculate(&format!("({v} * {i}) in VA"), context)?;
            Ok(format!("real power: {real}; apparent power: {apparent}"))
        })())
    }
}

impl ElectricalQueries {
    fn calculate(&self, expression: &str, context: &Context) -> Result<String, Error> {
        self.compositions
            .evaluate(expression, context)
            .unwrap_or_else(|| Err(Error("invalid_expression".into())))
    }

    fn role(
        &self,
        input: &str,
        reference: &str,
        domain: Domain,
        context: &Context,
    ) -> Result<String, Error> {
        typed_role(&self.compositions, input, reference, domain, context)
    }

    fn lower(&self, input: &str, context: &Context) -> Result<Option<String>, Error> {
        // Full sentence rules assign roles, rather than scanning unrelated arithmetic for numbers.
        if !re!(r"(?i)\b(resistor|resistors|resistance|ohms?|voltage|battery|cell|circuit|capacitor|capacitance|transformer|power factor|PF|AC load|AC appliance|heater)\b").is_match(input) {
            return Ok(None);
        }
        let input = input.trim().trim_end_matches(['.', '?']);
        if let Some(expression) = self.lower_models(input, context)? {
            return Ok(Some(expression));
        }
        macro_rules! q {
            ($c:ident, $n:literal, $unit:literal, $domain:ident) => {
                self.role(&$c[$n], $unit, Domain::$domain, context)?
            };
        }
        macro_rules! rule {
            ($pattern:literal, $target:literal, $c:ident, $formula:expr) => {
                if let Some($c) = re!($pattern).captures(input) {
                    let expression = $formula;
                    return Ok(Some(format!("({expression}) in {}", $target)));
                }
            };
        }
        // DC Ohm law and resistive power.
        rule!(
            r"(?i)^a (.+?) source across a (.+?) resistor: current$",
            "A",
            c,
            format!(
                "{} / {}",
                q!(c, 1, "V", Nonnegative),
                q!(c, 2, "Ω", Positive)
            )
        );
        rule!(
            r"(?i)^find the voltage drop across (.+?) when (.+?) flows$",
            "V",
            c,
            format!(
                "{} * {}",
                q!(c, 1, "Ω", Nonnegative),
                q!(c, 2, "A", Nonnegative)
            )
        );
        rule!(
            r"(?i)^what resistance would draw (.+?) from (.+?)$",
            "Ω",
            c,
            format!(
                "{} / {}",
                q!(c, 2, "V", Nonnegative),
                q!(c, 1, "A", Positive)
            )
        );
        rule!(
            r"(?i)^calculate power dissipated by a (.+?) resistor carrying (.+?)$",
            "W",
            c,
            format!(
                "{} * square({})",
                q!(c, 1, "Ω", Nonnegative),
                q!(c, 2, "A", Nonnegative)
            )
        );

        // Passive finite networks: parallel branches must have positive resistance.
        rule!(
            r"(?i)^two resistors of (.+?) and (.+?) are in series\. what is the total$",
            "Ω",
            c,
            format!(
                "sum({},{})",
                q!(c, 1, "Ω", Nonnegative),
                q!(c, 2, "Ω", Nonnegative)
            )
        );
        rule!(
            r"(?i)^a (.+?) and (.+?) resistor are connected in parallel; equivalent resistance$",
            "Ω",
            c,
            format!(
                "1 / (1 / {} + 1 / {})",
                q!(c, 1, "Ω", Positive),
                q!(c, 2, "Ω", Positive)
            )
        );
        rule!(
            r"(?i)^what is the total resistance of (.+?) in series with a parallel pair of (.+?) and (.+?)$",
            "Ω",
            c,
            format!(
                "{} + 1 / (1 / {} + 1 / {})",
                q!(c, 1, "Ω", Nonnegative),
                q!(c, 2, "Ω", Positive),
                q!(c, 3, "Ω", Positive)
            )
        );
        rule!(
            r"(?i)^calculate the equivalent resistance of (.+?) in parallel with (.+?), then in series with (.+?)$",
            "Ω",
            c,
            format!(
                "1 / (1 / {} + 1 / {}) + {}",
                q!(c, 1, "Ω", Positive),
                q!(c, 2, "Ω", Positive),
                q!(c, 3, "Ω", Nonnegative)
            )
        );

        // Energy from nominal ratings; finite runtime only under the stated ideal/full-capacity model.
        rule!(
            r"(?i)^what energy in Wh is stored in a (.+?), (.+?) battery$",
            "Wh",
            c,
            format!(
                "{} * {}",
                q!(c, 1, "V", Positive),
                q!(c, 2, "Ah", Nonnegative)
            )
        );
        rule!(
            r"(?i)^how many joules are in a (.+?), (.+?) cell$",
            "J",
            c,
            format!(
                "{} * {}",
                q!(c, 1, "V", Positive),
                q!(c, 2, "Ah", Nonnegative)
            )
        );
        rule!(
            r"(?i)^a (.+?) battery rated (.+?) supplies a (.+?) load\. estimate ideal runtime in hours$",
            "hours",
            c,
            {
                let _voltage = q!(c, 1, "V", Positive);
                format!(
                    "{} / {}",
                    q!(c, 2, "Ah", Nonnegative),
                    q!(c, 3, "A", Positive)
                )
            }
        );
        rule!(
            r"(?i)^a (.+?), (.+?) battery powers a (.+?) device\. estimate runtime in hours, assuming full rated capacity$",
            "hours",
            c,
            format!(
                "{} * {} / {}",
                q!(c, 1, "V", Positive),
                q!(c, 2, "Ah", Nonnegative),
                q!(c, 3, "W", Positive)
            )
        );
        if let Some(c) = re!(r"(?i)^a (.+?) battery with (.+?) capacity delivers (.+?)\. how many (.+?) is its runtime$").captures(input) {
            let _voltage = q!(c,1,"V",Positive);
            let expression = format!("{} / {}", q!(c,2,"Ah",Nonnegative), q!(c,3,"A",Positive));
            return Ok(Some(format!("({expression}) in {}", &c[4])));
        }

        // Real power P=Vrms*Irms*PF. Leading/lagging labels never negate P.
        rule!(
            r"(?i)^an AC load has (.+?) RMS, (.+?) RMS, and power factor (.+?)(?: lagging| leading)?\. calculate real power in watts$",
            "W",
            c,
            format!(
                "{} * {} * {}",
                q!(c, 1, "V", Nonnegative),
                q!(c, 2, "A", Nonnegative),
                q!(c, 3, "1", PowerFactor)
            )
        );
        rule!(
            r"(?i)^a (.+?) RMS motor draws (.+?) RMS at power factor (.+?)(?: lagging| leading)?\. find real input power$",
            "W",
            c,
            format!(
                "{} * {} * {}",
                q!(c, 1, "V", Nonnegative),
                q!(c, 2, "A", Nonnegative),
                q!(c, 3, "1", PowerFactor)
            )
        );
        rule!(
            r"(?i)^a (.+?) AC load is supplied at (.+?) RMS with PF (.+?)\. find RMS current, using P=VI·PF$",
            "A",
            c,
            format!(
                "{} / ({} * {})",
                q!(c, 1, "W", Nonnegative),
                q!(c, 2, "V", Positive),
                q!(c, 3, "1", PositivePowerFactor)
            )
        );
        rule!(
            r"(?i)^a (.+?) AC appliance at (.+?) RMS has PF (.+?)\. calculate its RMS current from P=VI·PF$",
            "A",
            c,
            format!(
                "{} / ({} * {})",
                q!(c, 1, "W", Nonnegative),
                q!(c, 2, "V", Positive),
                q!(c, 3, "1", PositivePowerFactor)
            )
        );
        rule!(
            r"(?i)^an apparent power of (.+?) at power factor (.+?) corresponds to what real power$",
            "W",
            c,
            format!(
                "{} * {}",
                q!(c, 1, "VA", Nonnegative),
                q!(c, 2, "1", PowerFactor)
            )
        );
        if let Some(c) = re!(r"(?i)^at (.+?) RMS and (.+?) RMS, an AC load has power factor (.+?)(?: leading| lagging)?\. what are its real power and apparent power$").captures(input) {
            let v = q!(c,1,"V",Nonnegative);
            let i = q!(c,2,"A",Nonnegative);
            let pf = q!(c,3,"1",PowerFactor);
            return Ok(Some(format!("electrical_power_pair({v},{i},{pf})")));
        }
        // A pure resistor's PF is unity. Do not choose one of two contradictory supplied models.
        if let Some(c) = re!(r"(?i)^a (.+?) RMS source drives a (.+?) resistor at (.+?)(?: lagging| leading)? power factor; calculate the real power$").captures(input) {
            let v = q!(c,1,"V",Nonnegative);
            let r = q!(c,2,"Ω",Positive);
            let _pf = q!(c,3,"1",PowerFactor);
            if self.compositions.quantity_value(&c[3], "1", context)? != 1.0 {
                return Err(Error("invalid_physical_value".into()));
            }
            return Ok(Some(format!("(square({v}) / {r}) in W")));
        }
        Ok(None)
    }
}