use alloc::vec::Vec;
use core::cmp::Reverse;
use sas_plus::Task;
use super::Factoring;
use crate::Error;
use crate::decoupled::DecoupledTask;
use crate::search;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Strategy {
Fork,
InvertedFork,
XShape,
IncidentArcs,
MaxLeaves,
Generalized,
}
impl Strategy {
pub const ALL: [Self; 6] = [
Self::Fork,
Self::InvertedFork,
Self::XShape,
Self::IncidentArcs,
Self::MaxLeaves,
Self::Generalized,
];
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Objective {
Optimal,
Satisficing,
}
#[derive(Clone, Copy, Debug)]
struct Sample {
solved: bool,
expanded: u64,
work: u64,
initial_h: u64,
best_h: u64,
}
impl Sample {
fn run(
task: &Task,
factoring: &Factoring,
objective: Objective,
expansions: u64,
) -> Option<Self> {
let optimal = objective == Objective::Optimal;
let (probe, expanded) = search::sample(task, factoring, optimal, expansions).ok()?;
let solved = !probe.cut_off;
Some(Self {
solved,
expanded,
work: probe.work.max(1),
initial_h: probe.initial_h.unwrap_or(0),
best_h: probe.best_h.unwrap_or(0),
})
}
fn beats(&self, other: &Self, objective: Objective) -> bool {
let wide = u128::from;
if self.solved != other.solved {
return self.solved;
}
if self.solved {
return self.work < other.work;
}
match objective {
Objective::Optimal => {
wide(self.expanded) * wide(other.work) > wide(other.expanded) * wide(self.work)
}
Objective::Satisficing => {
let ours = wide(self.initial_h) * wide(other.best_h.max(1));
let theirs = wide(other.initial_h) * wide(self.best_h.max(1));
ours > theirs || (ours == theirs && self.work < other.work)
}
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct FactoringScore {
pub leaves: usize,
pub mobile_leaves: usize,
pub leaf_actions: usize,
pub global_actions: usize,
pub max_leaf_states: usize,
pub total_leaf_states: usize,
}
impl FactoringScore {
#[must_use]
pub fn leaf_action_share(&self) -> f64 {
let total = self.leaf_actions + self.global_actions;
if total == 0 {
return 0.0;
}
#[expect(clippy::cast_precision_loss, reason = "operator counts are small")]
let share = self.leaf_actions as f64 / total as f64;
share
}
fn key(&self) -> (Share, usize, Reverse<usize>) {
(
Share(self.leaf_actions, self.leaf_actions + self.global_actions),
self.mobile_leaves,
Reverse(self.max_leaf_states),
)
}
}
#[derive(Clone, Copy, Debug)]
struct Share(usize, usize);
impl Share {
fn parts(self) -> (u128, u128) {
let widen = |n: usize| u128::try_from(n).expect("usize fits in u128");
(widen(self.0), widen(self.1.max(1)))
}
}
impl PartialEq for Share {
fn eq(&self, other: &Self) -> bool {
self.cmp(other).is_eq()
}
}
impl Eq for Share {}
impl PartialOrd for Share {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Share {
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
let ((a, b), (c, d)) = (self.parts(), other.parts());
(a * d).cmp(&(c * b))
}
}
impl Factoring {
#[must_use]
pub fn with_strategy(task: &Task, strategy: Strategy) -> Self {
match strategy {
Strategy::Fork => Self::fork(task),
Strategy::InvertedFork => Self::inverted_fork(task),
Strategy::XShape => Self::x_shape(task),
Strategy::IncidentArcs => Self::incident_arcs(task),
Strategy::MaxLeaves => Self::max_leaves(task),
Strategy::Generalized => Self::generalized(task),
}
}
pub fn with_free_leaf_actions(&self, task: &Task) -> Result<Task, Error> {
let decoupled = DecoupledTask::new(task, self)?;
let mut free = task.clone();
for action in decoupled.leaves.iter().flat_map(|l| &l.actions) {
free.operators[action.op].cost = 0;
}
Ok(free)
}
pub fn score(&self, task: &Task) -> Result<FactoringScore, Error> {
let decoupled = DecoupledTask::new(task, self)?;
let leaves = &decoupled.leaves;
Ok(FactoringScore {
leaves: leaves.len(),
mobile_leaves: leaves.iter().filter(|l| !l.actions.is_empty()).count(),
leaf_actions: leaves.iter().map(|l| l.actions.len()).sum(),
global_actions: decoupled.globals.len(),
max_leaf_states: leaves.iter().map(|l| l.size).max().unwrap_or(0),
total_leaf_states: leaves.iter().map(|l| l.size).sum(),
})
}
#[must_use]
pub fn auto(task: &Task) -> Self {
Strategy::ALL
.iter()
.rev()
.filter_map(|&s| {
let factoring = Self::with_strategy(task, s);
factoring.score(task).ok().map(|score| (score, factoring))
})
.filter(|(score, _)| score.mobile_leaves >= 2)
.max_by_key(|(score, _)| score.key())
.map_or_else(
|| Self::from_leaves(task, alloc::vec::Vec::new()),
|(_, f)| f,
)
}
#[must_use]
pub fn auto_by_sample(task: &Task, objective: Objective, expansions: u64) -> Self {
let mut candidates: Vec<Self> = Vec::new();
for &strategy in &Strategy::ALL {
let factoring = Self::with_strategy(task, strategy);
let usable = factoring
.score(task)
.is_ok_and(|score| score.mobile_leaves >= 2);
if usable && !candidates.contains(&factoring) {
candidates.push(factoring);
}
}
if candidates.len() <= 1 {
return candidates
.pop()
.unwrap_or_else(|| Self::from_leaves(task, Vec::new()));
}
let mut best: Option<(Sample, Self)> = None;
for factoring in candidates {
let Some(sample) = Sample::run(task, &factoring, objective, expansions) else {
continue;
};
if best
.as_ref()
.is_none_or(|(b, _)| sample.beats(b, objective))
{
best = Some((sample, factoring));
}
}
best.map_or_else(|| Self::from_leaves(task, Vec::new()), |(_, f)| f)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn sample(solved: bool, expanded: u64, work: u64, (initial_h, best_h): (u64, u64)) -> Sample {
Sample {
solved,
expanded,
work,
initial_h,
best_h,
}
}
#[test]
fn samples_rank_as_the_paper_does() {
let (optimal, satisficing) = (Objective::Optimal, Objective::Satisficing);
let done = sample(true, 5, 50, (4, 0));
let faster = sample(false, 100, 1_000, (4, 2));
let slower = sample(false, 100, 3_000, (8, 2));
assert!(done.beats(&faster, optimal) && !faster.beats(&done, optimal));
assert!(sample(true, 9, 40, (4, 0)).beats(&done, optimal));
assert!(faster.beats(&slower, optimal) && !slower.beats(&faster, optimal));
assert!(slower.beats(&faster, satisficing) && !faster.beats(&slower, satisficing));
assert!(!faster.beats(&faster, satisficing), "ties do not win");
}
}