use super::{AlgebraQueries, ENTRY_BITS, bounded, error, integer_queries, literal, solution};
use crate::plugins::{model_coordinates, syntax};
use crate::{Context, Error, ModelPosition, Outcome, Plugin, re};
use num_bigint::BigInt;
use num_rational::BigRational;
use num_traits::{One, Signed, ToPrimitive, Zero};
fn integer(value: i64) -> BigRational {
BigRational::from_integer(value.into())
}
fn scalar_error(error: Error) -> Error {
if matches!(
error.0.as_str(),
"invalid_integer_expression" | "non_rational_expression"
) {
super::error("invalid_expression")
} else {
error
}
}
fn role(value: BigRational) -> Result<BigRational, Error> {
if value.numer().bits().max(value.denom().bits()) > ENTRY_BITS {
return Err(error("integer_limit"));
}
Ok(value)
}
fn equation(input: &str, names: &[&str]) -> Result<(Vec<BigRational>, BigRational), Error> {
let normalized = syntax::word_operators(input).replace(" equals ", "=");
let (left, right) = normalized
.split_once('=')
.ok_or_else(|| error("invalid_expression"))?;
let (a, ac) = integer_queries::affine_value(left.trim(), names).map_err(scalar_error)?;
let (b, bc) = integer_queries::affine_value(right.trim(), names).map_err(scalar_error)?;
let coefficients = ac
.into_iter()
.zip(bc)
.map(|(a, b)| role(a - b))
.collect::<Result<_, _>>()?;
Ok((coefficients, role(b - a)?))
}
fn solve(equations: &[&str], names: &[&str]) -> Result<Vec<BigRational>, Error> {
let rows = equations
.iter()
.map(|input| equation(input, names))
.collect::<Result<Vec<_>, _>>()?;
let (matrix, rhs) = rows.into_iter().unzip();
solution(matrix, rhs)
}
fn report(fields: &[(&str, BigRational)]) -> Result<String, Error> {
let fields = fields
.iter()
.map(|(name, value)| literal(value, false).map(|value| format!("{name}|{value}")))
.collect::<Result<Vec<_>, _>>()?;
let output = format!("algebra_summary({})", fields.join(";"));
if output.len() > 4096 {
return Err(error("integer_limit"));
}
Ok(output)
}
fn exact_system_report(fields: &[(&str, BigRational)]) -> Result<String, Error> {
let fields = fields
.iter()
.map(|(name, value)| literal(value, false).map(|value| format!("{name}|{value}")))
.collect::<Result<Vec<_>, _>>()?;
report_limit(format!("algebra_exact_system({})", fields.join(";")))
}
fn report_limit(output: String) -> Result<String, Error> {
if output.len() > 4096 {
Err(error("integer_limit"))
} else {
Ok(output)
}
}
fn integer_solutions(names: [&str; 2], pairs: &[(BigInt, BigInt)]) -> Result<String, Error> {
let values = if pairs.is_empty() {
"none".into()
} else {
pairs
.iter()
.map(|(a, b)| format!("{a},{b}"))
.collect::<Vec<_>>()
.join(";")
};
report_limit(format!(
"algebra_solutions({},{}|{values})",
names[0], names[1]
))
}
fn solutions_in_bounds(
names: [&str; 2],
coefficients: &[BigRational],
rhs: &BigRational,
bounds: [(BigInt, BigInt); 2],
) -> Result<String, Error> {
for (lower, upper) in &bounds {
role(BigRational::from_integer(lower.clone()))?;
role(BigRational::from_integer(upper.clone()))?;
if upper < lower {
return Err(error("invalid_interval"));
}
}
let [(first_lower, first_upper), (second_lower, second_upper)] = bounds;
let span = (&first_upper - &first_lower)
.to_u64()
.filter(|span| *span < 100_000)
.ok_or_else(|| error("integer_limit"))?;
let mut pairs = Vec::new();
for index in 0..=span {
let first = &first_lower + BigInt::from(index);
let residual =
bounded(rhs - bounded(&coefficients[0] * BigRational::from_integer(first.clone()))?)?;
if coefficients[1].is_zero() {
if residual.is_zero() {
let remaining = 256 - pairs.len();
let second_span = (&second_upper - &second_lower)
.to_usize()
.filter(|span| *span < remaining)
.ok_or_else(|| error("integer_limit"))?;
for second in 0..=second_span {
pairs.push((first.clone(), &second_lower + BigInt::from(second)));
}
}
} else {
let second = bounded(residual / &coefficients[1])?;
if second.is_integer()
&& second >= BigRational::from_integer(second_lower.clone())
&& second <= BigRational::from_integer(second_upper.clone())
{
pairs.push((first, second.to_integer()));
if pairs.len() > 256 {
return Err(error("integer_limit"));
}
}
}
}
integer_solutions(names, &pairs)
}
fn matrix_report(engine: &AlgebraQueries, input: &str, context: &Context) -> Result<String, Error> {
let matrix = engine.matrix(input, context)?;
let size = matrix.len();
if size != matrix[0].len() {
return Err(error("invalid_matrix"));
}
let reduced = super::eliminate(matrix.clone(), size)?;
if reduced.pivots.len() != size {
return Err(error("singular_matrix"));
}
let mut inverse = vec![vec![BigRational::zero(); size]; size];
for column in 0..size {
let mut basis = vec![BigRational::zero(); size];
basis[column] = BigRational::one();
for (row, value) in solution(matrix.clone(), basis)?.into_iter().enumerate() {
inverse[row][column] = value;
}
}
let rows = inverse
.into_iter()
.map(|row| {
format!(
"[{}]",
row.into_iter()
.map(|value| value.to_string())
.collect::<Vec<_>>()
.join(", ")
)
})
.collect::<Vec<_>>()
.join(", ");
report_limit(format!(
"determinant: {}; inverse: [{rows}]",
reduced.determinant
))
}
fn exact_square_root(value: &BigRational) -> Option<BigRational> {
let numerator = value.numer().sqrt();
let denominator = value.denom().sqrt();
(&numerator * &numerator == *value.numer() && &denominator * &denominator == *value.denom())
.then(|| BigRational::new(numerator, denominator))
}
fn quadratic_result(
variable: &str,
terms: [BigRational; 3],
real_only: bool,
multiplicity: bool,
) -> Result<String, Error> {
let [c, b, a] = terms;
if a.is_zero() {
if b.is_zero() {
return report_limit(if c.is_zero() {
format!("all values of {variable}")
} else {
"no solutions".into()
});
}
return report_limit(format!("{variable} = {}", bounded(-c / b)?));
}
let discriminant = bounded(bounded(&b * &b)? - bounded(integer(4) * &a * &c)?)?;
let center = bounded(-b / (integer(2) * &a))?;
if discriminant.is_zero() {
return report_limit(if multiplicity {
format!("{variable} = {center}, {center}")
} else {
format!("{variable} = {center}")
});
}
let imaginary = discriminant.is_negative();
if imaginary && real_only {
return Ok("no real solutions".into());
}
let radicand = bounded(discriminant.abs() / bounded(integer(4) * &a * &a)?)?;
if let Some(magnitude) = exact_square_root(&radicand) {
if imaginary {
let part = if magnitude.is_one() {
"i".into()
} else if magnitude.is_integer() {
format!("{magnitude}i")
} else {
format!("({magnitude})i")
};
return report_limit(if center.is_zero() {
format!("{variable} = ± {part}")
} else {
format!("{variable} = {center} ± {part}")
});
}
let lower = bounded(¢er - &magnitude)?;
let upper = bounded(center + magnitude)?;
return report_limit(format!("{variable} = {lower}, {upper}"));
}
let radical = if radicand.is_integer() {
format!("√{radicand}")
} else {
format!("√({radicand})")
};
let part = if imaginary {
format!("i{radical}")
} else {
radical
};
report_limit(if center.is_zero() {
format!("{variable} = ± {part}")
} else {
format!("{variable} = {center} ± {part}")
})
}
fn absolute_affine_result(
variable: &str,
constant: BigRational,
slope: BigRational,
target: BigRational,
) -> Result<String, Error> {
if target.is_negative() {
return Ok("no solutions".into());
}
if slope.is_zero() {
return report_limit(if constant.abs() == target {
format!("all values of {variable}")
} else {
"no solutions".into()
});
}
let mut roots = [
bounded((-&target - &constant) / &slope)?,
bounded((target - constant) / slope)?,
];
roots.sort();
report_limit(if roots[0] == roots[1] {
format!("{variable} = {}", roots[0])
} else {
format!("{variable} = {}, {}", roots[0], roots[1])
})
}
fn absolute_piecewise_result(
variable: &str,
constant: BigRational,
coefficients: Vec<BigRational>,
bars: Vec<(BigRational, BigRational)>,
) -> Result<String, Error> {
let mut breaks = bars
.iter()
.filter(|(_, slope)| !slope.is_zero())
.map(|(constant, slope)| role(-constant / slope))
.collect::<Result<Vec<_>, _>>()?;
breaks.sort();
breaks.dedup();
let residual = |x: &BigRational| -> Result<BigRational, Error> {
let mut value = role(&constant + &coefficients[0] * x)?;
for (weight, (offset, slope)) in coefficients[1..].iter().zip(&bars) {
value = role(value + weight * (offset + slope * x).abs())?;
}
Ok(value)
};
let mut intervals: Vec<(Option<BigRational>, Option<BigRational>)> = Vec::new();
let mut points = Vec::new();
for i in 0..=breaks.len() {
let left = i.checked_sub(1).map(|j| &breaks[j]);
let right = breaks.get(i);
let sample = match (left, right) {
(Some(left), Some(right)) => role((left + right) / integer(2))?,
(Some(left), None) => role(left + integer(1))?,
(None, Some(right)) => role(right - integer(1))?,
(None, None) => BigRational::zero(),
};
let mut offset = constant.clone();
let mut slope = coefficients[0].clone();
for (weight, (term_offset, term_slope)) in coefficients[1..].iter().zip(&bars) {
let sign = if term_offset + term_slope * &sample < BigRational::zero() {
-weight
} else {
weight.clone()
};
offset = role(offset + &sign * term_offset)?;
slope = role(slope + sign * term_slope)?;
}
if slope.is_zero() {
if offset.is_zero() {
intervals.push((left.cloned(), right.cloned()));
}
} else {
let root = role(-offset / slope)?;
if left.is_none_or(|bound| root > *bound) && right.is_none_or(|bound| root < *bound) {
points.push(root);
}
}
}
for point in &breaks {
if residual(point)?.is_zero() {
points.push(point.clone());
}
}
let mut merged: Vec<(Option<BigRational>, Option<BigRational>)> = Vec::new();
for (left, right) in intervals {
if let Some(previous) = merged.last_mut()
&& previous.1 == left
{
previous.1 = right;
continue;
}
merged.push((left, right));
}
if merged.len() == 1 && merged[0].0.is_none() && merged[0].1.is_none() {
return report_limit(format!("all values of {variable}"));
}
points.sort();
points.dedup();
points.retain(|point| {
!merged.iter().any(|(left, right)| {
left.as_ref().is_none_or(|bound| point >= bound)
&& right.as_ref().is_none_or(|bound| point <= bound)
})
});
if merged.is_empty() {
return report_limit(if points.is_empty() {
"no solutions".into()
} else {
format!(
"{variable} = {}",
points
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(", ")
)
});
}
let mut pieces: Vec<(Option<BigRational>, String)> = merged
.iter()
.map(|(left, right)| {
let text = match (left, right) {
(None, Some(right)) => format!("(-∞, {right}]"),
(Some(left), None) => format!("[{left}, ∞)"),
(Some(left), Some(right)) => format!("[{left}, {right}]"),
(None, None) => unreachable!(),
};
(left.clone(), text)
})
.collect();
pieces.extend(
points
.into_iter()
.map(|point| (Some(point.clone()), format!("{{{point}}}"))),
);
pieces.sort_by(|a, b| a.0.cmp(&b.0));
report_limit(format!(
"{variable} ∈ {}",
pieces
.into_iter()
.map(|(_, text)| text)
.collect::<Vec<_>>()
.join(" ∪ ")
))
}
fn absolute_piecewise(input: &str) -> Result<String, Error> {
if input.len() > 4096 {
return Err(error("integer_limit"));
}
let (original_left, original_right) = input
.split_once('=')
.ok_or_else(|| error("invalid_expression"))?;
if original_right.contains('=') {
return Err(error("invalid_expression"));
}
let variable = integer_queries::quadratic_variable(&format!(
"{} + {}",
original_left.replace('|', ""),
original_right.replace('|', "")
))
.map_err(scalar_error)?;
let mut normalized = String::new();
let mut interiors = Vec::new();
let mut remaining = input;
let placeholders = ('a'..='z')
.filter(|candidate| !input.contains(*candidate) && variable != candidate.to_string())
.take(7)
.collect::<Vec<_>>();
while let Some(start) = remaining.find('|') {
normalized.push_str(&remaining[..start]);
let tail = &remaining[start + 1..];
let end = tail.find('|').ok_or_else(|| error("invalid_expression"))?;
let inside = tail[..end].trim();
if inside.is_empty() || interiors.len() >= placeholders.len() {
return Err(error("invalid_expression"));
}
interiors.push(inside.to_owned());
normalized.push(placeholders[interiors.len() - 1]);
remaining = &tail[end + 1..];
}
if interiors.is_empty() {
return Err(error("invalid_expression"));
}
normalized.push_str(remaining);
let (left, right) = normalized
.split_once('=')
.ok_or_else(|| error("invalid_expression"))?;
if right.contains('=') {
return Err(error("invalid_expression"));
}
let mut names = vec![variable.clone()];
names.extend(placeholders[..interiors.len()].iter().map(char::to_string));
let names = names.iter().map(String::as_str).collect::<Vec<_>>();
let (left_constant, left_coefficients) =
integer_queries::affine_value(left.trim(), &names).map_err(scalar_error)?;
let (right_constant, right_coefficients) =
integer_queries::affine_value(right.trim(), &names).map_err(scalar_error)?;
let constant = role(left_constant - right_constant)?;
let coefficients = left_coefficients
.into_iter()
.zip(right_coefficients)
.map(|(left, right)| role(left - right))
.collect::<Result<Vec<_>, _>>()?;
let bars = interiors
.into_iter()
.map(|inside| {
let (constant, coefficients) =
integer_queries::affine_value(&inside, &[&variable]).map_err(scalar_error)?;
Ok((role(constant)?, role(coefficients[0].clone())?))
})
.collect::<Result<Vec<_>, Error>>()?;
absolute_piecewise_result(&variable, constant, coefficients, bars)
}
const PIECEWISE_DIGITS: &[u8; 16] = b"ghijklmnopqrstuv";
fn encode_piecewise(input: &str) -> String {
input
.bytes()
.flat_map(|byte| {
[
PIECEWISE_DIGITS[(byte >> 4) as usize] as char,
PIECEWISE_DIGITS[(byte & 15) as usize] as char,
]
})
.collect()
}
fn decode_piecewise(input: &str) -> Result<String, Error> {
if input.is_empty() || !input.is_ascii() || !input.len().is_multiple_of(2) {
return Err(error("invalid_expression"));
}
let bytes = input
.as_bytes()
.as_chunks::<2>()
.0
.iter()
.map(|pair| {
let nibble = |digit: u8| {
PIECEWISE_DIGITS
.iter()
.position(|candidate| *candidate == digit)
.ok_or_else(|| error("invalid_expression"))
};
Ok(((nibble(pair[0])? as u8) << 4) | nibble(pair[1])? as u8)
})
.collect::<Result<Vec<_>, Error>>()?;
String::from_utf8(bytes).map_err(|_| error("invalid_expression"))
}
pub(super) fn rewrite(
engine: &AlgebraQueries,
input: &str,
context: &Context,
position: ModelPosition,
) -> Outcome {
let input = input.trim().trim_end_matches(['.', '?']);
if let Some(c) = re!(r"(?i)^using exact arithmetic, solve the system (.+?) and (.+?); report ([a-z]|determinant), ([a-z]|determinant), and ([a-z]|determinant)$").captures(input) {
return Some((|| {
let goals = [&c[3], &c[4], &c[5]];
let mut names = goals
.iter()
.copied()
.filter(|goal| !goal.eq_ignore_ascii_case("determinant"))
.collect::<Vec<_>>();
if position != ModelPosition::Standalone
|| names.len() != 2
|| names[0].eq_ignore_ascii_case(names[1])
{
return Err(error("invalid_expression"));
}
names.sort();
let first = equation(&c[1].replace('−', "-"), &names)?;
let second = equation(&c[2].replace('−', "-"), &names)?;
let determinant = bounded(&first.0[0] * &second.0[1] - &first.0[1] * &second.0[0])?;
let values = solution(vec![first.0, second.0], vec![first.1, second.1])?;
let fields = goals
.iter()
.map(|goal| {
if goal.eq_ignore_ascii_case("determinant") {
Ok((*goal, determinant.clone()))
} else {
let at = names.iter().position(|name| *name == *goal)
.ok_or_else(|| error("invalid_expression"))?;
Ok((*goal, values[at].clone()))
}
})
.collect::<Result<Vec<_>, Error>>()?;
exact_system_report(&fields)
})());
}
if let Some(c) =
re!(r"(?i)^solve (.+?) over the reals and report every solution in increasing order$")
.captures(input)
&& c[1].contains('|')
{
return Some((|| {
if position != ModelPosition::Standalone {
return Err(error("invalid_expression"));
}
if c[1].len() > 4096 {
return Err(error("integer_limit"));
}
report_limit(format!("algebra_piecewise({})", encode_piecewise(&c[1])))
})());
}
if let Some(c) = re!(r"(?i)^find (?:every|all) real solutions? of \|([^|]+)\|\s*=\s*(.+?) and list them in increasing order$").captures(input) {
return Some((|| {
if position != ModelPosition::Standalone {
return Err(error("invalid_expression"));
}
if input.len() > 4096 {
return Err(error("integer_limit"));
}
let inside = c[1].replace('−', "-");
let variable = integer_queries::quadratic_variable(&inside).map_err(scalar_error)?;
let (constant, coefficients) =
integer_queries::affine_value(&inside, &[&variable]).map_err(scalar_error)?;
let (numerator, denominator) =
integer_queries::ratio_value(&c[2]).map_err(scalar_error)?;
let target = role(BigRational::new(numerator, denominator))?;
let constant = role(constant)?;
let slope = role(coefficients[0].clone())?;
report_limit(format!(
"algebra_absolute({variable}|{constant}|{slope}|{target})"
))
})());
}
if let Some(c) = re!(r"(?i)^(?:compute|calculate|find) the determinant and inverse of the matrix with rows (.+), reporting both$").captures(input) {
return Some((|| {
if position != ModelPosition::Standalone {
return Err(error("invalid_expression"));
}
let normalized_rows = re!(r"(?i),?\s+and\s+").replace_all(&c[1], ", ");
let rows = super::structural_arguments(&normalized_rows)?;
let rows = rows
.into_iter()
.map(|row| {
row.strip_prefix('(')
.and_then(|row| row.strip_suffix(')'))
.map(|row| format!("[{row}]"))
.ok_or_else(|| error("invalid_matrix"))
})
.collect::<Result<Vec<_>, _>>()?;
let matrix = format!("[{}]", rows.join(","));
if matrix.len() > 4096 {
return Err(error("integer_limit"));
}
engine.matrix(&matrix, context)?;
report_limit(format!("algebra_matrix_report({matrix})"))
})());
}
if let Some(c) = re!(r"(?i)^given (.+?) and (.+?), calculate ([a-z])([a-z]) and ([a-z]) squared plus ([a-z]) squared$").captures(input) {
return Some((|| {
let names = [&c[3], &c[4]];
if names[0] == names[1] || !names.contains(&&c[5]) || !names.contains(&&c[6]) || c[5] == c[6] {
return Err(error("invalid_expression"));
}
let values = solve(&[&c[1], &c[2]], &names)?;
let bindings = [(names[0], values[0].clone()), (names[1], values[1].clone())];
let product_label = format!("{}{}", &c[3], &c[4]);
let sum_label = format!("{}^2+{}^2", &c[5], &c[6]);
let at = |goal: &str| integer_queries::ratio_with_bindings(goal, &bindings)
.map_err(scalar_error)
.and_then(bounded);
report(&[
(&product_label, at(&format!("{}*{}", &c[3], &c[4]))?),
(&sum_label, at(&sum_label)?),
])
})());
}
if let Some(result) = super::declared_formula::rewrite(engine, input, context, position) {
return Some(result);
}
if let Some(c) =
re!(r"(?i)^solve (.+?), then (?:calculate|evaluate) ([a-z]) (squared|cubed)(.*)$")
.captures(input)
.filter(|_| !input.contains(" for that value of "))
{
return Some((|| {
let values = solve(&[&c[1]], &[&c[2]])?;
let power = if c[3].eq_ignore_ascii_case("squared") {
2
} else {
3
};
let goal = format!("{}^{power}{}", &c[2], syntax::word_operators(&c[4]));
let result = integer_queries::ratio_with_bindings(&goal, &[(&c[2], values[0].clone())])
.map_err(scalar_error)?;
literal(&bounded(result)?, position == ModelPosition::Standalone)
})());
}
let pattern = re!(
r"(?i)^solve (.+?), then (?:calculate|evaluate) ((?:[-+]?(?:\d+(?:\.\d*)?|\.\d+)\s*\*?\s*)?([a-z])(?:[+\-*/^()\s].*)?)$"
);
if let Some(c) = pattern
.captures(input)
.filter(|_| !input.contains(" for that value of "))
{
return Some((|| {
let values = solve(&[&c[1]], &[&c[3]])?;
let goal = syntax::word_operators(&c[2]);
let result = integer_queries::ratio_with_bindings(&goal, &[(&c[3], values[0].clone())])
.map_err(scalar_error)?;
literal(&bounded(result)?, position == ModelPosition::Standalone)
})());
}
let pattern =
re!(r"(?i)^if (.+?) and (.+?), find ([a-z])\^2\s*\+\s*([a-z])\^2 and ([a-z])([a-z])$");
if let Some(c) = pattern.captures(input) {
return Some((|| {
let names = [&c[3], &c[4]];
if !names.contains(&&c[5]) || !names.contains(&&c[6]) {
return Err(error("invalid_expression"));
}
let values = solve(&[&c[1], &c[2]], &names)?;
let bindings = [(names[0], values[0].clone()), (names[1], values[1].clone())];
let sum_label = format!("{}^2+{}^2", names[0], names[1]);
let product_label = format!("{}{}", &c[5], &c[6]);
let product = format!("{}*{}", &c[5], &c[6]);
let at = |goal: &str| {
integer_queries::ratio_with_bindings(goal, &bindings)
.map_err(scalar_error)
.and_then(bounded)
};
report(&[
(&sum_label, at(&sum_label)?),
(&product_label, at(&product)?),
])
})());
}
let pattern = re!(
r"(?i)^find all integer solutions to (.+?) with ([a-z]) and ([a-z]) both between (.+?) and (.+?) inclusive$"
);
if let Some(c) = pattern.captures(input) {
return Some((|| {
let names = [&c[2], &c[3]];
if names[0] == names[1] {
return Err(error("invalid_expression"));
}
let (coefficients, rhs) = equation(&c[1], &names)?;
let lower = integer_queries::value(&c[4]).map_err(scalar_error)?;
let upper = integer_queries::value(&c[5]).map_err(scalar_error)?;
solutions_in_bounds(
names,
&coefficients,
&rhs,
[(lower.clone(), upper.clone()), (lower, upper)],
)
})());
}
let intervals = input.replace('−', "-");
if let Some(c) = re!(r"(?i)^find all integer solutions to (.+?) with (.+?)\s*≤\s*([a-z])\s*≤\s*(.+?) and (.+?)\s*≤\s*([a-z])\s*≤\s*(.+)$").captures(&intervals) {
return Some((|| {
let names = [&c[3], &c[6]];
if names[0] == names[1] {
return Err(error("invalid_expression"));
}
let (coefficients, rhs) = equation(&c[1], &names)?;
let bound = |input: &str| integer_queries::value(input).map_err(scalar_error);
solutions_in_bounds(
names,
&coefficients,
&rhs,
[(bound(&c[2])?, bound(&c[4])?), (bound(&c[5])?, bound(&c[7])?)],
)
})());
}
let pattern = re!(
r"(?i)^a rectangle has perimeter (.+?) and length (.+?) greater than twice its width; find its area$"
);
if let Some(c) = pattern.captures(input) {
return Some((|| {
let perimeter = model_coordinates::read(&c[1], "cm", &engine.engine, context)?;
let difference = model_coordinates::read(&c[2], "cm", &engine.engine, context)?;
let values = solution(
vec![vec![integer(2), integer(2)], vec![integer(1), integer(-2)]],
vec![role(perimeter.value)?, role(difference.value)?],
)?;
if values.iter().any(|value| !value.is_positive()) {
return Err(error("invalid_physical_quantity"));
}
let area = bounded(&values[0] * &values[1])?;
let coefficient = if perimeter.authored && difference.authored {
literal(&area, false)?
} else {
let value = area
.to_f64()
.filter(|value| value.is_finite())
.ok_or_else(|| error("numeric_overflow"))?;
if !area.is_zero() && value == 0.0 {
return Err(error("numeric_underflow"));
}
format!("real({value:e})")
};
Ok(format!("({coefficient}) * (1 cm)^2 in cm^2"))
})());
}
let pattern = re!(
r"(?i)^the sum of three consecutive odd integers is (.+?); state the integers and their product$"
);
if let Some(c) = pattern.captures(input) {
return Some((|| {
let total = engine.scalar(&c[1], context)?;
let first = solution(
vec![vec![integer(3)]],
vec![bounded(total - BigRational::from_integer(6.into()))?],
)?
.remove(0);
if !first.is_integer() {
return Err(error("integer_required"));
}
if (&first.to_integer() % 2u32).is_zero() {
return Err(error("invalid_integer_argument"));
}
let second = bounded(&first + BigRational::from_integer(2.into()))?;
let third = bounded(&first + BigRational::from_integer(4.into()))?;
let product = bounded(bounded(&first * &second)? * &third)?;
report(&[
("first integer", first),
("second integer", second),
("third integer", third),
("product", product),
])
})());
}
let pattern = re!(
r"(?i)^a function is defined by ([a-z])\(([a-z])\)\s*=\s*(.+?); find ([a-z])\((.+?)\) and the difference ([a-z])\((.+?)\)\s*-\s*([a-z])\((.+)\)$"
);
if let Some(c) = pattern.captures(input) {
return Some((|| {
if [4, 6, 8].iter().any(|index| c[*index] != c[1]) {
return Err(error("invalid_expression"));
}
let at = |argument: &str| {
let value = engine.scalar(argument, context)?;
integer_queries::ratio_with_bindings(&c[3], &[(&c[2], value)])
.map_err(scalar_error)
.and_then(bounded)
};
let value = at(&c[5])?;
let difference = bounded(at(&c[7])? - at(&c[9])?)?;
let first_label = format!("{}({})", &c[1], c[5].trim());
let second_label = format!("{}({})-{}({})", &c[1], c[7].trim(), &c[1], c[9].trim());
report(&[(&first_label, value), (&second_label, difference)])
})());
}
if let Some(c) =
re!(r"(?i)^solve (.+?), then evaluate (.+?) for that value of ([a-z])$").captures(input)
{
return Some((|| {
let values = solve(&[&c[1]], &[&c[3]])?;
let result = integer_queries::ratio_with_bindings(&c[2], &[(&c[3], values[0].clone())])
.map_err(scalar_error)?;
literal(&bounded(result)?, position == ModelPosition::Standalone)
})());
}
if let Some(c) =
re!(r"(?i)^if (.+?) and (.+?), find ([a-z]), ([a-z]), and their product$").captures(input)
{
return Some((|| {
let values = solve(&[&c[1], &c[2]], &[&c[3], &c[4]])?;
let product = bounded(&values[0] * &values[1])?;
report(&[
(&c[3], values[0].clone()),
(&c[4], values[1].clone()),
("product", product),
])
})());
}
let pattern = re!(
r"(?i)^find the slope and y-intercept of the line through \(([^,]+), ([^,]+)\) and \(([^,]+), ([^,]+)\)$"
);
if let Some(c) = pattern.captures(input) {
return Some((|| {
let x1 = engine.scalar(&c[1], context)?;
let y1 = engine.scalar(&c[2], context)?;
let x2 = engine.scalar(&c[3], context)?;
let y2 = engine.scalar(&c[4], context)?;
let delta = bounded(x2 - &x1)?;
if delta.is_zero() {
return Err(error("division_by_zero"));
}
let slope = bounded((y2 - &y1) / delta)?;
let intercept = bounded(y1 - &slope * x1)?;
report(&[("slope", slope), ("y-intercept", intercept)])
})());
}
if let Some(c) = re!(
r"(?i)^a number is (.+?)% of another number, and their sum is (.+?); find both numbers$"
)
.captures(input)
{
return Some((|| {
let proportion =
bounded(engine.scalar(&c[1], context)? / BigRational::from_integer(100.into()))?;
let total = engine.scalar(&c[2], context)?;
let values = solution(
vec![
vec![BigRational::one(), -proportion],
vec![BigRational::one(), BigRational::one()],
],
vec![BigRational::zero(), total],
)?;
report(&[
("first number", values[0].clone()),
("other number", values[1].clone()),
])
})());
}
let pattern = re!(
r"(?i)^if ([a-z]) varies inversely with ([a-z]) and ([a-z])\s*=\s*(.+?) when ([a-z])\s*=\s*(.+?), find ([a-z]) when ([a-z])\s*=\s*(.+)$"
);
if let Some(c) = pattern.captures(input) {
return Some((|| {
if c[1] == c[2] || c[1] != c[3] || c[2] != c[5] || c[1] != c[7] || c[2] != c[8] {
return Err(error("invalid_expression"));
}
let y = engine.scalar(&c[4], context)?;
let old_x = engine.scalar(&c[6], context)?;
let new_x = engine.scalar(&c[9], context)?;
if old_x.is_zero() || new_x.is_zero() {
return Err(error("division_by_zero"));
}
let result = bounded(bounded(y * old_x)? / new_x)?;
literal(&result, position == ModelPosition::Standalone)
})());
}
let (body, mut domain, mut multiplicity) = if let Some(c) =
re!(r"(?i)^find all (real|complex) solutions to (.+)$").captures(input)
{
(c[2].to_owned(), Some(c[1].to_ascii_lowercase()), false)
} else if let Some(c) =
re!(r"(?i)^find (?:(both|all) )?(real|complex) roots of (.+)$").captures(input)
{
(
c[3].to_owned(),
Some(c[2].to_ascii_lowercase()),
c.get(1)
.is_some_and(|word| word.as_str().eq_ignore_ascii_case("both")),
)
} else if let Some(c) = re!(r"(?i)^what are the (real|complex) roots of (.+)$").captures(input)
{
(c[2].to_owned(), Some(c[1].to_ascii_lowercase()), false)
} else if let Some(c) = re!(r"(?i)^find (?:all )?(?:the )?roots of (.+)$").captures(input) {
(c[1].to_owned(), None, false)
} else {
if integer_queries::finite_solution_request(input) {
return None;
}
let c = re!(r"(?i)^solve (.+)$").captures(input)?;
if !c[1].contains('=') {
return None;
}
(c[1].to_owned(), None, false)
};
Some((|| {
if position != ModelPosition::Standalone {
return Err(error("invalid_expression"));
}
if input.len() > 4096 {
return Err(error("integer_limit"));
}
let mut body = body.as_str();
let mut specified_variable: Option<String> = None;
for _ in 0..3 {
if let Some(c) = re!(r"(?i);\s*give both roots$").find(body) {
if multiplicity {
return Err(error("invalid_expression"));
}
multiplicity = true;
body = body[..c.start()].trim_end();
} else if let Some(c) = re!(r"(?i),\s*including multiplicity$").find(body) {
if multiplicity {
return Err(error("invalid_expression"));
}
multiplicity = true;
body = body[..c.start()].trim_end();
} else if let Some(c) = re!(r"(?i)\s+over the (real|complex) numbers$").captures(body) {
let requested = c[1].to_ascii_lowercase();
if domain.is_some() {
return Err(error("invalid_expression"));
}
domain = Some(requested);
body = body[..c.get(0).unwrap().start()].trim_end();
} else if let Some(c) = re!(r"(?i)\s+for ([a-z])$").captures(body) {
if specified_variable.is_some() {
return Err(error("invalid_expression"));
}
specified_variable = Some(c[1].to_owned());
body = body[..c.get(0).unwrap().start()].trim_end();
} else {
break;
}
}
let body = body.replace('−', "-").replace('²', "^2");
let (left, right) = body
.split_once('=')
.ok_or_else(|| error("invalid_expression"))?;
let expression = format!("({left})-({right})");
let variable = integer_queries::quadratic_variable(&expression).map_err(scalar_error)?;
if specified_variable
.as_deref()
.is_some_and(|name| name != variable.as_str())
{
return Err(error("invalid_expression"));
}
let [constant, linear, quadratic] =
integer_queries::quadratic_value(&expression, &variable).map_err(scalar_error)?;
let (constant, linear, quadratic) = (role(constant)?, role(linear)?, role(quadratic)?);
if multiplicity && quadratic.is_zero() {
return Err(error("invalid_expression"));
}
report_limit(format!(
"algebra_quadratic({variable}|{}|{}|{constant}|{linear}|{quadratic})",
domain.as_deref().unwrap_or("complex"),
u8::from(multiplicity)
))
})())
}
pub(super) fn evaluate(engine: &AlgebraQueries, input: &str, context: &Context) -> Outcome {
if let Some(result) = super::declared_formula::evaluate(engine, input, context) {
return Some(result);
}
if let Some(inner) = input
.strip_prefix("algebra_piecewise(")
.and_then(|value| value.strip_suffix(')'))
{
return Some(decode_piecewise(inner).and_then(|input| absolute_piecewise(&input)));
}
if let Some(inner) = input
.strip_prefix("algebra_absolute(")
.and_then(|input| input.strip_suffix(')'))
{
return Some((|| {
if input.len() > 4096 {
return Err(error("integer_limit"));
}
let fields = inner.split('|').collect::<Vec<_>>();
let [variable, constant, slope, target] = fields.as_slice() else {
return Err(error("invalid_expression"));
};
if variable.len() != 1 || !variable.as_bytes()[0].is_ascii_alphabetic() {
return Err(error("invalid_expression"));
}
let coefficient = |s: &str| {
let (n, d) = integer_queries::ratio_value(s).map_err(scalar_error)?;
role(BigRational::new(n, d))
};
absolute_affine_result(
variable,
coefficient(constant)?,
coefficient(slope)?,
coefficient(target)?,
)
})());
}
if let Some(matrix) = input
.strip_prefix("algebra_matrix_report(")
.and_then(|input| input.strip_suffix(')'))
{
return Some(matrix_report(engine, matrix, context));
}
if let Some(inner) = input
.strip_prefix("algebra_quadratic(")
.and_then(|s| s.strip_suffix(')'))
{
return Some((|| {
if input.len() > 4096 {
return Err(error("integer_limit"));
}
let fields = inner.split('|').collect::<Vec<_>>();
let [variable, domain, multiplicity, c, b, a] = fields.as_slice() else {
return Err(error("invalid_expression"));
};
if variable.len() != 1 || !variable.as_bytes()[0].is_ascii_alphabetic() {
return Err(error("invalid_expression"));
}
if !matches!(*domain, "real" | "complex") {
return Err(error("invalid_expression"));
}
if !matches!(*multiplicity, "0" | "1") {
return Err(error("invalid_expression"));
}
let coefficient = |s: &str| {
let (n, d) = integer_queries::ratio_value(s).map_err(scalar_error)?;
role(BigRational::new(n, d))
};
quadratic_result(
variable,
[coefficient(c)?, coefficient(b)?, coefficient(a)?],
*domain == "real",
*multiplicity == "1",
)
})());
}
if let Some(inner) = input
.strip_prefix("algebra_solutions(")
.and_then(|s| s.strip_suffix(')'))
{
return Some((|| {
let (names, values) = inner
.split_once('|')
.ok_or_else(|| error("invalid_expression"))?;
let names = names.split(',').collect::<Vec<_>>();
if names.len() != 2
|| names[0] == names[1]
|| names
.iter()
.any(|name| name.len() != 1 || !name.as_bytes()[0].is_ascii_alphabetic())
{
return Err(error("invalid_expression"));
}
if values == "none" {
return Ok("solutions: none".into());
}
let mut pairs = Vec::new();
for pair in values.split(';') {
let values = pair
.split(',')
.map(integer_queries::value)
.collect::<Result<Vec<_>, _>>()?;
if values.len() != 2 {
return Err(error("invalid_expression"));
}
pairs.push(format!(
"({}, {})",
integer_queries::decimal(&values[0]),
integer_queries::decimal(&values[1])
));
}
if pairs.len() > 256 {
return Err(error("integer_limit"));
}
report_limit(format!("solutions: {}", pairs.join("; ")))
})());
}
if let Some(inner) = input
.strip_prefix("algebra_exact_system(")
.and_then(|value| value.strip_suffix(')'))
{
return Some((|| {
if input.len() > 4096 {
return Err(error("integer_limit"));
}
let fields = inner
.split(';')
.map(|field| {
let (name, value) = field
.split_once('|')
.ok_or_else(|| error("invalid_expression"))?;
Ok((name, engine.scalar(value, context)?))
})
.collect::<Result<Vec<_>, Error>>()?;
if fields.len() != 3
|| fields
.iter()
.filter(|(name, _)| *name == "determinant")
.count()
!= 1
|| fields
.iter()
.filter(|(name, _)| *name != "determinant")
.any(|(name, _)| name.len() != 1 || !name.as_bytes()[0].is_ascii_alphabetic())
|| fields[0].0 == fields[1].0
|| fields[0].0 == fields[2].0
|| fields[1].0 == fields[2].0
{
return Err(error("invalid_expression"));
}
Ok(fields
.into_iter()
.map(|(name, value)| {
let display = if value.is_integer() {
integer_queries::decimal(value.numer())
} else {
format!(
"{}/{}",
integer_queries::decimal(value.numer()),
integer_queries::decimal(value.denom())
)
};
format!("{name}: {display}")
})
.collect::<Vec<_>>()
.join("; "))
})());
}
let inner = input.strip_prefix("algebra_summary(")?.strip_suffix(')')?;
Some((|| {
let fields = inner
.split(';')
.map(|field| {
let (name, value) = field
.split_once('|')
.ok_or_else(|| error("invalid_expression"))?;
Ok((name, engine.scalar(value, context)?))
})
.collect::<Result<Vec<_>, Error>>()?;
let labels = fields.iter().map(|(name, _)| *name).collect::<Vec<_>>();
let sequence = labels
== [
"first integer",
"second integer",
"third integer",
"product",
];
let function = labels.len() == 2
&& re!(r"^[a-zA-Z]\([^|;]+\)$").is_match(labels[0])
&& re!(r"^[a-zA-Z]\([^|;]+\)-[a-zA-Z]\([^|;]+\)$").is_match(labels[1]);
let derived = labels.len() == 2
&& re!(r"^[a-zA-Z]\^2\+[a-zA-Z]\^2$").is_match(labels[0])
&& labels[1].len() == 2
&& labels[1].bytes().all(|letter| letter.is_ascii_alphabetic());
let derived_reverse = labels.len() == 2
&& labels[0].len() == 2
&& labels[0].bytes().all(|letter| letter.is_ascii_alphabetic())
&& re!(r"^[a-zA-Z]\^2\+[a-zA-Z]\^2$").is_match(labels[1]);
let valid = sequence
|| function
|| derived
|| derived_reverse
|| labels == ["slope", "y-intercept"]
|| labels == ["first number", "other number"]
|| labels.len() == 3
&& labels[2] == "determinant"
&& labels[0] != labels[1]
&& labels[..2]
.iter()
.all(|name| name.len() == 1 && name.as_bytes()[0].is_ascii_alphabetic())
|| labels.len() == 3
&& labels[2] == "product"
&& labels[0] != labels[1]
&& labels[..2]
.iter()
.all(|name| name.len() == 1 && name.as_bytes()[0].is_ascii_alphabetic());
if !valid {
return Err(error("invalid_expression"));
}
if sequence {
if fields[..3].iter().any(|(_, value)| !value.is_integer()) {
return Err(error("integer_required"));
}
if (&fields[0].1.to_integer() % 2u32).is_zero()
|| fields[1].1 != &fields[0].1 + BigRational::from_integer(2.into())
|| fields[2].1 != &fields[1].1 + BigRational::from_integer(2.into())
|| fields[3].1 != &fields[0].1 * &fields[1].1 * &fields[2].1
{
return Err(error("invalid_integer_argument"));
}
return Ok(format!(
"integers: {}; product: {}",
fields[..3]
.iter()
.map(|(_, value)| integer_queries::decimal(&value.to_integer()))
.collect::<Vec<_>>()
.join(", "),
integer_queries::decimal(&fields[3].1.to_integer())
));
}
let mut output = Vec::new();
for (name, value) in fields {
let expression = literal(&value, true)?;
let display = if value.is_integer() {
integer_queries::IntegerQueries.evaluate(&expression, context)
} else {
engine.engine.evaluate(&expression, context)
}
.ok_or_else(|| error("invalid_expression"))??;
output.push(format!("{name}: {display}"));
}
Ok(output.join("; "))
})())
}