use alloc::vec;
use alloc::vec::Vec;
use sas_plus::{CausalGraph, OpId, Task, VarId};
use super::{Candidate, mobility, neighbours};
use crate::decoupled::leaf_action_of;
use crate::factoring::leaf_states;
const MAX_INDEPENDENT_SETS: usize = 16;
const WORK_BUDGET: usize = 1 << 24;
pub(super) fn factoring(task: &Task) -> Candidate {
let growth = Growth::new(task);
let eligible = (0..task.num_variables())
.filter(|&v| !task.variables[v].is_derived() && leaf_states(task, &[v]).is_some())
.collect();
let mut best: Option<Candidate> = None;
for set in maximum_independent_sets(&growth.neighbours, eligible) {
let candidate = growth.post_process(set);
if best.as_ref().is_none_or(|b| candidate.mobile > b.mobile) {
best = Some(candidate);
}
}
best.unwrap_or(Candidate {
mobile: 0,
leaves: Vec::new(),
})
}
struct Growth<'a> {
task: &'a Task,
neighbours: Vec<Vec<VarId>>,
touching: Vec<Vec<OpId>>,
}
#[derive(Clone)]
struct Leaves {
vars: Vec<Vec<VarId>>,
leaf_of: Vec<Option<usize>>,
mobile: Vec<bool>,
}
impl Leaves {
fn mobile_count(&self) -> usize {
self.mobile.iter().filter(|&&m| m).count()
}
}
impl<'a> Growth<'a> {
fn new(task: &'a Task) -> Self {
let neighbours = neighbours(task, &CausalGraph::new(task));
let mut touching = vec![Vec::new(); task.num_variables()];
for (op, operator) in task.operators.iter().enumerate() {
let conditions = operator.eff.iter().flat_map(|e| &e.conditions);
let effects = operator.eff.iter().map(|e| e.fact.var);
let mut vars: Vec<VarId> = operator
.pre
.iter()
.chain(conditions)
.map(|f| f.var)
.chain(effects)
.collect();
vars.sort_unstable();
vars.dedup();
for v in vars {
touching[v].push(op);
}
}
Self {
task,
neighbours,
touching,
}
}
fn leaves(&self, vars: Vec<Vec<VarId>>) -> Leaves {
let mut leaf_of = vec![None; self.task.num_variables()];
for (leaf, members) in vars.iter().enumerate() {
for &v in members {
leaf_of[v] = Some(leaf);
}
}
let mobile = mobility(self.task, &vars);
Leaves {
vars,
leaf_of,
mobile,
}
}
fn post_process(&self, set: Vec<VarId>) -> Candidate {
let seeded = self.leaves(set.into_iter().map(|v| vec![v]).collect());
let grown = self.maximize_flexibility(seeded);
let kept = grown
.vars
.into_iter()
.zip(grown.mobile)
.filter_map(|(leaf, mobile)| mobile.then_some(leaf))
.collect();
let best = self.maximize_flexibility(self.leaves(kept));
Candidate {
mobile: best.mobile_count(),
leaves: best.vars,
}
}
fn maximize_flexibility(&self, start: Leaves) -> Leaves {
let mut best = start.clone();
let mut current = start;
while let Some(next) = self.best_extension(¤t) {
current = next;
if current.mobile_count() >= best.mobile_count() {
best = current.clone();
}
}
best
}
fn best_extension(&self, current: &Leaves) -> Option<Leaves> {
let mut best: Option<(usize, VarId, usize)> = None;
for v in (0..self.task.num_variables()).filter(|&v| self.may_join(current, v)) {
let Some(leaf) = only_neighbour_leaf(&self.neighbours[v], ¤t.leaf_of) else {
continue;
};
if leaf_states(self.task, &joined(¤t.vars[leaf], v)).is_none() {
continue;
}
let mobile = self.mobile_count_after(current, v, leaf);
if best.is_none_or(|(count, _, _)| mobile > count) {
best = Some((mobile, v, leaf));
}
}
let (_, v, leaf) = best?;
Some(self.moved(current, v, leaf))
}
fn may_join(&self, current: &Leaves, v: VarId) -> bool {
current.leaf_of[v].is_none() && !self.task.variables[v].is_derived()
}
fn mobile_count_after(&self, current: &Leaves, v: VarId, leaf: usize) -> usize {
if !self.task.axioms.is_empty() {
let mut vars = current.vars.clone();
vars[leaf] = joined(&vars[leaf], v);
return mobility(self.task, &vars).iter().filter(|&&m| m).count();
}
let others = current.mobile_count() - usize::from(current.mobile[leaf]);
others + usize::from(self.becomes_mobile(current, v, leaf))
}
fn becomes_mobile(&self, current: &Leaves, v: VarId, leaf: usize) -> bool {
let leaf_of = |u: VarId| {
if u == v {
Some(leaf)
} else {
current.leaf_of[u]
}
};
current.mobile[leaf]
|| self.touching[v]
.iter()
.any(|&op| leaf_action_of(leaf_of, &self.task.operators[op]) == Some(leaf))
}
fn moved(&self, current: &Leaves, v: VarId, leaf: usize) -> Leaves {
let mut vars = current.vars.clone();
vars[leaf] = joined(&vars[leaf], v);
if !self.task.axioms.is_empty() {
return self.leaves(vars);
}
let mut next = Leaves {
vars,
leaf_of: current.leaf_of.clone(),
mobile: current.mobile.clone(),
};
next.mobile[leaf] = self.becomes_mobile(current, v, leaf);
next.leaf_of[v] = Some(leaf);
debug_assert_eq!(
next.mobile,
mobility(self.task, &next.vars),
"incremental mobility"
);
next
}
}
fn joined(leaf: &[VarId], v: VarId) -> Vec<VarId> {
let mut out = leaf.to_vec();
out.push(v);
out.sort_unstable();
out
}
fn only_neighbour_leaf(neighbours: &[VarId], leaf_of: &[Option<usize>]) -> Option<usize> {
let mut found = None;
for leaf in neighbours.iter().filter_map(|&u| leaf_of[u]) {
if *found.get_or_insert(leaf) != leaf {
return None;
}
}
found
}
fn maximum_independent_sets(neighbours: &[Vec<VarId>], candidates: Vec<VarId>) -> Vec<Vec<VarId>> {
let mut enumeration = Enumeration {
neighbours,
best: 0,
sets: Vec::new(),
work: 0,
};
enumeration.branch(&mut Vec::new(), candidates);
enumeration.sets
}
struct Enumeration<'a> {
neighbours: &'a [Vec<VarId>],
best: usize,
sets: Vec<Vec<VarId>>,
work: usize,
}
impl Enumeration<'_> {
fn branch(&mut self, chosen: &mut Vec<VarId>, candidates: Vec<VarId>) {
self.work += 1;
if self.is_hopeless(chosen.len() + candidates.len()) {
return;
}
let Some(v) = self.highest_degree(&candidates) else {
self.record(chosen, &candidates);
return;
};
let rest: Vec<VarId> = candidates.into_iter().filter(|&u| u != v).collect();
let apart = rest
.iter()
.copied()
.filter(|u| self.neighbours[v].binary_search(u).is_err())
.collect();
self.branch(chosen, rest);
chosen.push(v);
self.branch(chosen, apart);
chosen.pop();
}
fn is_hopeless(&self, reachable: usize) -> bool {
let spent = self.work > WORK_BUDGET && !self.sets.is_empty();
let full = self.sets.len() >= MAX_INDEPENDENT_SETS && reachable <= self.best;
spent || full || reachable < self.best
}
fn highest_degree(&mut self, candidates: &[VarId]) -> Option<VarId> {
self.work += candidates
.iter()
.map(|&v| self.neighbours[v].len())
.sum::<usize>();
candidates
.iter()
.map(|&v| {
let degree = self.neighbours[v]
.iter()
.filter(|u| candidates.binary_search(u).is_ok())
.count();
(degree, v)
})
.filter(|&(degree, _)| degree > 0)
.max_by(|(da, va), (db, vb)| da.cmp(db).then(vb.cmp(va)))
.map(|(_, v)| v)
}
fn record(&mut self, chosen: &[VarId], rest: &[VarId]) {
let mut set: Vec<VarId> = chosen.iter().chain(rest).copied().collect();
set.sort_unstable();
if set.len() > self.best {
self.best = set.len();
self.sets.clear();
}
if self.sets.len() < MAX_INDEPENDENT_SETS {
self.sets.push(set);
}
}
}
#[cfg(test)]
mod tests {
use alloc::vec::Vec;
use sas_plus::random::Rng;
use super::*;
fn random_graph(rng: &mut Rng, n: usize, percent: u64) -> Vec<Vec<VarId>> {
let mut neighbours = vec![Vec::new(); n];
for u in 0..n {
for v in u + 1..n {
if rng.range(0, 99) < percent {
neighbours[u].push(v);
neighbours[v].push(u);
}
}
}
for list in &mut neighbours {
list.sort_unstable();
}
neighbours
}
fn brute_force(neighbours: &[Vec<VarId>]) -> Vec<Vec<VarId>> {
let n = neighbours.len();
let independent = |mask: u32| {
(0..n).all(|u| mask >> u & 1 == 0 || neighbours[u].iter().all(|&v| mask >> v & 1 == 0))
};
let sets: Vec<u32> = (0..1_u32 << n).filter(|&m| independent(m)).collect();
let best = sets.iter().map(|m| m.count_ones()).max().unwrap_or(0);
sets.into_iter()
.filter(|m| m.count_ones() == best)
.map(|m| (0..n).filter(|&u| m >> u & 1 == 1).collect())
.collect()
}
#[test]
fn enumeration_matches_brute_force() {
let mut rng = Rng::new(7);
for round in 0..300 {
let n = usize::try_from(rng.range(0, 11)).expect("small");
let percent = rng.range(10, 70);
let neighbours = random_graph(&mut rng, n, percent);
let expected = brute_force(&neighbours);
let mut found = maximum_independent_sets(&neighbours, (0..n).collect());
for set in &found {
assert!(
expected.contains(set),
"round {round}: {set:?} is no maximum set"
);
}
found.sort();
found.dedup();
let wanted = expected.len().min(MAX_INDEPENDENT_SETS);
assert_eq!(found.len(), wanted, "round {round}: {neighbours:?}");
}
}
#[test]
fn enumeration_respects_candidates() {
let neighbours = vec![vec![1, 2, 3], vec![0], vec![0], vec![0]];
assert_eq!(
maximum_independent_sets(&neighbours, vec![0, 1, 2, 3]),
[[1, 2, 3]]
);
assert_eq!(maximum_independent_sets(&neighbours, vec![0]), [[0]]);
}
}