mod supplied;
mod wording;
use super::{
compositions::Compositions, compound_units, integer_queries, syntax, units::format_quantity,
};
use crate::{Context, Error, ModelPosition, Outcome, Plugin, re};
use num_traits::Signed;
#[derive(Default)]
pub struct ThermalQueries {
engine: Compositions,
}
impl Plugin for ThermalQueries {
fn rewrite_call(
&self,
name: &str,
arguments: &str,
context: &Context,
_: ModelPosition,
) -> Outcome {
if !calls().is_match(&format!("{name}(")) {
return None;
}
Some(
ThermalRequest {
engine: &self.engine,
context,
}
.call(name, arguments),
)
}
fn rewrite_model(&self, input: &str, context: &Context, _: ModelPosition) -> Outcome {
ThermalRequest {
engine: &self.engine,
context,
}
.wording(input)
}
fn evaluate(&self, input: &str, context: &Context) -> Outcome {
let input = syntax::ungroup(input);
if let Some(expression) = input
.strip_prefix("thermal_specific_heat(")
.and_then(|s| s.strip_suffix(')'))
{
return Some(
self.engine
.quantity_value(expression, "J/(kg*K)", context)
.map(|value| format!("{} J/(kg K)", crate::number(value))),
);
}
if let Some(inner) = input
.strip_prefix("thermal_report(")
.and_then(|s| s.strip_suffix(')'))
{
return Some(self.evaluate_report(inner, context));
}
if let Some(expression) = input
.strip_prefix("thermal_coefficient(")
.and_then(|s| s.strip_suffix(')'))
{
return Some(
self.engine
.quantity_value(expression, "1/K", context)
.map(|value| format!("{} per °C", crate::number(value))),
);
}
let fields = input.strip_prefix("thermal_interval(")?.strip_suffix(')')?;
Some((|| {
let (expression, target) = fields
.split_once(';')
.ok_or_else(|| Error("invalid_expression".into()))?;
self.format_interval(expression, target, context)
})())
}
fn rewrite(&self, input: &str, context: &Context) -> Outcome {
let request = ThermalRequest {
engine: &self.engine,
context,
};
let expression = match syntax::rewrite_groups(input, |s| request.wording(s)) {
Some(Ok(expression)) => expression,
Some(Err(error)) => return Some(Err(error)),
None => input.to_string(),
};
match syntax::rewrite_calls(&expression, calls(), |name, arguments| {
request.call(name.trim(), arguments)
}) {
Ok(lowered) if lowered != input => Some(Ok(lowered)),
Err(error) => Some(Err(error)),
_ => None,
}
}
}
impl ThermalQueries {
fn format_interval(
&self,
expression: &str,
target: &str,
context: &Context,
) -> Result<String, Error> {
let target = if target.trim().eq_ignore_ascii_case("kelvins") {
"K"
} else {
target.trim()
};
let unit = self
.engine
.units
.unit(target)
.filter(|u| u.dimension == [0, 0, 0, 1, 0, 0, 0, 0])
.ok_or_else(|| Error("incompatible_units".into()))?;
let value = self.engine.quantity_value(expression, "K", context)? / unit.scale;
Ok(format_quantity(value, &unit))
}
fn evaluate_report(&self, inner: &str, context: &Context) -> Result<String, Error> {
if inner.len() > 4096 {
return Err(Error("invalid_expression".into()));
}
let fields = inner.split(';').collect::<Vec<_>>();
if !(2..=3).contains(&fields.len()) {
return Err(Error("invalid_expression".into()));
}
let mut output = Vec::new();
for field in fields {
let parts = field.split('|').collect::<Vec<_>>();
let [kind, target, expression] = parts.as_slice() else {
return Err(Error("invalid_expression".into()));
};
let (label, display) = match *kind {
"temperature" => {
self.engine.quantity_value(expression, "K", context)?;
let display = self
.engine
.evaluate(&format!("({expression}) in {target}"), context)
.ok_or_else(|| Error("invalid_expression".into()))??;
("temperature", display)
}
"energy" => {
self.engine
.quantity_value(&format!("1 {target}"), "J", context)?;
self.engine.quantity_value(expression, "J", context)?;
let display = self
.engine
.evaluate(&format!("({expression}) in {target}"), context)
.ok_or_else(|| Error("invalid_expression".into()))??;
("energy", display)
}
"change" => (
"temperature change",
self.format_interval(expression, target, context)?,
),
_ => return Err(Error("invalid_expression".into())),
};
output.push(format!("{label}: {display}"));
}
Ok(output.join("; "))
}
}
fn calls() -> &'static regex::Regex {
re!(r"(?i)\b(?:sensible_heat|latent_heat|thermal_final_temperature|heat_capacity_energy)\s*\(")
}
pub(super) fn supplied_formula_role(
role: &str,
value: &str,
engine: &Compositions,
context: &Context,
) -> Result<String, Error> {
let request = ThermalRequest { engine, context };
match role.trim().to_ascii_lowercase().as_str() {
"coefficient" => request.coefficient(value),
"initial length" => request.role(value, "m", false),
"temperature rise" => {
let rise = request.rise(value)?;
let interval = format!("({rise}*(1 K))");
engine.quantity_value(&interval, "K", context)?;
Ok(interval)
}
_ => Err(Error("invalid_expression".into())),
}
}
struct ThermalRequest<'a> {
engine: &'a Compositions,
context: &'a Context,
}
impl ThermalRequest<'_> {
fn role(&self, input: &str, unit: &str, positive: bool) -> Result<String, Error> {
let value = self.engine.quantity_value(input, unit, self.context)?;
if value < 0.0 || (positive && value == 0.0) {
return Err(Error("invalid_physical_quantity".into()));
}
Ok(format!("({input})"))
}
fn exact(&self, expression: &str) -> Result<Option<String>, Error> {
match integer_queries::ratio_value(expression) {
Ok((n, d)) => Ok(Some(format!("rational({n},{d})"))),
Err(e)
if matches!(
e.0.as_str(),
"invalid_integer_expression" | "non_rational_expression"
) =>
{
Ok(None)
}
Err(e) => Err(e),
}
}
fn temperature(&self, input: &str) -> Result<String, Error> {
self.temperature_coordinate(input, true)
}
fn temperature_coordinate(&self, input: &str, absolute: bool) -> Result<String, Error> {
let mut value = self.engine.quantity_value(input, "K", self.context)?;
let input = syntax::ungroup(input).trim();
for (index, _) in input.char_indices() {
let Some(unit) = self.engine.units.unit(input[index..].trim()) else {
continue;
};
let scalar = input[..index].trim();
let expression = match unit.symbol.as_str() {
"°C" if absolute => format!("({scalar})+27315/100"),
"°F" if absolute => format!("(({scalar})-32)*5/9+27315/100"),
"°C" => scalar.to_string(),
"°F" => format!("({scalar})*5/9"),
"K" => scalar.to_string(),
_ => continue,
};
match integer_queries::ratio_value(&expression) {
Ok((n, d)) => {
if absolute && n.is_negative() {
return Err(Error("invalid_physical_quantity".into()));
}
return Ok(format!("rational({n},{d})"));
}
Err(e)
if matches!(
e.0.as_str(),
"invalid_integer_expression" | "non_rational_expression"
) =>
{
if !absolute {
value -= unit.offset;
}
break;
}
Err(e) => return Err(e),
}
}
if absolute && value < 0.0 {
return Err(Error("invalid_physical_quantity".into()));
}
Ok(format!("real({value:e})"))
}
fn rise(&self, input: &str) -> Result<String, Error> {
let scalar = self.temperature_coordinate(input, false)?;
self.role(&scalar, "1", false)
}
fn sensible(
&self,
mass: &str,
capacity: &str,
start: &str,
end: &str,
) -> Result<String, Error> {
let mass = self.role(mass, "kg", false)?;
let capacity = self.capacity(capacity, "J/(kg*K)")?;
let difference = self.difference(start, end)?;
Ok(format!("({mass}*{capacity}*({difference})*(1 K))"))
}
fn latent(&self, mass: &str, heat: &str) -> Result<String, Error> {
Ok(format!(
"({}*{})",
self.role(mass, "kg", false)?,
self.role(heat, "J/kg", true)?
))
}
fn final_temperature(
&self,
mass: &str,
capacity: &str,
start: &str,
heat: &str,
) -> Result<String, Error> {
let mass = self.role(mass, "kg", true)?;
let capacity = self.capacity(capacity, "J/(kg*K)")?;
let start = self.temperature(start)?;
self.engine.quantity_value(heat, "J", self.context)?;
let expression = format!("(({start})*(1 K)+({heat})/({mass}*{capacity}))");
self.role(&expression, "K", false)?;
Ok(expression)
}
fn call(&self, name: &str, arguments: &str) -> Result<String, Error> {
let ranges = syntax::groups(arguments).ok_or_else(|| Error("invalid_expression".into()))?;
let mut start = 0;
let mut args = Vec::new();
for (index, ch) in arguments.char_indices() {
if ch == ',' && !ranges.iter().any(|range| range.contains(&index)) {
args.push(arguments[start..index].trim());
start = index + 1;
}
}
args.push(arguments[start..].trim());
match (name.to_ascii_lowercase().as_str(), args.as_slice()) {
("sensible_heat", [m, c, a, b]) => self.sensible(m, c, a, b),
("latent_heat", [m, l]) => self.latent(m, l),
("heat_capacity_energy", [c, a, b]) => self.capacity_energy(c, a, b),
("thermal_final_temperature", [m, c, t, q]) => self.final_temperature(m, c, t, q),
_ => Err(Error("invalid_expression".into())),
}
}
fn directed_heat(
&self,
mass: &str,
capacity: &str,
start: &str,
end: &str,
cooling: bool,
target: &str,
) -> Result<String, Error> {
let heat = self.sensible(mass, capacity, start, end)?;
self.direction(start, end, Some(cooling))?;
Ok(format!(
"{} in {target}",
if cooling { format!("-({heat})") } else { heat }
))
}
fn direction(&self, start: &str, end: &str, cooling: Option<bool>) -> Result<(), Error> {
if let Some(cooling) = cooling {
let difference = self.difference(start, end)?;
let change = self.engine.quantity_value(&difference, "1", self.context)?;
if (cooling && change > 0.0) || (!cooling && change < 0.0) {
return Err(Error("invalid_physical_quantity".into()));
}
}
Ok(())
}
fn capacity_units(&self, input: &str) -> String {
compound_units::explicit_products(input, |leaf| self.engine.units.unit(leaf).is_some())
}
fn capacity_expression(&self, input: &str) -> String {
for (index, _) in input.char_indices() {
let original = input[index..].trim();
let units = self.capacity_units(original);
let Some(factors) = compound_units::factors(&units, |leaf| {
!leaf.contains(['/', '*', '·', '(', ')']) && self.engine.units.unit(leaf).is_some()
}) else {
continue;
};
if units == original
&& !factors.iter().any(|(leaf, _)| {
self.engine
.units
.unit(leaf)
.is_some_and(|u| u.offset != 0.0)
})
{
continue;
}
let mut expression = format!("({})", input[..index].trim());
for (leaf, power) in factors {
let unit = self.engine.units.unit(&leaf).unwrap();
let factor = match unit.symbol.as_str() {
"°C" => "(1 K)".into(),
"°F" => "(rational(5,9)*(1 K))".into(),
_ => format!("(1 {leaf})"),
};
expression.push_str(&format!("*({factor})^({power})"));
}
return expression;
}
input.to_string()
}
fn capacity(&self, input: &str, reference: &str) -> Result<String, Error> {
self.role(&self.capacity_expression(input), reference, true)
}
fn coefficient(&self, input: &str) -> Result<String, Error> {
let degrees = re!(r"(?i)\bdegree (celsius|fahrenheit)\b").replace_all(input, "degrees $1");
let reciprocal = re!(r"(?i)\s+per\s+").replace(°rees, " 1/");
let expression = self.capacity_expression(&reciprocal);
self.engine
.quantity_value(&expression, "1/K", self.context)?;
Ok(format!("({expression})"))
}
fn difference(&self, start: &str, end: &str) -> Result<String, Error> {
let expression = format!(
"({})-({})",
self.temperature(end)?,
self.temperature(start)?
);
Ok(self.exact(&expression)?.unwrap_or(expression))
}
fn capacity_energy(&self, capacity: &str, start: &str, end: &str) -> Result<String, Error> {
Ok(format!(
"({}*({})*(1 K))",
self.capacity(capacity, "J/K")?,
self.difference(start, end)?
))
}
fn interval(&self, scalar: &str, target: &str) -> String {
format!("thermal_interval(({scalar})*(1 K);{target})")
}
}