use super::{Goal, Model, Request, invalid, physical};
use crate::{Error, Outcome, re};
use num_rational::BigRational;
use num_traits::{Signed, ToPrimitive, Zero};
type Goals = Vec<(Goal, Option<String>)>;
fn toward(direction: &str) -> bool {
matches!(
direction.to_ascii_lowercase().as_str(),
"approaches" | "toward" | "moves toward"
)
}
fn log_positive_ratio(numerator: &BigRational, denominator: &BigRational) -> Result<f64, Error> {
let change = (numerator - denominator) / denominator;
if let Some(delta) = change.to_f64()
&& delta.is_finite()
&& delta.abs() <= 0.5
{
return Ok(delta.ln_1p());
}
let logarithm = |value: &BigRational| {
value
.to_f64()
.filter(|number| number.is_finite() && *number > 0.0)
.map(f64::ln)
.ok_or_else(|| Error("numeric_underflow".into()))
};
Ok(logarithm(numerator)? - logarithm(denominator)?)
}
impl Request<'_> {
pub(super) fn wording(&self, input: &str) -> Outcome {
self.lower_wording(input).transpose()
}
fn goals(input: &str) -> Result<Goals, Error> {
let input =
re!(r"(?i)\s+using f_heard\s*=\s*f_source\s*\*\s*\(v\s*\+\s*vo\)/\(v\s*-\s*vs\)$")
.replace(input, "");
if re!(r"(?i)^(?:find|calculate) (?:the )?(?:heard|observed|received) frequency$")
.is_match(&input)
|| re!(r"(?i)^evaluate (?:the )?(?:doppler expression|heard frequency)$")
.is_match(&input)
{
return Ok(vec![(Goal::Frequency, None)]);
}
if re!(r"(?i)^(?:find|calculate) (?:the )?(?:heard|observed) frequency and period$")
.is_match(&input)
{
return Ok(vec![(Goal::Frequency, None), (Goal::Period, None)]);
}
if re!(r"(?i)^(?:infer|find|calculate) (?:the )?source frequency$").is_match(&input) {
return Ok(vec![(Goal::Source, None)]);
}
if let Some(c) = re!(r"(?i)^(?:find|calculate) (?:the )?(?:heard|observed) frequency, then calculate (?:the )?period in (.+)$").captures(&input) {
return Ok(vec![(Goal::Frequency, None), (Goal::Period, Some(c[1].to_string()))]);
}
Err(invalid())
}
fn medium_request(input: &str) -> Result<(String, Goals), Error> {
let input =
re!(r"(?i) and use positive velocities toward each other to ").replace(input, ", ");
let c = re!(r"(?i)^(?:with (?:stationary-medium speed |medium speed )?v\s*=\s*|with sound speed |(?:take|set|use) (?:medium speed )?v\s*=\s*|(?:stationary-medium|medium) speed (?:is\s+|v\s*=\s*))(.+?)(?: in still air)?(?:[;,]\s*|\s+and\s+)((?:find|calculate|infer|evaluate) .+)$")
.captures(&input).ok_or_else(invalid)?;
Ok((c[1].to_string(), Self::goals(&c[2])?))
}
fn motion_answer(
&self,
f: &str,
vo: &str,
vs: &str,
tail: &str,
heard: bool,
) -> Result<String, Error> {
let (v, goals) = Self::medium_request(tail)?;
let model = self.model(f, &v, vo, vs)?;
self.motion_answer_in(model, &goals, heard)
}
fn motion_answer_in(&self, model: Model, goals: &Goals, heard: bool) -> Result<String, Error> {
if heard && (goals.len() != 1 || !matches!(goals[0].0, Goal::Source))
|| !heard && goals.iter().any(|(goal, _)| matches!(goal, Goal::Source))
{
return Err(invalid());
}
self.answer_in(model, goals)
}
fn motion_clauses(&self, input: &str) -> Result<Option<String>, Error> {
macro_rules! family {
($pattern:literal, $c:ident, $answer:expr) => {
if let Some($c) = re!($pattern).captures(input) {
return Ok(Some($answer?));
}
};
}
family!(
r"(?i)^a (.+?) (?:sound )?source (approaches|recedes from|moves toward|moves away from) a stationary (?:listener|observer) at (.+?); (.+)$",
c,
self.motion_answer(
&c[1],
"0 m/s",
&self.speed(&c[3], toward(&c[2]))?,
&c[4],
false
)
);
family!(
r"(?i)^a source emits (.+?) and moves (toward|away from) a stationary (?:observer|listener) at (.+?); (.+)$",
c,
self.motion_answer(
&c[1],
"0 m/s",
&self.speed(&c[3], toward(&c[2]))?,
&c[4],
false
)
);
family!(
r"(?i)^a stationary (.+?) source is approached by an (?:observer|listener) at (.+?); (.+)$",
c,
self.motion_answer(&c[1], &self.speed(&c[2], true)?, "0 m/s", &c[3], false)
);
family!(
r"(?i)^an (?:observer|listener) moves (toward|away from) a stationary (.+?) source at (.+?); (.+)$",
c,
self.motion_answer(
&c[2],
&self.speed(&c[3], toward(&c[1]))?,
"0 m/s",
&c[4],
false
)
);
family!(
r"(?i)^a (.+?) source moves (toward|away) at (.+?) (?:while|from) (?:the|an) (?:observer|listener) (?:moves|moving) (toward|away)(?: it| from the source)? at (.+?); (.+)$",
c,
self.motion_answer(
&c[1],
&self.speed(&c[5], toward(&c[4]))?,
&self.speed(&c[3], toward(&c[2]))?,
&c[6],
false
)
);
family!(
r"(?i)^a stationary (?:observer|listener) hears (.+?) from a source moving (toward|away from) (?:them|it) at (.+?); (.+)$",
c,
self.motion_answer(
&c[1],
"0 m/s",
&self.speed(&c[3], toward(&c[2]))?,
&c[4],
true
)
);
family!(
r"(?i)^a source emits (.+?) while stationary and a stationary (?:observer|listener) is in a medium with speed v\s*=\s*(.+?); (.+)$",
c,
self.answer_in(
self.model(&c[1], &c[2], "0 m/s", "0 m/s")?,
&Self::goals(&c[3])?
)
);
if let Some(c) = re!(r"(?i)^a (.+?) source approaches an (?:observer|listener) who approaches it at (.+?); (.+)$").captures(input) {
let (v, _) = Self::medium_request(&c[3])?;
self.coordinate(&c[1], "Hz", true)?;
self.speed(&c[2], true)?;
self.coordinate(&v, "m/s", true)?;
return Err(invalid());
}
Ok(None)
}
fn lower_wording(&self, input: &str) -> Result<Option<String>, Error> {
if !re!(r"(?i)\b(?:doppler|sound|source|siren|echo)\b").is_match(input) {
return Ok(None);
}
let input = input
.replace('−', "-")
.replace("f′", "fprime")
.replace("f'", "fprime");
let input = input.split_whitespace().collect::<Vec<_>>().join(" ");
let input = input.trim().trim_end_matches(['.', '?']);
macro_rules! rule {
($pattern:literal, $c:ident, $answer:expr) => {
if let Some($c) = re!($pattern).captures(input) {
return Ok(Some($answer?));
}
};
}
rule!(
r"(?i)^a speaker emits (.+?) dB sound level\. a second independent speaker at the same location also emits (.+?) dB; what combined level results using intensity addition and dB\s*=\s*10\s*(?:\*\s*)?log10\s*\(\s*I\s*/\s*I(?:₀|0)\s*\)$",
c,
{
let first = self.coordinate(&c[1], "1", false)?;
let second = self.coordinate(&c[2], "1", false)?;
let first = first
.value
.to_f64()
.ok_or_else(|| Error("numeric_overflow".into()))?;
let second = second
.value
.to_f64()
.ok_or_else(|| Error("numeric_overflow".into()))?;
let high = first.max(second);
let low = first.min(second);
let combined = high
+ 10.0 * (10.0_f64.powf((low - high) / 10.0)).ln_1p() / std::f64::consts::LN_10;
if !combined.is_finite() {
return Err(Error("numeric_overflow".into()));
}
Ok(format!("acoustics_level(real({combined:e}))"))
}
);
rule!(
r"(?i)^a sound level is l\s*=\s*10\s*log10\s*\(\s*i\s*/\s*i(?:₀|0)\s*\) decibels, with i\s*=\s*(.+?) and supplied reference intensity i(?:₀|0)\s*=\s*(.+?)\. find l in decibels$",
c,
{
let intensity = self.coordinate(&c[1], "W/m²", true)?;
let reference = self.coordinate(&c[2], "W/m²", true)?;
let level = 10.0 * log_positive_ratio(&intensity.value, &reference.value)?
/ std::f64::consts::LN_10;
if !level.is_finite() {
return Err(Error("numeric_overflow".into()));
}
Ok(format!("acoustics_level(real({level:e}))"))
}
);
rule!(
r"(?i)^a sound source emits (.+?) dB at (.+?) in a free field; assuming spherical spreading with no absorption, what level is expected at (.+)$",
c,
{
let initial = self.coordinate(&c[1], "1", false)?;
let reference = self.coordinate(&c[2], "m", true)?;
let target = self.coordinate(&c[3], "m", true)?;
let level = initial
.value
.to_f64()
.ok_or_else(|| Error("numeric_overflow".into()))?;
let log_radius_ratio = log_positive_ratio(&reference.value, &target.value)?;
let result = level + 20.0 * log_radius_ratio / std::f64::consts::LN_10;
if !result.is_finite() {
return Err(Error("numeric_overflow".into()));
}
Ok(format!("acoustics_level(real({result:e}))"))
}
);
rule!(
r"(?i)^an echo returns after (.+?) in air; if sound speed is (.+?), calculate the reflector distance assuming the sound travels out and back$",
c,
{
let elapsed = self.coordinate(&c[1], "s", true)?;
let speed = self.coordinate(&c[2], "m/s", true)?;
self.result(
elapsed.value * speed.value / num_rational::BigRational::from_integer(2.into()),
"m",
elapsed.authored && speed.authored,
)
.map(|distance| format!("{distance} in m"))
}
);
rule!(
r"(?i)^a sound pulse travels (.+?) in air over (.+?)\. using that measured speed, how long would it take to travel (.+)$",
c,
{
let observed_distance = self.coordinate(&c[1], "m", true)?;
let observed_time = self.coordinate(&c[2], "s", true)?;
let target_distance = self.coordinate(&c[3], "m", false)?;
if target_distance.value.is_negative() {
return Err(physical());
}
self.result(
target_distance.value * observed_time.value / observed_distance.value,
"s",
observed_distance.authored
&& observed_time.authored
&& target_distance.authored,
)
}
);
rule!(
r"(?i)^a source emits (.+?) sound and approaches a stationary observer at (.+?); sound speed is (.+?) in still air, so find heard frequency$",
c,
self.answer(
self.model(&c[1], &c[3], "0 m/s", &self.speed(&c[2], true)?)?,
&[Goal::Frequency]
)
);
rule!(
r"(?i)^a source recedes at (.+?) from an observer who also moves away at (.+?); emitted frequency is (.+?) and sound speed is (.+?); calculate received frequency$",
c,
self.answer(
self.model(
&c[3],
&c[4],
&self.speed(&c[2], false)?,
&self.speed(&c[1], false)?
)?,
&[Goal::Frequency]
)
);
rule!(
r"(?i)^a siren has period (.+?) and moves toward a stationary listener at (.+?); with still-medium sound speed (.+?), calculate emitted and heard frequencies$",
c,
{
let period = self.coordinate(&c[1], "s", true)?;
let emitted = self.result(period.value.recip(), "Hz", period.authored)?;
self.answer(
self.model(&emitted, &c[3], "0 m/s", &self.speed(&c[2], true)?)?,
&[Goal::Emitted, Goal::Frequency],
)
}
);
rule!(
r"(?i)^a stationary source emits (.+?) in air where sound speed is (.+?); calculate wavelength and period$",
c,
self.answer(
self.model(&c[1], &c[2], "0 m/s", "0 m/s")?,
&[Goal::PlainWavelength, Goal::PlainPeriod]
)
);
rule!(
r"(?i)^a source approaches a stationary observer at (.+?) while emitting (.+?) in a medium with sound speed (.+?); calculate the classical doppler expression's outcome$",
c,
self.answer(
self.model(&c[2], &c[3], "0 m/s", &self.speed(&c[1], true)?)?,
&[Goal::Frequency]
)
);
rule!(
r"(?i)^a stationary source emits (.+?); an observer recedes at (.+?) in a still medium where sound speed is (.+?); find observed period$",
c,
self.answer(
self.model(&c[1], &c[3], &self.speed(&c[2], false)?, "0 m/s")?,
&[Goal::Period]
)
);
rule!(
r"(?i)^a sound wave travels (.+?) in (.+?); find speed, then calculate wavelength for frequency (.+?)$",
c,
{
let distance = self.coordinate(&c[1], "m", false)?;
let duration = self.coordinate(&c[2], "s", true)?;
if distance.value.is_negative() {
return Err(physical());
}
let speed = self.result(
distance.value / duration.value,
"m/s",
distance.authored && duration.authored,
)?;
self.answer(
self.model(&c[3], &speed, "0 m/s", "0 m/s")?,
&[Goal::Speed, Goal::PlainWavelength],
)
}
);
rule!(
r"(?i)^a stationary (.+?) siren is heard by an observer moving (toward|away) at (.+?) through still air at (.+?); (.+)$",
c,
self.motion_answer_in(
self.model(&c[1], &c[4], &self.speed(&c[3], toward(&c[2]))?, "0 m/s")?,
&Self::goals(&c[5])?,
false
)
);
rule!(
r"(?i)^a source emitting (.+?) (recedes|approaches) at (.+?) while an observer (recedes|approaches) at (.+?) in a stationary medium with sound speed (.+?); (.+)$",
c,
self.motion_answer_in(
self.model(
&c[1],
&c[6],
&self.speed(&c[5], toward(&c[4]))?,
&self.speed(&c[3], toward(&c[2]))?
)?,
&Self::goals(&c[7])?,
false
)
);
rule!(
r"(?i)^a stationary source emits a tone with period (.+?) in air where sound speed is (.+?); determine frequency and wavelength$",
c,
{
let period = self.coordinate(&c[1], "s", true)?;
let f = self.result(period.value.recip(), "Hz", period.authored)?;
self.answer(
self.model(&f, &c[2], "0 m/s", "0 m/s")?,
&[Goal::Frequency, Goal::Wavelength],
)
}
);
rule!(
r"(?i)^a source moving toward an observer at (.+?) emits (.+?) in still air with sound speed (.+?); state the doppler formula result or its physical limitation$",
c,
self.answer(
self.model(&c[2], &c[3], "0 m/s", &self.speed(&c[1], true)?)?,
&[Goal::Frequency]
)
);
rule!(
r"(?i)^sound travels at (.+?); an observer moves toward a stationary (.+?) source at (.+?); using fprime = f\(v \+ vo\)/\(v - vs\), where vo is positive toward the source and vs positive toward the observer, find observed frequency$",
c,
self.answer(
self.model(&c[2], &c[1], &self.speed(&c[3], true)?, "0 m/s")?,
&[Goal::Frequency]
)
);
rule!(
r"(?i)^a stationary observer hears a (.+?) source moving toward them at (.+?); use fprime = f\(v \+ vo\)/\(v - vs\), v = (.+?), vo positive toward source, vs positive toward observer, and calculate fprime$",
c,
self.answer(
self.model(&c[1], &c[3], "0 m/s", &self.speed(&c[2], true)?)?,
&[Goal::Frequency]
)
);
rule!(
r"(?i)^a (.+?) source and observer approach each other at (.+?) and (.+?) respectively; with sound speed (.+?) and fprime = f\(v \+ vo\)/\(v - vs\), both direction speeds positive toward the other, find the heard frequency$",
c,
self.answer(
self.model(
&c[1],
&c[4],
&self.speed(&c[3], true)?,
&self.speed(&c[2], true)?
)?,
&[Goal::Frequency]
)
);
rule!(
r"(?i)^using fprime = f\(v \+ vo\)/\(v - vs\), with vo positive toward the source and vs positive toward the observer, calculate the frequency for f = (.+?), v = (.+?), vo = (.+?), vs = (.+?)$",
c,
self.answer(self.model(&c[1], &c[2], &c[3], &c[4])?, &[Goal::Frequency])
);
rule!(
r"(?i)^a source emitting (.+?) moves away from a stationary observer at (.+?); with sound speed (.+?) and doppler model fprime = f\(v \+ vo\)/\(v - vs\), use vo positive toward source and vs positive toward observer, and find fprime$",
c,
self.answer(
self.model(&c[1], &c[3], "0 m/s", &self.speed(&c[2], false)?)?,
&[Goal::Frequency]
)
);
rule!(
r"(?i)^a (.+?) source moves toward an observer at (.+?) while the observer moves away from it at (.+?); use v = (.+?) and fprime = f\(v \+ vo\)/\(v - vs\), with vo positive toward source and vs positive toward observer$",
c,
self.answer(
self.model(
&c[1],
&c[4],
&self.speed(&c[3], false)?,
&self.speed(&c[2], true)?
)?,
&[Goal::Frequency]
)
);
rule!(
r"(?i)^an observer approaches a stationary source at (.+?) and hears (.+?); sound speed is (.+?), use fprime = f\(v \+ vo\)/\(v - vs\), vo positive toward source and vs positive toward observer, to infer source frequency$",
c,
self.answer(
self.model(&c[2], &c[3], &self.speed(&c[1], true)?, "0 m/s")?,
&[Goal::Source]
)
);
rule!(
r"(?i)^a (.+?) source approaches at (.+?) and an observer approaches at (.+?); with sound speed (.+?) and fprime = f\(v \+ vo\)/\(v - vs\), directions positive toward each other, calculate heard frequency and shift from emitted frequency$",
c,
self.answer(
self.model(
&c[1],
&c[4],
&self.speed(&c[3], true)?,
&self.speed(&c[2], true)?
)?,
&[Goal::Frequency, Goal::Shift]
)
);
rule!(
r"(?i)^a (.+?) tone comes from a source receding at (.+?) while an observer approaches at (.+?); with v = (.+?) and the stated signed-speed convention, calculate observed frequency, frequency difference, and percentage change$",
c,
self.answer(
self.model(
&c[1],
&c[4],
&self.speed(&c[3], true)?,
&self.speed(&c[2], false)?
)?,
&[Goal::Frequency, Goal::Shift, Goal::PercentChange]
)
);
rule!(
r"(?i)^a source emits (.+?) and moves toward a stationary observer at (.+?); with sound speed (.+?), find heard frequency, frequency increase, and the heard-to-emitted ratio$",
c,
self.answer(
self.model(&c[1], &c[3], "0 m/s", &self.speed(&c[2], true)?)?,
&[Goal::Frequency, Goal::Increase, Goal::Ratio]
)
);
rule!(
r"(?i)^a stationary source emits (.+?); an observer approaches at (.+?) with sound speed (.+?); calculate observed frequency, frequency increase, and wavelength of the observed sound in the stationary air$",
c,
self.answer(
self.model(&c[1], &c[3], &self.speed(&c[2], true)?, "0 m/s")?,
&[Goal::Frequency, Goal::Increase, Goal::Wavelength]
)
);
rule!(
r"(?i)^a (.+?) source approaches a stationary observer at (.+?) in sound speed (.+?); calculate fprime, period of the heard tone, and percentage frequency increase$",
c,
self.answer(
self.model(&c[1], &c[3], "0 m/s", &self.speed(&c[2], true)?)?,
&[Goal::Frequency, Goal::Period, Goal::PercentIncrease]
)
);
rule!(
r"(?i)^a source emits (.+?) and recedes at (.+?) from a stationary observer; use v = (.+?) and the explicit signed doppler formula to calculate the heard frequency and difference$",
c,
self.answer(
self.model(&c[1], &c[3], "0 m/s", &self.speed(&c[2], false)?)?,
&[Goal::Frequency, Goal::Shift]
)
);
rule!(
r"(?i)^a (.+?) source approaches at (.+?) while an observer recedes at (.+?); sound speed is (.+?), use vo positive toward source and vs positive toward observer, and calculate observed frequency$",
c,
self.answer(
self.model(
&c[1],
&c[4],
&self.speed(&c[3], false)?,
&self.speed(&c[2], true)?
)?,
&[Goal::Frequency]
)
);
rule!(
r"(?i)^(?:use|using) fprime = f\(v \+ vo\)/\(v - vs\), with vo positive toward source and vs positive toward observer; the request gives v = (.+?), vs = (.+?), f = (.+?), vo = (.+?) and asks for finite observed frequency$",
c,
self.answer(
self.model(
&c[3],
&c[1],
&if c[4].trim() == "0" {
"0 m/s".into()
} else {
c[4].to_string()
},
&c[2]
)?,
&[Goal::Frequency]
)
);
rule!(
r"(?i)^for the stated doppler formula fprime = f\(v \+ vo\)/\(v - vs\), with v = (.+?), source speed vs = (.+?) positive toward observer, observer stationary, and f = (.+?), determine whether the model gives a physically valid finite result$",
c,
self.answer(
self.model(&c[3], &c[1], "0 m/s", &self.speed(&c[2], true)?)?,
&[Goal::Frequency]
)
);
if re!(r"(?i)^a doppler request says a .+? source and observer each move at .+? and asks for the heard frequency, but gives neither sound speed nor whether the motions are toward or away$").is_match(input)
|| re!(r#"(?i)^a source is said to move [“"]toward[”"] the observer at .+?, and the observer [“"]away[”"] at .+?; calculate the doppler shift for a .+? tone without a sound speed$"#).is_match(input)
{
return Err(invalid());
}
rule!(
r"(?i)^using fprime = f\(v \+ vo\)/\(v - vs\), with vo positive toward source and vs positive toward observer, f = (.+?), v = (.+?), vs = (.+?), vo = (.+?), and the observer is stationary; calculate observed frequency$",
c,
{
let model = self.model(&c[1], &c[2], &c[4], &c[3])?;
if !model.wave.vo.value.is_zero() {
return Err(physical());
}
self.answer(model, &[Goal::Frequency])
}
);
rule!(
r"(?i)^using fprime = f\(v \+ vo\)/\(v - vs\), with vo positive toward source and vs positive toward observer, f = (.+?), v = (.+?), vo = (.+?), and vs = (.+?); calculate observed frequency$",
c,
self.answer(self.model(&c[1], &c[2], &c[3], &c[4])?, &[Goal::Frequency])
);
self.motion_clauses(input)
}
}