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> Tracker<T>
17where
18    T: Clone + PartialOrd,
19{
20    pub fn new() -> Self {
21        Tracker {
22            best: None,
23            current: None,
24            stagnation: 0,
25        }
26    }
27
28    pub fn update(&mut self, other: &T, optimize: &Objective) {
29        self.current = Some(other.clone());
30
31        if let Some(best) = &self.best {
32            if optimize.is_better(other, best) {
33                self.best = Some(other.clone());
34                self.stagnation = 0;
35            } else {
36                self.stagnation += 1;
37            }
38        } else {
39            self.best = Some(other.clone());
40            self.stagnation = 0;
41        }
42    }
43
44    pub fn stagnation(&self) -> usize {
45        self.stagnation
46    }
47
48    pub fn best(&self) -> Option<&T> {
49        self.best.as_ref()
50    }
51
52    pub fn current(&self) -> Option<&T> {
53        self.current.as_ref()
54    }
55}