optimum/core/solver/
hook.rs

1//! Defines a `Hook` trait for [Solver][super::Solver] and basic `Hook` structs.
2//!
3//!  It's highly recommended that you create `Hook` traits for your metaheuristics to allow callers to add custom
4//! behavior into your metaheuristic.
5
6use super::super::{Evaluation, Problem};
7
8/// This trait allows callers to hook into special moments in the execution of the `Solver` to do things such as logging.
9pub trait IterHook<P: Problem> {
10    /// Called right after the iteration is performed. `new` is the newly generated evaluation yield by [iterate][super::Solver::iterate].
11    fn iterated(&mut self, _new: &Evaluation<P>) {}
12
13    /// Called when the "global" best is being replaced by a new evaluation.
14    fn better_changed(&mut self, _old: &Evaluation<P>, _new: &Evaluation<P>) {}
15}
16
17/// It does nothing.
18pub struct Empty;
19
20impl<P: Problem> IterHook<P> for Empty {}
21
22/// This hook just prints the iteration's values on stderr.
23pub struct Print(usize);
24
25impl Print {
26    /// Creates a new `Print` hook.
27    pub fn new() -> Self {
28        Self(0)
29    }
30}
31
32impl Default for Print {
33    fn default() -> Self {
34        Self::new()
35    }
36}
37
38impl<P: Problem> IterHook<P> for Print
39where
40    P::Value: std::fmt::Display,
41{
42    fn iterated(&mut self, new: &Evaluation<P>) {
43        self.0 += 1;
44        eprintln!("ITER {} VALUE {}", self.0, new.value());
45    }
46}