use super::{Domain, ElectricalQueries};
use crate::plugins::{integer_queries, model_coordinates};
use crate::{Context, Error, Outcome, re};
use num_rational::BigRational;
use num_traits::{One, Signed, ToPrimitive, Zero};
use std::cmp::Ordering;
fn current_target(target: &str) -> String {
let Some(c) = re!(r"(?i)^(pico|nano|micro|milli|kilo|mega|giga|tera)?(?:amps?|amperes?)$")
.captures(target.trim())
else {
return target.to_owned();
};
let prefix = match c
.get(1)
.map(|prefix| prefix.as_str().to_ascii_lowercase())
.as_deref()
{
Some("pico") => "p",
Some("nano") => "n",
Some("micro") => "µ",
Some("milli") => "m",
Some("kilo") => "k",
Some("mega") => "M",
Some("giga") => "G",
Some("tera") => "T",
_ => "",
};
format!("{prefix}A")
}
impl ElectricalQueries {
fn network_label(label: &str) -> bool {
matches!(
label,
"total resistance"
| "source current"
| "parallel network voltage"
| "first parallel resistor voltage"
| "second parallel resistor voltage"
| "series resistor voltage"
| "first parallel resistor current"
| "second parallel resistor current"
| "series resistor power"
| "first parallel resistor power"
| "second parallel resistor power"
| "total power"
| "source power"
)
}
const MIXED_LABELS: [&'static str; 8] = [
"equivalent resistance",
"source current",
"series resistor current",
"series resistor voltage",
"first parallel resistor current",
"first parallel resistor voltage",
"second parallel resistor current",
"second parallel resistor voltage",
];
const MIXED_POWER_LABELS: [&'static str; 7] = [
"total resistance",
"source current",
"series resistor voltage",
"parallel network voltage",
"series resistor power",
"first parallel resistor power",
"second parallel resistor power",
];
fn mixed_network(
&self,
series: &str,
first: &str,
second: &str,
supply: &str,
context: &Context,
) -> Result<(String, String, String, String, String, String), Error> {
let series = self.role(series, "Ω", Domain::Nonnegative, context)?;
let first = self.role(first, "Ω", Domain::Positive, context)?;
let second = self.role(second, "Ω", Domain::Positive, context)?;
let supply = self.role(supply, "V", Domain::Signed, context)?;
let parallel = format!("(1/(1/{first}+1/{second}))");
let total = self.role(
&format!("{series}+{parallel}"),
"Ω",
Domain::Positive,
context,
)?;
Ok((series, first, second, supply, parallel, total))
}
fn transformer_turns(
&self,
primary: &str,
secondary: &str,
) -> Result<(num_bigint::BigInt, num_bigint::BigInt), Error> {
let primary = integer_queries::value(primary)?;
let secondary = integer_queries::value(secondary)?;
if !primary.is_positive() || !secondary.is_positive() {
return Err(Error("invalid_physical_value".into()));
}
Ok((primary, secondary))
}
fn network_projection(
&self,
series_input: &str,
first_input: &str,
second_input: &str,
supply_input: &str,
goals: &str,
context: &Context,
) -> Result<String, Error> {
let (series, first, second, voltage, parallel, total) = self.mixed_network(
series_input,
first_input,
second_input,
supply_input,
context,
)?;
let current = format!("{voltage}/{total}");
let network_voltage = format!("({current})*{parallel}");
let requested = re!(r"(?i),\s*(?:and\s+)?|\s+and\s+")
.split(goals)
.map(str::trim)
.collect::<Vec<_>>();
let mut fields = Vec::new();
for goal in requested {
let mut add = |label, unit, expression| fields.push((label, unit, expression));
match goal.to_ascii_lowercase().as_str() {
"total resistance"
| "equivalent resistance"
| "total equivalent resistance"
| "circuit resistance" => add("total resistance", "Ω", total.clone()),
"source current"
| "supply current"
| "current from the source"
| "total current" => add("source current", "A", current.clone()),
"parallel-section voltage"
| "parallel network voltage"
| "voltage on the parallel network"
| "voltage across the parallel pair"
| "branch voltage" => add("parallel network voltage", "V", network_voltage.clone()),
"voltage across each branch" | "voltage across both branches" => {
add(
"first parallel resistor voltage",
"V",
network_voltage.clone(),
);
add(
"second parallel resistor voltage",
"V",
network_voltage.clone(),
);
}
"branch currents"
| "current in each branch"
| "currents in both branches"
| "both branch currents"
| "each parallel-branch current"
| "current through each branch"
| "currents" => {
add(
"first parallel resistor current",
"A",
format!("({network_voltage})/{first}"),
);
add(
"second parallel resistor current",
"A",
format!("({network_voltage})/{second}"),
);
}
"total power" | "total resistor power" => {
add("total power", "W", format!("{voltage}*{current}"))
}
"source power" => add("source power", "W", format!("{voltage}*{current}")),
"power in every resistor" | "power dissipated by each resistor" => {
add(
"series resistor power",
"W",
format!("square({current})*{series}"),
);
add(
"first parallel resistor power",
"W",
format!("square({network_voltage})/{first}"),
);
add(
"second parallel resistor power",
"W",
format!("square({network_voltage})/{second}"),
);
}
"power in the series resistor" => add(
"series resistor power",
"W",
format!("square({current})*{series}"),
),
_ => {
let reference = re!(r"(?i)^power in the (.+?) resistor$")
.captures(goal)
.ok_or_else(|| Error("invalid_expression".into()))?;
if self.same_role(&reference[1], series_input, "Ω", context)? {
add(
"series resistor power",
"W",
format!("square({current})*{series}"),
);
} else if self.same_role(&reference[1], first_input, "Ω", context)? {
add(
"first parallel resistor power",
"W",
format!("square({network_voltage})/{first}"),
);
} else if self.same_role(&reference[1], second_input, "Ω", context)? {
add(
"second parallel resistor power",
"W",
format!("square({network_voltage})/{second}"),
);
} else {
return Err(Error("invalid_physical_value".into()));
}
}
}
}
if fields.len() < 5 || fields.len() > 11 {
return Err(Error("invalid_expression".into()));
}
self.report(&fields, context)
}
fn elapsed_charge_duration(&self, input: &str, context: &Context) -> Result<String, Error> {
if let Some(c) =
re!(r"(?i)^(.+?)\s+(hours?|hrs?|h)\s+(?:and\s+)?(.+?)\s+(minutes?|mins?|min)$")
.captures(input.trim())
{
let hours = self.role(
&format!("{} {}", &c[1], &c[2]),
"seconds",
Domain::Nonnegative,
context,
)?;
let minutes = self.role(
&format!("{} {}", &c[3], &c[4]),
"seconds",
Domain::Nonnegative,
context,
)?;
return Ok(format!("({hours} + {minutes})"));
}
self.role(input, "seconds", Domain::Nonnegative, context)
}
fn capacitor_coefficient(input: &str) -> String {
let input = re!(r"(?P<coefficient>[+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*[×*]\s*10\s*\^\s*(?P<exponent>[+-]?\d+)")
.replace_all(input.trim(), "${coefficient}e${exponent}");
input.replace('×', "*")
}
fn capacitor_input(input: &str) -> String {
let input = Self::capacitor_coefficient(input);
input
.strip_suffix(" F")
.map_or_else(|| input.clone(), |value| format!("{value} farads"))
}
fn capacitor_role(&self, input: &str, context: &Context) -> Result<String, Error> {
let input = Self::capacitor_input(input);
self.role(&input, "farads", Domain::Positive, context)
}
fn same_role(
&self,
left: &str,
right: &str,
unit: &str,
context: &Context,
) -> Result<bool, Error> {
self.compositions.quantity_value(left, unit, context)?;
self.compositions.quantity_value(right, unit, context)?;
Ok(self.compositions.quantity_order(left, right, context)? == Ordering::Equal)
}
fn require_branch(
&self,
selected: &str,
branches: &[&str],
context: &Context,
) -> Result<(), Error> {
for branch in branches {
if self.same_role(selected, branch, "Ω", context)? {
return Ok(());
}
}
Err(Error("invalid_physical_value".into()))
}
fn require_consistent(
&self,
stated: &str,
implied: &str,
unit: &str,
context: &Context,
) -> Result<(), Error> {
if self.same_role(stated, implied, unit, context)? {
Ok(())
} else {
Err(Error("invalid_physical_value".into()))
}
}
fn require_elapsed_equivalence(
&self,
left: &str,
right: &str,
context: &Context,
) -> Result<(), Error> {
let left_coordinate =
model_coordinates::read(left, "seconds", &self.compositions, context)?;
let right_coordinate =
model_coordinates::read(right, "seconds", &self.compositions, context)?;
if left_coordinate.authored && right_coordinate.authored {
if left_coordinate.value == right_coordinate.value {
Ok(())
} else {
Err(Error("invalid_physical_value".into()))
}
} else {
self.require_consistent(left, right, "seconds", context)
}
}
fn report(&self, fields: &[(&str, &str, String)], context: &Context) -> Result<String, Error> {
let mixed = fields.len() == Self::MIXED_LABELS.len()
&& fields
.iter()
.zip(Self::MIXED_LABELS)
.all(|(field, label)| field.0 == label);
let mixed_power = fields.len() == Self::MIXED_POWER_LABELS.len()
&& fields
.iter()
.zip(Self::MIXED_POWER_LABELS)
.all(|(field, label)| field.0 == label);
let projection = (5..=11).contains(&fields.len())
&& fields
.iter()
.all(|(label, _, _)| Self::network_label(label))
&& {
let mut labels = fields.iter().map(|field| field.0).collect::<Vec<_>>();
labels.sort_unstable();
labels.dedup();
labels.len() == fields.len()
};
if fields.len() > 4 && !mixed && !mixed_power && !projection {
return Err(Error("invalid_expression".into()));
}
for (label, target, expression) in fields {
self.validate_report_field(label, target, expression, context)?;
}
let result = format!(
"{}({})",
if mixed {
"electrical_mixed_summary"
} else if mixed_power {
"electrical_power_summary"
} else if projection {
"electrical_network_projection"
} else {
"electrical_summary"
},
fields
.iter()
.map(|(label, target, expression)| {
let target = if matches!(
*label,
"current" | "first branch current" | "second branch current"
) {
current_target(target)
} else {
target.to_string()
};
format!("{label}|{target}|{expression}")
})
.collect::<Vec<_>>()
.join(";")
);
if result.len() > 4096 {
return Err(Error("invalid_expression".into()));
}
Ok(result)
}
fn validate_report_field(
&self,
label: &str,
target: &str,
expression: &str,
context: &Context,
) -> Result<(), Error> {
let reference = match label {
"current"
| "source current"
| "total current"
| "first branch current"
| "second branch current"
| "series resistor current"
| "first parallel resistor current"
| "second parallel resistor current"
| "secondary current" => "A",
"power"
| "load power"
| "source power"
| "combined power"
| "total power"
| "series resistor power"
| "first parallel resistor power"
| "second parallel resistor power" => "W",
"voltage"
| "terminal voltage"
| "first resistor voltage"
| "second resistor voltage"
| "series resistor voltage"
| "parallel network voltage"
| "first parallel resistor voltage"
| "second parallel resistor voltage"
| "secondary voltage" => "V",
"secondary RMS voltage" => "V",
"resistance"
| "total resistance"
| "equivalent resistance"
| "effective resistance" => "Ω",
"energy" => "J",
"charge" => "coulombs",
"capacitance" => "farads",
"time constant" => "seconds",
"standard uncertainty" => "A",
_ => {
let percentage = label
.strip_prefix("time to ")
.and_then(|value| value.strip_suffix('%'))
.ok_or_else(|| Error("invalid_expression".into()))?;
let (n, d) = integer_queries::ratio_value(percentage)?;
let percentage = model_coordinates::bounded(BigRational::new(n, d))?;
if percentage < BigRational::zero()
|| percentage >= BigRational::from_integer(100.into())
{
return Err(Error("invalid_physical_value".into()));
}
"seconds"
}
};
self.compositions
.quantity_value(&format!("1 {target}"), reference, context)?;
self.compositions
.quantity_value(expression, target, context)?;
Ok(())
}
pub(super) fn evaluate_models(&self, input: &str, context: &Context) -> Outcome {
if let Some((inner, mixed, mixed_power, projection)) = input
.strip_prefix("electrical_mixed_summary(")
.and_then(|s| s.strip_suffix(')'))
.map(|inner| (inner, true, false, false))
.or_else(|| {
input
.strip_prefix("electrical_power_summary(")
.and_then(|s| s.strip_suffix(')'))
.map(|inner| (inner, false, true, false))
})
.or_else(|| {
input
.strip_prefix("electrical_network_projection(")
.and_then(|s| s.strip_suffix(')'))
.map(|inner| (inner, false, false, true))
})
.or_else(|| {
input
.strip_prefix("electrical_summary(")
.and_then(|s| s.strip_suffix(')'))
.map(|inner| (inner, false, false, false))
})
{
return Some((|| {
if input.len() > 4096 {
return Err(Error("invalid_expression".into()));
}
let fields = inner.split(';').collect::<Vec<_>>();
if (mixed
&& (fields.len() != Self::MIXED_LABELS.len()
|| fields
.iter()
.zip(Self::MIXED_LABELS)
.any(|(field, label)| field.split('|').next() != Some(label))))
|| (mixed_power
&& (fields.len() != Self::MIXED_POWER_LABELS.len()
|| fields
.iter()
.zip(Self::MIXED_POWER_LABELS)
.any(|(field, label)| field.split('|').next() != Some(label))))
|| (projection
&& (!(5..=11).contains(&fields.len()) || {
let mut labels = fields
.iter()
.map(|field| field.split('|').next().unwrap_or(""))
.collect::<Vec<_>>();
if labels.iter().any(|label| !Self::network_label(label)) {
true
} else {
labels.sort_unstable();
labels.dedup();
labels.len() != fields.len()
}
}))
|| (!mixed && !mixed_power && !projection && !(2..=4).contains(&fields.len()))
{
return Err(Error("invalid_expression".into()));
}
let mut output = Vec::new();
for field in fields {
let parts = field.split('|').collect::<Vec<_>>();
if parts.len() != 3 {
return Err(Error("invalid_expression".into()));
}
let (label, target, expression) = (parts[0], parts[1], parts[2]);
self.validate_report_field(label, target, expression, context)?;
let display =
self.calculate(&format!("({expression}) in {target}"), context)?;
output.push(format!("{label}: {display}"));
}
Ok(output.join("; "))
})());
}
let (kind, inner) = if let Some(inner) = input
.strip_prefix("electrical_battery_check(")
.and_then(|s| s.strip_suffix(')'))
{
("battery", inner)
} else {
let inner = input
.strip_prefix("electrical_power_triangle(")
.and_then(|s| s.strip_suffix(')'))?;
("triangle", inner)
};
Some((|| {
let args = super::super::named_quantities::function_arguments(inner, false)?;
if kind == "battery" && args.len() == 3 {
let v = self.role(args[0], "V", Domain::Nonnegative, context)?;
let i = self.role(args[1], "A", Domain::Nonnegative, context)?;
let r = self.role(args[2], "Ω", Domain::Positive, context)?;
self.require_consistent(&v, &format!("{i} * {r}"), "V", context)?;
let power = self.calculate(&format!("({v} * {i}) in W"), context)?;
Ok(format!("battery power: {power}; consistent: true"))
} else if kind == "triangle" && args.len() == 2 {
let s = self.role(args[0], "VA", Domain::Positive, context)?;
let p = self.role(args[1], "W", Domain::Nonnegative, context)?;
if self.compositions.quantity_order(&p, &s, context)? == Ordering::Greater {
return Err(Error("invalid_physical_value".into()));
}
let factor = self.calculate(&format!("{p} / {s}"), context)?;
let reactive =
self.calculate(&format!("sqrt(square({s}) - square({p})) in var"), context)?;
Ok(format!(
"power factor: {factor}; reactive power magnitude: {reactive}"
))
} else {
Err(Error("invalid_expression".into()))
}
})())
}
pub(super) fn lower_models(
&self,
input: &str,
context: &Context,
) -> Result<Option<String>, Error> {
if let Some(c) = re!(r"(?i)^a sensor reports (.+?) with independent standard uncertainty (.+?), and a (.+?)-ohm resistor has independent standard uncertainty (.+?); using I\s*=\s*V\s*/\s*R and first-order uncertainty propagation, report current and its standard uncertainty$").captures(input) {
let resistance_input = format!("{} ohms", &c[3]);
let voltage = self.role(&c[1], "V", Domain::Signed, context)?;
self.role(&c[2], "V", Domain::Nonnegative, context)?;
let resistance = self.role(&resistance_input, "Ω", Domain::Positive, context)?;
self.role(&c[4], "Ω", Domain::Nonnegative, context)?;
let v = model_coordinates::read(&c[1], "V", &self.compositions, context)?;
let uv = model_coordinates::read(&c[2], "V", &self.compositions, context)?;
let r = model_coordinates::read(&resistance_input, "Ω", &self.compositions, context)?;
let ur = model_coordinates::read(&c[4], "Ω", &self.compositions, context)?;
let current = model_coordinates::bounded(&v.value / &r.value)?;
let voltage_term = model_coordinates::bounded(&uv.value / &r.value)?;
let resistance_term = model_coordinates::bounded(
&v.value * &ur.value / (&r.value * &r.value),
)?;
let variance = model_coordinates::bounded(
model_coordinates::bounded(&voltage_term * &voltage_term)?
+ model_coordinates::bounded(&resistance_term * &resistance_term)?,
)?;
let uncertainty = model_coordinates::computed_root(variance, |expression| {
self.compositions.quantity_value(expression, "1", context)
})?;
let uncertainty_float = uncertainty
.to_f64()
.filter(|value| value.is_finite())
.ok_or_else(|| Error("numeric_overflow".into()))?;
if !uncertainty.is_zero() && uncertainty_float == 0.0 {
return Err(Error("numeric_underflow".into()));
}
let current_expression = if v.authored && r.authored {
format!("(rational({},{}) A)", current.numer(), current.denom())
} else {
format!("{voltage}/{resistance}")
};
return self.report(&[
("current", "A", current_expression),
("standard uncertainty", "A", format!("real({uncertainty_float:e}) A")),
], context).map(Some);
}
if let Some(c) = re!(r"(?i)^an ideal transformer has (.+?) primary turns, (.+?) secondary turns, and primary voltage (.+?) AC\. (?:find|calculate) secondary voltage and secondary current if primary current is (.+)$")
.captures(input)
{
let (primary, secondary) = self.transformer_turns(&c[1], &c[2])?;
let voltage = self.role(&c[3], "V", Domain::Nonnegative, context)?;
let current = self.role(&c[4], "A", Domain::Nonnegative, context)?;
return self.report(
&[
(
"secondary voltage",
"V",
format!("{voltage} * rational({secondary},{primary})"),
),
(
"secondary current",
"A",
format!("{current} * rational({primary},{secondary})"),
),
],
context,
).map(Some);
}
if let Some(c) = re!(r"(?i)^an ideal transformer has (.+?) primary turns, (.+?) secondary turns, and (.+?) RMS across the primary\. use Vs\s*/\s*Vp\s*=\s*Ns\s*/\s*Np to find the secondary RMS voltage; with a (.+?) resistive load, find secondary current and load power$").captures(input) {
let (primary, secondary) = self.transformer_turns(&c[1], &c[2])?;
let voltage = self.role(&c[3], "V", Domain::Nonnegative, context)?;
let load = self.role(&c[4], "Ω", Domain::Positive, context)?;
let secondary_voltage = format!("{voltage}*rational({secondary},{primary})");
return self.report(&[
("secondary RMS voltage", "V", secondary_voltage.clone()),
("secondary current", "A", format!("({secondary_voltage})/{load}")),
("load power", "W", format!("square({secondary_voltage})/{load}")),
], context).map(Some);
}
if let Some(c) = re!(r"(?i)^a capacitor of (.+?) is charged through a (.+?) resistor\. (?:calculate|find) the RC time constant in (seconds|s) and the time to reach (.+?) of (?:the )?final voltage, using t\s*=\s*-\s*RC\s*\*\s*ln\s*\(\s*1\s*-\s*(.+?)\s*\)$")
.captures(input)
{
let invalid = || Error("invalid_expression".into());
let stated = re!(r"(?i)^(.+?)(?:%|\s+percent)$")
.captures(c[4].trim())
.ok_or_else(invalid)?;
let ratio = |value: &str| {
let (numerator, denominator) = integer_queries::ratio_value(value)?;
model_coordinates::bounded(BigRational::new(numerator, denominator))
};
let fraction = ratio(&stated[1])? / BigRational::from_integer(100.into());
let authored = ratio(&c[5])?;
if fraction != authored {
return Err(Error("invalid_physical_value".into()));
}
if fraction < BigRational::zero() || fraction >= BigRational::one() {
return Err(Error("invalid_physical_value".into()));
}
let capacitance = self.capacitor_role(&c[1], context)?;
let resistor = c[2].replace("-ohm", "ohm");
let resistance = self.role(&resistor, "Ω", Domain::Positive, context)?;
let r = model_coordinates::read(&resistance, "Ω", &self.compositions, context)?;
let cap = model_coordinates::read(&capacitance, "farads", &self.compositions, context)?;
let tau = model_coordinates::bounded(r.value * cap.value)?;
let tau_float = tau.to_f64().ok_or_else(|| Error("numeric_overflow".into()))?;
let mut time_scale = tau_float;
let log = if fraction.is_zero() {
0.0
} else if fraction < BigRational::new(1.into(), 2.into()) {
let part = fraction.to_f64().ok_or_else(|| Error("numeric_underflow".into()))?;
if part.is_normal() {
-(-part).ln_1p()
} else {
time_scale = model_coordinates::bounded(&tau * &fraction)?
.to_f64().ok_or_else(|| Error("numeric_overflow".into()))?;
1.0
}
} else {
let remaining = BigRational::one() - &fraction;
if let Some(value) = remaining.to_f64().filter(|value| value.is_normal()) {
-value.ln()
} else {
let exponent = remaining.numer().bits() as i64 - remaining.denom().bits() as i64;
let power = num_bigint::BigInt::one() << exponent.unsigned_abs() as usize;
let scale = if exponent < 0 {
BigRational::from_integer(power)
} else {
BigRational::new(1.into(), power)
};
let normalized = model_coordinates::bounded(remaining * scale)?
.to_f64().ok_or_else(|| Error("numeric_overflow".into()))?;
-normalized.ln() - exponent as f64 * std::f64::consts::LN_2
}
};
let charging_time = time_scale * log;
if !charging_time.is_finite() {
return Err(Error("numeric_overflow".into()));
}
if !fraction.is_zero() && charging_time == 0.0 {
return Err(Error("numeric_underflow".into()));
}
let label = format!("time to {}%", stated[1].trim());
return self.report(
&[
("time constant", "s", format!("{resistance} * {capacitance}")),
(&label, "s", format!("real({charging_time:e}) s")),
],
context,
).map(Some);
}
if let Some(c) = re!(r"(?i)^a capacitor stores E\s*=\s*CV(?:²|\^2)\s*/\s*2; use C\s*=\s*(.+?) and V\s*=\s*(.+?) to give the finite energy in (.+)$").captures(input) {
let capacitance = self.capacitor_role(&c[1], context)?;
let voltage_input = Self::capacitor_coefficient(&c[2]);
let voltage = self.role(&voltage_input, "V", Domain::Nonnegative, context)?;
self.compositions.quantity_value(&format!("1 {}", &c[3]), "J", context)?;
let exact_capacitance = model_coordinates::read(
&Self::capacitor_input(&c[1]), "farads", &self.compositions, context,
)?;
let exact_voltage = model_coordinates::read(
&voltage_input, "V", &self.compositions, context,
)?;
let energy = if exact_capacitance.authored && exact_voltage.authored {
let joules = model_coordinates::bounded(
exact_capacitance.value * exact_voltage.value.clone() * exact_voltage.value
/ BigRational::from_integer(2.into()),
)?;
format!("(rational({},{}) J)", joules.numer(), joules.denom())
} else {
format!("({capacitance}*square({voltage})/2)")
};
self.compositions.quantity_value(&energy, "J", context)?;
return Ok(Some(format!("{energy} in {}", &c[3])));
}
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:expr, $c:ident, $formula:expr) => {
if let Some($c) = re!($pattern).captures(input) {
let expression = $formula;
return Ok(Some(format!("({expression}) in {}", $target)));
}
};
}
if let Some(c) = re!(r"(?i)^a battery supplies (.+?) for (.+?)\. how many (.+?) and (.+?) of charge is that, using (.+?)\s*=\s*(.+)$")
.captures(input)
{
let charge_target = |target: &str| {
let target = target.trim().to_ascii_lowercase().replace('-', " ");
match target.as_str() {
"amp hour" | "amp hours" | "ah" => Some("Ah"),
"coulomb" | "coulombs" => Some("coulombs"),
_ => None,
}
};
let first = charge_target(&c[3])
.ok_or_else(|| Error("invalid_expression".into()))?;
let second = charge_target(&c[4])
.filter(|target| *target != first)
.ok_or_else(|| Error("invalid_expression".into()))?;
self.require_elapsed_equivalence(&c[5], &c[6], context)?;
let current = q!(c, 1, "A", Nonnegative);
let duration = self.elapsed_charge_duration(&c[2], context)?;
let charge = format!("{current} * {duration}");
return self.report(
&[("charge", first, charge.clone()), ("charge", second, charge)],
context,
).map(Some);
}
if let Some(c) = re!(r"(?i)^for the model P\s*=\s*V\s*\^\s*2\s*/\s*R with V\s*=\s*(.+?) and R\s*=\s*(.+?), calculate power and the current given I\s*=\s*V\s*/\s*R$").captures(input) {
let voltage = q!(c, 1, "V", Nonnegative);
let resistance = q!(c, 2, "Ω", Positive);
return self.report(&[("power", "W", format!("square({voltage}) / {resistance}")),
("current", "A", format!("{voltage} / {resistance}"))], context).map(Some);
}
if let Some(c) = re!(r"(?i)^three resistors (.+?), (.+?), and (.+?) ohms are in parallel across an ideal (.+?) source; report equivalent resistance, total current, and total power$").captures(input) {
let first = self.role(&format!("{} ohms", &c[1]), "Ω", Domain::Positive, context)?;
let second = self.role(&format!("{} ohms", &c[2]), "Ω", Domain::Positive, context)?;
let third = self.role(&format!("{} ohms", &c[3]), "Ω", Domain::Positive, context)?;
let voltage = q!(c, 4, "V", Nonnegative);
let equivalent = format!("1 / (1 / {first} + 1 / {second} + 1 / {third})");
let current = format!("{voltage} / ({equivalent})");
return self.report(&[("equivalent resistance", "Ω", equivalent),
("total current", "A", current.clone()),
("total power", "W", format!("{voltage} * ({current})"))], context).map(Some);
}
if let Some(c) = re!(r"(?i)^a (.+?) source is connected across a (.+?) resistor; what current flows in (.+?) and what power is dissipated in (.+)$").captures(input) {
let voltage = q!(c, 1, "V", Nonnegative);
let resistance = q!(c, 2, "Ω", Positive);
let current = format!("{voltage}/{resistance}");
return self.report(&[("current", &c[3], current.clone()),
("power", &c[4], format!("{voltage}*({current})"))], context).map(Some);
}
if let Some(c) = re!(r"(?i)^a (.+?) battery supplies a (.+?) load for (.+?); how much energy is used in (.+?) and (.+?), given (.+?)\s*=\s*(.+)$").captures(input) {
let voltage = q!(c, 1, "V", Nonnegative);
let current = q!(c, 2, "A", Nonnegative);
let duration = q!(c, 3, "seconds", Nonnegative);
self.require_consistent(&c[6], &c[7], "J", context)?;
let energy = format!("{voltage}*{current}*{duration}");
let target = |input: &str| {
let name = input.replace('-', " ");
self.compositions.units.unit(&name).map(|unit| unit.symbol)
.unwrap_or(name)
};
return self.report(&[("energy", &target(&c[4]), energy.clone()),
("energy", &target(&c[5]), energy)], context).map(Some);
}
if let Some(c) = re!(r"(?i)^a (.+?) resistor and a (.+?) resistor are in series across (.+?); (?:find|calculate) total resistance, current, and voltage across each$").captures(input) {
let first = q!(c, 1, "Ω", Nonnegative);
let second = q!(c, 2, "Ω", Nonnegative);
let voltage = q!(c, 3, "V", Signed);
let total = self.role(&format!("{first}+{second}"), "Ω", Domain::Positive, context)?;
let current = format!("{voltage}/{total}");
return self.report(&[("total resistance", "Ω", total), ("current", "A", current.clone()),
("first resistor voltage", "V", format!("({current})*{first}")),
("second resistor voltage", "V", format!("({current})*{second}"))], context).map(Some);
}
if let Some(c) = re!(r"(?i)^a (.+?) source is connected to (.+?) and (.+?) in series\. (?:find|calculate|give) equivalent resistance, circuit current, and voltage drop across each resistor$").captures(input) {
let voltage = q!(c, 1, "V", Signed);
let first = q!(c, 2, "Ω", Nonnegative);
let second = q!(c, 3, "Ω", Nonnegative);
let total = self.role(&format!("{first}+{second}"), "Ω", Domain::Positive, context)?;
let current = format!("{voltage}/{total}");
return self.report(&[("equivalent resistance", "Ω", total),
("total current", "A", current.clone()),
("first resistor voltage", "V", format!("({current})*{first}")),
("second resistor voltage", "V", format!("({current})*{second}"))], context).map(Some);
}
if let Some(c) = re!(r"(?i)^two resistors of (.+?) and (.+?) are in parallel across an ideal (.+?) supply\. (?:give|report|find) equivalent resistance, total current, and current through each branch$").captures(input) {
let first = q!(c, 1, "Ω", Positive);
let second = q!(c, 2, "Ω", Positive);
let voltage = q!(c, 3, "V", Signed);
let equivalent = format!("1/(1/{first}+1/{second})");
let first_current = format!("{voltage}/{first}");
let second_current = format!("{voltage}/{second}");
return self.report(&[("equivalent resistance", "Ω", equivalent),
("total current", "A", format!("({first_current})+({second_current})")),
("first branch current", "A", first_current),
("second branch current", "A", second_current)], context).map(Some);
}
if let Some(c) = re!(r"(?i)^an ideal (.+?) resistor is in series with a parallel pair of (.+?) and (.+?), supplied by (.+?); calculate equivalent resistance, source current, and the current and voltage for each resistor$").captures(input) {
let (series, first, second, voltage, parallel, total) =
self.mixed_network(&c[1], &c[2], &c[3], &c[4], context)?;
let source_current = format!("{voltage}/{total}");
let series_voltage = format!("({source_current})*{series}");
let parallel_voltage = format!("({source_current})*{parallel}");
return self.report(&[
("equivalent resistance", "Ω", total),
("source current", "A", source_current.clone()),
("series resistor current", "A", source_current),
("series resistor voltage", "V", series_voltage),
("first parallel resistor current", "A", format!("({parallel_voltage})/{first}")),
("first parallel resistor voltage", "V", parallel_voltage.clone()),
("second parallel resistor current", "A", format!("({parallel_voltage})/{second}")),
("second parallel resistor voltage", "V", parallel_voltage),
], context).map(Some);
}
if let Some(c) = re!(r"(?i)^a (.+?) ideal source drives a (.+?) resistor in series with a parallel network of (.+?) and (.+?) resistors\. find total resistance, source current, voltage across each series element and the parallel network, and power in all three resistors$").captures(input) {
let (series, first, second, voltage, parallel, total) =
self.mixed_network(&c[2], &c[3], &c[4], &c[1], context)?;
let current = format!("{voltage}/{total}");
let series_voltage = format!("({current})*{series}");
let network_voltage = format!("({current})*{parallel}");
return self.report(&[
("total resistance", "Ω", total),
("source current", "A", current.clone()),
("series resistor voltage", "V", series_voltage.clone()),
("parallel network voltage", "V", network_voltage.clone()),
("series resistor power", "W", format!("square({current})*{series}")),
("first parallel resistor power", "W", format!("square({network_voltage})/{first}")),
("second parallel resistor power", "W", format!("square({network_voltage})/{second}")),
], context).map(Some);
}
if let Some(c) = re!(r"(?i)^connect a (.+?) ideal supply to a (.+?) resistor in series with parallel (.+?) and (.+?) resistors\. report (.+)$").captures(input) {
return self.network_projection(&c[2], &c[3], &c[4], &c[1], &c[5], context).map(Some);
}
if let Some(c) = re!(r"(?i)^a (.+?) ideal source feeds a (.+?) resistor in series with a parallel pair of (.+?) and (.+?) resistors\. find (.+)$").captures(input) {
return self.network_projection(&c[2], &c[3], &c[4], &c[1], &c[5], context).map(Some);
}
if let Some(c) = re!(r"(?i)^an ideal (.+?) battery drives a (.+?) series resistor followed by (.+?) and (.+?) resistors in parallel\. calculate (.+)$").captures(input) {
return self.network_projection(&c[2], &c[3], &c[4], &c[1], &c[5], context).map(Some);
}
if let Some(c) = re!(r"(?i)^with an ideal (.+?) source, put (.+?) in series with a parallel combination of (.+?) and (.+?)\. determine (.+)$").captures(input) {
return self.network_projection(&c[2], &c[3], &c[4], &c[1], &c[5], context).map(Some);
}
if let Some(c) = re!(r"(?i)^a (.+?) ideal source is connected to (.+?) in series with parallel (.+?) and (.+?)\. find (.+)$").captures(input) {
return self.network_projection(&c[2], &c[3], &c[4], &c[1], &c[5], context).map(Some);
}
if let Some(c) = re!(r"(?i)^an ideal (.+?) supply feeds a (.+?) series resistor and parallel branches of (.+?) and (.+?)\. give (.+)$").captures(input) {
return self.network_projection(&c[2], &c[3], &c[4], &c[1], &c[5], context).map(Some);
}
if let Some(c) = re!(r"(?i)^for a (.+?) ideal supply with (.+?) in series and (.+?) parallel to (.+?), calculate (.+)$").captures(input) {
return self.network_projection(&c[2], &c[3], &c[4], &c[1], &c[5], context).map(Some);
}
if let Some(c) = re!(r"(?i)^a (.+?) ideal source feeds a (.+?) resistor in series with parallel (.+?) and (.+?) resistors\. report (.+)$").captures(input) {
return self.network_projection(&c[2], &c[3], &c[4], &c[1], &c[5], context).map(Some);
}
if let Some(c) = re!(r"(?i)^two (.+?) resistors are in parallel and connected in series with (.+?) across (.+?); (?:calculate|find) total resistance and source current$").captures(input) {
let branch = q!(c, 1, "Ω", Positive);
let series = q!(c, 2, "Ω", Nonnegative);
let voltage = q!(c, 3, "V", Signed);
let total = format!("{branch}/2+{series}");
return self.report(&[("total resistance", "Ω", total.clone()),
("source current", "A", format!("{voltage}/({total})"))], context).map(Some);
}
if let Some(c) = re!(r"(?i)^a (.+?) and (.+?) resistor are in parallel across (.+?); report equivalent resistance, branch currents, and total power$").captures(input) {
let first = q!(c, 1, "Ω", Positive);
let second = q!(c, 2, "Ω", Positive);
let voltage = q!(c, 3, "V", Signed);
let equivalent = format!("1/(1/{first}+1/{second})");
let first_current = format!("{voltage}/{first}");
let second_current = format!("{voltage}/{second}");
return self.report(&[("equivalent resistance", "Ω", equivalent),
("first branch current", "A", first_current.clone()), ("second branch current", "A", second_current.clone()),
("total power", "W", format!("{voltage}*(({first_current})+({second_current}))"))], context).map(Some);
}
if let Some(c) = re!(r"(?i)^a (.+?) supply drives (.+?) through a device for (.+?); (?:calculate|find) resistance, power, charge, and energy$").captures(input) {
let voltage = q!(c, 1, "V", Signed);
let current = q!(c, 2, "A", Positive);
let duration = q!(c, 3, "seconds", Nonnegative);
let power = format!("{voltage}*{current}");
return self.report(&[("resistance", "Ω", format!("{voltage}/{current}")),
("power", "W", power.clone()), ("charge", "coulombs", format!("{current}*{duration}")),
("energy", "J", format!("({power})*{duration}"))], context).map(Some);
}
if let Some(c) = re!(r"(?i)^a (.+?) capacitor is charged to (.+?); (?:find|calculate) capacitance in (.+?), charge, and stored energy$").captures(input) {
let capacitance = self.capacitor_role(&c[1], context)?;
let voltage = q!(c, 2, "V", Signed);
return self.report(&[("capacitance", &c[3], capacitance.clone()),
("charge", "coulombs", format!("{capacitance}*{voltage}")),
("energy", "J", format!("{capacitance}*square({voltage})/2"))], context).map(Some);
}
if let Some(c) = re!(r"(?i)^a (.+?), (.+?) appliance draws what current and has what effective resistance assuming fixed resistance$").captures(input) {
let voltage = q!(c, 1, "V", Positive);
let power = q!(c, 2, "W", Positive);
return self.report(&[("current", "A", format!("{power}/{voltage}")),
("effective resistance", "Ω", format!("square({voltage})/{power}"))], context).map(Some);
}
if let Some(c) =
re!(r"(?i)^a (.+?) heater runs for (.+?); report energy in (.+?) and (.+)$")
.captures(input)
{
let power = q!(c, 1, "W", Nonnegative);
let duration = q!(c, 2, "seconds", Nonnegative);
let energy = format!("{power} * {duration}");
return self
.report(
&[("energy", &c[3], energy.clone()), ("energy", &c[4], energy)],
context,
)
.map(Some);
}
if let Some(c) = re!(r"(?i)^a (.+?) battery with internal resistance (.+?) supplies a (.+?) load; (?:determine|find|calculate) current and terminal voltage$").captures(input) {
let emf = q!(c, 1, "V", Nonnegative);
let internal = q!(c, 2, "Ω", Nonnegative);
let load = q!(c, 3, "Ω", Nonnegative);
let total = self.role(&format!("{internal} + {load}"), "Ω", Domain::Positive, context)?;
let current = format!("{emf}/{total}");
return self.report(&[("current", "A", current.clone()), ("terminal voltage", "V", format!("({current})*{load}"))], context).map(Some);
}
if let Some(c) =
re!(r"(?i)^a (.+?) capacitor at (.+?) stores what charge in (.+?) and energy in (.+)$")
.captures(input)
{
let capacitance = self.capacitor_role(&c[1], context)?;
let voltage = q!(c, 2, "V", Signed);
return self
.report(
&[
("charge", &c[3], format!("{capacitance}*{voltage}")),
(
"energy",
&c[4],
format!("{capacitance}*square({voltage})/2"),
),
],
context,
)
.map(Some);
}
if let Some(c) = re!(r"(?i)^(?:calculate|find) the capacitance needed to store (.+?) at (.+?), in (.+?) and (.+)$").captures(input) {
let charge = if let Some(number) = c[1].trim().strip_suffix(" C") {
format!("{number} coulombs")
} else { c[1].to_owned() };
let charge = self.role(&charge, "coulombs", Domain::Nonnegative, context)?;
let voltage = q!(c, 2, "V", Positive);
let capacitance = format!("{charge}/{voltage}");
return self.report(&[("capacitance", &c[3], capacitance.clone()), ("capacitance", &c[4], capacitance)], context).map(Some);
}
if let Some(c) = re!(r"(?i)^a (.+?) resistor is connected to (.+?); (?:find|calculate) current in (.+?) and (.+?) and the power in (.+)$").captures(input) {
let r = q!(c, 1, "Ω", Positive);
let v = q!(c, 2, "V", Nonnegative);
let current = format!("{v} / {r}");
return self.report(&[("current", &c[3], current.clone()),
("current", &c[4], current.clone()),
("power", &c[5], format!("{v} * ({current})"))], context).map(Some);
}
if let Some(c) = re!(r"(?i)^with voltage (.+?) and current (.+?), (?:determine|find|calculate) resistance and electrical power, including units$").captures(input) {
let v = q!(c, 1, "V", Nonnegative);
let i = q!(c, 2, "A", Positive);
return self.report(&[("resistance", "Ω", format!("{v} / {i}")),
("power", "W", format!("{v} * {i}"))], context).map(Some);
}
if let Some(c) = re!(r"(?i)^a (.+?) current flows through (.+?) for (.+?); (?:calculate|find) voltage and energy in (.+)$").captures(input) {
let i = q!(c, 1, "A", Nonnegative);
let r = q!(c, 2, "Ω", Nonnegative);
let t = q!(c, 3, "seconds", Nonnegative);
return self.report(&[("voltage", "V", format!("{i} * {r}")),
("energy", &c[4], format!("square({i}) * {r} * {t}"))], context).map(Some);
}
if let Some(c) = re!(r"(?i)^a (.+?) resistor and a (.+?) resistor are connected in parallel across (.+?); (?:calculate|find) branch currents and combined power$").captures(input) {
let a = q!(c, 1, "Ω", Positive);
let b = q!(c, 2, "Ω", Positive);
let v = q!(c, 3, "V", Nonnegative);
let first = format!("{v} / {a}");
let second = format!("{v} / {b}");
return self.report(&[("first branch current", "A", first.clone()),
("second branch current", "A", second.clone()),
("combined power", "W", format!("{v} * (({first}) + ({second}))"))], context).map(Some);
}
if let Some(c) = re!(r"(?i)^for a (.+?) source and (.+?) load, (?:determine|find|calculate) current and power from the ideal Ohm[’']s law model$").captures(input) {
let v = q!(c, 1, "V", Nonnegative);
let r = q!(c, 2, "Ω", Positive);
let current = format!("{v} / {r}");
return self.report(&[("current", "A", current.clone()),
("power", "W", format!("{v} * ({current})"))], context).map(Some);
}
rule!(
r"(?i)^a component has (.+?) across it and carries (.+?); (?:calculate|find) its resistance using V\s*=\s*IR$",
"Ω",
c,
format!(
"{} / {}",
q!(c, 1, "V", Nonnegative),
q!(c, 2, "A", Positive)
)
);
if let Some(c) = re!(r"(?i)^a (.+?) resistor carries (.+?) for (.+?); (?:find|calculate) voltage, power, and energy$").captures(input) {
let r = q!(c, 1, "Ω", Nonnegative);
let i = q!(c, 2, "A", Nonnegative);
let t = q!(c, 3, "seconds", Nonnegative);
let power = format!("square({i}) * {r}");
return self.report(&[("voltage", "V", format!("{i} * {r}")),
("power", "W", power.clone()),
("energy", "J", format!("({power}) * {t}"))], context).map(Some);
}
rule!(
r"(?i)^a battery rated (.+?) drives (.+?) for (.+?); (?:calculate|find) electrical energy in (.+?) using power times elapsed seconds$",
&c[4],
c,
{
let v = q!(c, 1, "V", Positive);
let i = q!(c, 2, "A", Nonnegative);
let t = q!(c, 3, "seconds", Nonnegative);
format!("{v} * {i} * {t}")
}
);
rule!(
r"(?i)^at (.+?), a resistor with resistance (.+?) carries what current according to Ohm[’']s law$",
"A",
c,
format!(
"{} / {}",
q!(c, 1, "V", Nonnegative),
q!(c, 2, "Ω", Positive)
)
);
if let Some(c) = re!(r"(?i)^use Ohm[’']s law to find current for (.+?) across (.+?), then (?:calculate|find) the power dissipated$").captures(input) {
let v = q!(c, 1, "V", Nonnegative);
let r = q!(c, 2, "Ω", Positive);
let current = format!("{v} / {r}");
return self.report(&[("current", "A", current.clone()),
("power", "W", format!("{v} * ({current})"))], context).map(Some);
}
if let Some(c) = re!(r"(?i)^a circuit draws (.+?) from a (.+?) supply for (.+?); report energy in (.+?) and (.+)$").captures(input) {
let i = q!(c, 1, "A", Nonnegative);
let v = q!(c, 2, "V", Nonnegative);
let t = q!(c, 3, "seconds", Nonnegative);
let energy = format!("{v} * {i} * {t}");
let first = c[4].replace('-', " ");
let second = c[5].replace('-', " ");
return self.report(&[("energy", &first, energy.clone()),
("energy", &second, energy)], context).map(Some);
}
if let Some(c) = re!(r"(?i)^a capacitor charge is (.+?) at (.+?); (?:determine|calculate|find) capacitance in (.+?) and (.+)$").captures(input) {
let charge = q!(c, 1, "coulombs", Nonnegative);
let v = q!(c, 2, "V", Positive);
let capacitance = format!("{charge} / {v}");
return self.report(&[("capacitance", &c[3], capacitance.clone()),
("capacitance", &c[4], capacitance)], context).map(Some);
}
rule!(
r"(?i)^simplify (.+?) DC across a (.+?) resistor in series with a parallel pair of (.+?) and (.+?): give the total current in (.+?)$",
&c[5],
c,
{
let v = q!(c, 1, "V", Nonnegative);
let series = q!(c, 2, "Ω", Nonnegative);
let a = q!(c, 3, "Ω", Positive);
let b = q!(c, 4, "Ω", Positive);
format!("{v} / ({series} + 1 / (1 / {a} + 1 / {b}))")
}
);
rule!(
r"(?i)^for an ideal (.+?) battery supplying (.+?) for (.+?), calculate the energy delivered in (.+?), assuming constant voltage and current$",
&c[4],
c,
{
let v = q!(c, 1, "V", Positive);
let i = q!(c, 2, "A", Nonnegative);
let t = q!(c, 3, "seconds", Nonnegative);
format!("{v} * {i} * {t}")
}
);
rule!(
r"(?i)^a (.+?) RMS AC source feeds a (.+?) resistor\. what RMS current flows$",
"A",
c,
format!(
"{} / {}",
q!(c, 1, "V", Nonnegative),
q!(c, 2, "Ω", Positive)
)
);
rule!(
r"(?i)^find the equivalent resistance of (.+?), (.+?), and (.+?) resistors connected in parallel$",
"Ω",
c,
format!(
"1 / (1 / {} + 1 / {} + 1 / {})",
q!(c, 1, "Ω", Positive),
q!(c, 2, "Ω", Positive),
q!(c, 3, "Ω", Positive)
)
);
rule!(
r"(?i)^three resistors, (.+?), (.+?), and (.+?), are in series across (.+?) DC\. find the voltage across the (.+?) resistor$",
"V",
c,
{
let a = q!(c, 1, "Ω", Nonnegative);
let b = q!(c, 2, "Ω", Nonnegative);
let d = q!(c, 3, "Ω", Nonnegative);
let v = q!(c, 4, "V", Nonnegative);
let branch = q!(c, 5, "Ω", Nonnegative);
self.require_branch(&branch, &[&a, &b, &d], context)?;
let total = format!("sum({a},{b},{d})");
self.role(&total, "Ω", Domain::Positive, context)?;
format!("{v} * {branch} / {total}")
}
);
rule!(
r"(?i)^an ideal (.+?) battery drives a (.+?) resistor for (.+?)\. calculate charge transferred in (?:C|coulombs?)$",
"coulombs",
c,
format!(
"{} / {} * {}",
q!(c, 1, "V", Nonnegative),
q!(c, 2, "Ω", Positive),
q!(c, 3, "seconds", Nonnegative)
)
);
rule!(
r"(?i)^a rated ideal (.+?), (.+?) battery supplies a constant (.+?) load\. calculate runtime in (.+?), assuming its full rated capacity is usable$",
&c[4],
c,
{
let _voltage = q!(c, 1, "V", Positive);
let capacity = q!(c, 2, "Ah", Nonnegative);
let current = q!(c, 3, "A", Positive);
format!("{capacity} / {current}")
}
);
rule!(
r"(?i)^for an ideal (.+?) battery rated (.+?), calculate stored energy in (.+?), assuming the rated voltage stays constant throughout discharge$",
&c[3],
c,
{
let v = q!(c, 1, "V", Positive);
let capacity = q!(c, 2, "Ah", Nonnegative);
format!("{v} * {capacity}")
}
);
rule!(
r"(?i)^at (.+?) RMS, a load draws (.+?) RMS with power factor (.+?) lagging\. calculate reactive power in var, using Q = V I sqrt\(1 [−-] PF[²2]\)$",
"var",
c,
format!(
"{} * {} * sqrt(1 - square({}))",
q!(c, 1, "V", Nonnegative),
q!(c, 2, "A", Nonnegative),
q!(c, 3, "1", PowerFactor)
)
);
if let Some(c) =
re!(r"(?i)^given (.+?) RMS, (.+?) RMS, and real power (.+?), compute the power factor$")
.captures(input)
{
let v = q!(c, 1, "V", Positive);
let i = q!(c, 2, "A", Positive);
let p = q!(c, 3, "W", Nonnegative);
let expression = format!("{p} / ({v} * {i})");
self.role(&expression, "1", Domain::PowerFactor, context)?;
return Ok(Some(expression));
}
rule!(
r"(?i)^a purely resistive (.+?) load receives (.+?)\. calculate its RMS voltage$",
"V",
c,
format!(
"sqrt({} * {})",
q!(c, 1, "Ω", Positive),
q!(c, 2, "W", Nonnegative)
)
);
if let Some(c)=re!(r"(?i)^a (.+?) DC battery delivers (.+?) through a series network whose total resistance is (.+?)\. calculate battery power and check whether the stated current is consistent with Ohm[’']s law$").captures(input) {
let v=q!(c,1,"V",Nonnegative);
let i=q!(c,2,"A",Nonnegative);
let r=q!(c,3,"Ω",Positive);
self.require_consistent(&v,&format!("{i} * {r}"),"V",context)?;
return Ok(Some(format!("electrical_battery_check({v},{i},{r})")));
}
if let Some(c)=re!(r"(?i)^the load has (.+?) apparent power and (.+?) real power\. calculate power factor and reactive power magnitude using Q = sqrt\(S[²2] [−-] P[²2]\)$").captures(input) {
let s=q!(c,1,"VA",Positive);
let p=q!(c,2,"W",Nonnegative);
if self.compositions.quantity_order(&p,&s,context)?==Ordering::Greater {
return Err(Error("invalid_physical_value".into()));
}
return Ok(Some(format!("electrical_power_triangle({s},{p})")));
}
if let Some(c)=re!(r"(?i)^a (.+?) RMS source feeds a (.+?) load at PF (.+?)\. find current assuming the load is a series resistor; state whether that assumption is compatible with PF (.+?)$").captures(input) {
let v=q!(c,1,"V",Nonnegative);
let r=q!(c,2,"Ω",Positive);
let pf=q!(c,3,"1",PowerFactor);
let repeated=q!(c,4,"1",PowerFactor);
self.require_consistent(&pf,&repeated,"1",context)?;
self.require_consistent(&pf,"1","1",context)?;
return Ok(Some(format!("({v} / {r}) in A")));
}
rule!(
r"(?i)^a (.+?) DC source has a (.+?) series resistor followed by (.+?) parallel to (.+?)\. what is the current in the (.+?) leg$",
"A",
c,
{
let v = q!(c, 1, "V", Nonnegative);
let series = q!(c, 2, "Ω", Nonnegative);
let a = q!(c, 3, "Ω", Positive);
let b = q!(c, 4, "Ω", Positive);
let branch = q!(c, 5, "Ω", Positive);
self.require_branch(&branch, &[&a, &b], context)?;
let parallel = format!("(1 / (1 / {a} + 1 / {b}))");
format!("{v} / ({series} + {parallel}) * {parallel} / {branch}")
}
);
if let Some(c)=re!(r"(?i)^a (.+?) ideal battery is connected directly across an ideal (.+?) short circuit; calculate current and explain whether it is finite$").captures(input) {
let _v=q!(c,1,"V",Nonnegative);
let _r=q!(c,2,"Ω",Nonnegative);
return Err(Error("invalid_physical_value".into()));
}
if let Some(c)=re!(r"(?i)^a load at (.+?) RMS draws (.+?) RMS at PF (.+?) while also being specified to consume (.+?); identify whether all three specifications can hold simultaneously$").captures(input) {
let v=q!(c,1,"V",Nonnegative);
let i=q!(c,2,"A",Nonnegative);
let pf=q!(c,3,"1",PowerFactor);
let p=q!(c,4,"W",Nonnegative);
self.require_consistent(&p,&format!("{v} * {i} * {pf}"),"W",context)?;
return Ok(Some("true".into()));
}
if let Some(c)=re!(r"(?i)^a (.+?) resistor is said to dissipate (.+?) while carrying (.+?) DC; check whether the power and current agree$").captures(input) {
let r=q!(c,1,"Ω",Nonnegative);
let p=q!(c,2,"W",Nonnegative);
let i=q!(c,3,"A",Nonnegative);
self.require_consistent(&p,&format!("square({i}) * {r}"),"W",context)?;
return Ok(Some("true".into()));
}
if let Some(c) =
re!(r"(?i)^convert (.+?) into ohms using the definition (.+?) = (.+?)$").captures(input)
{
let _left = q!(c, 2, "seconds", Positive);
let _right = q!(c, 3, "seconds", Positive);
self.require_consistent(&c[2], &c[3], "seconds", context)?;
return Ok(Some(format!("({}) in ohms", &c[1])));
}
if let Some(c) = re!(
r"(?i)^a (.+?) RMS source feeds a (.+?) resistor and asks for the current in (.+?)$"
)
.captures(input)
{
let v = q!(c, 1, "V", Nonnegative);
let r = q!(c, 2, "Ω", Positive);
return Ok(Some(format!("({v} / {r}) in {}", &c[3])));
}
Ok(None)
}
}