use super::{compositions::Compositions, model_coordinates, named_quantities, syntax};
use crate::{Context, Error, ModelPosition, Outcome, Plugin, re};
use model_coordinates::Coordinate;
use num_rational::BigRational;
use num_traits::{Signed, ToPrimitive, Zero};
mod wording;
#[derive(Default)]
pub struct AcousticsQueries {
engine: Compositions,
}
impl Plugin for AcousticsQueries {
fn rewrite_call(
&self,
name: &str,
arguments: &str,
context: &Context,
_: ModelPosition,
) -> Outcome {
if !matches!(
name.to_ascii_lowercase().as_str(),
"doppler_frequency"
| "doppler_source_frequency"
| "doppler_shift"
| "doppler_ratio"
| "doppler_wavelength"
) {
return None;
}
self.rewrite(&format!("{name}({arguments})"), context)
}
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_calls(
input,
re!(
r"(?i)\b(?:doppler_frequency|doppler_source_frequency|doppler_shift|doppler_ratio|doppler_wavelength)\s*\("
),
|name, arguments| request.call(name.trim(), arguments),
) {
Ok(expression) => expression,
Err(error) => return Some(Err(error)),
};
match syntax::rewrite_groups(&expression, |part| request.wording(part)) {
Some(result) => Some(result),
None if expression != input => Some(Ok(expression)),
None => None,
}
}
fn evaluate(&self, input: &str, context: &Context) -> Outcome {
let input = syntax::ungroup(input);
if let Some(level) = input
.strip_prefix("acoustics_level(")
.and_then(|s| s.strip_suffix(')'))
{
return Some(
self.engine
.quantity_value(level, "1", context)
.map(|value| format!("{} dB", crate::number(value))),
);
}
if !input.contains("acoustics_report(") {
return None;
}
Some((|| {
let inner = input
.strip_prefix("acoustics_report(")
.and_then(|s| s.strip_suffix(')'))
.ok_or_else(invalid)?;
let fields = inner.split(';').collect::<Vec<_>>();
if !(2..=3).contains(&fields.len()) {
return Err(invalid());
}
let mut output = Vec::new();
for field in fields {
let (label, expression) = field.split_once('|').ok_or_else(invalid)?;
let goal = Goal::from_tag(label).ok_or_else(invalid)?;
let coordinate = self
.engine
.quantity_value(expression, goal.unit(), context)?;
if goal.requires_nonnegative() && coordinate < 0.0
|| matches!(
goal,
Goal::Source
| Goal::Period
| Goal::PlainPeriod
| Goal::Wavelength
| Goal::PlainWavelength
) && coordinate == 0.0
|| matches!(goal, Goal::PercentChange) && coordinate < -100.0
{
return Err(physical());
}
let value = self
.engine
.evaluate(expression, context)
.ok_or_else(invalid)??;
output.push(format!(
"{}: {value}{}",
goal.label(),
if goal.percent() { "%" } else { "" }
));
}
Ok(output.join("; "))
})())
}
}
fn invalid() -> Error {
Error("invalid_expression".into())
}
fn physical() -> Error {
Error("invalid_physical_value".into())
}
#[derive(Clone, Copy)]
enum Goal {
Frequency,
Source,
Emitted,
Shift,
Increase,
PercentChange,
PercentIncrease,
Ratio,
Period,
PlainPeriod,
Wavelength,
PlainWavelength,
Speed,
}
impl Goal {
fn label(self) -> &'static str {
match self {
Self::Frequency => "observed frequency",
Self::Source | Self::Emitted => "source frequency",
Self::Shift => "frequency shift",
Self::Increase => "frequency increase",
Self::PercentChange => "percentage change",
Self::PercentIncrease => "percentage increase",
Self::Ratio => "heard-to-emitted ratio",
Self::Period => "observed period",
Self::PlainPeriod => "period",
Self::Wavelength => "wavelength in stationary air",
Self::PlainWavelength => "wavelength",
Self::Speed => "speed",
}
}
fn tag(self) -> &'static str {
match self {
Self::PercentChange => "pct_change",
Self::PercentIncrease => "pct_increase",
_ => self.label(),
}
}
fn from_tag(label: &str) -> Option<Self> {
[
Self::Frequency,
Self::Source,
Self::Shift,
Self::Increase,
Self::PercentChange,
Self::PercentIncrease,
Self::Ratio,
Self::Period,
Self::PlainPeriod,
Self::Wavelength,
Self::PlainWavelength,
Self::Speed,
]
.into_iter()
.find(|goal| goal.tag() == label)
}
fn unit(self) -> &'static str {
match self {
Self::Period | Self::PlainPeriod => "s",
Self::Wavelength | Self::PlainWavelength => "m",
Self::Speed => "m/s",
Self::Ratio | Self::PercentChange | Self::PercentIncrease => "1",
_ => "Hz",
}
}
fn percent(self) -> bool {
matches!(self, Self::PercentChange | Self::PercentIncrease)
}
fn requires_nonnegative(self) -> bool {
!matches!(self, Self::Shift | Self::PercentChange)
}
}
struct Wave {
v: Coordinate,
vo: Coordinate,
vs: Coordinate,
}
impl Wave {
fn denominator(&self) -> BigRational {
&self.v.value - &self.vs.value
}
fn numerator(&self) -> BigRational {
&self.v.value + &self.vo.value
}
fn validate(&self) -> Result<(), Error> {
let denominator = self.denominator();
if denominator.is_zero() {
return Err(Error("division_by_zero".into()));
}
if denominator.is_negative() || self.numerator().is_negative() {
return Err(physical());
}
Ok(())
}
fn authored(&self) -> bool {
self.v.authored && self.vo.authored && self.vs.authored
}
}
struct Model {
f: Coordinate,
wave: Wave,
}
impl Model {
fn value(&self, goal: Goal) -> Result<BigRational, Error> {
let numerator = self.wave.numerator();
let denominator = self.wave.denominator();
let change = &self.wave.vo.value + &self.wave.vs.value;
let value = match goal {
Goal::Frequency => &self.f.value * &numerator / &denominator,
Goal::Source => {
if numerator.is_zero() {
return Err(Error("division_by_zero".into()));
}
&self.f.value * &denominator / &numerator
}
Goal::Emitted => self.f.value.clone(),
Goal::Shift | Goal::Increase => &self.f.value * &change / &denominator,
Goal::PercentChange | Goal::PercentIncrease => {
change / &denominator * BigRational::from_integer(100.into())
}
Goal::Ratio => numerator / denominator,
Goal::Period | Goal::PlainPeriod => {
if numerator.is_zero() {
return Err(Error("division_by_zero".into()));
}
denominator / (&self.f.value * numerator)
}
Goal::Wavelength | Goal::PlainWavelength => denominator / &self.f.value,
Goal::Speed => self.wave.v.value.clone(),
};
if matches!(goal, Goal::Increase | Goal::PercentIncrease) && value.is_negative() {
return Err(physical());
}
model_coordinates::bounded(value)
}
}
struct Request<'a> {
plugin: &'a AcousticsQueries,
context: &'a Context,
}
impl Request<'_> {
fn coordinate(
&self,
input: &str,
reference: &str,
positive: bool,
) -> Result<Coordinate, Error> {
let coordinate =
model_coordinates::read(input, reference, &self.plugin.engine, self.context)?;
if positive && coordinate.value <= BigRational::zero() {
return Err(physical());
}
Ok(coordinate)
}
fn wave(&self, v: &str, vo: &str, vs: &str) -> Result<Wave, Error> {
let wave = Wave {
v: self.coordinate(v, "m/s", true)?,
vo: self.coordinate(vo, "m/s", false)?,
vs: self.coordinate(vs, "m/s", false)?,
};
wave.validate()?;
Ok(wave)
}
fn model(&self, f: &str, v: &str, vo: &str, vs: &str) -> Result<Model, Error> {
Ok(Model {
f: self.coordinate(f, "Hz", true)?,
wave: self.wave(v, vo, vs)?,
})
}
fn result(&self, value: BigRational, unit: &str, authored: bool) -> Result<String, Error> {
let value = model_coordinates::bounded(value)?;
let scalar = if authored {
format!("rational({},{})", value.numer(), value.denom())
} else {
let computed = value
.to_f64()
.filter(|v| v.is_finite())
.ok_or_else(|| Error("numeric_overflow".into()))?;
if computed == 0.0 && !value.is_zero() {
return Err(Error("numeric_underflow".into()));
}
format!("real({computed:e})")
};
let expression = if unit == "1" {
scalar
} else {
format!("(({scalar}) {unit})")
};
if expression.len() > 4096 {
return Err(Error("integer_limit".into()));
}
self.plugin
.engine
.quantity_value(&expression, unit, self.context)?;
Ok(expression)
}
fn answer(&self, model: Model, goals: &[Goal]) -> Result<String, Error> {
let fields = goals.iter().map(|goal| (*goal, None)).collect::<Vec<_>>();
self.answer_in(model, &fields)
}
fn answer_in(&self, model: Model, goals: &[(Goal, Option<String>)]) -> Result<String, Error> {
let authored = model.f.authored && model.wave.authored();
let fields = goals
.iter()
.map(|(goal, target)| {
let mut expression = self.result(model.value(*goal)?, goal.unit(), authored)?;
if let Some(target) = target {
self.plugin.engine.quantity_value(
&format!("1 {target}"),
goal.unit(),
self.context,
)?;
expression = format!("({expression}) in {target}");
}
Ok((goal.tag(), expression))
})
.collect::<Result<Vec<_>, Error>>()?;
if fields.len() == 1 {
return Ok(fields.into_iter().next().ok_or_else(invalid)?.1);
}
Ok(format!(
"acoustics_report({})",
fields
.into_iter()
.map(|(label, expression)| format!("{label}|{expression}"))
.collect::<Vec<_>>()
.join(";")
))
}
fn speed(&self, input: &str, toward: bool) -> Result<String, Error> {
let coordinate = self.coordinate(input, "m/s", false)?;
if coordinate.value.is_negative() {
return Err(physical());
}
let value = if toward {
coordinate.value
} else {
-coordinate.value
};
self.result(value, "m/s", coordinate.authored)
}
fn call(&self, name: &str, arguments: &str) -> Result<String, Error> {
let args = named_quantities::function_arguments(arguments, false)?;
let name = name.to_ascii_lowercase();
if name == "doppler_ratio" && args.len() == 3 {
let wave = self.wave(args[0], args[1], args[2])?;
return self.result(wave.numerator() / wave.denominator(), "1", wave.authored());
}
if name == "doppler_wavelength" && args.len() == 3 {
return self.answer(
self.model(args[0], args[1], "0 m/s", args[2])?,
&[Goal::Wavelength],
);
}
if args.len() != 4 {
return Err(invalid());
}
let goal = match name.as_str() {
"doppler_frequency" => Goal::Frequency,
"doppler_source_frequency" => Goal::Source,
"doppler_shift" => Goal::Shift,
_ => return Err(invalid()),
};
self.answer(self.model(args[0], args[1], args[2], args[3])?, &[goal])
}
}