use alloc::collections::BTreeSet;
use alloc::string::String;
use core::cmp::Ordering;
use pddl::{
BinaryComparison, BinaryOp, EqualityAtomicFormula, FluentComparison, FluentExpression,
FunctionHead, FunctionTerm, MetricFluentExpression, MultiOp, PrimitiveEffect, Term,
};
use super::{EvalError, Evaluator, Scope, Verdict};
use crate::atom::{lower, Atom};
use crate::render;
use crate::report::{Construct, Unmet};
impl Evaluator<'_, '_> {
pub(super) fn comparison(
&self,
comparison: &FluentComparison,
scope: &Scope,
want: bool,
) -> Verdict {
let left = self.value(comparison.first(), scope)?;
let right = self.value(comparison.second(), scope)?;
if let Some(observer) = self.observer {
let mut observer = observer.borrow_mut();
observer.differences.push(left - right);
let degree = degree(comparison.first(), scope, &observer.moving).max(degree(
comparison.second(),
scope,
&observer.moving,
));
observer.nonlinear |= degree > 1;
}
let order = compare(left, right, self.tolerance);
let holds = match comparison.comparison() {
BinaryComparison::GreaterThan => order == Ordering::Greater,
BinaryComparison::LessThan => order == Ordering::Less,
BinaryComparison::Equal => order == Ordering::Equal,
BinaryComparison::GreaterOrEqual => order != Ordering::Less,
BinaryComparison::LessThanOrEqual => order != Ordering::Greater,
};
Ok((holds != want).then(|| Unmet::Comparison {
condition: render::comparison(comparison, scope),
left,
right,
expected: want,
}))
}
pub fn value(&self, exp: &FluentExpression, scope: &Scope) -> Result<f64, EvalError> {
let value = match exp {
FluentExpression::Number(number) => **number,
FluentExpression::Function(head) => return self.fluent(&fluent_atom(head, scope)),
FluentExpression::Negative(inner) => -self.value(inner, scope)?,
FluentExpression::BinaryOp(op, left, right) => {
let left = self.value(left, scope)?;
let right = self.value(right, scope)?;
binary(*op, left, right).ok_or_else(|| division(exp, scope))?
}
FluentExpression::MultiOp(op, first, rest) => {
let mut total = self.value(first, scope)?;
for item in rest {
total = multi(*op, total, self.value(item, scope)?);
}
total
}
};
finite(value, || render::expression(exp, scope))
}
pub fn fluent(&self, atom: &Atom) -> Result<f64, EvalError> {
if let Some(observer) = self.observer {
observer.borrow_mut().fluents.insert(atom.clone());
}
let value = self
.state
.fluents
.get(atom)
.copied()
.ok_or_else(|| EvalError::Undefined(atom.clone()))?;
finite(value, || alloc::format!("{atom}"))
}
pub fn metric(&self, exp: &MetricFluentExpression, total_time: f64) -> Result<f64, EvalError> {
let value = match exp {
MetricFluentExpression::Number(number) => **number,
MetricFluentExpression::Function(symbol, names)
if self.model.is_total_time(symbol, names.len()) =>
{
total_time
}
MetricFluentExpression::Function(symbol, names) => {
let arguments = names.iter().map(|name| lower(name)).collect();
return self.fluent(&Atom::lowered(lower(symbol), arguments));
}
MetricFluentExpression::Negative(inner) => -self.metric(inner, total_time)?,
MetricFluentExpression::BinaryOp(op, left, right) => {
let left = self.metric(left, total_time)?;
let right = self.metric(right, total_time)?;
binary(*op, left, right)
.ok_or_else(|| EvalError::DivisionByZero(String::from("metric")))?
}
MetricFluentExpression::MultiOp(op, first, rest) => {
let mut total = self.metric(first, total_time)?;
for item in rest {
total = multi(*op, total, self.metric(item, total_time)?);
}
total
}
MetricFluentExpression::TotalTime => total_time,
MetricFluentExpression::IsViolated(_) => {
return Err(EvalError::Unsupported(Construct::Preferences));
}
};
finite(value, || String::from("metric"))
}
}
pub fn degree(exp: &FluentExpression, scope: &Scope, moving: &BTreeSet<Atom>) -> u32 {
match exp {
FluentExpression::Number(_) => 0,
FluentExpression::Function(head) => u32::from(moving.contains(&fluent_atom(head, scope))),
FluentExpression::Negative(inner) => degree(inner, scope, moving),
FluentExpression::BinaryOp(op, left, right) => {
let (left, right) = (degree(left, scope, moving), degree(right, scope, moving));
match op {
BinaryOp::Addition | BinaryOp::Subtraction => left.max(right),
BinaryOp::Multiplication => left.saturating_add(right),
BinaryOp::Division if right > 0 => u32::MAX,
BinaryOp::Division => left,
}
}
FluentExpression::MultiOp(op, first, rest) => {
let degrees = core::iter::once(&**first)
.chain(rest)
.map(|e| degree(e, scope, moving));
match op {
MultiOp::Addition => degrees.max().unwrap_or(0),
MultiOp::Multiplication => degrees.fold(0, u32::saturating_add),
}
}
}
}
pub fn compare(left: f64, right: f64, tolerance: f64) -> Ordering {
let scale = 1.0_f64.max(left.abs()).max(right.abs());
if (left - right).abs() <= tolerance * scale {
Ordering::Equal
} else if left < right {
Ordering::Less
} else {
Ordering::Greater
}
}
pub fn binary(op: BinaryOp, left: f64, right: f64) -> Option<f64> {
match op {
BinaryOp::Multiplication => Some(left * right),
BinaryOp::Addition => Some(left + right),
BinaryOp::Subtraction => Some(left - right),
BinaryOp::Division if right == 0.0 => None,
BinaryOp::Division => Some(left / right),
}
}
pub fn multi(op: MultiOp, total: f64, next: f64) -> f64 {
match op {
MultiOp::Addition => total + next,
MultiOp::Multiplication => total * next,
}
}
pub fn finite(value: f64, text: impl FnOnce() -> String) -> Result<f64, EvalError> {
if value.is_finite() {
Ok(value)
} else {
Err(EvalError::NonFinite(text()))
}
}
fn division(exp: &FluentExpression, scope: &Scope) -> EvalError {
EvalError::DivisionByZero(render::expression(exp, scope))
}
pub fn numeric_equality(equality: &EqualityAtomicFormula<Term>) -> Option<FluentComparison> {
let (Term::Function(left), Term::Function(right)) = (equality.first(), equality.second())
else {
return None;
};
Some(FluentComparison::new(
BinaryComparison::Equal,
FluentExpression::Function(head(left)),
FluentExpression::Function(head(right)),
))
}
fn head(term: &FunctionTerm) -> FunctionHead {
FunctionHead::WithTerms(term.symbol().clone(), term.terms().to_vec())
}
pub fn numeric_assignment(effect: &PrimitiveEffect) -> Option<(FunctionHead, FluentExpression)> {
let PrimitiveEffect::AssignObjectFluent(target, Some(Term::Function(source))) = effect else {
return None;
};
Some((head(target), FluentExpression::Function(head(source))))
}
pub fn fluent_atom(head: &FunctionHead, scope: &Scope) -> Atom {
match head {
FunctionHead::Simple(symbol) => Atom::lowered(lower(symbol), alloc::vec::Vec::new()),
FunctionHead::WithTerms(symbol, terms) => {
let arguments = terms.iter().map(|t| super::resolve(t, scope)).collect();
Atom::lowered(lower(symbol), arguments)
}
}
}