use alloc::format;
use alloc::vec;
use alloc::vec::Vec;
use planning_heuristics::LmCut;
use sas_plus::{Effect, Fact, Operator, State, Task, Variable};
use crate::heuristic::{FactPrices, fact_offsets};
#[derive(Clone, Debug)]
pub(super) struct Levels {
template: Task,
offsets: Vec<usize>,
defaults: Vec<usize>,
}
impl Levels {
pub(super) fn new(task: &Task) -> Self {
let offsets = fact_offsets(task);
let id = |f: &Fact| offsets[f.var] + usize::try_from(f.value).expect("value fits usize");
let binary = |f: &Fact| Fact::new(id(f), 1);
let facts = *offsets.last().expect("has a final entry");
let mut operators: Vec<Operator> = task
.operators
.iter()
.map(|op| Operator {
name: op.name.clone(),
pre: op.pre.iter().map(binary).collect(),
eff: op
.eff
.iter()
.map(|e| Effect {
conditions: e.conditions.iter().map(binary).collect(),
fact: binary(&e.fact),
})
.collect(),
cost: op.cost,
})
.collect();
operators.extend(task.axioms.iter().map(|axiom| Operator {
name: "axiom".into(),
pre: axiom.conditions.iter().map(binary).collect(),
eff: vec![Effect::new(binary(&axiom.head))],
cost: 0,
}));
let defaults = (0..task.num_variables())
.filter(|&v| task.variables[v].is_derived())
.map(|v| id(&Fact::new(v, task.initial.0[v])))
.collect();
let template = Task {
variables: (0..facts)
.map(|f| Variable::new(format!("f{f}"), 2))
.collect(),
operators,
initial: State(vec![0; facts]),
goal: task.goal.iter().map(binary).collect(),
axioms: vec![],
};
Self {
template,
offsets,
defaults,
}
}
fn seeded(&self, facts: &FactPrices<'_>) -> Task {
let mut task = self.template.clone();
for &f in &self.defaults {
task.initial.0[f] = 1;
}
let mut priced: Vec<(Option<usize>, u64, usize)> = Vec::new();
for var in 0..self.offsets.len() - 1 {
for f in self.offsets[var]..self.offsets[var + 1] {
match facts.prices[f] {
0 => task.initial.0[f] = 1,
u64::MAX => {}
price => priced.push((facts.leaf_of(var), price, f)),
}
}
}
priced.sort_unstable();
let mut start = 0;
while start < priced.len() {
let (factor, price, _) = priced[start];
let mut end = start;
while end < priced.len() && priced[end].0 == factor && priced[end].1 == price {
end += 1;
}
let first = priced.partition_point(|&(other, ..)| other < factor);
task.operators.push(purchase(&priced[first..end], price));
start = end;
}
task
}
}
fn purchase(facts: &[(Option<usize>, u64, usize)], price: u64) -> Operator {
Operator {
name: "purchase".into(),
pre: vec![],
eff: facts
.iter()
.map(|&(_, _, f)| Effect::new(Fact::new(f, 1)))
.collect(),
cost: u32::try_from(price).unwrap_or(u32::MAX),
}
}
impl Levels {
pub(super) fn estimate(&self, facts: &FactPrices<'_>) -> Option<u64> {
let task = self.seeded(facts);
LmCut::new(&task).value(&task.initial)
}
}