1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//! Stop criteria, checked once per step at the loop boundary.
use super::config::{RaceSnapshot, StopReason};
use super::core::CoreEngine;
impl CoreEngine {
/// Check the stop criteria at this step: `Some(reason)` if one fires, `None`
/// to continue. `custom_stop` is independent and runs after the built-ins.
pub(crate) fn check_stop(&mut self, step: usize) -> Option<StopReason> {
// 1.
if let Some(max) = self.config.max_steps {
if step + 1 >= max {
return Some(StopReason::MaxSteps);
}
}
self.check_stop_outside_the_budget(step)
}
/// The same criteria at the TOP of a clock, for a RESUMED race whose clock
pub(crate) fn check_stop_before_clock(&mut self, next: usize) -> Option<StopReason> {
if let Some(max) = self.config.max_steps {
if next >= max {
return Some(StopReason::MaxSteps);
}
}
self.check_stop_outside_the_budget(next)
}
/// Ctrl+C, then the user's `custom_stop` — the criteria that do not count
/// clocks and so read the same from either end of one.
fn check_stop_outside_the_budget(&mut self, step: usize) -> Option<StopReason> {
// 0. Ctrl+C first — the user's intent outranks every bar, and abandoning
// flows through the same artifact path as a natural stop (step included).
if let Some(flag) = &self.interrupt_flag {
if flag.load(std::sync::atomic::Ordering::SeqCst) {
// CFY: the interrupt notice is a table, not a one-liner.
crate::utils::cfy::emit(&crate::utils::cfy::card(
"Race",
&crate::utils::cfy::kv(&[(
"ctrl+c".to_string(),
format!("graceful shutdown after step {step}"),
)]),
None,
));
return Some(StopReason::Interrupted);
}
}
// 2. Custom stop: joins the race IN ADDITION to the built-ins,
// criteria they don't model.
if let Some(stop) = self.config.custom_stop.as_ref() {
if stop(&self.snapshot(step)) {
return Some(StopReason::CustomStop);
}
}
None
}
/// Build the read-only [`RaceSnapshot`] for a custom stop: `best`/`worst`
/// direction-aware, `mean` is the plain arithmetic mean.
pub(crate) fn snapshot(&self, step: usize) -> RaceSnapshot {
let smoothed = self.smoothed_fitness_values();
let (best, worst, mean) = if smoothed.is_empty() {
(0.0, 0.0, 0.0)
} else {
let direction = self.fitness.direction();
let mut best = smoothed[0];
let mut worst = smoothed[0];
for &v in &smoothed[1..] {
if direction.is_better(v, best) {
best = v;
}
if direction.is_better(worst, v) {
worst = v;
}
}
let mean = smoothed.iter().sum::<f32>() / smoothed.len() as f32;
(best, worst, mean)
};
RaceSnapshot {
live_count: self.state.live_count(),
step,
best_smoothed_fitness: best,
worst_smoothed_fitness: worst,
mean_smoothed_fitness: mean,
culls: self.culls,
elapsed_seconds: self.elapsed_base_secs + self.started_at_wall.elapsed().as_secs(),
}
}
}