mod wording;
use super::{
compositions::Compositions,
model_coordinates::{self, Coordinate},
named_quantities, syntax,
};
use crate::{Context, Error, ModelPosition, Outcome, Plugin, re};
use num_rational::BigRational;
use num_traits::{Signed, ToPrimitive, Zero};
#[derive(Default)]
pub struct OpticsQueries {
engine: Compositions,
}
impl Plugin for OpticsQueries {
fn rewrite_call(
&self,
name: &str,
arguments: &str,
context: &Context,
position: ModelPosition,
) -> Outcome {
if !calls().is_match(&format!("{name}(")) {
return None;
}
Some(
Request {
engine: &self.engine,
context,
}
.call(name, arguments, position),
)
}
fn rewrite_model(&self, input: &str, context: &Context, _: ModelPosition) -> Outcome {
Request {
engine: &self.engine,
context,
}
.wording(input)
}
fn rewrite(&self, input: &str, context: &Context) -> Outcome {
let request = Request {
engine: &self.engine,
context,
};
let expression = match syntax::rewrite_groups(input, |s| request.wording(s)) {
Some(Ok(s)) => s,
Some(Err(e)) => return Some(Err(e)),
None => input.into(),
};
let whole = syntax::ungroup(&expression);
let standalone_angle = calls().find(whole).is_some_and(|found| {
found.start() == 0
&& matches!(
whole[..found.end() - 1]
.trim()
.to_ascii_lowercase()
.as_str(),
"snell_angle" | "critical_angle"
)
&& syntax::groups(whole).is_some_and(|groups| {
groups.len() == 1
&& groups[0].start == found.end()
&& groups[0].end + 1 == whole.len()
})
});
match syntax::rewrite_calls(&expression, calls(), |name, arguments| {
request.call(name.trim(), arguments, ModelPosition::Operand)
}) {
Ok(s) if s != input => Some(Ok(if standalone_angle {
format!("({s}) in rad")
} else {
s
})),
Err(e) => Some(Err(e)),
_ => None,
}
}
fn evaluate(&self, input: &str, context: &Context) -> Outcome {
let input = syntax::ungroup(input);
if input.contains("optics_answer(") {
return Some((|| {
let answer = input
.strip_prefix("optics_answer(")
.and_then(|s| s.strip_suffix(')'))
.ok_or_else(invalid)?;
match answer {
"no finite image distance" | "total internal reflection" => Ok(answer.into()),
_ => Err(invalid()),
}
})());
}
if !input.contains("optics_report(") {
return None;
}
Some((|| {
let fields = input
.strip_prefix("optics_report(")
.and_then(|s| s.strip_suffix(')'))
.ok_or_else(invalid)?;
let fields: Vec<_> = fields.split(';').collect();
if !(2..=4).contains(&fields.len()) {
return Err(invalid());
}
let mut answers = Vec::new();
for field in fields {
let (label, expression) = field.split_once('|').ok_or_else(invalid)?;
let (label, target) = label
.split_once('@')
.map_or((label, None), |(label, unit)| (label, Some(unit)));
let unit = match label {
"image distance" | "object distance" | "image height" | "focal length" => "m",
"magnification" | "magnification magnitude" => "1",
"critical angle" | "refracted angle" => "°",
"refraction possible" | "total internal reflection" => {
if target.is_some() || !matches!(expression, "true" | "false") {
return Err(invalid());
}
answers.push(format!("{label}: {expression}"));
continue;
}
"orientation" => {
if target.is_some() || !matches!(expression, "upright" | "inverted") {
return Err(invalid());
}
answers.push(format!("{label}: {expression}"));
continue;
}
_ => return Err(invalid()),
};
self.engine.quantity_value(expression, unit, context)?;
let target = target.unwrap_or(unit);
self.engine
.quantity_value(&target_quantity(target), unit, context)?;
let expression = if target == "1" {
expression.into()
} else {
format!("({expression}) in {target}")
};
let answer = self
.engine
.evaluate(&expression, context)
.ok_or_else(invalid)??;
let suffix = if label == "magnification magnitude" {
"%"
} else {
""
};
answers.push(format!("{label}: {answer}{suffix}"));
}
Ok(answers.join("; "))
})())
}
}
fn calls() -> &'static regex::Regex {
re!(
r"(?i)\b(?:lens_image_distance|lens_object_distance|lens_focal_length|lens_magnification|snell_angle|critical_angle)\s*\("
)
}
fn invalid() -> Error {
Error("invalid_expression".into())
}
fn physical() -> Error {
Error("invalid_physical_quantity".into())
}
fn target_quantity(unit: &str) -> String {
if unit == "1" {
"1".into()
} else {
format!("1 {unit}")
}
}
fn nonzero(value: &BigRational) -> Result<(), Error> {
if value.is_zero() {
Err(Error("division_by_zero".into()))
} else {
Ok(())
}
}
fn sinc(value: f64) -> f64 {
if value == 0.0 {
1.0
} else {
value.sin() / value
}
}
fn normalized_grazing_gap(
ratio: &BigRational,
beta: &BigRational,
delta: &BigRational,
) -> Result<(f64, f64), Error> {
let scale = beta.abs().max(delta.abs());
let numeric = || Error("numeric_overflow".into());
let normalized_beta = model_coordinates::bounded(beta / &scale)?
.to_f64()
.ok_or_else(numeric)?;
let normalized_delta = model_coordinates::bounded(delta / &scale)?
.to_f64()
.ok_or_else(numeric)?;
let radians = delta.to_f64().ok_or_else(numeric)?.to_radians();
let correction = normalized_delta
* (std::f64::consts::PI / 180.0)
* (radians * sinc(radians / 2.0).powi(2) / 4.0 - 3.0f64.sqrt() / 2.0 * sinc(radians));
let gap = ratio
.to_f64()
.ok_or_else(numeric)?
.mul_add(correction, normalized_beta);
Ok((gap, scale.to_f64().ok_or_else(numeric)?))
}
fn coordinate(value: BigRational, authored: bool) -> Result<Coordinate, Error> {
Ok(Coordinate {
value: model_coordinates::bounded(value)?,
authored,
})
}
fn report<S: AsRef<str>>(fields: &[(S, String)]) -> String {
format!(
"optics_report({})",
fields
.iter()
.map(|(label, s)| format!("{}|{s}", label.as_ref()))
.collect::<Vec<_>>()
.join(";")
)
}
struct Request<'a> {
engine: &'a Compositions,
context: &'a Context,
}
enum Refraction {
Transmitted(String),
TotalInternalReflection,
}
impl Request<'_> {
fn read(&self, input: &str, unit: &str) -> Result<Coordinate, Error> {
model_coordinates::read(input, unit, self.engine, self.context)
}
fn length(&self, input: &str) -> Result<Coordinate, Error> {
let value = self.read(input, "m")?;
nonzero(&value.value)?;
Ok(value)
}
fn index(&self, input: &str) -> Result<Coordinate, Error> {
let value = self.read(input, "1")?;
if value.value <= BigRational::zero() {
return Err(physical());
}
Ok(value)
}
fn emit(&self, value: &Coordinate, unit: &str) -> Result<String, Error> {
let rational = format!("rational({},{})", value.value.numer(), value.value.denom());
let expression = if unit == "1" {
rational
} else {
format!("(({rational}) {unit})")
};
if expression.len() > 4096 {
return Err(Error("integer_limit".into()));
}
let computed = self
.engine
.quantity_value(&expression, unit, self.context)?;
Ok(if value.authored {
expression
} else {
self.real(computed, unit)
})
}
fn real(&self, value: f64, unit: &str) -> String {
if unit == "1" {
format!("real({value:e})")
} else {
format!("(real({value:e})*(1 {unit}))")
}
}
fn image(&self, f: &Coordinate, object: &Coordinate) -> Result<Coordinate, Error> {
let difference = &object.value - &f.value;
nonzero(&difference)?;
coordinate(
&f.value * &object.value / difference,
f.authored && object.authored,
)
}
fn magnification(&self, object: &Coordinate, image: &Coordinate) -> Result<Coordinate, Error> {
nonzero(&object.value)?;
coordinate(
-&image.value / &object.value,
object.authored && image.authored,
)
}
fn focal(&self, object: &Coordinate, image: &Coordinate) -> Result<Coordinate, Error> {
let sum = &object.value + &image.value;
nonzero(&sum)?;
coordinate(
&object.value * &image.value / sum,
object.authored && image.authored,
)
}
fn lens_inverse_answer(
&self,
first: &str,
image: &str,
target: &str,
kind: &str,
paired: bool,
) -> Result<String, Error> {
let first = self.length(first)?;
let image = self.length(image)?;
let (object, result, label) = if target == "object" {
self.focal_kind(&first, kind)?;
let object = self.image(&first, &image)?;
let result = self.emit(&object, "m")?;
(object, result, "object distance")
} else {
let f = self.focal(&first, &image)?;
self.focal_kind(&f, kind)?;
let result = self.emit(&f, "m")?;
(first, result, "focal length")
};
if !paired {
return Ok(format!("{result} in m"));
}
let m = self.emit(&self.magnification(&object, &image)?, "1")?;
Ok(report(&[(label, result), ("magnification", m)]))
}
fn focal_kind(&self, f: &Coordinate, kind: &str) -> Result<(), Error> {
if kind.eq_ignore_ascii_case("converging") && f.value.is_negative()
|| kind.eq_ignore_ascii_case("diverging") && f.value.is_positive()
{
return Err(physical());
}
Ok(())
}
fn lens_answer(
&self,
f: &str,
object: &str,
height: Option<&str>,
kind: &str,
output: &str,
) -> Result<String, Error> {
let f = self.length(f)?;
self.focal_kind(&f, kind)?;
let object = self.length(object)?;
let image = self.image(&f, &object)?;
let di = self.emit(&image, "m")?;
if output == "distance" {
return Ok(format!("{di} in m"));
}
let m = self.magnification(&object, &image)?;
let magnification = self.emit(&m, "1")?;
if output == "magnification" {
return Ok(magnification);
}
let mut fields = vec![("image distance", di), ("magnification", magnification)];
if output == "absolute_report" {
let magnitude = coordinate(
m.value.abs() * BigRational::from_integer(100.into()),
m.authored,
)?;
fields.push(("magnification magnitude", self.emit(&magnitude, "1")?));
}
if let Some(height) = height {
let height = self.read(height, "m")?;
if height.value.is_negative() {
return Err(physical());
}
let hi = coordinate(&m.value * height.value, m.authored && height.authored)?;
fields.push(("image height", self.emit(&hi, "m")?));
}
Ok(report(&fields))
}
fn lens_height_report(
&self,
f: &str,
object: &str,
height: &str,
kind: &str,
fields: &[(String, String)],
) -> Result<String, Error> {
self.lens_report(f, object, Some(height), kind, fields)
}
fn lens_report(
&self,
f: &str,
object: &str,
height: Option<&str>,
kind: &str,
fields: &[(String, String)],
) -> Result<String, Error> {
let f = self.length(f)?;
self.focal_kind(&f, kind)?;
let object = self.length(object)?;
let height = height.map(|h| self.read(h, "m")).transpose()?;
if height.as_ref().is_some_and(|h| h.value.is_negative()) {
return Err(physical());
}
let mut answers = Vec::new();
for (label, target) in fields {
let unit = match label.as_str() {
"focal length" | "object distance" | "image distance" | "image height" => "m",
"magnification" => "1",
_ => return Err(invalid()),
};
self.engine
.quantity_value(&target_quantity(target), unit, self.context)?;
let value = match label.as_str() {
"focal length" => self.emit(&f, unit)?,
"object distance" => self.emit(&object, unit)?,
"image distance" => self.emit(&self.image(&f, &object)?, unit)?,
_ => {
let image = self.image(&f, &object)?;
let magnification = self.magnification(&object, &image)?;
if label == "magnification" {
self.emit(&magnification, unit)?
} else {
let height = height.as_ref().ok_or_else(invalid)?;
let image_height = coordinate(
&magnification.value * &height.value,
magnification.authored && height.authored,
)?;
self.emit(&image_height, unit)?
}
}
};
answers.push((format!("{label}@{target}"), value));
}
if let [(_, value)] = answers.as_slice() {
let target = &fields[0].1;
Ok(if target == "1" {
value.to_owned()
} else {
format!("({value}) in {target}")
})
} else {
Ok(report(&answers))
}
}
fn snell_from_basis(
&self,
n1: &str,
n2: &str,
incident: &str,
basis: &str,
) -> Result<String, Error> {
self.snell_from_basis_output(n1, n2, incident, basis, "angle")
}
fn snell_from_basis_output(
&self,
n1: &str,
n2: &str,
incident: &str,
basis: &str,
output: &str,
) -> Result<String, Error> {
if basis.eq_ignore_ascii_case("normal") {
return self.snell_answer(n1, n2, incident, output);
}
let angle = self.read(incident, "°")?;
if angle.value.is_negative() || angle.value > BigRational::from_integer(90.into()) {
return Err(physical());
}
let normal = coordinate(
BigRational::from_integer(90.into()) - angle.value,
angle.authored,
)?;
self.snell_answer(n1, n2, &self.emit(&normal, "°")?, output)
}
fn refraction(&self, n1: &str, n2: &str, incident: &str) -> Result<Refraction, Error> {
let n1 = self.index(n1)?;
let n2 = self.index(n2)?;
let theta = self.read(incident, "°")?;
if theta.value.is_negative() || theta.value > BigRational::from_integer(90.into()) {
return Err(physical());
}
if n1.value == n2.value {
return self.emit(&theta, "°").map(Refraction::Transmitted);
}
let ratio = model_coordinates::bounded(n1.value / n2.value)?;
let half = BigRational::new(1.into(), 2.into());
let delta = &theta.value - BigRational::from_integer(30.into());
if theta.authored && delta.is_positive() && ratio >= BigRational::from_integer(2.into()) {
return Ok(Refraction::TotalInternalReflection);
}
if theta.authored
&& !delta.is_zero()
&& delta.abs() <= BigRational::from_integer(1.into())
&& ratio >= BigRational::new(3.into(), 2.into())
&& ratio <= BigRational::new(5.into(), 2.into())
{
let beta = BigRational::from_integer(1.into()) - &ratio * half;
let (gap, scale) = normalized_grazing_gap(&ratio, &beta, &delta)?;
if gap < 0.0 {
return Ok(Refraction::TotalInternalReflection);
}
let gap = gap * scale;
let angle = 90.0 - 2.0 * (gap / 2.0).sqrt().asin().to_degrees();
let expression = self.real(angle, "°");
self.engine.quantity_value(&expression, "°", self.context)?;
return Ok(Refraction::Transmitted(expression));
}
let sine = if theta.authored && theta.value.is_zero() {
BigRational::zero()
} else if theta.authored && theta.value == BigRational::from_integer(30.into()) {
BigRational::new(1.into(), 2.into())
} else if theta.authored && theta.value == BigRational::from_integer(90.into()) {
BigRational::from_integer(1.into())
} else {
let radians = self.engine.quantity_value(incident, "rad", self.context)?;
BigRational::from_float(radians.sin())
.ok_or_else(|| Error("numeric_overflow".into()))?
};
let sine = model_coordinates::bounded(ratio * sine)?;
if sine > BigRational::from_integer(1.into()) {
Ok(Refraction::TotalInternalReflection)
} else {
self.angle(&sine).map(Refraction::Transmitted)
}
}
fn angle(&self, sine: &BigRational) -> Result<String, Error> {
if sine > &BigRational::from_integer(1.into()) {
return Err(physical());
}
let value = Coordinate {
value: sine.clone(),
authored: true,
};
let scalar = self.emit(&value, "1")?;
let sine = self.engine.quantity_value(&scalar, "1", self.context)?;
let angle = sine.asin();
let expression = self.real(angle, "rad");
self.engine
.quantity_value(&expression, "rad", self.context)?;
Ok(expression)
}
fn critical_ratio(&self, n1: &str, n2: &str) -> Result<BigRational, Error> {
let n1 = self.index(n1)?;
let n2 = self.index(n2)?;
if n1.value <= n2.value {
return Err(physical());
}
model_coordinates::bounded(n2.value / n1.value)
}
fn critical(&self, n1: &str, n2: &str) -> Result<String, Error> {
let ratio = self.critical_ratio(n1, n2)?;
if ratio == BigRational::new(1.into(), 2.into()) {
return self.emit(
&coordinate(BigRational::from_integer(30.into()), true)?,
"°",
);
}
self.angle(&ratio)
}
fn snell_answer(&self, n1: &str, n2: &str, theta: &str, output: &str) -> Result<String, Error> {
let refraction = self.refraction(n1, n2, theta)?;
let transmission = matches!(refraction, Refraction::Transmitted(_));
match output {
"tir" => Ok((!transmission).to_string()),
"critical" => Ok(report(&[
("critical angle", self.critical(n1, n2)?),
("refraction possible", transmission.to_string()),
])),
"conditional" if !transmission => Ok("optics_answer(total internal reflection)".into()),
_ => match refraction {
Refraction::Transmitted(angle) => Ok(format!("{angle} in °")),
Refraction::TotalInternalReflection => Err(physical()),
},
}
}
fn call(&self, name: &str, arguments: &str, position: ModelPosition) -> Result<String, Error> {
let args = named_quantities::function_arguments(arguments, false)?;
let name = name.to_ascii_lowercase();
let expression = match (name.as_str(), args.as_slice()) {
("lens_image_distance", [f, o]) | ("lens_object_distance", [f, o]) => {
let f = self.length(f)?;
let other = self.length(o)?;
self.emit(&self.image(&f, &other)?, "m")
}
("lens_focal_length", [o, i]) => {
let o = self.length(o)?;
let i = self.length(i)?;
self.emit(&self.focal(&o, &i)?, "m")
}
("lens_magnification", [o, i]) => {
let o = self.length(o)?;
let i = self.length(i)?;
self.emit(&self.magnification(&o, &i)?, "1")
}
("snell_angle", [n1, n2, theta]) => match self.refraction(n1, n2, theta)? {
Refraction::Transmitted(angle) => Ok(angle),
Refraction::TotalInternalReflection => Err(physical()),
},
("critical_angle", [n1, n2]) => self.critical(n1, n2),
_ => Err(invalid()),
}?;
Ok(
if position == ModelPosition::Standalone
&& matches!(name.as_str(), "snell_angle" | "critical_angle")
{
format!("({expression}) in rad")
} else {
expression
},
)
}
}