use super::{Geometry, norm};
use crate::{Context, Error, Outcome, Plugin, re};
use num_rational::BigRational;
use num_traits::{Signed, ToPrimitive, Zero};
impl Geometry {
fn validate_field(
&self,
label: &str,
target: &str,
expression: &str,
context: &Context,
) -> Result<(), Error> {
if matches!(label, "components" | "unit vector" | "cross product") {
if !target.is_empty() {
return Err(Error("invalid_expression".into()));
}
let components = self.vector(expression, context)?;
if label == "unit vector" {
for component in &components {
self.engine.quantity_value(component, "1", context)?;
}
}
return Ok(());
}
let reference = match label {
"width"
| "length"
| "perimeter"
| "perimeter before cutting"
| "boundary length"
| "other leg"
| "circumference" => Some("m"),
"area"
| "remaining area"
| "surface area"
| "lateral surface area"
| "standard uncertainty" => Some("m²"),
"volume" | "one-rod volume" | "total volume" => Some("m³"),
"cylinder mass" | "cuboid mass" | "one-rod mass" | "total mass" => Some("kg"),
"direction angle" => Some("degrees"),
"magnitude" | "dot product" => None,
_ => return Err(Error("invalid_expression".into())),
};
if let Some(reference) = reference {
self.engine.quantity_value(expression, reference, context)?;
self.engine
.quantity_value(&format!("1 {target}"), reference, context)?;
}
if !target.is_empty() {
self.target(target)?;
self.engine.quantity_value(expression, target, context)?;
} else {
self.engine
.quantity_order(expression, expression, context)?;
}
Ok(())
}
fn display_field(
&self,
label: &str,
target: &str,
expression: &str,
context: &Context,
) -> Result<String, Error> {
if matches!(label, "components" | "unit vector" | "cross product") {
let components = self.vector(expression, context)?;
let values = components
.iter()
.map(|component| {
self.engine
.evaluate(component, context)
.ok_or_else(|| Error("invalid_expression".into()))?
})
.collect::<Result<Vec<_>, _>>()?;
return Ok(format!("({})", values.join(", ")));
}
let formula = if target.is_empty() {
expression.to_owned()
} else {
format!("({expression}) in {target}")
};
self.engine
.evaluate(&formula, context)
.ok_or_else(|| Error("invalid_expression".into()))?
}
pub(super) fn summary(
&self,
fields: &[(&str, &str, String)],
context: &Context,
) -> Result<String, Error> {
for (label, target, expression) in fields {
self.validate_field(label, target, expression, context)?;
}
let result = format!(
"geometry_summary({})",
fields
.iter()
.map(|(label, target, expression)| format!("{label}|{target}|{expression}"))
.collect::<Vec<_>>()
.join(";")
);
if result.len() > 4096 {
return Err(Error("invalid_expression".into()));
}
Ok(result)
}
pub(super) fn evaluate_report(&self, input: &str, context: &Context) -> Outcome {
let inner = input.strip_prefix("geometry_summary(")?.strip_suffix(')')?;
Some((|| {
if input.len() > 4096 {
return Err(Error("invalid_expression".into()));
}
let fields = inner.split(';').collect::<Vec<_>>();
if !(2..=3).contains(&fields.len())
&& !(fields.len() == 4
&& fields
.iter()
.zip([
"one-rod volume|",
"one-rod mass|",
"total volume|",
"total mass|",
])
.all(|(field, label)| field.starts_with(label)))
{
return Err(Error("invalid_expression".into()));
}
let mut validated = Vec::new();
for field in fields {
let parts = field.split('|').collect::<Vec<_>>();
if parts.len() != 3 {
return Err(Error("invalid_expression".into()));
}
self.validate_field(parts[0], parts[1], parts[2], context)?;
validated.push(parts);
}
let mut output = Vec::new();
for parts in validated {
let value = self.display_field(parts[0], parts[1], parts[2], context)?;
output.push(format!("{}: {value}", parts[0]));
}
Ok(output.join("; "))
})())
}
pub(super) fn length_target(&self, input: &str) -> String {
input
.char_indices()
.find_map(|(at, _)| {
let unit = self.engine.units.unit(input[at..].trim())?;
(unit.dimension == [1, 0, 0, 0, 0, 0, 0, 0]).then_some(unit.symbol)
})
.unwrap_or_else(|| "m".into())
}
fn read_length_coordinate(
&self,
role: &str,
context: &Context,
) -> Result<super::super::model_coordinates::Coordinate, Error> {
let error = match super::super::model_coordinates::read(role, "m", &self.engine, context) {
Ok(coordinate) => return Ok(coordinate),
Err(error) => error,
};
if error.0 != "incompatible_units" {
return Err(error);
}
for (at, _) in role.char_indices().skip(1) {
let coefficient = role[..at].trim();
let unit = role[at..].trim();
if self.engine.units.unit(unit).is_some()
&& self
.engine
.quantity_value(&format!("1 {unit}"), "m", context)
.is_ok()
&& self
.engine
.quantity_value(coefficient, "1", context)
.is_ok()
{
return super::super::model_coordinates::read(
&format!("({coefficient}) {unit}"),
"m",
&self.engine,
context,
);
}
}
Err(error)
}
fn typed_length_coordinate(
coordinate: &super::super::model_coordinates::Coordinate,
) -> Result<String, Error> {
if coordinate.authored {
Ok(format!(
"(rational({},{}) m)",
coordinate.value.numer(),
coordinate.value.denom()
))
} else {
let value = coordinate
.value
.to_f64()
.filter(|value| value.is_finite())
.ok_or_else(|| Error("numeric_overflow".into()))?;
if value == 0.0 && !coordinate.value.is_zero() {
return Err(Error("numeric_underflow".into()));
}
Ok(format!("(real({value:e}) m)"))
}
}
fn mass_in_kg(
&self,
mass: &BigRational,
authored: bool,
context: &Context,
) -> Result<String, Error> {
self.mass_in_unit(mass, authored, "kg", context)
}
fn mass_in_unit(
&self,
mass: &BigRational,
authored: bool,
target: &str,
context: &Context,
) -> Result<String, Error> {
let scalar = if authored {
format!("rational({},{})", mass.numer(), mass.denom())
} else {
let value = mass
.to_f64()
.filter(|value| value.is_finite())
.ok_or_else(|| Error("numeric_overflow".into()))?;
if value == 0.0 && !mass.is_zero() {
return Err(Error("numeric_underflow".into()));
}
format!("real({value:e})")
};
self.output(format!("({scalar} kg)"), target, "kg", context)
}
fn mass_expression(mass: &BigRational, authored: bool) -> Result<String, Error> {
Self::quantity_expression(mass, "kg", authored)
}
fn quantity_expression(
value: &BigRational,
unit: &str,
authored: bool,
) -> Result<String, Error> {
let value = super::super::model_coordinates::bounded(value.clone())?;
let coefficient = if authored {
format!("rational({},{})", value.numer(), value.denom())
} else {
let float = value
.to_f64()
.filter(|value| value.is_finite())
.ok_or_else(|| Error("numeric_overflow".into()))?;
if float == 0.0 && !value.is_zero() {
return Err(Error("numeric_underflow".into()));
}
format!("real({float:e})")
};
Ok(format!("({coefficient} {unit})"))
}
fn supplied_component_mass(
&self,
shape: &str,
density: &str,
pi: &super::super::model_coordinates::Coordinate,
context: &Context,
) -> Result<(String, &'static str, BigRational, bool), Error> {
let bounded = super::super::model_coordinates::bounded;
let density =
super::super::model_coordinates::read(density, "kg/m³", &self.engine, context)?;
if !density.value.is_positive() {
return Err(Error("invalid_geometry".into()));
}
if let Some(c) =
re!(r"(?i)^a ([a-z]+) cylinder of radius (.+?) and height (.+?)$").captures(shape)
{
let radius = self.read_length_coordinate(&c[2], context)?;
let height = self.read_length_coordinate(&c[3], context)?;
if radius.value.is_negative() || height.value.is_negative() {
return Err(Error("invalid_geometry".into()));
}
let mass = bounded(
&pi.value * &radius.value * &radius.value * &height.value * &density.value,
)?;
return Ok((
c[1].to_ascii_lowercase(),
"cylinder mass",
mass,
radius.authored && height.authored && density.authored,
));
}
if let Some(c) =
re!(r"(?i)^a ([a-z]+) cuboid (.+?) (?:by|×|x) (.+?) (?:by|×|x) (.+?)$").captures(shape)
{
let lengths = [2, 3, 4]
.map(|at| self.read_length_coordinate(&c[at], context))
.into_iter()
.collect::<Result<Vec<_>, _>>()?;
if lengths.iter().any(|length| length.value.is_negative()) {
return Err(Error("invalid_geometry".into()));
}
let mass = bounded(
lengths
.iter()
.fold(density.value.clone(), |value, length| value * &length.value),
)?;
return Ok((
c[1].to_ascii_lowercase(),
"cuboid mass",
mass,
lengths.iter().all(|length| length.authored) && density.authored,
));
}
Err(Error("invalid_expression".into()))
}
fn spherical_shell_mass(
&self,
outer: &super::super::model_coordinates::Coordinate,
inner: &super::super::model_coordinates::Coordinate,
density: &super::super::model_coordinates::Coordinate,
pi: &super::super::model_coordinates::Coordinate,
context: &Context,
) -> Result<String, Error> {
if outer.value.is_negative()
|| inner.value.is_negative()
|| inner.value > outer.value
|| !density.value.is_positive()
|| !pi.authored
|| !pi.value.is_positive()
{
return Err(Error("invalid_geometry".into()));
}
let volume_difference =
&outer.value * &outer.value * &outer.value - &inner.value * &inner.value * &inner.value;
let mass = super::super::model_coordinates::bounded(
BigRational::from_integer(4.into()) * &pi.value * &density.value * volume_difference
/ BigRational::from_integer(3.into()),
)?;
self.mass_in_kg(
&mass,
outer.authored && inner.authored && density.authored,
context,
)
}
pub(super) fn lower_report(
&self,
input: &str,
context: &Context,
) -> Result<Option<String>, Error> {
if input.len() > 4096 {
return Ok(None);
}
if let Some(result) = self.lower_supplied(input, context)? {
return Ok(Some(result));
}
if let Some(c) = re!(r"(?i)^for (.+?) identical [a-z]+ rods? each (.+?) long with circular diameter (.+?), density (.+?) and (?:pi|π)\s*=\s*(.+?), (?:report|give) one-rod volume and mass and total volume and mass using consistent SI units$").captures(input) {
let count = super::super::integer_queries::value(&c[1])?;
if !count.is_positive() {
return Err(Error("invalid_geometry".into()));
}
let length = self.read_length_coordinate(&c[2], context)?;
let diameter = self.read_length_coordinate(&c[3], context)?;
let density = super::super::model_coordinates::read(&c[4], "kg/m³", &self.engine, context)?;
let pi = super::super::model_coordinates::read(&c[5], "1", &self.engine, context)?;
if length.value.is_negative() || diameter.value.is_negative()
|| !density.value.is_positive() || !pi.value.is_positive() || !pi.authored
{
return Err(Error("invalid_geometry".into()));
}
let bounded = super::super::model_coordinates::bounded;
let radius = bounded(&diameter.value / BigRational::from_integer(2.into()))?;
let volume = bounded(bounded(&pi.value * &radius)? * bounded(&radius * &length.value)?)?;
let mass = bounded(&volume * &density.value)?;
let count = BigRational::from_integer(count);
let total_volume = bounded(&volume * &count)?;
let total_mass = bounded(&mass * count)?;
let authored = length.authored && diameter.authored && density.authored;
return self.summary(&[
("one-rod volume", "m³", Self::quantity_expression(&volume, "m³", authored)?),
("one-rod mass", "kg", Self::mass_expression(&mass, authored)?),
("total volume", "m³", Self::quantity_expression(&total_volume, "m³", authored)?),
("total mass", "kg", Self::mass_expression(&total_mass, authored)?),
], context).map(Some);
}
if let Some(c) = re!(r"(?i)^a composite block has (.+?) joined without overlap to (.+?)\. with (?:π|pi)\s*=\s*(.+?), ([a-z]+) density (.+?), and ([a-z]+) density (.+?), calculate both masses and their sum$").captures(input) {
let pi = super::super::model_coordinates::read(&c[3], "1", &self.engine, context)?;
if !pi.authored || !pi.value.is_positive() || c[4].eq_ignore_ascii_case(&c[6]) {
return Err(Error("invalid_geometry".into()));
}
let material = |shape: &str| re!(r"(?i)^a ([a-z]+) (?:cylinder|cuboid)\b").captures(shape).map(|m| m[1].to_ascii_lowercase()).ok_or_else(|| Error("invalid_expression".into()));
let first_name = material(&c[1])?;
let second_name = material(&c[2])?;
if first_name == second_name || ![&first_name, &second_name].iter().all(|name| name.eq_ignore_ascii_case(&c[4]) || name.eq_ignore_ascii_case(&c[6])) {
return Err(Error("invalid_geometry".into()));
}
let first_density = if first_name.eq_ignore_ascii_case(&c[4]) { &c[5] } else { &c[7] };
let second_density = if second_name.eq_ignore_ascii_case(&c[4]) { &c[5] } else { &c[7] };
let first = self.supplied_component_mass(&c[1], first_density, &pi, context)?;
let second = self.supplied_component_mass(&c[2], second_density, &pi, context)?;
if first.1 == second.1 {
return Err(Error("invalid_geometry".into()));
}
let mass = super::super::model_coordinates::bounded(&first.2 + &second.2)?;
let supplied_mass_unit = |density: &str| re!(r"(?i)\b(kg|g)\s*/").captures(density).map(|m| m[1].to_ascii_lowercase());
let target = match (supplied_mass_unit(&c[5]), supplied_mass_unit(&c[7])) {
(Some(a), Some(b)) if a == b => a,
_ => "kg".into(),
};
return self.summary(&[
(first.1, &target, Self::mass_expression(&first.2, pi.authored && first.3)?),
(second.1, &target, Self::mass_expression(&second.2, pi.authored && second.3)?),
("total mass", &target, Self::mass_expression(&mass, pi.authored && first.3 && second.3)?),
], context).map(Some);
}
if let Some(c) = re!(r"(?i)^compute the mass of a non-overlapping composite made from a cuboid (.+?) (?:×|x) (.+?) (?:×|x) (.+?) and a cylinder of radius (.+?) and height (.+?); use (?:pi|π)\s*=\s*(.+?), cuboid density (.+?), cylinder density (.+?), and return (grams|g|kilograms|kg)$").captures(input) {
let a = self.read_length_coordinate(&c[1], context)?;
let b = self.read_length_coordinate(&c[2], context)?;
let depth = self.read_length_coordinate(&c[3], context)?;
let radius = self.read_length_coordinate(&c[4], context)?;
let height = self.read_length_coordinate(&c[5], context)?;
let pi = super::super::model_coordinates::read(&c[6], "1", &self.engine, context)?;
let cuboid_density = super::super::model_coordinates::read(&c[7], "kg/m³", &self.engine, context)?;
let cylinder_density = super::super::model_coordinates::read(&c[8], "kg/m³", &self.engine, context)?;
if [&a, &b, &depth, &radius, &height]
.into_iter()
.any(|length| length.value.is_negative())
|| !pi.authored || !pi.value.is_positive()
|| !cuboid_density.value.is_positive()
|| !cylinder_density.value.is_positive()
{
return Err(Error("invalid_geometry".into()));
}
let bounded = super::super::model_coordinates::bounded;
let cuboid_mass = bounded(&a.value * &b.value * &depth.value * &cuboid_density.value)?;
let cylinder_mass = bounded(&pi.value * &radius.value * &radius.value * &height.value * &cylinder_density.value)?;
let mass = bounded(cuboid_mass + cylinder_mass)?;
let authored = a.authored && b.authored && depth.authored && radius.authored
&& height.authored && pi.authored && cuboid_density.authored && cylinder_density.authored;
return self.mass_in_unit(&mass, authored, &c[9], context).map(Some);
}
if let Some(c) = re!(r"(?i)^find the mass in (?:kilograms|kg) of a hollow sphere with outer diameter (.+?) and uniform wall thickness (.+?), given density (.+?) and (?:pi|π)\s*=\s*(.+?); use the difference of outer and inner spherical volumes and convert (.+?) to (.+?)$").captures(input) {
let diameter = self.read_length_coordinate(&c[1], context)?;
let wall = self.read_length_coordinate(&c[2], context)?;
let density = super::super::model_coordinates::read(&c[3], "kg/m³", &self.engine, context)?;
let pi = super::super::model_coordinates::read(&c[4], "1", &self.engine, context)?;
let stated_left = super::super::model_coordinates::read(&c[5], "kg", &self.engine, context)?;
let stated_right = super::super::model_coordinates::read(&c[6], "kg", &self.engine, context)?;
if stated_left.value != stated_right.value || diameter.value.is_negative()
|| wall.value.is_negative() {
return Err(Error("invalid_geometry".into()));
}
let outer = super::super::model_coordinates::Coordinate {
value: super::super::model_coordinates::bounded(
&diameter.value / BigRational::from_integer(2.into()),
)?,
authored: diameter.authored,
};
if wall.value > outer.value {
return Err(Error("invalid_geometry".into()));
}
let inner = super::super::model_coordinates::Coordinate {
value: super::super::model_coordinates::bounded(&outer.value - &wall.value)?,
authored: diameter.authored && wall.authored,
};
return self.spherical_shell_mass(&outer, &inner, &density, &pi, context).map(Some);
}
if let Some(c) = re!(r"(?i)^a spherical shell has outer radius (.+?) and inner radius (.+?), with uniform density (.+?)\. use (?:pi|π)\s*=\s*(.+?) and (?:calculate|find) its mass, treating it as the volume difference of two spheres$").captures(input) {
let outer = self.read_length_coordinate(&c[1], context)?;
let inner = self.read_length_coordinate(&c[2], context)?;
let density = super::super::model_coordinates::read(&c[3], "kg/m³", &self.engine, context)?;
let pi = super::super::model_coordinates::read(&c[4], "1", &self.engine, context)?;
return self.spherical_shell_mass(&outer, &inner, &density, &pi, context).map(Some);
}
if let Some(c) = re!(r"(?i)^a plate consists of a (.+?) by (.+?) rectangle plus a semicircle attached along one (.+?) edge; semicircle radius is (.+?), total uniform thickness is (.+?), density is (.+?), and (?:pi|π)\s*=\s*(.+?)\. (?:find|calculate) the total mass, with the pieces non-overlapping$").captures(input) {
let width = self.read_length_coordinate(&c[1], context)?;
let height = self.read_length_coordinate(&c[2], context)?;
let edge = self.read_length_coordinate(&c[3], context)?;
let radius = self.read_length_coordinate(&c[4], context)?;
let thickness = self.read_length_coordinate(&c[5], context)?;
let density = super::super::model_coordinates::read(&c[6], "kg/m³", &self.engine, context)?;
let pi = super::super::model_coordinates::read(&c[7], "1", &self.engine, context)?;
if !width.value.is_positive() || !height.value.is_positive()
|| radius.value.is_negative() || thickness.value.is_negative()
|| !density.value.is_positive() || !pi.authored || !pi.value.is_positive()
|| (edge.value != width.value && edge.value != height.value)
|| edge.value != &radius.value * BigRational::from_integer(2.into()) {
return Err(Error("invalid_geometry".into()));
}
let area = &width.value * &height.value
+ &pi.value * &radius.value * &radius.value / BigRational::from_integer(2.into());
let mass = super::super::model_coordinates::bounded(area * &thickness.value * &density.value)?;
return self.mass_in_kg(
&mass,
width.authored && height.authored && edge.authored && radius.authored
&& thickness.authored && density.authored,
context,
).map(Some);
}
if let Some(c) = re!(r"(?i)^a (.+?) by (.+?) plate has a radius-(.+?) circular hole centered inside it\. the rectangle is [a-z]+, density (.+?), and the hole is air\. with plate thickness (.+?) and (?:π|pi)\s*=\s*(.+?), find the plate mass$").captures(input) {
let width = self.read_length_coordinate(&c[1], context)?;
let height = self.read_length_coordinate(&c[2], context)?;
let radius = self.read_length_coordinate(&c[3], context)?;
let density = super::super::model_coordinates::read(&c[4], "g/cm³", &self.engine, context)?;
let thickness = self.read_length_coordinate(&c[5], context)?;
let pi = super::super::model_coordinates::read(&c[6], "1", &self.engine, context)?;
if !width.value.is_positive() || !height.value.is_positive()
|| radius.value.is_negative() || thickness.value.is_negative()
|| !density.value.is_positive() || !pi.authored || !pi.value.is_positive()
|| &radius.value * num_rational::BigRational::from_integer(2.into()) > width.value
|| &radius.value * num_rational::BigRational::from_integer(2.into()) > height.value {
return Err(Error("invalid_geometry".into()));
}
let bounded = super::super::model_coordinates::bounded;
let area = bounded(
bounded(&width.value * &height.value)?
- bounded(&pi.value * &radius.value * &radius.value)?,
)?;
if area.is_negative() {
return Err(Error("invalid_geometry".into()));
}
let volume = bounded(area * &thickness.value)?;
let cubic_centimeters = super::super::model_coordinates::read("1 m³", "cm³", &self.engine, context)?.value;
let mass = bounded(bounded(volume * cubic_centimeters)? * &density.value)?;
let scalar = if width.authored && height.authored && radius.authored
&& density.authored && thickness.authored {
format!("rational({},{})", mass.numer(), mass.denom())
} else {
let value = mass.to_f64().filter(|value| value.is_finite())
.ok_or_else(|| Error("numeric_overflow".into()))?;
if value == 0.0 && !mass.is_zero() {
return Err(Error("numeric_underflow".into()));
}
format!("real({value:e})")
};
return self.output(format!("({scalar} g)"), "g", "g", context).map(Some);
}
let boundary = re!(r"(?i)^a rectangle (.+?) by (.+?) has a circular hole of radius (.+?); with (?:π|pi)\s*=\s*(.+?), report (remaining area and boundary length including the hole circumference|boundary length including the hole circumference and remaining area)$").captures(input);
let material_boundary = boundary.is_some();
let boundary_first = boundary
.as_ref()
.is_some_and(|c| c[5].to_ascii_lowercase().starts_with("boundary"));
if let Some(c) = boundary.or_else(|| re!(r"(?i)^a rectangular plate measures (.+?) by (.+?) and has a circular hole of radius (.+?) centered inside it\. using (?:π|pi)\s*=\s*(.+?), report remaining area and the plate perimeter before cutting$").captures(input)) {
let width = self.read_length_coordinate(&c[1], context)?;
let height = self.read_length_coordinate(&c[2], context)?;
let radius = self.read_length_coordinate(&c[3], context)?;
let pi = super::super::model_coordinates::read(&c[4], "1", &self.engine, context)?;
if !width.value.is_positive() || !height.value.is_positive()
|| radius.value.is_negative() || !pi.authored || !pi.value.is_positive()
|| &radius.value * num_rational::BigRational::from_integer(2.into()) > width.value
|| &radius.value * num_rational::BigRational::from_integer(2.into()) > height.value {
return Err(Error("invalid_geometry".into()));
}
let (area, perimeter) = if width.authored && height.authored && radius.authored {
let bounded = super::super::model_coordinates::bounded;
let plate = bounded(&width.value * &height.value)?;
let hole = bounded(&pi.value * &radius.value * &radius.value)?;
let area = bounded(plate - hole)?;
let two = num_rational::BigRational::from_integer(2.into());
let outer = bounded((&width.value + &height.value) * &two)?;
let perimeter = if material_boundary {
let hole_boundary = bounded(&pi.value * &radius.value * &two)?;
bounded(outer + hole_boundary)?
} else {
outer
};
(
format!("rational({},{}) m²", area.numer(), area.denom()),
format!("rational({},{}) m", perimeter.numer(), perimeter.denom()),
)
} else {
let width = Self::typed_length_coordinate(&width)?;
let height = Self::typed_length_coordinate(&height)?;
let radius = Self::typed_length_coordinate(&radius)?;
let pi = format!("rational({},{})", pi.value.numer(), pi.value.denom());
(
format!("{width}*{height}-{pi}*square({radius})"),
if material_boundary {
format!("2*({width}+{height})+2*{pi}*{radius}")
} else {
format!("2*({width}+{height})")
},
)
};
let unit = self.length_target(&c[1]);
let area_unit = format!("{unit}²");
let mut fields = [
("remaining area", area_unit.as_str(), area),
(if material_boundary { "boundary length" } else { "perimeter before cutting" }, unit.as_str(), perimeter),
];
if boundary_first {
fields.swap(0, 1);
}
return self.summary(&fields, context).map(Some);
}
if let Some(c) = re!(r"(?i)^a cylinder has radius (.+?) and height (.+?); using (?:π|pi)\s*=\s*(.+?), compute volume and lateral surface area$").captures(input) {
let radius = self.read_length_coordinate(&c[1], context)?;
let height = self.read_length_coordinate(&c[2], context)?;
let pi = super::super::model_coordinates::read(&c[3], "1", &self.engine, context)?;
if radius.value.is_negative() || height.value.is_negative() || !pi.authored
|| !pi.value.is_positive() {
return Err(Error("invalid_geometry".into()));
}
let (volume, lateral) = if radius.authored && height.authored {
let bounded = super::super::model_coordinates::bounded;
let side = bounded(&pi.value * &radius.value * &height.value)?;
let volume = bounded(&side * &radius.value)?;
let lateral = bounded(side * num_rational::BigRational::from_integer(2.into()))?;
(
format!("rational({},{}) m³", volume.numer(), volume.denom()),
format!("rational({},{}) m²", lateral.numer(), lateral.denom()),
)
} else {
let radius = Self::typed_length_coordinate(&radius)?;
let height = Self::typed_length_coordinate(&height)?;
let pi = format!("rational({},{})", pi.value.numer(), pi.value.denom());
(
format!("{pi}*square({radius})*{height}"),
format!("2*{pi}*{radius}*{height}"),
)
};
return self.summary(&[
("volume", "m³", volume),
("lateral surface area", "m²", lateral),
], context).map(Some);
}
if let Some(c) = re!(r"(?i)^a rectangular plate measures (.+?) by (.+?), each dimension with independent standard uncertainty (.+?); using first-order uncertainty propagation, report area and propagated standard uncertainty$").captures(input) {
let unit = self.length_target(&c[1]);
let read = |role: &str| {
super::super::model_coordinates::read(role, &unit, &self.engine, context)
};
let a = read(&c[1])?;
let b = read(&c[2])?;
let uncertainty = read(&c[3])?;
if !a.value.is_positive() || !b.value.is_positive() || uncertainty.value.is_negative() {
return Err(Error("invalid_geometry".into()));
}
let bounded = super::super::model_coordinates::bounded;
let first = bounded(&b.value * &uncertainty.value)?;
let second = bounded(&a.value * &uncertainty.value)?;
let variance = bounded(bounded(&first * &first)? + bounded(&second * &second)?)?;
let root = super::super::model_coordinates::computed_root(variance, |expression| {
self.engine.quantity_value(expression, "1", context)
})?;
let value = root.to_f64().filter(|value| value.is_finite())
.ok_or_else(|| Error("numeric_overflow".into()))?;
if !root.is_zero() && value == 0.0 {
return Err(Error("numeric_underflow".into()));
}
let target = format!("{unit}²");
return self.summary(&[
("area", &target, format!("({})*({})", &c[1], &c[2])),
("standard uncertainty", &target, format!("real({value:e}) {target}")),
], context).map(Some);
}
if let Some(c) = re!(r"(?i)^a box measures (.+?) by (.+?) by (.+?); find its (volume|total surface area) in (.+?) and its (volume|total surface area) in (.+)$").captures(input) {
if c[4].eq_ignore_ascii_case(&c[6]) {
return Err(Error("invalid_expression".into()));
}
let a = self.length(&c[1], context)?.0;
let b = self.length(&c[2], context)?.0;
let height = self.length(&c[3], context)?.0;
let volume = format!("{a}*{b}*{height}");
let area = format!("2*({a}*{b}+{a}*{height}+{b}*{height})");
let fields = [(&c[4], &c[5]), (&c[6], &c[7])].map(|(goal, target)| {
if goal.eq_ignore_ascii_case("volume") {
("volume", target, volume.clone())
} else {
("surface area", target, area.clone())
}
});
return self.summary(&fields, context).map(Some);
}
if let Some(c) = re!(
r"(?i)^a rectangle has perimeter (.+?) and length (.+?); what are its width and area$"
)
.captures(input)
{
let perimeter =
super::super::model_coordinates::read(&c[1], "m", &self.engine, context)?;
let length = super::super::model_coordinates::read(&c[2], "m", &self.engine, context)?;
let width = super::super::model_coordinates::bounded(
&perimeter.value / num_rational::BigRational::from_integer(2.into())
- &length.value,
)?;
if !length.value.is_positive() || !width.is_positive() {
return Err(Error("invalid_geometry".into()));
}
let target = self.length_target(&c[2]);
let width = format!("({})/2-({})", &c[1], &c[2]);
return self
.summary(
&[
("width", &target, width.clone()),
(
"area",
&format!("{target}²"),
format!("({})*({width})", &c[2]),
),
],
context,
)
.map(Some);
}
if let Some(c) = re!(r"(?i)^a circular [a-z '-]+ has radius (.+?); using (?:pi|π) exactly as (.+?), what are its area and circumference$").captures(input) {
let (radius, value) = self.length(&c[1], context)?;
if value == 0.0 {
return Err(Error("invalid_geometry".into()));
}
let pi = self.constant(&c[2], context)?;
let target = self.length_target(&c[1]);
return self.summary(&[("area", &format!("{target}²"), format!("{pi}*square({radius})")),
("circumference", &target, format!("2*{pi}*{radius}"))], context).map(Some);
}
if let Some(c) = re!(r"(?i)^what is the vector sum of (\(.+\)) and (\(.+\)), and what is the magnitude of the resulting vector$").captures(input) {
let a = self.vector(&c[1], context)?;
let b = self.vector(&c[2], context)?;
if a.len() != b.len() {
return Err(Error("invalid_vector".into()));
}
self.engine.quantity_order(&a[0], &b[0], context)?;
let components = a.iter().zip(&b).map(|(a,b)| format!("({a}+{b})")).collect::<Vec<_>>();
return self.summary(&[("components", "", format!("({})", components.join(","))),
("magnitude", "", norm(&components))], context).map(Some);
}
if let Some(c) = re!(
r"(?i)^a displacement vector is (\(.+\)) (.+?); give its magnitude and its unit vector$"
)
.captures(input)
{
self.target(&c[2])?;
self.engine
.quantity_value(&format!("1 {}", &c[2]), "m", context)?;
let scalars = self.vector(&c[1], context)?;
for scalar in &scalars {
self.engine.quantity_value(scalar, "1", context)?;
}
let mut zero = true;
for scalar in &scalars {
zero &= super::super::model_coordinates::read(scalar, "1", &self.engine, context)?
.value
.is_zero();
}
if zero {
return Err(Error("division_by_zero".into()));
}
let components = scalars
.iter()
.map(|part| format!("({part}* (1 {}))", &c[2]))
.collect::<Vec<_>>();
let magnitude = norm(&components);
let direction = components
.iter()
.map(|part| format!("{part}/({magnitude})"))
.collect::<Vec<_>>();
return self
.summary(
&[
("magnitude", "m", magnitude),
("unit vector", "", format!("({})", direction.join(","))),
],
context,
)
.map(Some);
}
Ok(None)
}
}