solverforge_solver/termination/
unimproved.rs

1//! Termination conditions based on lack of improvement.
2
3use std::cell::RefCell;
4use std::fmt::Debug;
5use std::marker::PhantomData;
6use std::time::{Duration, Instant};
7
8use solverforge_core::domain::PlanningSolution;
9use solverforge_core::score::Score;
10use solverforge_scoring::ScoreDirector;
11
12use super::Termination;
13use crate::scope::SolverScope;
14
15/// Terminates if no improvement occurs for a specified number of steps.
16///
17/// This is useful to avoid spending too much time when the solver has
18/// plateaued and is unlikely to find better solutions.
19///
20/// # Example
21///
22/// ```
23/// use solverforge_solver::termination::UnimprovedStepCountTermination;
24/// use solverforge_core::score::SimpleScore;
25/// use solverforge_core::domain::PlanningSolution;
26///
27/// #[derive(Clone)]
28/// struct MySolution;
29/// impl PlanningSolution for MySolution {
30///     type Score = SimpleScore;
31///     fn score(&self) -> Option<Self::Score> { None }
32///     fn set_score(&mut self, _: Option<Self::Score>) {}
33/// }
34///
35/// // Terminate after 100 steps without improvement
36/// let term = UnimprovedStepCountTermination::<MySolution>::new(100);
37/// ```
38pub struct UnimprovedStepCountTermination<S: PlanningSolution> {
39    limit: u64,
40    state: RefCell<UnimprovedState<S::Score>>,
41    _phantom: PhantomData<fn() -> S>,
42}
43
44impl<S: PlanningSolution> Debug for UnimprovedStepCountTermination<S> {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        let state = self.state.borrow();
47        f.debug_struct("UnimprovedStepCountTermination")
48            .field("limit", &self.limit)
49            .field("steps_since_improvement", &state.steps_since_improvement)
50            .finish()
51    }
52}
53
54#[derive(Clone)]
55struct UnimprovedState<Sc: Score> {
56    last_best_score: Option<Sc>,
57    steps_since_improvement: u64,
58    last_checked_step: Option<u64>,
59}
60
61impl<Sc: Score> Default for UnimprovedState<Sc> {
62    fn default() -> Self {
63        Self {
64            last_best_score: None,
65            steps_since_improvement: 0,
66            last_checked_step: None,
67        }
68    }
69}
70
71impl<S: PlanningSolution> UnimprovedStepCountTermination<S> {
72    /// Creates a termination that stops after `limit` steps without improvement.
73    pub fn new(limit: u64) -> Self {
74        Self {
75            limit,
76            state: RefCell::new(UnimprovedState::default()),
77            _phantom: PhantomData,
78        }
79    }
80}
81
82// Safety: The RefCell is only accessed from within is_terminated,
83// which is called from a single thread during solving.
84unsafe impl<S: PlanningSolution> Send for UnimprovedStepCountTermination<S> {}
85
86impl<S: PlanningSolution, D: ScoreDirector<S>> Termination<S, D>
87    for UnimprovedStepCountTermination<S>
88{
89    fn is_terminated(&self, solver_scope: &SolverScope<S, D>) -> bool {
90        let mut state = self.state.borrow_mut();
91        let current_step = solver_scope.total_step_count();
92
93        // Avoid rechecking on the same step
94        if state.last_checked_step == Some(current_step) {
95            return state.steps_since_improvement >= self.limit;
96        }
97        state.last_checked_step = Some(current_step);
98
99        let current_best = solver_scope.best_score();
100
101        match (&state.last_best_score, current_best) {
102            (None, Some(score)) => {
103                // First score recorded
104                state.last_best_score = Some(*score);
105                state.steps_since_improvement = 0;
106            }
107            (Some(last), Some(current)) => {
108                if *current > *last {
109                    // Improvement found
110                    state.last_best_score = Some(*current);
111                    state.steps_since_improvement = 0;
112                } else {
113                    // No improvement
114                    state.steps_since_improvement += 1;
115                }
116            }
117            (Some(_), None) => {
118                // Score became unavailable (shouldn't happen normally)
119                state.steps_since_improvement += 1;
120            }
121            (None, None) => {
122                // No score yet
123            }
124        }
125
126        state.steps_since_improvement >= self.limit
127    }
128}
129
130/// Terminates if no improvement occurs for a specified duration.
131///
132/// This is useful for time-boxed optimization where you want to ensure
133/// progress is being made, but also allow more time if improvements are found.
134///
135/// # Example
136///
137/// ```
138/// use std::time::Duration;
139/// use solverforge_solver::termination::UnimprovedTimeTermination;
140/// use solverforge_core::score::SimpleScore;
141/// use solverforge_core::domain::PlanningSolution;
142///
143/// #[derive(Clone)]
144/// struct MySolution;
145/// impl PlanningSolution for MySolution {
146///     type Score = SimpleScore;
147///     fn score(&self) -> Option<Self::Score> { None }
148///     fn set_score(&mut self, _: Option<Self::Score>) {}
149/// }
150///
151/// // Terminate after 5 seconds without improvement
152/// let term = UnimprovedTimeTermination::<MySolution>::seconds(5);
153/// ```
154pub struct UnimprovedTimeTermination<S: PlanningSolution> {
155    limit: Duration,
156    state: RefCell<UnimprovedTimeState<S::Score>>,
157    _phantom: PhantomData<fn() -> S>,
158}
159
160impl<S: PlanningSolution> Debug for UnimprovedTimeTermination<S> {
161    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
162        f.debug_struct("UnimprovedTimeTermination")
163            .field("limit", &self.limit)
164            .finish()
165    }
166}
167
168struct UnimprovedTimeState<Sc: Score> {
169    last_best_score: Option<Sc>,
170    last_improvement_time: Option<Instant>,
171}
172
173impl<Sc: Score> Default for UnimprovedTimeState<Sc> {
174    fn default() -> Self {
175        Self {
176            last_best_score: None,
177            last_improvement_time: None,
178        }
179    }
180}
181
182impl<S: PlanningSolution> UnimprovedTimeTermination<S> {
183    /// Creates a termination that stops after `limit` time without improvement.
184    pub fn new(limit: Duration) -> Self {
185        Self {
186            limit,
187            state: RefCell::new(UnimprovedTimeState::default()),
188            _phantom: PhantomData,
189        }
190    }
191
192    /// Creates a termination with limit in milliseconds.
193    pub fn millis(ms: u64) -> Self {
194        Self::new(Duration::from_millis(ms))
195    }
196
197    /// Creates a termination with limit in seconds.
198    pub fn seconds(secs: u64) -> Self {
199        Self::new(Duration::from_secs(secs))
200    }
201}
202
203// Safety: The RefCell is only accessed from within is_terminated,
204// which is called from a single thread during solving.
205unsafe impl<S: PlanningSolution> Send for UnimprovedTimeTermination<S> {}
206
207impl<S: PlanningSolution, D: ScoreDirector<S>> Termination<S, D> for UnimprovedTimeTermination<S> {
208    fn is_terminated(&self, solver_scope: &SolverScope<S, D>) -> bool {
209        let mut state = self.state.borrow_mut();
210        let current_best = solver_scope.best_score();
211        let now = Instant::now();
212
213        match (&state.last_best_score, current_best) {
214            (None, Some(score)) => {
215                // First score recorded
216                state.last_best_score = Some(*score);
217                state.last_improvement_time = Some(now);
218                false
219            }
220            (Some(last), Some(current)) => {
221                if *current > *last {
222                    // Improvement found
223                    state.last_best_score = Some(*current);
224                    state.last_improvement_time = Some(now);
225                    false
226                } else {
227                    // No improvement - check time
228                    state
229                        .last_improvement_time
230                        .map(|t| now.duration_since(t) >= self.limit)
231                        .unwrap_or(false)
232                }
233            }
234            (Some(_), None) => {
235                // Score became unavailable
236                state
237                    .last_improvement_time
238                    .map(|t| now.duration_since(t) >= self.limit)
239                    .unwrap_or(false)
240            }
241            (None, None) => {
242                // No score yet, don't terminate
243                false
244            }
245        }
246    }
247}