Skip to main content

radiate_core/domain/
tracker.rs

1use crate::Objective;
2#[cfg(feature = "serde")]
3use serde::{Deserialize, Serialize};
4
5#[derive(Debug, Clone)]
6#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7pub struct Tracker<T>
8where
9    T: Clone + PartialOrd,
10{
11    pub best: Option<T>,
12    pub current: Option<T>,
13    pub stagnation: usize,
14}
15
16impl<T> Default for Tracker<T>
17where
18    T: Clone + PartialOrd,
19{
20    fn default() -> Self {
21        Self::new()
22    }
23}
24
25impl<T> Tracker<T>
26where
27    T: Clone + PartialOrd,
28{
29    pub fn new() -> Self {
30        Tracker {
31            best: None,
32            current: None,
33            stagnation: 0,
34        }
35    }
36
37    pub fn update(&mut self, other: &T, optimize: &Objective) {
38        self.current = Some(other.clone());
39
40        if let Some(best) = &self.best {
41            if optimize.is_better(other, best) {
42                self.best = Some(other.clone());
43                self.stagnation = 0;
44            } else {
45                self.stagnation += 1;
46            }
47        } else {
48            self.best = Some(other.clone());
49            self.stagnation = 0;
50        }
51    }
52
53    pub fn stagnation(&self) -> usize {
54        self.stagnation
55    }
56
57    pub fn best(&self) -> Option<&T> {
58        self.best.as_ref()
59    }
60
61    pub fn current(&self) -> Option<&T> {
62        self.current.as_ref()
63    }
64}