1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
use crate::{core::Callbacks, traits::Status};
use std::convert::Infallible;
/// A trait representing an [`Algorithm`] which can be used to solve a problem `P`.
///
/// This trait is implemented for the algorithms found in the [`algorithms`](`crate::algorithms`) module and contains
/// all the methods needed to [`process`](`Algorithm::process`) a problem.
pub trait Algorithm<P, S: Status, U = (), E = Infallible>: Send + Sync {
/// A type which holds a summary of the algorithm's ending state.
type Summary;
/// The configuration struct for the algorithm.
type Config;
/// The initialization payload for a single run.
type Init;
/// Any setup work done before the main steps of the algorithm should be done here.
///
/// # Errors
///
/// Returns an `Err(E)` if any internal evaluation of the problem `P` fails.
fn initialize(
&mut self,
problem: &P,
status: &mut S,
args: &U,
init: &Self::Init,
config: &Self::Config,
) -> Result<(), E>;
/// The main "step" of an algorithm, which is repeated until termination conditions are met or
/// the max number of steps have been taken.
///
/// # Errors
///
/// Returns an `Err(E)` if any internal evaluation of the problem `P` fails.
fn step(
&mut self,
current_step: usize,
problem: &P,
status: &mut S,
args: &U,
config: &Self::Config,
) -> Result<(), E>;
/// Runs any steps needed by the [`Algorithm`] after termination or convergence. This will run
/// regardless of whether the [`Algorithm`] converged.
///
/// # Errors
///
/// Returns an `Err(E)` if any internal evaluation of the problem `P` fails.
#[allow(unused_variables)]
fn postprocessing(
&mut self,
problem: &P,
status: &mut S,
args: &U,
config: &Self::Config,
) -> Result<(), E> {
Ok(())
}
/// Generates a new [`Algorithm::Summary`] from the current state of the [`Algorithm`], which can be displayed or used elsewhere.
///
/// # Errors
///
/// Returns an `Err(E)` if any internal evaluation of the problem `P` fails.
#[allow(unused_variables)]
fn summarize(
&self,
current_step: usize,
problem: &P,
status: &S,
args: &U,
init: &Self::Init,
config: &Self::Config,
) -> Result<Self::Summary, E>;
/// Reset the algorithm to its initial state.
fn reset(&mut self) {}
/// Process the given problem using this [`Algorithm`].
///
/// This method first runs [`Algorithm::initialize`], then runs [`Algorithm::step`] in a loop,
/// terminating if any supplied [`Terminator`](crate::traits::Terminator)s return
/// [`ControlFlow::Break`](`std::ops::ControlFlow::Break`). Finally, regardless of convergence,
/// [`Algorithm::postprocessing`] is called. [`Algorithm::summarize`] is called to create a
/// summary of the [`Algorithm`]'s state.
///
/// # Errors
///
/// Returns an `Err(E)` if any internal evaluation of the problem `P` fails.
fn process<I, C>(
&mut self,
problem: &P,
args: &U,
init: I,
config: Self::Config,
callbacks: C,
) -> Result<Self::Summary, E>
where
I: Into<Self::Init>,
C: Into<Callbacks<Self, P, S, U, E, Self::Config>>,
Self: Sized,
{
let init = init.into();
let mut status = S::default();
let mut cbs: Callbacks<Self, P, S, U, E, Self::Config> = callbacks.into();
self.initialize(problem, &mut status, args, &init, &config)?;
if status.check_invariants().is_break() {
self.postprocessing(problem, &mut status, args, &config)?;
return self.summarize(0, problem, &status, args, &init, &config);
}
let mut current_step = 0;
loop {
self.step(current_step, problem, &mut status, args, &config)?;
if status.check_invariants().is_break() {
break;
}
if cbs
.check_for_termination(current_step, self, problem, &mut status, args, &config)
.is_break()
{
break;
}
current_step += 1;
}
self.postprocessing(problem, &mut status, args, &config)?;
self.summarize(current_step, problem, &status, args, &init, &config)
}
/// Process the given problem using this [`Algorithm`] and the algorithm's default callbacks.
///
/// This method first runs [`Algorithm::initialize`], then runs [`Algorithm::step`] in a loop,
/// terminating if any of the [`Algorithm::default_callbacks`] return
/// [`ControlFlow::Break`](`std::ops::ControlFlow::Break`). Finally, regardless of convergence,
/// [`Algorithm::postprocessing`] is called. [`Algorithm::summarize`] is called to create a
/// summary of the [`Algorithm`]'s state.
///
/// # Errors
///
/// Returns an `Err(E)` if any internal evaluation of the problem `P` fails.
fn process_with_default_callbacks<I>(
&mut self,
problem: &P,
user_data: &U,
init: I,
config: Self::Config,
) -> Result<Self::Summary, E>
where
I: Into<Self::Init>,
Self: Sized,
{
self.process(problem, user_data, init, config, Self::default_callbacks())
}
/// Process the given problem using this [`Algorithm`] with default config and default callbacks.
///
/// This method is similar to [`Algorithm::process`], except it uses
/// [`Default::default`] for the algorithm configuration and
/// [`Algorithm::default_callbacks`] for the callback set.
///
/// # Errors
///
/// Returns an `Err(E)` if any internal evaluation of the problem `P` fails.
fn process_default<I>(
&mut self,
problem: &P,
user_data: &U,
init: I,
) -> Result<Self::Summary, E>
where
I: Into<Self::Init>,
Self: Sized,
Self::Config: Default,
{
self.process(
problem,
user_data,
init,
Self::Config::default(),
Self::default_callbacks(),
)
}
/// Provides a set of reasonable default callbacks specific to this [`Algorithm`].
fn default_callbacks() -> Callbacks<Self, P, S, U, E, Self::Config>
where
Self: Sized,
{
Callbacks::empty()
}
}
/// A trait for algorithm configs which can propagate parameter names into summaries.
pub trait SupportsParameterNames
where
Self: Sized,
{
/// A helper method to get the mutable internal parameter name storage.
fn get_parameter_names_mut(&mut self) -> &mut Option<Vec<String>>;
/// Set the names associated with each parameter.
fn with_parameter_names<I, S>(mut self, parameter_names: I) -> Self
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
*self.get_parameter_names_mut() = Some(
parameter_names
.into_iter()
.map(|name| name.as_ref().to_string())
.collect(),
);
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::{StatusMessage, StatusType};
use serde::{Deserialize, Serialize};
use std::{convert::Infallible, ops::ControlFlow};
#[derive(Clone, Default, Serialize, Deserialize)]
struct InvariantStatus {
message: StatusMessage,
invalid: bool,
}
impl Status for InvariantStatus {
fn reset(&mut self) {
self.message.reset();
self.invalid = false;
}
fn message(&self) -> &StatusMessage {
&self.message
}
fn set_message(&mut self) -> &mut StatusMessage {
&mut self.message
}
fn check_invariants(&mut self) -> ControlFlow<()> {
if self.invalid {
self.message.fail_with_message("invariant failed");
return ControlFlow::Break(());
}
ControlFlow::Continue(())
}
}
#[derive(Default)]
struct InvariantAlgorithm {
steps: usize,
}
#[derive(Clone, Copy)]
struct InvariantConfig {
fail_after_initialize: bool,
fail_after_step: bool,
}
impl Algorithm<(), InvariantStatus, (), Infallible> for InvariantAlgorithm {
type Summary = (usize, StatusMessage);
type Config = InvariantConfig;
type Init = ();
fn initialize(
&mut self,
_problem: &(),
status: &mut InvariantStatus,
_args: &(),
_init: &Self::Init,
config: &Self::Config,
) -> Result<(), Infallible> {
status.message.initialize();
status.invalid = config.fail_after_initialize;
Ok(())
}
fn step(
&mut self,
_current_step: usize,
_problem: &(),
status: &mut InvariantStatus,
_args: &(),
config: &Self::Config,
) -> Result<(), Infallible> {
self.steps += 1;
status.message.step();
status.invalid = config.fail_after_step;
Ok(())
}
fn summarize(
&self,
_current_step: usize,
_problem: &(),
status: &InvariantStatus,
_args: &(),
_init: &Self::Init,
_config: &Self::Config,
) -> Result<Self::Summary, Infallible> {
Ok((self.steps, status.message.clone()))
}
}
#[test]
fn process_checks_status_invariants_after_initialize() {
let mut algorithm = InvariantAlgorithm::default();
let config = InvariantConfig {
fail_after_initialize: true,
fail_after_step: false,
};
let (steps, message) = algorithm
.process(&(), &(), (), config, Callbacks::empty())
.unwrap();
assert_eq!(steps, 0);
assert!(matches!(message.status_type, StatusType::Failed));
assert_eq!(message.text(), Some("invariant failed"));
}
#[test]
fn process_checks_status_invariants_after_step() {
let mut algorithm = InvariantAlgorithm::default();
let config = InvariantConfig {
fail_after_initialize: false,
fail_after_step: true,
};
let (steps, message) = algorithm
.process(&(), &(), (), config, Callbacks::empty())
.unwrap();
assert_eq!(steps, 1);
assert!(matches!(message.status_type, StatusType::Failed));
assert_eq!(message.text(), Some("invariant failed"));
}
}