pub(crate) mod contexts;
use alloc::borrow::Cow;
use alloc::collections::BinaryHeap;
use alloc::vec::Vec;
use core::cmp::Reverse;
use sas_plus::{OpId, State, Task};
use crate::{Heuristic, Relaxation};
const UNREACHED: u64 = u64::MAX;
const START: usize = usize::MAX;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ActionLandmark {
ops: Vec<OpId>,
cost: u64,
}
impl ActionLandmark {
#[must_use]
pub fn ops(&self) -> &[OpId] {
&self.ops
}
#[must_use]
pub fn cost(&self) -> u64 {
self.cost
}
}
#[derive(Clone, Debug)]
pub struct LmCut<'r> {
relaxation: Cow<'r, Relaxation>,
costs: Vec<u64>,
op_of: Option<Vec<OpId>>,
exact: bool,
head_starts: Vec<usize>,
by_head: Vec<u32>,
num_task_ops: usize,
work: Work,
}
#[derive(Clone, Debug, Default)]
struct Work {
remaining: Vec<u64>,
seed: Vec<u64>,
cut_seeds: Vec<usize>,
hmax: Vec<u64>,
missing: Vec<u32>,
pcf: Vec<usize>,
done: Vec<bool>,
heap: BinaryHeap<Reverse<(u64, usize)>>,
in_zone: Vec<bool>,
in_start: Vec<bool>,
stack: Vec<usize>,
in_cut: Vec<bool>,
cut: Vec<OpId>,
}
const MAX_CONTEXTS: usize = 64;
impl LmCut<'static> {
#[must_use]
pub fn new(task: &Task) -> Self {
match contexts::split(task, MAX_CONTEXTS) {
Some(split) => {
let mut h = Self::from_cow(Cow::Owned(Relaxation::new(&split.task)));
h.op_of = Some(split.op_of);
h.num_task_ops = task.operators.len();
h
}
None => Self::from_cow(Cow::Owned(Relaxation::new(task))),
}
}
}
impl LmCut<'static> {
pub(crate) fn unsplit(relaxation: Relaxation) -> Self {
Self::from_cow(Cow::Owned(relaxation))
}
}
impl<'r> LmCut<'r> {
#[must_use]
pub fn with_relaxation(relaxation: &'r Relaxation) -> Self {
Self::from_cow(Cow::Borrowed(relaxation))
}
fn from_cow(relaxation: Cow<'r, Relaxation>) -> Self {
let costs = (0..relaxation.num_operators())
.map(|op| relaxation.op_rules(op).first().map_or(0, |r| r.cost))
.collect();
let (head_starts, by_head) = head_index(&relaxation);
let exact = (0..relaxation.num_operators()).all(|op| {
let rules = relaxation.op_rules(op);
rules.iter().all(|r| r.conditions == rules[0].conditions)
});
Self {
num_task_ops: relaxation.num_operators(),
relaxation,
costs,
op_of: None,
exact,
head_starts,
by_head,
work: Work::default(),
}
}
#[must_use]
pub fn value(&mut self, state: &State) -> Option<u64> {
self.load_state(state);
self.work.remaining.clone_from(&self.costs);
self.cut_sum()
}
#[must_use]
pub fn value_seeded(&mut self, seeds: &[Option<u64>], costs: Option<&[u64]>) -> Option<u64> {
self.load_seeds(seeds);
self.load_costs(costs);
self.cut_sum()
}
#[must_use]
pub fn h_max_seeded(&mut self, seeds: &[Option<u64>], costs: Option<&[u64]>) -> Option<u64> {
self.load_seeds(seeds);
self.load_costs(costs);
self.goal_h_max()
}
pub fn seed_state(&self, state: &State, seeds: &mut Vec<Option<u64>>) {
seeds.clear();
seeds.resize(self.relaxation.num_facts(), None);
for fact in self.relaxation.state_facts(state) {
seeds[fact as usize] = Some(0);
}
}
#[must_use]
pub fn relaxation(&self) -> &Relaxation {
&self.relaxation
}
pub(crate) fn h_max_under(&mut self, state: &State, costs: &[u64]) -> Option<u64> {
self.load_state(state);
self.work.remaining.clear();
self.work.remaining.extend_from_slice(costs);
self.goal_h_max()
}
fn cut_sum(&mut self) -> Option<u64> {
let mut total = 0_u64;
let h_max = self.run(|_, cost| total = total.saturating_add(cost))?;
debug_assert!(!self.exact || total >= h_max, "LM-cut dominates h_max");
Some(total.max(h_max))
}
fn goal_h_max(&mut self) -> Option<u64> {
if self.relaxation.goal_facts().is_empty() {
return Some(0);
}
let goal = self.hmax()?;
Some(self.work.hmax[goal])
}
fn load_state(&mut self, state: &State) {
let seed = &mut self.work.seed;
seed.clear();
seed.resize(self.relaxation.num_facts(), UNREACHED);
for fact in self.relaxation.state_facts(state) {
seed[fact as usize] = 0;
}
}
fn load_seeds(&mut self, seeds: &[Option<u64>]) {
assert_eq!(
seeds.len(),
self.relaxation.num_facts(),
"one seed per fact"
);
self.work.seed.clear();
self.work
.seed
.extend(seeds.iter().map(|s| s.unwrap_or(UNREACHED)));
}
fn load_costs(&mut self, costs: Option<&[u64]>) {
let Some(costs) = costs else {
self.work.remaining.clone_from(&self.costs);
return;
};
assert_eq!(costs.len(), self.num_task_ops, "one cost per operator");
let remaining = &mut self.work.remaining;
remaining.clear();
match &self.op_of {
Some(op_of) => remaining.extend(op_of.iter().map(|&op| costs[op])),
None => remaining.extend_from_slice(costs),
}
}
pub(crate) fn costs(&self) -> &[u64] {
&self.costs
}
#[must_use]
pub fn is_exact(&self) -> bool {
self.exact
}
#[must_use]
pub fn landmarks(&mut self, state: &State) -> Option<Vec<ActionLandmark>> {
let mut found = Vec::new();
let op_of = self.op_of.take();
self.load_state(state);
self.work.remaining.clone_from(&self.costs);
let done = self.run(|ops, cost| {
let mut ops: Vec<OpId> = match &op_of {
Some(op_of) => ops.iter().map(|&op| op_of[op]).collect(),
None => ops.to_vec(),
};
ops.sort_unstable();
ops.dedup();
found.push(ActionLandmark { ops, cost });
});
self.op_of = op_of;
done?;
Some(found)
}
fn run(&mut self, mut found: impl FnMut(&[OpId], u64)) -> Option<u64> {
if self.relaxation.goal_facts().is_empty() {
return Some(0);
}
let mut goal = self.hmax()?;
let h_max = self.work.hmax[goal];
while self.work.hmax[goal] > 0 {
self.goal_zone(goal);
self.start_side();
let cost = self.charge_cut();
found(&self.work.cut, cost);
goal = self.hmax().expect("costs only shrink");
}
Some(h_max)
}
fn hmax(&mut self) -> Option<usize> {
let relaxation = &*self.relaxation;
let work = &mut self.work;
work.reset(relaxation);
for &fact in relaxation.free_facts() {
work.offer(fact as usize, 0);
}
for fact in 0..work.seed.len() {
if work.seed[fact] != UNREACHED {
work.offer(fact, work.seed[fact]);
}
}
for &r in relaxation.unconditioned() {
let rule = &relaxation.rules()[r as usize];
work.pcf[r as usize] = START;
work.offer(rule.head, work.rule_cost(rule));
}
while let Some(Reverse((value, fact))) = work.heap.pop() {
if core::mem::replace(&mut work.done[fact], true) {
continue;
}
for &r in relaxation.watchers(fact) {
let r = r as usize;
work.missing[r] -= 1;
if work.missing[r] == 0 {
work.pcf[r] = fact;
let rule = &relaxation.rules()[r];
work.offer(rule.head, value + work.rule_cost(rule));
}
}
}
argmax_goal(relaxation, &work.hmax)
}
fn goal_zone(&mut self, goal: usize) {
let relaxation = &*self.relaxation;
let work = &mut self.work;
work.in_zone.fill(false);
work.in_zone[goal] = true;
work.stack.push(goal);
while let Some(fact) = work.stack.pop() {
for &r in &self.by_head[self.head_starts[fact]..self.head_starts[fact + 1]] {
let r = r as usize;
let rule = &relaxation.rules()[r];
if work.missing[r] != 0 || work.rule_cost(rule) != 0 {
continue;
}
let pcf = work.pcf[r];
debug_assert_ne!(pcf, START, "zone facts have positive h_max");
if !core::mem::replace(&mut work.in_zone[pcf], true) {
work.stack.push(pcf);
}
}
}
}
fn start_side(&mut self) {
let relaxation = &*self.relaxation;
let work = &mut self.work;
work.in_start.fill(false);
work.cut.clear();
work.cut_seeds.clear();
for &fact in relaxation.free_facts() {
work.enter_start(fact as usize);
}
for fact in 0..work.seed.len() {
if work.seed[fact] == UNREACHED {
continue;
}
if work.in_zone[fact] {
work.cut_seeds.push(fact);
} else {
work.enter_start(fact);
}
}
for &r in relaxation.unconditioned() {
work.follow(relaxation, r as usize);
}
while let Some(fact) = work.stack.pop() {
for &r in relaxation.watchers(fact) {
let r = r as usize;
if work.missing[r] == 0 && work.pcf[r] == fact {
work.follow(relaxation, r);
}
}
}
}
fn charge_cut(&mut self) -> u64 {
let work = &mut self.work;
let cost = work
.cut
.iter()
.map(|&op| work.remaining[op])
.chain(work.cut_seeds.iter().map(|&fact| work.seed[fact]))
.min()
.expect("a goal of positive h_max has a non-empty cut");
debug_assert!(cost > 0, "cut rules have positive cost");
for &op in &work.cut {
work.remaining[op] -= cost;
work.in_cut[op] = false;
}
for &fact in &work.cut_seeds {
work.seed[fact] -= cost;
}
cost
}
}
impl Work {
fn reset(&mut self, relaxation: &Relaxation) {
let facts = relaxation.num_facts();
let rules = relaxation.rules();
self.hmax.clear();
self.hmax.resize(facts, UNREACHED);
self.done.clear();
self.done.resize(facts, false);
self.in_zone.resize(facts, false);
self.in_start.resize(facts, false);
self.in_cut.resize(relaxation.num_operators(), false);
self.pcf.resize(rules.len(), START);
self.missing.clear();
self.missing
.extend(rules.iter().map(|r| to_u32(r.conditions.len())));
self.heap.clear();
self.stack.clear();
}
fn rule_cost(&self, rule: &crate::relaxation::Rule) -> u64 {
rule.op.map_or(0, |op| self.remaining[op])
}
fn offer(&mut self, fact: usize, value: u64) {
if value < self.hmax[fact] {
self.hmax[fact] = value;
self.heap.push(Reverse((value, fact)));
}
}
fn enter_start(&mut self, fact: usize) {
if !self.in_zone[fact] && !core::mem::replace(&mut self.in_start[fact], true) {
self.stack.push(fact);
}
}
fn follow(&mut self, relaxation: &Relaxation, r: usize) {
let rule = &relaxation.rules()[r];
if !self.in_zone[rule.head] {
self.enter_start(rule.head);
return;
}
let op = rule
.op
.expect("an axiom into the goal zone has its precondition choice in the zone");
if !core::mem::replace(&mut self.in_cut[op], true) {
self.cut.push(op);
}
}
}
impl Heuristic<State> for LmCut<'_> {
fn estimate(&mut self, state: &State) -> Option<u32> {
self.value(state)
.map(|v| u32::try_from(v).unwrap_or(u32::MAX))
}
}
fn argmax_goal(relaxation: &Relaxation, hmax: &[u64]) -> Option<usize> {
let goals = relaxation.goal_facts();
if goals.iter().any(|&g| hmax[g] == UNREACHED) {
return None;
}
goals.iter().copied().max_by_key(|&g| hmax[g])
}
fn head_index(relaxation: &Relaxation) -> (Vec<usize>, Vec<u32>) {
let mut starts = alloc::vec![0; relaxation.num_facts() + 1];
for rule in relaxation.rules() {
starts[rule.head + 1] += 1;
}
for f in 0..relaxation.num_facts() {
starts[f + 1] += starts[f];
}
let mut next = starts.clone();
let mut rules = alloc::vec![0; relaxation.rules().len()];
for (r, rule) in relaxation.rules().iter().enumerate() {
rules[next[rule.head]] = to_u32(r);
next[rule.head] += 1;
}
(starts, rules)
}
fn to_u32(n: usize) -> u32 {
u32::try_from(n).expect("fewer than 2^32 rules and conditions")
}