mod sampling;
use alloc::vec::Vec;
use sas_plus::{Fact, OpId, State, Task};
use crate::math::ln;
use crate::rng::SplitMix64;
use crate::{PathHeuristic, Relaxation};
use sampling::Graph;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct IntentionParams {
pub samples: usize,
pub seed: u64,
}
impl Default for IntentionParams {
fn default() -> Self {
Self {
samples: 100,
seed: 0,
}
}
}
#[derive(Clone, Debug)]
pub struct GoalIntention {
relaxation: Relaxation,
goal: Vec<f64>,
not_goal: Vec<f64>,
goal_samples: Vec<Vec<usize>>,
not_goal_samples: Vec<Vec<usize>>,
}
impl GoalIntention {
#[must_use]
pub fn new(task: &Task, params: &IntentionParams) -> Self {
Self::from_state(task, &task.initial_state(), params)
}
#[must_use]
pub fn from_state(task: &Task, state: &State, params: &IntentionParams) -> Self {
let relaxation = Relaxation::new(task);
let graph = Graph::new(&relaxation, state);
let open = |f: usize| graph.is_reachable(f) && !graph.is_initial(f);
let goals: Vec<usize> = relaxation
.goal_facts()
.iter()
.copied()
.filter(|&g| open(g))
.collect();
let others: Vec<usize> = (0..relaxation.num_facts())
.filter(|&f| open(f) && relaxation.goal_facts().binary_search(&f).is_err())
.collect();
let reached = relaxation
.goal_facts()
.iter()
.all(|&g| graph.is_reachable(g));
let mut rng = SplitMix64(params.seed);
let goal_samples = if reached {
graph.sample(&goals, params.samples, &mut rng)
} else {
Vec::new()
};
let not_goal_samples = graph.sample(&others, params.samples, &mut rng);
let goal = fact_probabilities(&relaxation, &graph, &goal_samples);
let not_goal = fact_probabilities(&relaxation, &graph, ¬_goal_samples);
let ops = relaxation.num_operators();
let operators_only = |samples: Vec<Vec<usize>>| -> Vec<Vec<usize>> {
samples
.into_iter()
.map(|s| s.into_iter().filter(|&x| x < ops).collect())
.collect()
};
Self {
goal,
not_goal,
goal_samples: operators_only(goal_samples),
not_goal_samples: operators_only(not_goal_samples),
relaxation,
}
}
#[must_use]
pub fn probability(&self, fact: Fact) -> f64 {
self.goal[self.relaxation.fact_id(fact)]
}
#[must_use]
pub fn not_goal_probability(&self, fact: Fact) -> f64 {
self.not_goal[self.relaxation.fact_id(fact)]
}
#[must_use]
pub fn samples(&self) -> &[Vec<OpId>] {
&self.goal_samples
}
#[must_use]
pub fn not_goal_samples(&self) -> &[Vec<OpId>] {
&self.not_goal_samples
}
pub fn likelihood_cost(&self, observed: impl IntoIterator<Item = Fact>) -> f64 {
let mut cost = Cost::default();
for f in observed {
cost.add(self, self.relaxation.fact_id(f));
}
cost.likelihood()
}
pub fn posterior_cost(&self, observed: impl IntoIterator<Item = Fact>) -> f64 {
let mut cost = Cost::default();
for f in observed {
cost.add(self, self.relaxation.fact_id(f));
}
cost.posterior()
}
#[must_use]
pub fn tracker(&self, kind: IntentionKind, restart: bool) -> IntentionTracker<'_> {
IntentionTracker {
intention: self,
kind,
restart,
}
}
fn goal_count(&self, state: &State) -> usize {
let goals = self.relaxation.goal_facts();
goals.len()
- self
.relaxation
.state_facts(state)
.filter(|&f| goals.binary_search(&(f as usize)).is_ok())
.count()
}
}
fn fact_probabilities(
relaxation: &Relaxation,
graph: &Graph<'_>,
samples: &[Vec<usize>],
) -> Vec<f64> {
let mut contained = alloc::vec![0_u32; graph.num_sources()];
for s in samples {
for &a in s {
contained[a] += 1;
}
}
let n = f64::from(
u32::try_from(samples.len())
.expect("fewer than 2^32 samples")
.max(1),
);
let mut achievers: Vec<(usize, usize)> = (0..relaxation.rules().len())
.map(|r| (relaxation.rules()[r].head, graph.source(r)))
.collect();
achievers.sort_unstable();
achievers.dedup();
let mut none = alloc::vec![1.0_f64; relaxation.num_facts()];
for (head, a) in achievers {
none[head] *= 1.0 - f64::from(contained[a]) / n;
}
none.into_iter().map(|p| 1.0 - p).collect()
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
struct Cost {
likelihood: f64,
not_goal: f64,
impossible: u32,
certain: u32,
}
impl Cost {
fn add(&mut self, intention: &GoalIntention, f: usize) {
let (p_goal, p_not_goal) = (intention.goal[f], intention.not_goal[f]);
if p_goal == 0.0 {
self.impossible += 1;
return;
}
self.likelihood -= ln(p_goal);
if p_not_goal == 0.0 {
self.certain += 1;
} else {
self.not_goal += ln(p_not_goal);
}
}
fn likelihood(&self) -> f64 {
if self.impossible > 0 {
f64::INFINITY
} else {
self.likelihood
}
}
fn posterior(&self) -> f64 {
if self.impossible > 0 {
f64::INFINITY
} else if self.certain > 0 {
f64::NEG_INFINITY
} else {
self.likelihood + self.not_goal
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum IntentionKind {
Likelihood,
Posterior,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Observation {
observed: Vec<u64>,
cost: Cost,
best_goal_count: usize,
}
#[derive(Clone, Copy, Debug)]
pub struct IntentionTracker<'g> {
intention: &'g GoalIntention,
kind: IntentionKind,
restart: bool,
}
impl IntentionTracker<'_> {
fn value(&self, info: &Observation) -> f64 {
match self.kind {
IntentionKind::Likelihood => info.cost.likelihood(),
IntentionKind::Posterior => info.cost.posterior(),
}
}
}
impl PathHeuristic<State, OpId, f64> for IntentionTracker<'_> {
type Info = Observation;
fn root(&mut self, state: &State) -> Observation {
Observation {
observed: alloc::vec![0; self.intention.relaxation.num_facts().div_ceil(64)],
cost: Cost::default(),
best_goal_count: self.intention.goal_count(state),
}
}
fn on_expand(
&mut self,
parent: &State,
parent_info: &Observation,
op: OpId,
child: &State,
) -> Observation {
let relaxation = &self.intention.relaxation;
let goal_count = self.intention.goal_count(child);
if self.restart && goal_count < parent_info.best_goal_count {
let mut info = self.root(child);
info.best_goal_count = goal_count;
return info;
}
let mut info = parent_info.clone();
let holds = |f: usize| {
let fact = relaxation.fact(f);
parent.0[fact.var] == fact.value
};
for rule in relaxation.op_rules(op) {
let head = rule.head;
let fired = rule.conditions.iter().all(|&c| holds(c));
let bit = 1_u64 << (head % 64);
if fired && info.observed[head / 64] & bit == 0 {
info.observed[head / 64] |= bit;
info.cost.add(self.intention, head);
}
}
info
}
fn merge(&mut self, kept: &mut Observation, other: &Observation) {
if self.value(other) < self.value(kept) {
kept.clone_from(other);
}
}
fn estimate(&mut self, _state: &State, info: &Observation) -> Option<f64> {
Some(self.value(info))
}
}