planning_qubo/sampler.rs
1//! The sampler interface and the classical samplers.
2//!
3//! A sampler owns its workspace: the model copy, the current state and the best state. A
4//! call on a model of the same size as the previous call allocates nothing, and the result
5//! borrows the best state from the workspace. Each thread uses its own sampler; models are
6//! `Send + Sync` and shared.
7//!
8//! A run stops when it finishes or when its [`Budget`] is exhausted. A stopped run continues
9//! with [`Sampler::resume`], so the work can spread over several time slices.
10//!
11//! ```mermaid
12//! stateDiagram-v2
13//! [*] --> Running: sample
14//! Running --> OutOfBudget: budget exhausted
15//! OutOfBudget --> Running: resume
16//! OutOfBudget --> Running: sample (restart)
17//! Running --> Finished: all work done
18//! Finished --> Running: sample
19//! ```
20
21mod adjacency;
22mod annealing;
23mod exhaustive;
24
25use core::fmt;
26
27pub use annealing::{AnnealingStats, InvalidSchedule, Schedule, SimulatedAnnealing};
28pub use exhaustive::{Exhaustive, ExhaustiveStats};
29use search_core::{Budget, Status};
30
31/// A source of low-energy samples for a model, classical or quantum.
32///
33/// [`Sampler::sample`] starts a run on a model; [`Sampler::resume`] continues a run that its
34/// budget stopped. Lower energy is better. A heuristic sampler need not return the optimum;
35/// callers draw again for more chances. The sampler checks the budget before each unit of
36/// work, so a limit of `n` units stops after exactly `n` units. A model without variables
37/// has no units of work, so its runs finish without a budget check.
38///
39/// The budget is taken by value, as in the other planning crates. Pass `&mut budget` for a
40/// closure that must keep its state across calls; [`Unlimited`](search_core::Unlimited) runs
41/// to the end.
42pub trait Sampler<Model> {
43 /// The work counters of one call, which the budget sees.
44 type Stats;
45
46 /// A sample: one value per binary variable of the model, usually with its energy. It
47 /// borrows the sampler's workspace.
48 type Sample<'a>
49 where
50 Self: 'a;
51
52 /// The error when the sampler cannot handle a model or a call.
53 type Error;
54
55 /// Starts a new run on `model`, and runs until it finishes or `budget` is exhausted.
56 ///
57 /// The run replaces any earlier run. The returned sample is the best state so far.
58 ///
59 /// # Errors
60 ///
61 /// Returns [`Self::Error`] if the sampler cannot handle the model, for example because
62 /// it is too large.
63 fn sample<B: Budget<Self::Stats>>(
64 &mut self,
65 model: &Model,
66 budget: B,
67 ) -> Result<Run<Self::Sample<'_>, Self::Stats>, Self::Error>;
68
69 /// Continues the current run until it finishes or `budget` is exhausted.
70 ///
71 /// The sampler keeps its own copy of the model, so the call needs no model. Resuming a
72 /// finished run does no work and returns the same sample.
73 ///
74 /// # Errors
75 ///
76 /// Returns [`Self::Error`] if no run exists yet.
77 fn resume<B: Budget<Self::Stats>>(
78 &mut self,
79 budget: B,
80 ) -> Result<Run<Self::Sample<'_>, Self::Stats>, Self::Error>;
81}
82
83/// The result of one [`Sampler::sample`] or [`Sampler::resume`] call.
84#[derive(Debug, Clone, Copy, PartialEq)]
85pub struct Run<S, Stats> {
86 /// The best state of the run so far.
87 pub sample: S,
88 /// Whether the run finished or the budget stopped it. With [`Status::Finished`] from
89 /// [`Exhaustive`], the sample is a ground state; after [`Status::OutOfBudget`],
90 /// [`Sampler::resume`] continues the run.
91 pub status: Status,
92 /// The work that this call did. Each call starts from zero.
93 pub stats: Stats,
94}
95
96/// An assignment of a QUBO model's variables and its energy, borrowed from a sampler.
97///
98/// Use `bits.to_vec()` to keep the assignment beyond the next sampler call.
99#[derive(Debug, Clone, Copy, PartialEq)]
100pub struct Sample<'a, T> {
101 /// The value of each variable, by index.
102 pub bits: &'a [bool],
103 /// The energy of `bits` under the model. Exact for [`i64`].
104 pub energy: T,
105}
106
107/// The error when a sampler cannot handle a model or a call.
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109#[non_exhaustive]
110pub enum SampleError {
111 /// The model has more variables than the sampler accepts, for example
112 /// [`Exhaustive::MAX_VARIABLES`].
113 TooManyVariables {
114 /// The number of variables of the model.
115 variables: usize,
116 /// The largest number of variables that the sampler accepts.
117 max: usize,
118 },
119 /// [`Sampler::resume`] was called before any [`Sampler::sample`] call.
120 NothingToResume,
121}
122
123impl fmt::Display for SampleError {
124 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125 match self {
126 Self::TooManyVariables { variables, max } => write!(
127 f,
128 "the model has {variables} variables; the sampler accepts at most {max}"
129 ),
130 Self::NothingToResume => f.write_str("there is no run to resume"),
131 }
132 }
133}
134
135impl core::error::Error for SampleError {}