solverforge_solver/termination/
unimproved.rs1use 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
15pub 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 pub fn new(limit: u64) -> Self {
74 Self {
75 limit,
76 state: RefCell::new(UnimprovedState::default()),
77 _phantom: PhantomData,
78 }
79 }
80}
81
82unsafe 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 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 state.last_best_score = Some(*score);
105 state.steps_since_improvement = 0;
106 }
107 (Some(last), Some(current)) => {
108 if *current > *last {
109 state.last_best_score = Some(*current);
111 state.steps_since_improvement = 0;
112 } else {
113 state.steps_since_improvement += 1;
115 }
116 }
117 (Some(_), None) => {
118 state.steps_since_improvement += 1;
120 }
121 (None, None) => {
122 }
124 }
125
126 state.steps_since_improvement >= self.limit
127 }
128}
129
130pub 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 pub fn new(limit: Duration) -> Self {
185 Self {
186 limit,
187 state: RefCell::new(UnimprovedTimeState::default()),
188 _phantom: PhantomData,
189 }
190 }
191
192 pub fn millis(ms: u64) -> Self {
194 Self::new(Duration::from_millis(ms))
195 }
196
197 pub fn seconds(secs: u64) -> Self {
199 Self::new(Duration::from_secs(secs))
200 }
201}
202
203unsafe 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 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 state.last_best_score = Some(*current);
224 state.last_improvement_time = Some(now);
225 false
226 } else {
227 state
229 .last_improvement_time
230 .map(|t| now.duration_since(t) >= self.limit)
231 .unwrap_or(false)
232 }
233 }
234 (Some(_), None) => {
235 state
237 .last_improvement_time
238 .map(|t| now.duration_since(t) >= self.limit)
239 .unwrap_or(false)
240 }
241 (None, None) => {
242 false
244 }
245 }
246 }
247}