use alloc::borrow::Cow;
use alloc::vec::Vec;
use sas_plus::{OpId, State, Task};
use crate::relaxation::Workspace;
use crate::{Combine, Heuristic, Relaxation, RelaxedPlan};
macro_rules! relaxation_heuristic {
($(#[$doc:meta])* $name:ident, $what:literal) => {
$(#[$doc])*
#[derive(Clone, Debug)]
pub struct $name<'r> {
relaxation: Cow<'r, Relaxation>,
workspace: Workspace,
}
impl $name<'static> {
#[doc = concat!("Builds ", $what, " for `task`, owning its relaxation.")]
#[must_use]
pub fn new(task: &Task) -> Self {
Self {
relaxation: Cow::Owned(Relaxation::new(task)),
workspace: Workspace::default(),
}
}
}
impl<'r> $name<'r> {
#[doc = concat!("Builds ", $what, " over a shared `relaxation`. Cheap: only the")]
#[must_use]
pub fn with_relaxation(relaxation: &'r Relaxation) -> Self {
Self {
relaxation: Cow::Borrowed(relaxation),
workspace: Workspace::default(),
}
}
#[must_use]
pub fn relaxation(&self) -> &Relaxation {
&self.relaxation
}
}
impl Heuristic<State> for $name<'_> {
fn estimate(&mut self, state: &State) -> Option<u32> {
self.value(state).map(|v| u32::try_from(v).unwrap_or(u32::MAX))
}
}
};
}
relaxation_heuristic!(
HMax,
"`h_max`"
);
relaxation_heuristic!(
HAdd,
"`h_add`"
);
relaxation_heuristic!(
HFf,
"`h_FF`"
);
impl HMax<'_> {
#[must_use]
pub fn value(&mut self, state: &State) -> Option<u64> {
self.relaxation
.goal_cost_in(state, Combine::Max, &mut self.workspace)
}
}
impl HAdd<'_> {
#[must_use]
pub fn value(&mut self, state: &State) -> Option<u64> {
self.relaxation
.goal_cost_in(state, Combine::Add, &mut self.workspace)
}
}
impl HFf<'_> {
#[must_use]
pub fn value(&mut self, state: &State) -> Option<u64> {
self.relaxation.relaxed_plan_in(state, &mut self.workspace)
}
#[must_use]
pub fn relaxed_plan(&mut self, state: &State) -> Option<RelaxedPlan> {
let cost = self
.relaxation
.relaxed_plan_in(state, &mut self.workspace)?;
Some(RelaxedPlan::new(self.workspace.plan.clone(), cost))
}
#[must_use]
pub fn preferred_operators(&mut self, state: &State) -> Option<Vec<OpId>> {
self.relaxation
.relaxed_plan_in(state, &mut self.workspace)?;
Some(self.relaxation.applicable_once(&self.workspace.plan, state))
}
}