use super::model_coordinates;
use super::{compositions::Compositions, integer_queries, named_quantities, syntax};
use crate::{Context, Error, ModelPosition, Outcome, Plugin, re};
use num_rational::BigRational;
use num_traits::{Signed, Zero};
#[derive(Default)]
pub struct FluidQueries {
engine: Compositions,
}
#[derive(Clone, Copy)]
enum Domain {
Signed,
Nonnegative,
Positive,
Nonzero,
}
impl Plugin for FluidQueries {
fn rewrite_call(
&self,
name: &str,
arguments: &str,
context: &Context,
_: ModelPosition,
) -> Outcome {
if !calls().is_match(&format!("{name}(")) {
return None;
}
Some(
Request {
plugin: self,
context,
}
.call(name, arguments),
)
}
fn rewrite_model(&self, input: &str, context: &Context, _: ModelPosition) -> Outcome {
Request {
plugin: self,
context,
}
.wording(input)
}
fn rewrite(&self, input: &str, context: &Context) -> Outcome {
let request = Request {
plugin: self,
context,
};
let expression = match syntax::rewrite_groups(input, |part| request.wording(part)) {
Some(Ok(expression)) => expression,
Some(Err(error)) => return Some(Err(error)),
None => input.into(),
};
match syntax::rewrite_calls(&expression, calls(), |name, arguments| {
request.call(name.trim(), arguments)
}) {
Ok(lowered) if lowered != input => Some(Ok(lowered)),
Err(error) => Some(Err(error)),
_ => None,
}
}
fn evaluate(&self, input: &str, context: &Context) -> Outcome {
let input = syntax::ungroup(input);
if !input.contains("fluid_summary(") {
return None;
}
Some((|| {
let inner = input
.strip_prefix("fluid_summary(")
.and_then(|s| s.strip_suffix(')'))
.ok_or_else(invalid)?;
let fields = inner.split(';').collect::<Vec<_>>();
const STAGES: [&str; 8] = [
"one", "two", "three", "four", "five", "six", "seven", "eight",
];
let staged = (2..=9).contains(&fields.len())
&& fields
.last()
.is_some_and(|field| field.starts_with("final amount|"))
&& fields[..fields.len() - 1]
.iter()
.enumerate()
.all(|(index, field)| {
field.starts_with(&format!("after stage {}|", STAGES[index]))
});
if fields.len() != 2
&& !staged
&& !(fields.len() == 3
&& fields
.iter()
.all(|field| field.starts_with("volumetric flow|")))
&& !(fields.len() == 3
&& fields[0].starts_with("cross-sectional area|")
&& fields[1].starts_with("volumetric flow|")
&& fields[2].starts_with("volumetric flow|"))
&& !(fields.len() == 3
&& fields[0].starts_with("first flow rate|")
&& fields[1].starts_with("second flow rate|")
&& fields[2].starts_with("flow rates agree|boolean|"))
{
return Err(invalid());
}
let mut outputs = Vec::new();
for field in fields {
let parts = field.split('|').collect::<Vec<_>>();
let (label, unit, expression) = match parts.as_slice() {
[label, expression] => (*label, field_unit(label)?, *expression),
[label, unit, expression] => (*label, *unit, *expression),
_ => return Err(invalid()),
};
if label == "flow rates agree" && unit == "boolean" {
if !matches!(expression, "true" | "false") {
return Err(invalid());
}
outputs.push(format!("{label}: {expression}"));
continue;
}
let reference = field_unit(label)?;
self.engine
.quantity_value(&format!("1 {unit}"), reference, context)?;
self.engine.quantity_value(expression, unit, context)?;
let value = self
.engine
.evaluate(&format!("({expression}) in {unit}"), context)
.ok_or_else(invalid)??;
outputs.push(format!("{label}: {value}"));
}
Ok(outputs.join("; "))
})())
}
}
fn calls() -> &'static regex::Regex {
re!(
r"(?i)\b(?:fluid_flow|fluid_speed|fluid_area|fluid_mass_flow|pipe_area|hydraulic_pressure|hydraulic_force|hydraulic_volume|hydraulic_work|hydrostatic_pressure|fluid_column_height)\s*\("
)
}
fn invalid() -> Error {
Error("invalid_expression".into())
}
fn diameter_flow_target(input: &str) -> &str {
match input.trim().to_ascii_lowercase().as_str() {
"cubic metres per second" => "m³/s",
"litres per second" => "L/s",
_ => input,
}
}
fn field_unit(label: &str) -> Result<&'static str, Error> {
Ok(match label {
"speed" | "outlet speed" => "m/s",
"mass flow rate" | "mass flow" => "kg/s",
"cross-sectional area" => "m²",
"total mass" => "kg",
"volumetric flow" | "volume flow" | "first flow rate" | "second flow rate"
| "net flow rate" => "m³/s",
"work" => "J",
"volume" | "final volume" | "final amount" | "after stage one" | "after stage two"
| "after stage three" | "after stage four" | "after stage five" | "after stage six"
| "after stage seven" | "after stage eight" => "m³",
"force" => "N",
"displacement" | "pressure head" => "m",
"pressure"
| "pressure increase"
| "pressure difference"
| "gauge pressure"
| "hydrostatic pressure" => "Pa",
_ => return Err(invalid()),
})
}
fn summary(fields: &[(&str, String)]) -> String {
format!(
"fluid_summary({})",
fields
.iter()
.map(|(label, expression)| { format!("{label}|{expression}") })
.collect::<Vec<_>>()
.join(";")
)
}
struct Request<'a> {
plugin: &'a FluidQueries,
context: &'a Context,
}
impl Request<'_> {
fn check(value: &BigRational, domain: Domain) -> Result<(), Error> {
if matches!(domain, Domain::Nonzero) && value.is_zero() {
return Err(Error("division_by_zero".into()));
}
if matches!(domain, Domain::Nonnegative | Domain::Positive) && value.is_negative()
|| matches!(domain, Domain::Positive) && value.is_zero()
{
return Err(Error("invalid_physical_quantity".into()));
}
Ok(())
}
fn role(&self, input: &str, unit: &str, domain: Domain) -> Result<BigRational, Error> {
let value = model_coordinates::read(input, unit, &self.plugin.engine, self.context)?.value;
Self::check(&value, domain)?;
Ok(value)
}
fn result(&self, value: BigRational, unit: &str, domain: Domain) -> Result<String, Error> {
let value = model_coordinates::bounded(value)?;
Self::check(&value, domain)?;
let expression = format!("((rational({},{})) {unit})", value.numer(), value.denom());
if expression.len() > 4096 {
return Err(Error("integer_limit".into()));
}
self.plugin
.engine
.quantity_value(&expression, unit, self.context)?;
Ok(expression)
}
fn call(&self, name: &str, arguments: &str) -> Result<String, Error> {
let args = named_quantities::function_arguments(arguments, false)?;
let name = name.to_ascii_lowercase();
let role = |i: usize, unit: &str, domain| self.role(args[i], unit, domain);
let (value, unit, domain) = match (name.as_str(), args.len()) {
("fluid_flow", 2) => (
role(0, "m²", Domain::Positive)? * role(1, "m/s", Domain::Signed)?,
"m³/s",
Domain::Signed,
),
("fluid_speed", 2) => (
role(0, "m³/s", Domain::Signed)? / role(1, "m²", Domain::Positive)?,
"m/s",
Domain::Signed,
),
("fluid_area", 2) => (
role(0, "m³/s", Domain::Signed)? / role(1, "m/s", Domain::Nonzero)?,
"m²",
Domain::Nonnegative,
),
("fluid_mass_flow", 2) => (
role(0, "kg/m³", Domain::Positive)? * role(1, "m³/s", Domain::Signed)?,
"kg/s",
Domain::Signed,
),
("pipe_area", 1 | 2) => {
let diameter = role(0, "m", Domain::Positive)?;
let pi = self.role(
if args.len() == 2 { args[1] } else { "pi" },
"1",
Domain::Positive,
)?;
(
pi * &diameter * diameter / BigRational::from_integer(4.into()),
"m²",
Domain::Positive,
)
}
("hydraulic_pressure", 2) => (
role(0, "N", Domain::Signed)? / role(1, "m²", Domain::Positive)?,
"Pa",
Domain::Signed,
),
("hydraulic_force", 2) => (
role(0, "Pa", Domain::Signed)? * role(1, "m²", Domain::Positive)?,
"N",
Domain::Signed,
),
("hydraulic_volume", 2) => (
role(0, "m²", Domain::Positive)? * role(1, "m", Domain::Signed)?,
"m³",
Domain::Signed,
),
("hydraulic_work", 2) => (
role(0, "N", Domain::Signed)? * role(1, "m", Domain::Signed)?,
"J",
Domain::Signed,
),
("hydrostatic_pressure", 3) => (
role(0, "kg/m³", Domain::Positive)?
* role(1, "m/s²", Domain::Positive)?
* role(2, "m", Domain::Signed)?,
"Pa",
Domain::Signed,
),
("fluid_column_height", 3) => (
role(0, "Pa", Domain::Signed)?
/ (role(1, "kg/m³", Domain::Positive)? * role(2, "m/s²", Domain::Positive)?),
"m",
Domain::Signed,
),
_ => return Err(invalid()),
};
self.result(value, unit, domain)
}
fn report(&self, fields: &[(&str, &str, String)]) -> Result<String, Error> {
for (label, target, expression) in fields {
if *label == "flow rates agree" && *target == "boolean" {
if !matches!(expression.as_str(), "true" | "false") {
return Err(invalid());
}
continue;
}
self.plugin.engine.quantity_value(
&format!("1 {target}"),
field_unit(label)?,
self.context,
)?;
self.plugin
.engine
.quantity_value(expression, target, self.context)?;
}
let report = format!(
"fluid_summary({})",
fields
.iter()
.map(|(label, target, expression)| format!("{label}|{target}|{expression}"))
.collect::<Vec<_>>()
.join(";")
);
if report.len() > 4096 {
return Err(Error("integer_limit".into()));
}
Ok(report)
}
fn staged_stock_report(&self, input: &str) -> Option<Result<String, Error>> {
let c = re!(r"(?i)^a (?:stock )?(?:tank|reservoir|vessel) has (.+?) initially\. (.+?); calculate stage-end stocks and final amount$").captures(input)?;
Some((|| {
const STAGES: [&str; 8] = [
"one", "two", "three", "four", "five", "six", "seven", "eight",
];
let initial = self.role(&c[1], "L", Domain::Nonnegative)?;
let stages = c.get(2).unwrap().as_str();
let heads = re!(r"(?i)\bstage (one|two|three|four|five|six|seven|eight)\b")
.captures_iter(stages)
.collect::<Vec<_>>();
if heads.is_empty() || heads.len() > 8 {
return Err(invalid());
}
let mut transfers = Vec::with_capacity(heads.len());
for (index, head) in heads.iter().enumerate() {
if !head[1].eq_ignore_ascii_case(STAGES[index]) {
return Err(invalid());
}
let span = head.get(0).unwrap();
if index == 0 && !stages[..span.start()].trim().is_empty() {
return Err(invalid());
}
let end = heads
.get(index + 1)
.map_or(stages.len(), |next| next.get(0).unwrap().start());
let mut clause = stages[span.end()..end].trim();
if index + 1 < heads.len() {
clause = clause
.strip_suffix(", and")
.or_else(|| clause.strip_suffix(','))
.ok_or_else(invalid)?
.trim_end();
}
let Some(stage) = re!(r"(?i)^(adds|removes) (.+?)(?: for (.+))?$").captures(clause)
else {
return Err(invalid());
};
let amount = if let Some(duration) = stage.get(3) {
let rate = self.role(&stage[2], "L/min", Domain::Nonnegative)?;
let time = self.role(duration.as_str(), "min", Domain::Nonnegative)?;
model_coordinates::bounded(rate * time)?
} else {
self.role(&stage[2], "L", Domain::Nonnegative)?
};
transfers.push(if stage[1].eq_ignore_ascii_case("removes") {
-amount
} else {
amount
});
}
let mut stock = initial;
let mut fields = Vec::with_capacity(transfers.len() + 1);
for (index, transfer) in transfers.into_iter().enumerate() {
stock = model_coordinates::bounded(stock + transfer)?;
Request::check(&stock, Domain::Nonnegative)?;
let label = match index {
0 => "after stage one",
1 => "after stage two",
2 => "after stage three",
3 => "after stage four",
4 => "after stage five",
5 => "after stage six",
6 => "after stage seven",
_ => "after stage eight",
};
fields.push((
label,
"L",
self.result(stock.clone(), "L", Domain::Nonnegative)?,
));
}
fields.push((
"final amount",
"L",
self.result(stock, "L", Domain::Nonnegative)?,
));
self.report(&fields)
})())
}
fn wording(&self, input: &str) -> Outcome {
let input = input.trim().trim_end_matches(['.', '?']).replace('−', "-");
if let Some(report) = self.staged_stock_report(&input) {
return Some(report);
}
macro_rules! q {
($c:ident, $i:literal, $unit:literal, $domain:ident) => {
self.role(&$c[$i], $unit, Domain::$domain)?
};
}
macro_rules! rule {
($pattern:literal, $c:ident, $body:block) => {
if let Some($c) = re!($pattern).captures(&input) {
return Some((|| -> Result<String, Error> { $body })());
}
};
}
rule!(
r"(?i)^a [a-z]+ pipe with cross-sectional area (.+?) carries [a-z]+ at (.+?); (?:report|give) volumetric flow in (.+?), (.+?), and (.+)$",
c,
{
let area = q!(c, 1, "m²", Positive);
let speed = q!(c, 2, "m/s", Nonnegative);
let flow = self.result(
model_coordinates::bounded(area * speed)?,
"m³/s",
Domain::Nonnegative,
)?;
self.report(&[
("volumetric flow", &c[3], flow.clone()),
("volumetric flow", &c[4], flow.clone()),
("volumetric flow", &c[5], flow),
])
}
);
rule!(
r"(?i)^a pipe has inner diameter (.+?) and carries [a-z]+ at an average speed of (.+?); using pi\s*=\s*(.+?), calculate cross-sectional area and volumetric flow in (.+?) and (.+)$",
c,
{
let diameter = q!(c, 1, "m", Positive);
let speed = q!(c, 2, "m/s", Nonnegative);
let pi = q!(c, 3, "1", Positive);
let area = model_coordinates::bounded(
pi * &diameter * &diameter / BigRational::from_integer(4.into()),
)?;
let flow = model_coordinates::bounded(&area * speed)?;
let area = self.result(area, "m²", Domain::Positive)?;
let flow = self.result(flow, "m³/s", Domain::Nonnegative)?;
self.report(&[
("cross-sectional area", "m²", area),
("volumetric flow", diameter_flow_target(&c[4]), flow.clone()),
("volumetric flow", diameter_flow_target(&c[5]), flow),
])
}
);
rule!(
r"(?i)^a (?:reservoir|tank|vessel) starts with (.+?), receives (.+?), and then drains (.+?)\. convert all quantities consistently and report remaining volume in (.+)$",
c,
{
let initial = q!(c, 1, "L", Nonnegative);
let received = q!(c, 2, "L", Nonnegative);
let drained = q!(c, 3, "L", Nonnegative);
let scale = self.role(&format!("1 {}", &c[4]), "L", Domain::Positive)?;
let target = self
.plugin
.engine
.units
.unit(c[4].trim())
.ok_or_else(|| Error("incompatible_units".into()))?
.symbol;
let available = model_coordinates::bounded(initial + received)?;
if drained > available {
return Err(Error("invalid_physical_quantity".into()));
}
self.result(
model_coordinates::bounded((available - drained) / scale)?,
&target,
Domain::Nonnegative,
)
}
);
rule!(
r"(?i)^a water tank gains (.+?) for (.+?) and then loses (.+?) for (.+?); starting empty, how many (?:litres|liters) remain$",
c,
{
let inflow = q!(c, 1, "L/min", Nonnegative);
let filling_time = q!(c, 2, "minutes", Nonnegative);
let outflow = q!(c, 3, "L/min", Nonnegative);
let draining_time = q!(c, 4, "minutes", Nonnegative);
let available = model_coordinates::bounded(inflow * filling_time)?;
let drained = model_coordinates::bounded(outflow * draining_time)?;
if drained > available {
return Err(Error("invalid_physical_quantity".into()));
}
self.result(available - drained, "L", Domain::Nonnegative)
}
);
rule!(
r"(?i)^a tank receives (.+?) for (.+?) while draining (.+?) throughout\. starting with (.+?), state (final volume and net flow rate|net flow rate and final volume)$",
c,
{
let inflow = q!(c, 1, "L/min", Nonnegative);
let duration = q!(c, 2, "minutes", Nonnegative);
let drain = q!(c, 3, "L/min", Nonnegative);
let initial = q!(c, 4, "L", Nonnegative);
let net = model_coordinates::bounded(inflow - drain)?;
let final_volume = model_coordinates::bounded(
&initial + model_coordinates::bounded(&net * &duration)?,
)?;
let volume = self.result(final_volume, "L", Domain::Nonnegative)?;
let flow = self.result(net, "L/min", Domain::Signed)?;
let fields = if c[5].eq_ignore_ascii_case("final volume and net flow rate") {
[
("final volume", "L", volume),
("net flow rate", "L/min", flow),
]
} else {
[
("net flow rate", "L/min", flow),
("final volume", "L", volume),
]
};
self.report(&fields)
}
);
rule!(
r"(?i)^a pump lifts (.+?) of water through (.+?) with (.+?) efficiency; using water density (.+?) and g\s*=\s*(.+?), (?:find|calculate) input power$",
c,
{
let flow = q!(c, 1, "m³/s", Nonnegative);
let height = q!(c, 2, "m", Nonnegative);
let percentage = re!(r"(?i)^(.+?)(?:%|\s+percent)$")
.captures(c[3].trim())
.ok_or_else(invalid)?;
let (n, d) = integer_queries::ratio_value(&percentage[1])?;
let efficiency = model_coordinates::bounded(
BigRational::new(n, d) / BigRational::from_integer(100.into()),
)?;
Self::check(&efficiency, Domain::Positive)?;
if efficiency > BigRational::from_integer(1.into()) {
return Err(Error("invalid_physical_quantity".into()));
}
let density = q!(c, 4, "kg/m³", Positive);
let gravity = q!(c, 5, "m/s²", Positive);
Ok(format!(
"{} in W",
self.result(
density * flow * gravity * height / efficiency,
"W",
Domain::Nonnegative,
)?
))
}
);
rule!(
r"(?i)^use the supplied ideal gas relation P1V1\s*=\s*P2V2 at constant temperature: P1\s*=\s*(.+?), V1\s*=\s*(.+?), P2\s*=\s*(.+?); find V2 in litres$",
c,
{
let first_pressure = q!(c, 1, "Pa", Positive);
let first_volume = q!(c, 2, "L", Positive);
let second_pressure = q!(c, 3, "Pa", Positive);
Ok(format!(
"{} in L",
self.result(
first_pressure * first_volume / second_pressure,
"L",
Domain::Positive
)?
))
}
);
rule!(
r"(?i)^a liquid column follows ΔP\s*=\s*ρgh with supplied density (.+?), height (.+?), and g\s*=\s*(.+?); calculate pressure difference in (.+?) and (.+)$",
c,
{
let density = q!(c, 1, "kg/m³", Positive);
let height = q!(c, 2, "m", Nonnegative);
let gravity = q!(c, 3, "m/s²", Positive);
let pressure =
self.result(density * height * gravity, "Pa", Domain::Nonnegative)?;
self.report(&[
("pressure difference", &c[4], pressure.clone()),
("pressure difference", &c[5], pressure),
])
}
);
rule!(
r"(?i)^a pipe carries [a-z]+ at (.+?) through area (.+?); using density (.+?), calculate volume flow in (.+?) and mass flow in (.+)$",
c,
{
let speed = q!(c, 1, "m/s", Nonnegative);
let area = q!(c, 2, "m²", Positive);
let density = q!(c, 3, "kg/m³", Positive);
let flow = area * speed;
self.report(&[
(
"volume flow",
&c[4],
self.result(flow.clone(), "m³/s", Domain::Nonnegative)?,
),
(
"mass flow",
&c[5],
self.result(flow * density, "kg/s", Domain::Nonnegative)?,
),
])
}
);
rule!(
r"(?i)^a gas occupies (.+?) at (.+?); at constant temperature its pressure becomes (.+?), so use P1V1\s*=\s*P2V2 to calculate final volume$",
c,
{
let initial_volume = q!(c, 1, "L", Positive);
let initial_pressure = q!(c, 2, "Pa", Positive);
let final_pressure = q!(c, 3, "Pa", Positive);
Ok(format!(
"{} in L",
self.result(
initial_volume * initial_pressure / final_pressure,
"L",
Domain::Positive
)?
))
}
);
rule!(
r"(?i)^a (.+?) pipe carries [a-z]+ at (.+?); calculate volume flow in (.+?) and mass flow in (.+?) using density (.+)$",
c,
{
let area = q!(c, 1, "m²", Positive);
let speed = q!(c, 2, "m/s", Nonnegative);
let density = q!(c, 5, "kg/m³", Positive);
let flow = area * speed;
self.report(&[
(
"volume flow",
&c[3],
self.result(flow.clone(), "m³/s", Domain::Nonnegative)?,
),
(
"mass flow",
&c[4],
self.result(flow * density, "kg/s", Domain::Nonnegative)?,
),
])
}
);
rule!(
r"(?i)^[a-z]+ flows through a (.+?) pipe at (.+?) and narrows to (.+?); (?:calculate|find) outlet speed and flow in (.+)$",
c,
{
let inlet_area = q!(c, 1, "m²", Positive);
let speed = q!(c, 2, "m/s", Signed);
let outlet_area = q!(c, 3, "m²", Positive);
if outlet_area >= inlet_area {
return Err(Error("invalid_physical_quantity".into()));
}
let flow = inlet_area * speed;
let target = self
.plugin
.engine
.units
.unit(&c[4])
.ok_or_else(invalid)?
.symbol;
self.report(&[
(
"outlet speed",
"m/s",
self.result(&flow / outlet_area, "m/s", Domain::Signed)?,
),
(
"volumetric flow",
&target,
self.result(flow, "m³/s", Domain::Signed)?,
),
])
}
);
rule!(
r"(?i)^[a-z]+ moves horizontally from (.+?) to (.+?); using density (.+?), (?:calculate|find) change in dynamic pressure from one half rho v squared$",
c,
{
let initial = q!(c, 1, "m/s", Signed);
let final_speed = q!(c, 2, "m/s", Signed);
let density = q!(c, 3, "kg/m³", Positive);
let change = density * (&final_speed * &final_speed - &initial * &initial)
/ BigRational::from_integer(2.into());
Ok(format!(
"{} in Pa",
self.result(change, "Pa", Domain::Signed)?
))
}
);
rule!(
r"(?i)^a reservoir outlet is (.+?) below the surface; for [a-z]+ density (.+?) and g\s*=\s*(.+?), (?:calculate|find) gauge pressure and pressure head$",
c,
{
let head = q!(c, 1, "m", Nonnegative);
let density = q!(c, 2, "kg/m³", Positive);
let gravity = q!(c, 3, "m/s²", Positive);
let pressure = &head * density * gravity;
self.report(&[
(
"gauge pressure",
"Pa",
self.result(pressure, "Pa", Domain::Nonnegative)?,
),
(
"pressure head",
"m",
self.result(head, "m", Domain::Nonnegative)?,
),
])
}
);
rule!(
r"(?i)^a (.+?) pipe carries (.+?) of [a-z]+; (?:calculate|find) fluid speed and mass flow for density (.+)$",
c,
{
let area = q!(c, 1, "m²", Positive);
let flow = q!(c, 2, "m³/s", Signed);
let density = q!(c, 3, "kg/m³", Positive);
self.report(&[
(
"speed",
"m/s",
self.result(&flow / area, "m/s", Domain::Signed)?,
),
(
"mass flow rate",
"kg/s",
self.result(flow * density, "kg/s", Domain::Signed)?,
),
])
}
);
rule!(
r"(?i)^a (.+?) force acts over area (.+?); (?:calculate|find) pressure from force divided by area$",
c,
{
let force = q!(c, 1, "N", Signed);
let area = q!(c, 2, "m²", Positive);
Ok(format!(
"{} in Pa",
self.result(force / area, "Pa", Domain::Signed)?
))
}
);
rule!(
r"(?i)^a fluid cross-section increases from (.+?) to (.+?) while speed increases from (.+?) to (.+?); (?:calculate|find) each flow rate and assess continuity$",
c,
{
let initial_area = q!(c, 1, "m²", Positive);
let final_area = q!(c, 2, "m²", Positive);
let initial_speed = q!(c, 3, "m/s", Signed);
let final_speed = q!(c, 4, "m/s", Signed);
if final_area <= initial_area || final_speed <= initial_speed {
return Err(Error("invalid_physical_quantity".into()));
}
let first = initial_area * initial_speed;
let second = final_area * final_speed;
let agrees = (first == second).to_string();
self.report(&[
(
"first flow rate",
"m³/s",
self.result(first, "m³/s", Domain::Signed)?,
),
(
"second flow rate",
"m³/s",
self.result(second, "m³/s", Domain::Signed)?,
),
("flow rates agree", "boolean", agrees),
])
}
);
rule!(
r"(?i)^an ideal gas occupies (.+?) at (.+?); at constant temperature, (?:calculate|find) its volume at (.+)$",
c,
{
let volume = q!(c, 1, "L", Nonnegative);
let initial_pressure = q!(c, 2, "Pa", Positive);
let final_pressure = q!(c, 3, "Pa", Positive);
Ok(format!(
"{} in L",
self.result(
volume * initial_pressure / final_pressure,
"L",
Domain::Nonnegative
)?
))
}
);
rule!(
r"(?i)^a (.+?) force is applied over (.+?); (?:find|calculate) pressure in (.+?) and (.+)$",
c,
{
let force = q!(c, 1, "N", Nonnegative);
let area = q!(c, 2, "m²", Positive);
let pressure = self.result(force / area, "Pa", Domain::Nonnegative)?;
self.report(&[
("pressure", &c[3], pressure.clone()),
("pressure", &c[4], pressure),
])
}
);
rule!(
r"(?i)^a liquid of density (.+?) flows at (.+?) through area (.+?); (?:calculate|find) mass flow in (.+?) and (.+)$",
c,
{
let density = q!(c, 1, "kg/m³", Positive);
let speed = q!(c, 2, "m/s", Nonnegative);
let area = q!(c, 3, "m²", Positive);
let mass_flow = self.result(density * speed * area, "kg/s", Domain::Nonnegative)?;
self.report(&[
("mass flow rate", &c[4], mass_flow.clone()),
("mass flow rate", &c[5], mass_flow),
])
}
);
rule!(
r"(?i)^a (.+?) pipe narrows to (.+?) and speed rises from (.+?) to (.+?); (?:calculate|find) both flow rates and state whether they agree$",
c,
{
let first_area = q!(c, 1, "m²", Positive);
let second_area = q!(c, 2, "m²", Positive);
let first_speed = q!(c, 3, "m/s", Signed);
let second_speed = q!(c, 4, "m/s", Signed);
if second_area >= first_area || second_speed <= first_speed {
return Err(Error("invalid_physical_quantity".into()));
}
let first = first_area * first_speed;
let second = second_area * second_speed;
let agrees = (first == second).to_string();
self.report(&[
(
"first flow rate",
"m³/s",
self.result(first, "m³/s", Domain::Signed)?,
),
(
"second flow rate",
"m³/s",
self.result(second, "m³/s", Domain::Signed)?,
),
("flow rates agree", "boolean", agrees),
])
}
);
rule!(
r"(?i)^a channel has area (.+?) and (?:flow )?speed (.+?); (?:calculate|find) Q in (.+?) and convert (?:it )?to (.+)$",
c,
{
let area = q!(c, 1, "m²", Positive);
let speed = q!(c, 2, "m/s", Nonnegative);
let flow = self.result(area * speed, "m³/s", Domain::Nonnegative)?;
self.report(&[
("volumetric flow", &c[3], flow.clone()),
("volumetric flow", &c[4], flow),
])
}
);
rule!(
r"(?i)^[a-z]+ of density (.+?) flows through area (.+?) at (.+?) for (.+?); (?:find|calculate) mass flow in (.+?) and total mass in (.+)$",
c,
{
let rho = q!(c, 1, "kg/m³", Positive);
let area = q!(c, 2, "m²", Positive);
let speed = q!(c, 3, "m/s", Nonnegative);
let seconds = q!(c, 4, "seconds", Nonnegative);
let flow = rho * area * speed;
self.report(&[
(
"mass flow rate",
&c[5],
self.result(flow.clone(), "kg/s", Domain::Nonnegative)?,
),
(
"total mass",
&c[6],
self.result(flow * seconds, "kg", Domain::Nonnegative)?,
),
])
}
);
rule!(
r"(?i)^a (?:[a-z]+ )?column at depth (.+?) has rho\s*=\s*(.+?) and g\s*=\s*(.+?); (?:find|calculate) hydrostatic pressure, then force on area (.+)$",
c,
{
let depth = q!(c, 1, "m", Nonnegative);
let rho = q!(c, 2, "kg/m³", Positive);
let g = q!(c, 3, "m/s²", Positive);
let area = q!(c, 4, "m²", Positive);
let pressure = rho * g * depth;
self.report(&[
(
"hydrostatic pressure",
"Pa",
self.result(pressure.clone(), "Pa", Domain::Nonnegative)?,
),
(
"force",
"N",
self.result(pressure * area, "N", Domain::Nonnegative)?,
),
])
}
);
rule!(
r"(?i)^(?:find|calculate) (?:fluid )?flow speed for Q\s*=\s*(.+?) and area\s*=\s*(.+?)(?: using Q\s*=\s*A\*?v)?$",
c,
{
let flow = q!(c, 1, "m³/s", Nonnegative);
let area = q!(c, 2, "m²", Positive);
Ok(format!(
"{} in m/s",
self.result(flow / area, "m/s", Domain::Nonnegative)?
))
}
);
rule!(
r"(?i)^for Q\s*=\s*(.+?) and area\s*=\s*(.+?), (?:find|calculate) (?:the )?mass flow(?: rate)? (?:given|with) density (.+)$",
c,
{
let flow = q!(c, 1, "m³/s", Nonnegative);
let _area = q!(c, 2, "m²", Positive);
let rho = q!(c, 3, "kg/m³", Positive);
Ok(format!(
"{} in kg/s",
self.result(rho * flow, "kg/s", Domain::Nonnegative)?
))
}
);
rule!(
r"(?i)^a pipe carries [a-z]+ at (.+?) through a (.+?) section; find its mean speed from Q\s*=\s*Av$",
c,
{
let flow = q!(c, 1, "m³/s", Nonnegative);
let area = q!(c, 2, "m²", Positive);
Ok(format!(
"{} in m/s",
self.result(flow / area, "m/s", Domain::Nonnegative)?
))
}
);
rule!(
r"(?i)^for an incompressible fluid, A[₁1]\s*=\s*(.+?), v[₁1]\s*=\s*(.+?), and A[₂2]\s*=\s*(.+?); find v[₂2] using A[₁1]v[₁1]\s*=\s*A[₂2]v[₂2]$",
c,
{
let a = q!(c, 1, "m²", Positive);
let v = q!(c, 2, "m/s", Nonnegative);
let b = q!(c, 3, "m²", Positive);
Ok(format!(
"{} in m/s",
self.result(a * v / b, "m/s", Domain::Nonnegative)?
))
}
);
rule!(
r"(?i)^[a-z]+ of density (.+?) flows at (.+?) through a (.+?) pipe; find its mass flow rate$",
c,
{
let rho = q!(c, 1, "kg/m³", Positive);
let v = q!(c, 2, "m/s", Nonnegative);
let a = q!(c, 3, "m²", Positive);
Ok(format!(
"{} in kg/s",
self.result(rho * a * v, "kg/s", Domain::Nonnegative)?
))
}
);
rule!(
r"(?i)^[a-z]+ at (.+?) flows at (.+?) through a (.+?) diameter pipe; find the mean speed using A\s*=\s*πd²/4 and Q\s*=\s*Av$",
c,
{
let _ = q!(c, 1, "kg/m³", Positive);
let flow = q!(c, 2, "m³/s", Nonnegative);
let d = q!(c, 3, "m", Positive);
let pi = self.role("pi", "1", Domain::Positive)?;
let speed = flow * BigRational::from_integer(4.into()) / (pi * &d * d);
Ok(format!(
"{} in m/s",
self.result(speed, "m/s", Domain::Nonnegative)?
))
}
);
rule!(
r"(?i)^a liquid['’]s speed is (.+?) in a (.+?) section\. what section area gives speed (.+?) at the same volumetric flow$",
c,
{
let v = q!(c, 1, "m/s", Nonnegative);
let a = q!(c, 2, "m²", Positive);
let next = q!(c, 3, "m/s", Positive);
Ok(format!(
"{} in m²",
self.result(a * v / next, "m²", Domain::Nonnegative)?
))
}
);
rule!(
r"(?i)^at equal mass flow, a fluid with density (.+?) moves at (.+?) through (.+?)\. find its speed where density is (.+?) and area is (.+)$",
c,
{
let rho = q!(c, 1, "kg/m³", Positive);
let v = q!(c, 2, "m/s", Nonnegative);
let a = q!(c, 3, "m²", Positive);
let next_rho = q!(c, 4, "kg/m³", Positive);
let next_a = q!(c, 5, "m²", Positive);
Ok(format!(
"{} in m/s",
self.result(
rho * a * v / (next_rho * next_a),
"m/s",
Domain::Nonnegative
)?
))
}
);
rule!(
r"(?i)^for steady incompressible flow, calculate Q if a (.+?) diameter pipe has mean speed (.+?); use π\s*=\s*(.+)$",
c,
{
let d = q!(c, 1, "m", Positive);
let v = q!(c, 2, "m/s", Nonnegative);
let pi = q!(c, 3, "1", Positive);
Ok(format!(
"{} in m³/s",
self.result(
pi * &d * d * v / BigRational::from_integer(4.into()),
"m³/s",
Domain::Nonnegative
)?
))
}
);
rule!(
r"(?i)^a pipe narrows from (.+?) to (.+?) diameter\. if the upstream speed is (.+?) and flow is incompressible, find the downstream speed$",
c,
{
let before = q!(c, 1, "m", Positive);
let after = q!(c, 2, "m", Positive);
let v = q!(c, 3, "m/s", Nonnegative);
Self::check(&(&before - &after), Domain::Positive)?;
Ok(format!(
"{} in m/s",
self.result(
v * &before * before / (&after * &after),
"m/s",
Domain::Nonnegative
)?
))
}
);
rule!(
r"(?i)^[a-z]+ flows at (.+?) through a (.+?) diameter section\. find the mean speed and mass flow rate; use density (.+?) and π\s*=\s*(.+)$",
c,
{
let flow = q!(c, 1, "m³/s", Nonnegative);
let d = q!(c, 2, "m", Positive);
let rho = q!(c, 3, "kg/m³", Positive);
let pi = q!(c, 4, "1", Positive);
let speed = &flow * BigRational::from_integer(4.into()) / (pi * &d * d);
Ok(summary(&[
("speed", self.result(speed, "m/s", Domain::Nonnegative)?),
(
"mass flow rate",
self.result(rho * flow, "kg/s", Domain::Nonnegative)?,
),
]))
}
);
rule!(
r"(?i)^in a branching incompressible flow, (.+?) enters; two outlets carry (.+?) and (.+?)\. find the third outlet flow$",
c,
{
let a = q!(c, 1, "m³/s", Nonnegative);
let b = q!(c, 2, "m³/s", Nonnegative);
let d = q!(c, 3, "m³/s", Nonnegative);
Ok(format!(
"{} in m³/s",
self.result(a - b - d, "m³/s", Domain::Nonnegative)?
))
}
);
rule!(
r"(?i)^an ideal hydraulic press has piston areas (.+?) and (.+?)\. a (.+?) force acts on the small piston; find the large-piston force using equal pressure$",
c,
{
let a = q!(c, 1, "m²", Positive);
let b = q!(c, 2, "m²", Positive);
let force = q!(c, 3, "N", Nonnegative);
let (small, large) = if a < b { (a, b) } else { (b, a) };
Self::check(&(&large - &small), Domain::Positive)?;
Ok(format!(
"{} in N",
self.result(force * large / small, "N", Domain::Nonnegative)?
))
}
);
rule!(
r"(?i)^a hydraulic lift has piston area (.+?) and supports a (.+?) load\. find the required small-piston force if its area is (.+?); use g\s*=\s*(.+?) and ideal equal pressure$",
c,
{
let large = q!(c, 1, "m²", Positive);
let mass = q!(c, 2, "kg", Nonnegative);
let small = q!(c, 3, "m²", Positive);
let g = q!(c, 4, "m/s²", Positive);
Self::check(&(&large - &small), Domain::Positive)?;
Ok(format!(
"{} in N",
self.result(mass * g * small / large, "N", Domain::Nonnegative)?
))
}
);
rule!(
r"(?i)^a (.+?) force moves a hydraulic piston (.+?) by (.+?)\. find ideal work and the volume displaced$",
c,
{
let force = q!(c, 1, "N", Nonnegative);
let a = q!(c, 2, "m²", Positive);
let distance = q!(c, 3, "m", Nonnegative);
Ok(summary(&[
(
"work",
self.result(force * &distance, "J", Domain::Nonnegative)?,
),
(
"volume",
self.result(a * distance, "m³", Domain::Nonnegative)?,
),
]))
}
);
rule!(
r"(?i)^in an ideal hydraulic system, a (.+?) input piston moves down (.+?) against (.+?)\. find the force on a (.+?) output piston and its displacement; assume equal pressure and conserved displaced volume$",
c,
{
let a = q!(c, 1, "m²", Positive);
let distance = q!(c, 2, "m", Nonnegative);
let force = q!(c, 3, "N", Nonnegative);
let b = q!(c, 4, "m²", Positive);
Ok(summary(&[
(
"force",
self.result(force * &b / &a, "N", Domain::Nonnegative)?,
),
(
"displacement",
self.result(a * distance / b, "m", Domain::Nonnegative)?,
),
]))
}
);
rule!(
r"(?i)^a submerged flat panel has area (.+?) at uniform depth (.+?) in a liquid of density (.+?)\. find the pressure increase and ideal resultant force; use g\s*=\s*(.+?) and p\s*=\s*ρgh$",
c,
{
let a = q!(c, 1, "m²", Positive);
let h = q!(c, 2, "m", Nonnegative);
let rho = q!(c, 3, "kg/m³", Positive);
let g = q!(c, 4, "m/s²", Positive);
let pressure = rho * g * h;
Ok(summary(&[
(
"pressure increase",
self.result(pressure.clone(), "Pa", Domain::Nonnegative)?,
),
(
"force",
self.result(pressure * a, "N", Domain::Nonnegative)?,
),
]))
}
);
rule!(
r"(?i)^a hydraulic cylinder with piston area (.+?) must exert (.+?)\. find the required pressure and the force on a second piston of area (.+?); assume ideal equal pressure$",
c,
{
let a = q!(c, 1, "m²", Positive);
let force = q!(c, 2, "N", Nonnegative);
let b = q!(c, 3, "m²", Positive);
let pressure = force / a;
Ok(summary(&[
(
"pressure",
self.result(pressure.clone(), "Pa", Domain::Nonnegative)?,
),
(
"force",
self.result(pressure * b, "N", Domain::Nonnegative)?,
),
]))
}
);
rule!(
r"(?i)^a (.+?) load is raised vertically by (.+?) using an ideal hydraulic lift\. find the minimum input work; use g\s*=\s*(.+?) and assume no losses$",
c,
{
let mass = q!(c, 1, "kg", Nonnegative);
let h = q!(c, 2, "m", Nonnegative);
let g = q!(c, 3, "m/s²", Positive);
Ok(format!(
"{} in J",
self.result(mass * g * h, "J", Domain::Nonnegative)?
))
}
);
rule!(
r"(?i)^[a-z]+ of density (.+?) has a pressure increase of (.+?)\. find the equivalent fluid-column height using Δp\s*=\s*ρgh and g\s*=\s*(.+)$",
c,
{
let rho = q!(c, 1, "kg/m³", Positive);
let pressure = q!(c, 2, "Pa", Nonnegative);
let g = q!(c, 3, "m/s²", Positive);
Ok(format!(
"{} in m",
self.result(pressure / (rho * g), "m", Domain::Nonnegative)?
))
}
);
rule!(
r"(?i)^an ideal hydraulic ram has input area (.+?) and output area (.+?)\. find the input force needed to raise a (.+?) load; use g\s*=\s*(.+)$",
c,
{
let a = q!(c, 1, "m²", Positive);
let b = q!(c, 2, "m²", Positive);
let mass = q!(c, 3, "kg", Nonnegative);
let g = q!(c, 4, "m/s²", Positive);
Ok(format!(
"{} in N",
self.result(mass * g * a / b, "N", Domain::Nonnegative)?
))
}
);
rule!(
r"(?i)^[a-z]+ of density (.+?) is at depth (.+?)\. find gauge pressure and force on a (.+?) horizontal surface; use g\s*=\s*(.+)$",
c,
{
let rho = q!(c, 1, "kg/m³", Positive);
let h = q!(c, 2, "m", Nonnegative);
let a = q!(c, 3, "m²", Positive);
let g = q!(c, 4, "m/s²", Positive);
let pressure = rho * g * h;
Ok(summary(&[
(
"gauge pressure",
self.result(pressure.clone(), "Pa", Domain::Nonnegative)?,
),
(
"force",
self.result(pressure * a, "N", Domain::Nonnegative)?,
),
]))
}
);
None
}
}