Skip to main content

cost_partition/
lib.rs

1//! Cost partitioning over arbitrary [`Abstraction`]s (projections,
2//! merge-and-shrink, Cartesian abstractions, ...).
3//!
4//! Splitting each operator's cost among several abstractions, so that the
5//! parts sum to at most the original cost, makes the *sum* of their
6//! heuristics admissible.
7//!
8//! Implemented: saturated cost partitioning (Seipp, Keller & Helmert 2020)
9//! for a given order, and maximizing over several orders. Not yet
10//! implemented: greedy and diversified orders, general (negative) costs, an
11//! optimal LP baseline.
12
13#![no_std]
14#![forbid(unsafe_code)]
15
16extern crate alloc;
17
18use alloc::{vec, vec::Vec};
19use sas_plus::{Abstraction, LabeledTransitionSystem, State};
20
21/// The result of partitioning costs among abstractions in a fixed order.
22///
23/// Built by [`saturated_cost_partitioning`]. Its [`value`](Self::value) is the
24/// sum of the abstractions' goal distances under their shares of the costs,
25/// which is admissible because the shares sum to at most the original costs.
26pub struct CostPartitionedHeuristic<'a, A> {
27    /// The abstractions the costs were partitioned among.
28    abstractions: &'a [A],
29    /// Goal distances of each abstraction under its share of the costs.
30    ///
31    /// Indexed like `abstractions`, then by abstract state; `None` marks an
32    /// abstract state from which no goal is reachable.
33    distances: Vec<Vec<Option<u64>>>,
34    /// The cost function assigned to each abstraction, indexed like
35    /// `abstractions`, then by operator id.
36    cost_functions: Vec<Vec<u64>>,
37}
38
39impl<A: Abstraction> CostPartitionedHeuristic<'_, A> {
40    /// Sum of the abstraction heuristics; `None` if any detects a dead end.
41    ///
42    /// A state that some abstraction prunes ([`Abstraction::abstract_state`]
43    /// returns `None`) is a dead end too.
44    #[must_use]
45    pub fn value(&self, state: &State) -> Option<u64> {
46        self.abstractions
47            .iter()
48            .zip(&self.distances)
49            .try_fold(0, |sum, (a, d)| Some(sum + d[a.abstract_state(state)?]?))
50    }
51
52    /// Like [`value`](Self::value), given the abstract state of `state` in
53    /// each abstraction.
54    fn value_of(&self, abstract_states: &[usize]) -> Option<u64> {
55        debug_assert_eq!(abstract_states.len(), self.distances.len());
56
57        abstract_states
58            .iter()
59            .zip(&self.distances)
60            .try_fold(0, |sum, (&s, d)| Some(sum + d[s]?))
61    }
62
63    /// The cost function assigned to each abstraction.
64    ///
65    /// Indexed like the abstractions, then by operator id. For every operator,
66    /// the entries sum to at most its original cost. Abstractions that were
67    /// not in the order have all-zero cost functions.
68    #[must_use]
69    pub fn cost_functions(&self) -> &[Vec<u64>] {
70        &self.cost_functions
71    }
72}
73
74/// Saturated cost partitioning: each abstraction in `order` receives only the
75/// costs it needs to keep its goal distances (its *saturated* cost
76/// function); the rest goes to later abstractions. Abstractions not in
77/// `order` get zero costs.
78///
79/// `costs` holds the cost of each operator, indexed by operator id, which is
80/// the label of the abstractions' transitions.
81///
82/// # Panics
83///
84/// Panics if `order` contains an index outside `abstractions` or the same
85/// index twice, or if `costs.len()` differs from an abstraction's number of
86/// labels.
87pub fn saturated_cost_partitioning<'a, A: Abstraction>(
88    abstractions: &'a [A],
89    order: &[usize],
90    costs: &[u64],
91) -> CostPartitionedHeuristic<'a, A> {
92    let mut remaining = costs.to_vec();
93    let mut distances: Vec<Vec<Option<u64>>> = vec![Vec::new(); abstractions.len()];
94    let mut cost_functions = vec![vec![0; costs.len()]; abstractions.len()];
95    let mut seen = vec![false; abstractions.len()];
96
97    for &i in order {
98        // A second pass would overwrite the first one's distances while its costs stay spent.
99        assert!(
100            !core::mem::replace(&mut seen[i], true),
101            "saturated_cost_partitioning: abstraction {i} appears twice in order"
102        );
103        let lts = abstractions[i].lts();
104        let h = lts.goal_distances(&remaining);
105        let saturated = saturated_costs(lts, &h);
106        for (r, s) in remaining.iter_mut().zip(&saturated) {
107            debug_assert!(*s <= *r, "saturated cost exceeds remaining cost");
108            *r -= s;
109        }
110
111        distances[i] = h;
112        cost_functions[i] = saturated;
113    }
114
115    fill_skipped_distances(abstractions, &mut distances, costs.len());
116
117    CostPartitionedHeuristic {
118        abstractions,
119        distances,
120        cost_functions,
121    }
122}
123
124/// The saturated cost function of `lts` for its goal distances `h`.
125///
126/// Each label gets the largest drop in goal distance along one of its
127/// transitions: the least cost that keeps every goal distance in `h`.
128/// Transitions from or to dead states (`None`) need no cost.
129fn saturated_costs(lts: &LabeledTransitionSystem, h: &[Option<u64>]) -> Vec<u64> {
130    let mut saturated = vec![0u64; lts.num_labels];
131    for t in &lts.transitions {
132        if let (Some(hs), Some(hd)) = (h[t.src], h[t.dst]) {
133            saturated[t.label] = saturated[t.label].max(hs.saturating_sub(hd));
134        }
135    }
136
137    saturated
138}
139
140/// Fills in zero-cost goal distances for the abstractions the order skipped.
141///
142/// Their distances are empty until then. Under zero costs, they are `0` or
143/// `None`, so these abstractions add nothing but still detect dead ends.
144fn fill_skipped_distances<A: Abstraction>(
145    abstractions: &[A],
146    distances: &mut [Vec<Option<u64>>],
147    num_labels: usize,
148) {
149    let zero = vec![0; num_labels];
150    for (a, d) in abstractions.iter().zip(distances) {
151        if d.is_empty() {
152            *d = a.lts().goal_distances(&zero);
153        }
154    }
155}
156
157/// Maximum over several cost-partitioned heuristics (one per order).
158///
159/// Each order yields an admissible heuristic, so their maximum is admissible
160/// too, and at least as informed as each of them.
161pub struct MaxOverOrders<'a, A> {
162    /// The abstractions every order partitions costs among.
163    abstractions: &'a [A],
164    /// One saturated cost partitioning per order, all over `abstractions`.
165    heuristics: Vec<CostPartitionedHeuristic<'a, A>>,
166}
167
168impl<'a, A: Abstraction> MaxOverOrders<'a, A> {
169    /// Runs [`saturated_cost_partitioning`] once for each of `orders`.
170    ///
171    /// # Panics
172    ///
173    /// Panics if `orders` is empty, and under the same conditions as
174    /// [`saturated_cost_partitioning`], for any of the orders.
175    #[must_use]
176    pub fn new(abstractions: &'a [A], orders: &[Vec<usize>], costs: &[u64]) -> Self {
177        // With no orders, `value` would be 0 everywhere and miss dead ends.
178        assert!(
179            !orders.is_empty(),
180            "MaxOverOrders::new needs at least one order"
181        );
182        Self {
183            abstractions,
184            heuristics: orders
185                .iter()
186                .map(|o| saturated_cost_partitioning(abstractions, o, costs))
187                .collect(),
188        }
189    }
190
191    /// The cost-partitioned heuristic of each order.
192    #[must_use]
193    pub fn heuristics(&self) -> &[CostPartitionedHeuristic<'a, A>] {
194        &self.heuristics
195    }
196
197    /// The largest value over all orders; `None` if `state` is a dead end.
198    ///
199    /// Every component is admissible, so any component's dead end is a dead end.
200    #[must_use]
201    pub fn value(&self, state: &State) -> Option<u64> {
202        // Abstract states do not depend on the order: compute them once.
203        let abstract_states: Vec<usize> = self
204            .abstractions
205            .iter()
206            .map(|a| a.abstract_state(state))
207            .collect::<Option<_>>()?;
208
209        self.heuristics
210            .iter()
211            .try_fold(0, |best, h| Some(best.max(h.value_of(&abstract_states)?)))
212    }
213}
214
215/// Doctests for the code examples in README.md (not part of the API).
216#[cfg(doctest)]
217#[doc = include_str!("../README.md")]
218mod readme_doctests {}