Skip to main content

argmin/core/observers/
mod.rs

1// Copyright 2018-2024 argmin developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8//! # Observers
9//!
10//! Argmin offers an interface to observe the state of the solver at initialization as well as
11//! after every iteration. This includes the parameter vector, gradient, Jacobian, Hessian,
12//! iteration number, cost values and many more as well as solver-specific metrics. This interface
13//! can be used to implement loggers, send the information to a storage or to plot metrics.
14//!
15//! The observer `ParamWriter` saves the parameter vector to disk. It is distributed via the
16//! `argmin-observer-paramwriter` crate.
17//!
18//! The observer `SlogLogger` logs the progress of the optimization to screen or to disk.
19//! It can be found in the `argmin-observer-slog` crate.
20//!
21//! For each observer it can be defined how often it will observe the progress of the solver. This
22//! is indicated via the enum `ObserverMode` which can be either `Always`, `Never`, `NewBest`
23//! (whenever a new best solution is found) or `Every(i)` which means every `i`th iteration.
24//!
25//! Custom observers can be used as well by implementing the [`crate::core::observers::Observe`]
26//! trait.
27//!
28//! ## Example
29//!
30//! ```rust
31//! # #![allow(unused_imports)]
32//! # extern crate argmin;
33//! # extern crate argmin_testfunctions;
34//! # use argmin::core::{Error, Executor, CostFunction, Gradient, observers::ObserverMode};
35//! # use argmin_observer_slog::SlogLogger;
36//! # use argmin_observer_paramwriter::{ParamWriter, ParamWriterFormat};
37//! # use argmin::solver::gradientdescent::SteepestDescent;
38//! # use argmin::solver::linesearch::MoreThuenteLineSearch;
39//! # use argmin_testfunctions::{rosenbrock, rosenbrock_derivative};
40//! #
41//! # struct Rosenbrock {}
42//! #
43//! # /// Implement `CostFunction` for `Rosenbrock`
44//! # impl CostFunction for Rosenbrock {
45//! #     /// Type of the parameter vector
46//! #     type Param = Vec<f64>;
47//! #     /// Type of the return value computed by the cost function
48//! #     type Output = f64;
49//! #
50//! #     /// Apply the cost function to a parameter `p`
51//! #     fn cost(&self, p: &Self::Param) -> Result<Self::Output, Error> {
52//! #         Ok(rosenbrock(p))
53//! #     }
54//! # }
55//! #
56//! # /// Implement `Gradient` for `Rosenbrock`
57//! # impl Gradient for Rosenbrock {
58//! #     /// Type of the parameter vector
59//! #     type Param = Vec<f64>;
60//! #     /// Type of the return value computed by the cost function
61//! #     type Gradient = Vec<f64>;
62//! #
63//! #     /// Compute the gradient at parameter `p`.
64//! #     fn gradient(&self, p: &Self::Param) -> Result<Self::Gradient, Error> {
65//! #         Ok(rosenbrock_derivative(p))
66//! #     }
67//! # }
68//! #
69//! # fn run() -> Result<(), Error> {
70//! #
71//! # // Define cost function (must implement `CostFunction` and `Gradient`)
72//! # let problem = Rosenbrock { };
73//! #
74//! # // Define initial parameter vector
75//! # let init_param: Vec<f64> = vec![-1.2, 1.0];
76//! #
77//! # // Set up line search
78//! # let linesearch = MoreThuenteLineSearch::new();
79//! #
80//! # // Set up solver
81//! # let solver = SteepestDescent::new(linesearch);
82//! #
83//! // [...]
84//!
85//! let res = Executor::new(problem, solver)
86//!     .configure(|config| config.param(init_param).max_iters(2))
87//! # ;
88//! # let res = res
89//!     // Add an observer which will log all iterations to the terminal (without blocking)
90//!     .add_observer(SlogLogger::term_noblock(), ObserverMode::Always)
91//!     // Write parameter vector to `params/param.arg` every 20th iteration
92//!     .add_observer(
93//!         ParamWriter::new("params", "param", ParamWriterFormat::JSON),
94//!         ObserverMode::Every(20)
95//!     )
96//! # ;
97//! # let res = res
98//!     // run the solver on the defined problem
99//!     .run()?;
100//!
101//! // [...]
102//! #     Ok(())
103//! # }
104//! #
105//! # fn main() {
106//! #     if let Err(ref e) = run() {
107//! #         println!("{}", e);
108//! #         std::process::exit(1);
109//! #     }
110//! # }
111//! ```
112
113#[cfg(feature = "serde1")]
114use serde::{Deserialize, Serialize};
115
116use crate::core::{Error, State, KV};
117use std::default::Default;
118use std::sync::{Arc, Mutex};
119
120/// An interface which every observer is required to implement
121///
122/// # Example
123///
124/// ```
125/// use argmin::core::{Error, KV, State};
126/// use argmin::core::observers::Observe;
127///
128/// struct MyObserver {}
129///
130/// impl<I> Observe<I> for MyObserver
131/// where
132///     // Optional constraint on `I`. The `State` trait, which every state used in argmin needs to
133///     // implement, offers a range of methods which can be useful.
134///     I: State,
135/// {
136///     fn observe_init(&mut self, name: &str, state: &I, kv: &KV) -> Result<(), Error> {
137///         // Do something with `name` and/or `kv`
138///         // Is executed after initialization of a solver
139///         Ok(())
140///     }
141///
142///     fn observe_iter(&mut self, state: &I, kv: &KV) -> Result<(), Error> {
143///         // Do something with `state` and/or `kv`
144///         // Is executed after each iteration of a solver
145///         Ok(())
146///     }
147/// }
148/// ```
149pub trait Observe<I> {
150    /// Called once after initialization of the solver.
151    ///
152    /// Has access to the name of the solver via `name`, the initial `state` and to a key-value
153    /// store `kv` with settings of the solver.
154    fn observe_init(&mut self, _name: &str, _state: &I, _kv: &KV) -> Result<(), Error> {
155        Ok(())
156    }
157
158    /// Called at every iteration of the solver
159    ///
160    /// Has access to the current `state` of the solver (which always implements
161    /// [`State`](`crate::core::State`)) and to a key-value store `kv` with entries specific for
162    /// each solver.
163    fn observe_iter(&mut self, _state: &I, _kv: &KV) -> Result<(), Error> {
164        Ok(())
165    }
166
167    /// Called at the end of a solver run
168    ///
169    /// Has access to the final `state` of the solver (which always implements
170    /// [`State`](`crate::core::State`)).
171    fn observe_final(&mut self, _state: &I) -> Result<(), Error> {
172        Ok(())
173    }
174}
175
176type ObserversVec<I> = Vec<(Arc<Mutex<dyn Observe<I>>>, ObserverMode)>;
177
178/// Container for observers.
179///
180/// This type also implements [`Observe`] and therefore can be used like a single observer.
181/// Each observer has an [`ObserverMode`] attached which indicates when the observer will be
182/// called.
183#[derive(Clone, Default)]
184pub struct Observers<I> {
185    /// Vector of `Observe`rs with the corresponding `ObserverMode`
186    observers: ObserversVec<I>,
187}
188
189impl<I> Observers<I> {
190    /// Construct a new empty `Observers` instance.
191    ///
192    /// # Example
193    ///
194    /// ```
195    /// use argmin::core::observers::Observers;
196    /// use argmin::core::IterState;
197    ///
198    /// let observers: Observers<IterState<Vec<f64>, (), (), (), (), f64>> = Observers::new();
199    /// # assert!(observers.is_empty());
200    /// ```
201    pub fn new() -> Self {
202        Observers { observers: vec![] }
203    }
204
205    /// Add another observer with a corresponding [`ObserverMode`].
206    ///
207    /// # Example
208    ///
209    /// ```
210    /// use argmin::core::observers::{Observers, ObserverMode};
211    /// use argmin_observer_slog::SlogLogger;
212    /// use argmin::core::IterState;
213    ///
214    /// let mut observers: Observers<IterState<Vec<f64>, (), (), (), (), f64>> = Observers::new();
215    ///
216    /// let logger = SlogLogger::term();
217    /// observers.push(logger, ObserverMode::Always);
218    /// # assert!(!observers.is_empty());
219    /// ```
220    pub fn push<OBS: Observe<I> + 'static>(
221        &mut self,
222        observer: OBS,
223        mode: ObserverMode,
224    ) -> &mut Self {
225        self.observers.push((Arc::new(Mutex::new(observer)), mode));
226        self
227    }
228
229    /// Returns true if there are no observers stored.
230    ///
231    /// # Example
232    ///
233    /// ```
234    /// use argmin::core::observers::Observers;
235    /// use argmin::core::IterState;
236    ///
237    /// let observers: Observers<IterState<Vec<f64>, (), (), (), (), f64>> = Observers::new();
238    /// assert!(observers.is_empty());
239    /// ```
240    pub fn is_empty(&self) -> bool {
241        self.observers.is_empty()
242    }
243}
244
245/// Implementing [`Observe`] for [`Observers`] allows to use it like a single observer. In its
246/// implementation it will loop over all stored observers, checks if the conditions for observing
247/// are met and calls the actual observers if required.
248impl<I: State> Observe<I> for Observers<I> {
249    /// After initialization of the solver, this loops over all stored observers and calls them.
250    fn observe_init(&mut self, name: &str, state: &I, kv: &KV) -> Result<(), Error> {
251        for l in self.observers.iter() {
252            l.0.lock().unwrap().observe_init(name, state, kv)?
253        }
254        Ok(())
255    }
256
257    /// Called after each iteration.
258    ///
259    /// Loops over all observers, and based on whether the condition for calling the observers are
260    /// met, calls them.
261    fn observe_iter(&mut self, state: &I, kv: &KV) -> Result<(), Error> {
262        for l in self.observers.iter_mut() {
263            let iter = state.get_iter();
264            let observer = &mut l.0.lock().unwrap();
265            match l.1 {
266                ObserverMode::Always => observer.observe_iter(state, kv),
267                ObserverMode::Every(i) if iter.is_multiple_of(i) => {
268                    observer.observe_iter(state, kv)
269                }
270                ObserverMode::NewBest if state.is_best() => observer.observe_iter(state, kv),
271                ObserverMode::Never | ObserverMode::Every(_) | ObserverMode::NewBest => Ok(()),
272            }?
273        }
274        Ok(())
275    }
276
277    /// Called at the end of a solver run. Loops over all stored observers and calls `observe_final`
278    fn observe_final(&mut self, state: &I) -> Result<(), Error> {
279        for l in self.observers.iter() {
280            l.0.lock().unwrap().observe_final(state)?
281        }
282        Ok(())
283    }
284}
285
286/// Indicates when to call an observer.
287///
288/// `Always` calls the observer in every iteration, `Every(X)` calls the observer every X
289/// iterations, `NewBest` calls the observer only when a new best parameter vector is found and
290/// `Never` deactivates the observer.
291#[derive(Copy, Clone, Debug, Eq, PartialEq)]
292#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
293pub enum ObserverMode {
294    /// Never call the observer
295    Never,
296    /// Call observer in every iteration
297    Always,
298    /// Call observer every N iterations
299    Every(u64),
300    /// Call observer when new best is found
301    NewBest,
302}
303
304impl Default for ObserverMode {
305    /// The default for `ObserverMode` is `Always`
306    fn default() -> ObserverMode {
307        ObserverMode::Always
308    }
309}
310
311#[cfg(test)]
312mod tests {
313    use super::*;
314
315    send_sync_test!(observermode, ObserverMode);
316
317    #[test]
318    fn test_observers() {
319        use crate::core::observers::Observe;
320        use crate::core::{Error, IterState, KV};
321
322        struct TestStor {
323            pub solver_name: String,
324            pub init_called: usize,
325            pub iter_called: usize,
326        }
327
328        impl TestStor {
329            fn new() -> Arc<Mutex<TestStor>> {
330                Arc::new(Mutex::new(TestStor {
331                    solver_name: String::new(),
332                    init_called: 0,
333                    iter_called: 0,
334                }))
335            }
336        }
337
338        struct TestObs {
339            data: Arc<Mutex<TestStor>>,
340        }
341
342        impl<I> Observe<I> for TestObs {
343            fn observe_init(&mut self, name: &str, _state: &I, _kv: &KV) -> Result<(), Error> {
344                self.data.lock().unwrap().solver_name = name.into();
345                self.data.lock().unwrap().init_called += 1;
346                Ok(())
347            }
348
349            fn observe_iter(&mut self, _state: &I, _kv: &KV) -> Result<(), Error> {
350                self.data.lock().unwrap().iter_called += 1;
351                Ok(())
352            }
353        }
354
355        let test_stor_1 = TestStor::new();
356        let test_obs_1 = TestObs {
357            data: test_stor_1.clone(),
358        };
359
360        let test_stor_2 = TestStor::new();
361        let test_obs_2 = TestObs {
362            data: test_stor_2.clone(),
363        };
364
365        let test_stor_3 = TestStor::new();
366        let test_obs_3 = TestObs {
367            data: test_stor_3.clone(),
368        };
369
370        let test_stor_4 = TestStor::new();
371        let test_obs_4 = TestObs {
372            data: test_stor_4.clone(),
373        };
374
375        let storages = [test_stor_1, test_stor_2, test_stor_3, test_stor_4];
376
377        type TState = IterState<Vec<f64>, (), (), (), (), f64>;
378
379        let mut obs: Observers<TState> = Observers::new();
380        obs.push(test_obs_1, ObserverMode::Never)
381            .push(test_obs_2, ObserverMode::Always)
382            .push(test_obs_3, ObserverMode::Every(3))
383            .push(test_obs_4, ObserverMode::NewBest);
384
385        let mut state: TState = IterState::new();
386
387        obs.observe_init("test_solver", &state, &kv!()).unwrap();
388
389        // all `init_called` should be 1, all `iter_called` 0
390        for s in storages.iter() {
391            let observer = s.lock().unwrap();
392            assert_eq!(observer.solver_name, "test_solver");
393            assert_eq!(observer.init_called, 1);
394            assert_eq!(observer.iter_called, 0);
395        }
396
397        obs.observe_iter(&state, &kv!()).unwrap();
398
399        assert_eq!(storages[0].lock().unwrap().init_called, 1);
400        assert_eq!(storages[0].lock().unwrap().iter_called, 0);
401        assert_eq!(storages[1].lock().unwrap().init_called, 1);
402        assert_eq!(storages[1].lock().unwrap().iter_called, 1);
403        assert_eq!(storages[2].lock().unwrap().init_called, 1);
404        assert_eq!(storages[2].lock().unwrap().iter_called, 1);
405        assert_eq!(storages[3].lock().unwrap().init_called, 1);
406        assert_eq!(storages[3].lock().unwrap().iter_called, 1);
407
408        state.increment_iter();
409        obs.observe_iter(&state, &kv!()).unwrap();
410
411        assert_eq!(storages[0].lock().unwrap().init_called, 1);
412        assert_eq!(storages[0].lock().unwrap().iter_called, 0);
413        assert_eq!(storages[1].lock().unwrap().init_called, 1);
414        assert_eq!(storages[1].lock().unwrap().iter_called, 2);
415        assert_eq!(storages[2].lock().unwrap().init_called, 1);
416        assert_eq!(storages[2].lock().unwrap().iter_called, 1);
417        assert_eq!(storages[3].lock().unwrap().init_called, 1);
418        assert_eq!(storages[3].lock().unwrap().iter_called, 1);
419
420        state.increment_iter();
421        state.increment_iter();
422        obs.observe_iter(&state, &kv!()).unwrap();
423
424        assert_eq!(storages[0].lock().unwrap().init_called, 1);
425        assert_eq!(storages[0].lock().unwrap().iter_called, 0);
426        assert_eq!(storages[1].lock().unwrap().init_called, 1);
427        assert_eq!(storages[1].lock().unwrap().iter_called, 3);
428        assert_eq!(storages[2].lock().unwrap().init_called, 1);
429        assert_eq!(storages[2].lock().unwrap().iter_called, 2);
430        assert_eq!(storages[3].lock().unwrap().init_called, 1);
431        assert_eq!(storages[3].lock().unwrap().iter_called, 1);
432
433        state.increment_iter();
434        // "new best found"
435        state.last_best_iter = state.iter;
436        obs.observe_iter(&state, &kv!()).unwrap();
437
438        assert_eq!(storages[0].lock().unwrap().init_called, 1);
439        assert_eq!(storages[0].lock().unwrap().iter_called, 0);
440        assert_eq!(storages[1].lock().unwrap().init_called, 1);
441        assert_eq!(storages[1].lock().unwrap().iter_called, 4);
442        assert_eq!(storages[2].lock().unwrap().init_called, 1);
443        assert_eq!(storages[2].lock().unwrap().iter_called, 2);
444        assert_eq!(storages[3].lock().unwrap().init_called, 1);
445        assert_eq!(storages[3].lock().unwrap().iter_called, 2);
446    }
447}