mod continuous;
mod mutex;
mod pddl_plus;
mod timed;
use alloc::boxed::Box;
use alloc::collections::BTreeSet;
use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;
use core::cell::RefCell;
use pddl::{
ActionDefinition, AtomicFormula, DurativeActionDefinition, InitElement, Literal, Problem,
};
use super::{bind_parameters, finish, step_ref, stopped, Stop};
use crate::atom::{lower, Atom};
use crate::effects::Changes;
use crate::eval::{Evaluator, Observer, Scope};
use crate::model::Model;
use crate::plan::{Plan, PlanStep};
use crate::report::{Report, StepRef, StepTrace, ViolationKind};
use crate::state::State;
use continuous::{Flow, Interval, Rates};
use mutex::Footprint;
use pddl_plus::Dynamics;
use timed::{Collector, Memo, Moment};
pub use crate::model::SAME_TIME;
fn rounding_slack(time: f64) -> f64 {
SAME_TIME.max(time.abs() * 8.0 * f64::EPSILON)
}
pub struct Timeline<'v, 'a> {
pub model: &'v Model<'a>,
pub problem: &'a Problem,
pub tolerance: f64,
pub epsilon: f64,
pub duration_tolerance: f64,
}
struct Instance<'v> {
action: &'v DurativeActionDefinition,
scope: Scope,
duration: f64,
step: StepRef,
memo: Memo,
flows: Vec<Flow<'v>>,
}
struct Span {
step: StepRef,
start: f64,
end: f64,
}
impl Span {
fn overlapping(&self, earlier: &[Span]) -> Option<usize> {
earlier
.iter()
.find(|other| {
other.step.action.eq_ignore_ascii_case(&self.step.action)
&& self.start < other.end - SAME_TIME
&& other.start < self.end - SAME_TIME
})
.map(|other| other.step.number)
}
}
enum Kind<'v> {
Instant(&'v ActionDefinition, Scope),
Start(usize),
End(usize),
Literal(Atom, bool),
}
struct Event<'v> {
time: f64,
kind: Kind<'v>,
step: Option<StepRef>,
label: String,
}
struct Past {
time: f64,
label: String,
footprint: Footprint,
owner: Option<usize>,
}
type Failure = Box<(Option<StepRef>, Stop)>;
fn failure(step: Option<StepRef>, reason: Stop) -> Failure {
Box::new((step, reason))
}
impl<'v> Timeline<'v, '_> {
pub fn run(&self, initial: &State, plan: &Plan) -> Report {
let (mut instances, mut events) = match self.schedule(plan) {
Ok(scheduled) => scheduled,
Err(failed) => {
let (step, reason) = *failed;
return stopped(reason, step, String::from("plan"), Vec::new());
}
};
let makespan = events.iter().map(|event| event.time).fold(0.0, f64::max);
events.extend(self.timed_literals(makespan));
events.sort_by(|a, b| a.time.total_cmp(&b.time));
let dynamics = Dynamics::new(&self.evaluator(initial, None));
match self.happenings(initial, &mut instances, &events, &dynamics) {
Ok((state, trace)) => {
let evaluator = self.evaluator(&state, None);
finish(&evaluator, self.problem, makespan, trace)
}
Err((failed, trace)) => {
let (step, reason) = *failed;
let location = step.as_ref().map_or_else(
|| String::from("timeline"),
|s| format!("step {}", s.number),
);
stopped(reason, step, location, trace)
}
}
}
const fn evaluator<'s>(
&'s self,
state: &'s State,
observer: Option<&'s RefCell<Observer>>,
) -> Evaluator<'s, 'v> {
Evaluator {
model: self.model,
state,
tolerance: self.tolerance,
observer,
}
}
fn schedule(&self, plan: &Plan) -> Result<(Vec<Instance<'v>>, Vec<Event<'v>>), Failure> {
let timed = plan.steps().iter().any(|step| step.time().is_some());
let mut instances = Vec::new();
let mut events = Vec::new();
let mut spans: Vec<Span> = Vec::new();
for (index, step) in plan.steps().iter().enumerate() {
let at = step_ref(index, step);
let fail = |kind| Err(failure(Some(at.clone()), Stop::Invalid(kind)));
let time = match step.time() {
Some(time) if !(time.is_finite() && time >= 0.0) => {
return fail(ViolationKind::InvalidTime(time));
}
Some(time) => time,
None if timed => return fail(ViolationKind::MissingTimestamp),
#[expect(
clippy::cast_precision_loss,
reason = "plans of more than 2^53 steps do not fit in memory"
)]
None => (index + 1) as f64,
};
if let Some(action) = self.model.durative.get(step.action()) {
let instance = self.instance(action, step, &at)?;
let label = at.action.clone();
let end = time + instance.duration;
if !end.is_finite() {
return fail(ViolationKind::InvalidTime(end));
}
if end - time <= SAME_TIME {
return fail(ViolationKind::NonPositiveDuration(end - time));
}
let span = Span {
step: at.clone(),
start: time,
end,
};
if let Some(other) = span.overlapping(&spans) {
return fail(ViolationKind::SelfOverlap { other });
}
spans.push(span);
let number = instances.len();
events.push(event(
time,
Kind::Start(number),
&at,
format!("start {label}"),
));
events.push(event(end, Kind::End(number), &at, format!("end {label}")));
instances.push(instance);
} else {
let (action, scope) =
super::bind(self.model, step).map_err(|s| failure(Some(at.clone()), s))?;
if step.duration().is_some() {
return fail(ViolationKind::UnexpectedDuration);
}
let label = at.action.clone();
events.push(event(time, Kind::Instant(action, scope), &at, label));
}
}
Ok((instances, events))
}
fn instance(
&self,
action: &'v DurativeActionDefinition,
step: &PlanStep,
at: &StepRef,
) -> Result<Instance<'v>, Failure> {
let fail = |kind| Err(failure(Some(at.clone()), Stop::Invalid(kind)));
let scope = bind_parameters(self.model, action.parameters(), step)
.map_err(|reason| failure(Some(at.clone()), reason))?;
let Some(duration) = step.duration() else {
return fail(ViolationKind::MissingDuration);
};
if !(duration > SAME_TIME && duration.is_finite()) {
return fail(ViolationKind::NonPositiveDuration(duration));
}
Ok(Instance {
action,
scope,
duration,
step: at.clone(),
memo: Memo::new(),
flows: Vec::new(),
})
}
fn timed_literals(&self, makespan: f64) -> Vec<Event<'v>> {
let mut events = Vec::new();
for element in self.problem.init().iter() {
let InitElement::At(time, literal) = element else {
continue;
};
let (formula, positive) = match literal {
Literal::AtomicFormula(formula) => (formula, true),
Literal::NotAtomicFormula(formula) => (formula, false),
};
let AtomicFormula::Predicate(predicate) = formula else {
continue;
};
let time = **time;
if time > makespan + SAME_TIME {
continue;
}
let arguments = predicate.values().iter().map(|name| lower(name)).collect();
let atom = Atom::lowered(lower(predicate.predicate()), arguments);
let label = if positive {
format!("timed literal {atom} at {time}")
} else {
format!("timed literal (not {atom}) at {time}")
};
events.push(Event {
time,
kind: Kind::Literal(atom, positive),
step: None,
label,
});
}
events
}
fn happenings(
&self,
initial: &State,
instances: &mut [Instance<'v>],
events: &[Event<'v>],
dynamics: &Dynamics<'v>,
) -> Result<(State, Vec<StepTrace>), (Failure, Vec<StepTrace>)> {
let mut state = initial.clone();
let mut trace = Vec::new();
if let Err(failure) = self.cascade(dynamics, &mut state, 0.0, &mut trace) {
return Err((failure, trace));
}
let mut active = BTreeSet::new();
let mut recent: Vec<Past> = Vec::new();
let mut clock = 0.0;
let mut rest = events;
while let Some(first) = rest.first() {
let size = rest
.iter()
.take_while(|event| event.time - first.time <= SAME_TIME)
.count()
.max(1);
let (happening, later) = rest.split_at(size);
rest = later;
if first.time - clock > SAME_TIME {
let next = self.interval(
dynamics,
&state,
(instances, &active, &ends(happening)),
(clock, first.time),
&mut trace,
);
state = match next {
Ok(next) => next,
Err(failure) => return Err((failure, trace)),
};
clock = first.time;
}
let slack = rounding_slack(first.time);
recent.retain(|past| first.time - past.time < self.epsilon - slack);
match self.happen(&mut state, instances, happening, &mut recent) {
Ok(step) => trace.push(step),
Err(failure) => return Err((failure, trace)),
}
if let Err(failure) = self.cascade(dynamics, &mut state, first.time, &mut trace) {
return Err((failure, trace));
}
for event in happening {
match event.kind {
Kind::Start(index) => {
active.insert(index);
}
Kind::End(index) => {
active.remove(&index);
}
Kind::Instant(..) | Kind::Literal(..) => {}
}
}
}
Ok((state, trace))
}
fn interval(
&self,
dynamics: &Dynamics<'v>,
state: &State,
(instances, active, ending): (&[Instance<'v>], &BTreeSet<usize>, &BTreeSet<usize>),
(start, end): (f64, f64),
trace: &mut Vec<StepTrace>,
) -> Result<State, Failure> {
let running: Vec<&Instance<'v>> = active.iter().filter_map(|&i| instances.get(i)).collect();
let through: Vec<&Instance<'v>> = active
.difference(ending)
.filter_map(|&i| instances.get(i))
.collect();
if !dynamics.is_empty() {
let running = (running.as_slice(), through.as_slice());
return self.hybrid_interval(dynamics, state, running, start, end, trace);
}
let Some(first) = running.first() else {
return Ok(state.clone());
};
let flows: Vec<&Flow<'v>> = running.iter().flat_map(|i| &i.flows).collect();
let stop = |error| failure(Some(first.step.clone()), Stop::from(error));
let rates = continuous::rates(&self.evaluator(state, None), &flows).map_err(stop)?;
self.check_invariants(&running, state, &rates, start, end)?;
let next = continuous::advance(state, &rates, end - start).map_err(stop)?;
self.check_invariants_at(&through, &next, end)?;
Ok(next)
}
fn check_invariants(
&self,
running: &[&Instance<'v>],
state: &State,
rates: &Rates,
start: f64,
end: f64,
) -> Result<(), Failure> {
let interval = Interval {
start,
end,
state,
rates,
};
for instance in running {
let Some(invariant) = instance.action.condition() else {
continue;
};
let at = || Some(instance.step.clone());
let mut scope = instance.scope.clone();
match interval.check(self.model, self.tolerance, invariant, &mut scope) {
Ok(None) => {}
Ok(Some((time, unmet))) => {
let kind = ViolationKind::InvariantViolated { time, unmet };
return Err(failure(at(), Stop::Invalid(kind)));
}
Err(error) => return Err(failure(at(), Stop::from(error))),
}
}
Ok(())
}
fn check_invariants_at(
&self,
running: &[&Instance<'v>],
state: &State,
time: f64,
) -> Result<(), Failure> {
let evaluator = self.evaluator(state, None);
for instance in running {
let Some(invariant) = instance.action.condition() else {
continue;
};
let at = || Some(instance.step.clone());
let mut scope = instance.scope.clone();
match timed::condition(&evaluator, invariant, &mut scope, Moment::Over) {
Ok(None) => {}
Ok(Some(unmet)) => {
let kind = ViolationKind::InvariantViolated { time, unmet };
return Err(failure(at(), Stop::Invalid(kind)));
}
Err(error) => return Err(failure(at(), Stop::from(error))),
}
}
Ok(())
}
fn happen(
&self,
state: &mut State,
instances: &mut [Instance<'v>],
happening: &[Event<'v>],
recent: &mut Vec<Past>,
) -> Result<StepTrace, Failure> {
let mut merged = Changes::default();
let mut current: Vec<Past> = Vec::new();
for event in happening {
let fail = |reason| failure(event.step.clone(), reason);
let observer = RefCell::new(Observer::default());
let evaluator = self.evaluator(state, Some(&observer));
let result = run_event(&evaluator, event, instances, self.duration_tolerance);
let footprint = Footprint::new(
&observer.borrow(),
result.as_ref().unwrap_or(&Changes::default()),
);
let clash = recent.iter().chain(¤t).find(|past| {
(past.owner.is_none() || past.owner != owner(event))
&& past.footprint.interferes(&footprint)
});
if let Some(past) = clash {
let kind = ViolationKind::Interference {
event: event.label.clone(),
other: past.label.clone(),
time: event.time,
separation: event.time - past.time,
};
return Err(fail(Stop::Invalid(kind)));
}
merged.merge(result.map_err(fail)?);
current.push(Past {
time: event.time,
label: event.label.clone(),
footprint,
owner: owner(event),
});
}
let first_step = happening.first().and_then(|event| event.step.clone());
let mut step = merged
.apply(state)
.map_err(|error| failure(first_step, Stop::from(error)))?;
step.time = happening.first().map(|event| event.time);
step.events = happening.iter().map(|event| event.label.clone()).collect();
recent.extend(current);
Ok(step)
}
}
fn ends(happening: &[Event<'_>]) -> BTreeSet<usize> {
happening
.iter()
.filter_map(|event| match event.kind {
Kind::End(index) => Some(index),
Kind::Start(_) | Kind::Instant(..) | Kind::Literal(..) => None,
})
.collect()
}
const fn owner(event: &Event<'_>) -> Option<usize> {
match event.kind {
Kind::Start(index) | Kind::End(index) => Some(index),
Kind::Instant(..) | Kind::Literal(..) => None,
}
}
fn event<'v>(time: f64, kind: Kind<'v>, step: &StepRef, label: String) -> Event<'v> {
Event {
time,
kind,
step: Some(step.clone()),
label,
}
}
fn run_event<'v>(
evaluator: &Evaluator<'_, '_>,
event: &Event<'v>,
instances: &mut [Instance<'v>],
duration_tolerance: f64,
) -> Result<Changes, Stop> {
let mut changes = Changes::default();
match &event.kind {
Kind::Instant(action, scope) => {
let mut scope = scope.clone();
if let Some(unmet) = evaluator.preconditions(action.precondition(), &mut scope)? {
return Err(Stop::Invalid(ViolationKind::PreconditionUnsatisfied(unmet)));
}
if let Some(effects) = action.effect() {
changes.collect(evaluator, effects, &mut scope)?;
}
}
Kind::Start(index) | Kind::End(index) => {
let moment = if matches!(event.kind, Kind::Start(_)) {
Moment::Start
} else {
Moment::End
};
if let Some(instance) = instances.get_mut(*index) {
durative_event(
evaluator,
instance,
moment,
duration_tolerance,
&mut changes,
)?;
}
}
Kind::Literal(atom, true) => {
changes.add.insert(atom.clone());
}
Kind::Literal(atom, false) => {
changes.delete.insert(atom.clone());
}
}
Ok(changes)
}
fn durative_event(
evaluator: &Evaluator<'_, '_>,
instance: &mut Instance<'_>,
moment: Moment,
duration_tolerance: f64,
changes: &mut Changes,
) -> Result<(), Stop> {
let action = instance.action;
let mut scope = instance.scope.clone();
if let Some(constraint) = action.duration() {
let unmet = timed::duration(
evaluator,
constraint,
&scope,
instance.duration,
duration_tolerance,
moment,
)?;
if let Some(unmet) = unmet {
return Err(Stop::Invalid(ViolationKind::DurationConstraint(unmet)));
}
}
if let Some(condition) = action.condition() {
if let Some(unmet) = timed::condition(evaluator, condition, &mut scope, moment)? {
let kind = match moment {
Moment::End => ViolationKind::EndConditionUnsatisfied(unmet),
Moment::Start | Moment::Over => ViolationKind::StartConditionUnsatisfied(unmet),
};
return Err(Stop::Invalid(kind));
}
}
let Some(effect) = action.effect() else {
return Ok(());
};
let collector = Collector {
evaluator,
moment,
duration: instance.duration,
};
collector.collect(effect, &mut scope, &mut instance.memo, changes)?;
if moment == Moment::Start {
continuous::flows(evaluator, effect, &mut scope, &mut instance.flows)?;
}
Ok(())
}