stochastic_search/mo/heuristics.rs
1//! Multi-objective heuristics (Section 4 of Chen, Trevizan and Thiébaux 2023): the blind
2//! heuristic, ideal points of single-objective heuristics, the all-outcomes determinisation
3//! and value iteration on an abstraction.
4
5use core::hash::Hash;
6
7use alloc::vec::Vec;
8
9use hashbrown::HashMap;
10
11use crate::config::Config;
12use crate::mo::movi::mo_value_iteration;
13use crate::mo::{MoMdp, Objectives};
14use crate::model::{Goal, Heuristic};
15
16/// The blind multi-objective heuristic: the zero vector everywhere. Admissible for every
17/// MOSSP.
18///
19/// The cost-vector counterpart of [`Zero`](crate::Zero), which is `search-core`'s and
20/// covers scalar costs only.
21///
22/// ```
23/// use stochastic_search::{Heuristic, ZeroVector};
24///
25/// assert_eq!(Heuristic::<u8, Vec<[f64; 2]>>::estimate(&mut ZeroVector, &3), Some(vec![[0.0; 2]]));
26/// ```
27#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
28pub struct ZeroVector;
29
30impl<S, const N: usize> Heuristic<S, Vec<[f64; N]>> for ZeroVector {
31 fn estimate(&mut self, _state: &S) -> Option<Vec<[f64; N]>> {
32 Some(alloc::vec![[0.0; N]])
33 }
34}
35
36/// The ideal-point heuristic `H_ideal`: one single-objective heuristic per objective,
37/// combined into the single vector `[h_1(s), ..., h_N(s)]`.
38///
39/// Each `h_i` must be admissible for objective `i` alone (the SSP whose costs are the
40/// `i`-th components); then the ideal point is admissible, even in the set-domination
41/// sense of the paper's Definition 4.1. The paper instantiates it with `h^max` on the
42/// determinisation (`H^max_ideal`) and with SSP pattern databases (`H^pdb_ideal`); any
43/// `Heuristic<S, f64>` works, including the ones written for
44/// [`lrtdp`](crate::lrtdp()). A `None` (or infinite) estimate from any `h_i` proves a dead
45/// end.
46///
47/// # Example
48///
49/// ```
50/// use stochastic_search::{Heuristic, IdealPoint, heuristic_fn};
51///
52/// // The array needs one type: closures differ, function pointers do not.
53/// type Estimate = fn(&u32) -> Option<f64>;
54/// let distance: Estimate = |state| Some(f64::from(10 - state));
55/// let blind: Estimate = |_| Some(0.0);
56/// let mut ideal = IdealPoint([heuristic_fn(distance), heuristic_fn(blind)]);
57///
58/// assert_eq!(ideal.estimate(&4), Some(vec![[6.0, 0.0]]));
59/// ```
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub struct IdealPoint<H, const N: usize>(pub [H; N]);
62
63impl<S, H, const N: usize> Heuristic<S, Vec<[f64; N]>> for IdealPoint<H, N>
64where
65 H: Heuristic<S, f64>,
66{
67 fn estimate(&mut self, state: &S) -> Option<Vec<[f64; N]>> {
68 let mut vector = [0.0; N];
69 for (component, heuristic) in vector.iter_mut().zip(&mut self.0) {
70 let estimate = heuristic.estimate(state)?;
71 if estimate == f64::INFINITY {
72 return None;
73 }
74
75 *component = estimate;
76 }
77
78 Some(alloc::vec![vector])
79 }
80}
81
82/// The all-outcomes determinisation of an [`MoMdp`]: every outcome of every action becomes
83/// a deterministic action with the action's cost vector.
84///
85/// Actions are labeled by their successor state. Solving it with [`Abstraction`] (and the
86/// identity projection) gives the exact multi-objective determinisation heuristic, the
87/// strongest of the paper's `H_mo` family (which approximates it with `h^max` and pattern
88/// databases on a factored model).
89///
90/// The determinisation is admissible only in the scalarised sense of the
91/// [module docs](crate::mo): from a state that moves at zero cost to `s1` or `s2` with
92/// probability 0.5 each, where `s1` reaches the goal for `[1, 0]` and `s2` for `[0, 1]`,
93/// the determinisation estimates `{[1, 0], [0, 1]}` but the optimal value is
94/// `{[0.5, 0.5]}`, which neither vector dominates.
95///
96/// # Example
97///
98/// ```
99/// use stochastic_search::{Abstraction, Determinized, Heuristic, MoMdp, Objectives};
100///
101/// struct Coin;
102///
103/// impl MoMdp<2> for Coin {
104/// type State = u8;
105/// type Action = ();
106///
107/// fn actions(&self, state: &u8, mut emit: impl FnMut((), [f64; 2])) {
108/// emit((), if *state == 0 { [0.0, 0.0] } else if *state == 1 { [1.0, 0.0] } else { [0.0, 1.0] });
109/// }
110///
111/// fn outcomes(&self, state: &u8, _action: &(), mut emit: impl FnMut(u8, f64)) {
112/// if *state == 0 {
113/// emit(1, 0.5);
114/// emit(2, 0.5);
115/// } else {
116/// emit(3, 1.0);
117/// }
118/// }
119/// }
120///
121/// let determinized = Determinized(&Coin);
122/// let goal = |state: &u8| *state == 3;
123/// let mut heuristic = Abstraction::new(&determinized, |state: &u8| *state, &goal, Objectives::new([100.0; 2]));
124///
125/// let mut estimate = heuristic.estimate(&0).unwrap();
126/// estimate.sort_by(|a, b| a[0].total_cmp(&b[0]));
127/// assert_eq!(estimate, vec![[0.0, 1.0], [1.0, 0.0]]);
128/// ```
129#[derive(Debug, Clone, Copy)]
130pub struct Determinized<'a, M>(pub &'a M);
131
132impl<M, const N: usize> MoMdp<N> for Determinized<'_, M>
133where
134 M: MoMdp<N>,
135 M::State: Clone,
136{
137 type State = M::State;
138 type Action = M::State;
139
140 fn actions(&self, state: &M::State, mut emit: impl FnMut(M::State, [f64; N])) {
141 self.0.actions(state, |action, cost| {
142 self.0
143 .outcomes(state, &action, |target, _| emit(target, cost));
144 });
145 }
146
147 fn outcomes(&self, _state: &M::State, action: &M::State, mut emit: impl FnMut(M::State, f64)) {
148 emit(action.clone(), 1.0);
149 }
150}
151
152/// The abstraction heuristic: the exact multi-objective value of a smaller MOSSP, looked up
153/// through a projection of the states.
154///
155/// The explicit-state form of the paper's `H^pdb_mossp`, which solves each pattern
156/// database's projection with multi-objective topological value iteration: here, the first
157/// estimate of a projected state runs [`mo_value_iteration`](crate::mo_value_iteration())
158/// from it, and every value that run computes is cached. Over [`Determinized`] it gives the
159/// determinisation heuristic.
160///
161/// Admissible (in the scalarised sense of the [module docs](crate::mo)) when the
162/// abstraction is a relaxation: for every weight, the optimal weighted cost from
163/// `project(s)` is at most the one from `s`. And when the bound of `objectives` is large
164/// enough to contain the abstract optimal vectors. That bound caps the abstract problem,
165/// not the concrete one: a determinisation's path costs can exceed every concrete expected
166/// cost, so pass a bound above the abstract path costs, not the concrete `b`. A vector cut
167/// off by the inner bound is missing from the estimate, which then overestimates for the
168/// weights that favour it.
169///
170/// The estimate is never `None`. An abstract state without a vector under the inner bound,
171/// an inner run that fails, and one that exhausts its budget all fall back to the zero
172/// vector.
173///
174/// # Example
175///
176/// See [`Determinized`].
177pub struct Abstraction<'a, M: MoMdp<N>, P, G, const N: usize> {
178 /// The abstract MOSSP.
179 mdp: &'a M,
180 /// Maps a concrete state to its abstract state.
181 project: P,
182 /// The goal test of the abstract MOSSP.
183 goal: &'a G,
184 /// The bound and margin of the inner runs.
185 objectives: Objectives<N>,
186 /// The settings of the inner runs.
187 config: Config,
188 /// The value of every abstract state solved so far, without the bound `b`.
189 table: HashMap<M::State, Vec<[f64; N]>>,
190}
191
192impl<'a, M: MoMdp<N>, P, G, const N: usize> Abstraction<'a, M, P, G, N> {
193 /// An abstraction heuristic over `mdp` with goal `goal`, reached through `project`.
194 /// The inner runs use `objectives` and the default [`Config`].
195 pub fn new(mdp: &'a M, project: P, goal: &'a G, objectives: Objectives<N>) -> Self {
196 Self {
197 mdp,
198 project,
199 goal,
200 objectives,
201 config: Config::default(),
202 table: HashMap::new(),
203 }
204 }
205
206 /// Returns the same heuristic with another configuration for its inner runs.
207 #[must_use]
208 pub fn with_config(self, config: Config) -> Self {
209 Self { config, ..self }
210 }
211}
212
213impl<S, M, P, G, const N: usize> Heuristic<S, Vec<[f64; N]>> for Abstraction<'_, M, P, G, N>
214where
215 M: MoMdp<N>,
216 M::State: Clone + Eq + Hash,
217 P: FnMut(&S) -> M::State,
218 G: Goal<M::State>,
219{
220 fn estimate(&mut self, state: &S) -> Option<Vec<[f64; N]>> {
221 let abstract_state = (self.project)(state);
222 if !self.table.contains_key(&abstract_state) {
223 self.solve(abstract_state.clone());
224 }
225
226 match self.table.get(&abstract_state) {
227 Some(value) if !value.is_empty() => Some(value.clone()),
228 // No proper vector under the inner bound proves nothing about the concrete
229 // problem (its costs can exceed the abstract bound); fall back to blind.
230 _ => Some(alloc::vec![[0.0; N]]),
231 }
232 }
233}
234
235impl<M, P, G, const N: usize> Abstraction<'_, M, P, G, N>
236where
237 M: MoMdp<N>,
238 M::State: Clone + Eq + Hash,
239 G: Goal<M::State>,
240{
241 /// Solves the abstract MOSSP from `state` and caches every value of a converged run.
242 fn solve(&mut self, state: M::State) {
243 let Ok(solution) =
244 mo_value_iteration(self.mdp, state, self.goal, self.objectives, self.config)
245 else {
246 return;
247 };
248
249 if solution.status() == crate::Status::BudgetExhausted {
250 return;
251 }
252
253 for index in 0..solution.state_count() {
254 let id = crate::space::Id::try_from(index).expect("ids fit u32");
255 self.table
256 .entry(solution.state_of(id).clone())
257 .or_insert_with(|| solution.vectors_of(id).copied().collect());
258 }
259 }
260}