solverforge-solver 0.8.8

Solver engine for SolverForge
Documentation
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/* Solver statistics (zero-erasure).

Stack-allocated statistics for solver and phase performance tracking.
*/

use std::time::{Duration, Instant};

/* Solver-level statistics.

Tracks aggregate metrics across all phases of a solve run.

# Example

```
use solverforge_solver::stats::SolverStats;
use std::time::Duration;

let mut stats = SolverStats::default();
stats.start();
stats.record_step();
stats.record_generated_move(Duration::from_millis(1));
stats.record_evaluated_move(Duration::from_millis(2));
stats.record_move_accepted();
stats.record_generated_move(Duration::from_millis(1));
stats.record_evaluated_move(Duration::from_millis(2));

assert_eq!(stats.step_count, 1);
assert_eq!(stats.moves_evaluated, 2);
assert_eq!(stats.moves_accepted, 1);
```
*/
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct SolverTelemetry {
    pub elapsed: Duration,
    pub step_count: u64,
    pub moves_generated: u64,
    pub moves_evaluated: u64,
    pub moves_accepted: u64,
    pub score_calculations: u64,
    pub generation_time: Duration,
    pub evaluation_time: Duration,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Throughput {
    pub count: u64,
    pub elapsed: Duration,
}

pub(crate) fn whole_units_per_second(count: u64, elapsed: Duration) -> u128 {
    let nanos = elapsed.as_nanos();
    if nanos == 0 {
        0
    } else {
        u128::from(count)
            .saturating_mul(1_000_000_000)
            .checked_div(nanos)
            .unwrap_or(0)
    }
}

pub(crate) fn format_duration(duration: Duration) -> String {
    let secs = duration.as_secs();
    let nanos = duration.subsec_nanos();

    if secs >= 60 {
        let mins = secs / 60;
        let rem_secs = secs % 60;
        return format!("{mins}m {rem_secs}s");
    }

    if secs > 0 {
        let millis = nanos / 1_000_000;
        if millis == 0 {
            return format!("{secs}s");
        }
        return format!("{secs}s {millis}ms");
    }

    let millis = nanos / 1_000_000;
    if millis > 0 {
        return format!("{millis}ms");
    }

    let micros = nanos / 1_000;
    if micros > 0 {
        return format!("{micros}us");
    }

    format!("{nanos}ns")
}

#[derive(Debug, Default)]
pub struct SolverStats {
    start_time: Option<Instant>,
    pause_started_at: Option<Instant>,
    // Total steps taken across all phases.
    pub step_count: u64,
    // Total moves generated across all phases.
    pub moves_generated: u64,
    // Total moves evaluated across all phases.
    pub moves_evaluated: u64,
    // Total moves accepted across all phases.
    pub moves_accepted: u64,
    // Total score calculations performed.
    pub score_calculations: u64,
    generation_time: Duration,
    evaluation_time: Duration,
}

impl SolverStats {
    /// Marks the start of solving.
    pub fn start(&mut self) {
        self.start_time = Some(Instant::now());
        self.pause_started_at = None;
    }

    pub fn elapsed(&self) -> Duration {
        match (self.start_time, self.pause_started_at) {
            (Some(start), Some(paused_at)) => paused_at.duration_since(start),
            (Some(start), None) => start.elapsed(),
            _ => Duration::default(),
        }
    }

    pub fn pause(&mut self) {
        if self.start_time.is_some() && self.pause_started_at.is_none() {
            self.pause_started_at = Some(Instant::now());
        }
    }

    pub fn resume(&mut self) {
        if let (Some(start), Some(paused_at)) = (self.start_time, self.pause_started_at.take()) {
            self.start_time = Some(start + paused_at.elapsed());
        }
    }

    /// Records one or more generated candidate moves and the time spent generating them.
    pub fn record_generated_batch(&mut self, count: u64, duration: Duration) {
        self.moves_generated += count;
        self.generation_time += duration;
    }

    /// Records generation time that did not itself yield a counted move.
    pub fn record_generation_time(&mut self, duration: Duration) {
        self.generation_time += duration;
    }

    /// Records a single generated candidate move and the time spent generating it.
    pub fn record_generated_move(&mut self, duration: Duration) {
        self.record_generated_batch(1, duration);
    }

    /// Records a move evaluation and the time spent evaluating it.
    pub fn record_evaluated_move(&mut self, duration: Duration) {
        self.moves_evaluated += 1;
        self.evaluation_time += duration;
    }

    /// Records an accepted move.
    pub fn record_move_accepted(&mut self) {
        self.moves_accepted += 1;
    }

    /// Records a step completion.
    pub fn record_step(&mut self) {
        self.step_count += 1;
    }

    /// Records a score calculation.
    pub fn record_score_calculation(&mut self) {
        self.score_calculations += 1;
    }

    pub fn generated_throughput(&self) -> Throughput {
        Throughput {
            count: self.moves_generated,
            elapsed: self.generation_time,
        }
    }

    pub fn evaluated_throughput(&self) -> Throughput {
        Throughput {
            count: self.moves_evaluated,
            elapsed: self.evaluation_time,
        }
    }

    pub fn acceptance_rate(&self) -> f64 {
        if self.moves_evaluated == 0 {
            0.0
        } else {
            self.moves_accepted as f64 / self.moves_evaluated as f64
        }
    }

    pub fn generation_time(&self) -> Duration {
        self.generation_time
    }

    pub fn evaluation_time(&self) -> Duration {
        self.evaluation_time
    }

    pub fn snapshot(&self) -> SolverTelemetry {
        SolverTelemetry {
            elapsed: self.elapsed(),
            step_count: self.step_count,
            moves_generated: self.moves_generated,
            moves_evaluated: self.moves_evaluated,
            moves_accepted: self.moves_accepted,
            score_calculations: self.score_calculations,
            generation_time: self.generation_time,
            evaluation_time: self.evaluation_time,
        }
    }
}

/* Phase-level statistics.

Tracks metrics for a single solver phase.

# Example

```
use solverforge_solver::stats::PhaseStats;
use std::time::Duration;

let mut stats = PhaseStats::new(0, "LocalSearch");
stats.record_step();
stats.record_generated_move(Duration::from_millis(1));
stats.record_evaluated_move(Duration::from_millis(2));
stats.record_move_accepted();

assert_eq!(stats.phase_index, 0);
assert_eq!(stats.phase_type, "LocalSearch");
assert_eq!(stats.step_count, 1);
assert_eq!(stats.moves_accepted, 1);
```
*/
#[derive(Debug)]
pub struct PhaseStats {
    // Index of this phase (0-based).
    pub phase_index: usize,
    // Type name of the phase.
    pub phase_type: &'static str,
    start_time: Instant,
    // Number of steps taken in this phase.
    pub step_count: u64,
    // Number of moves generated in this phase.
    pub moves_generated: u64,
    // Number of moves evaluated in this phase.
    pub moves_evaluated: u64,
    // Number of moves accepted in this phase.
    pub moves_accepted: u64,
    // Number of score calculations in this phase.
    pub score_calculations: u64,
    generation_time: Duration,
    evaluation_time: Duration,
}

impl PhaseStats {
    /// Creates new phase statistics.
    pub fn new(phase_index: usize, phase_type: &'static str) -> Self {
        Self {
            phase_index,
            phase_type,
            start_time: Instant::now(),
            step_count: 0,
            moves_generated: 0,
            moves_evaluated: 0,
            moves_accepted: 0,
            score_calculations: 0,
            generation_time: Duration::default(),
            evaluation_time: Duration::default(),
        }
    }

    pub fn elapsed(&self) -> Duration {
        self.start_time.elapsed()
    }

    /// Records a step completion.
    pub fn record_step(&mut self) {
        self.step_count += 1;
    }

    /// Records one or more generated candidate moves and the time spent generating them.
    pub fn record_generated_batch(&mut self, count: u64, duration: Duration) {
        self.moves_generated += count;
        self.generation_time += duration;
    }

    /// Records generation time that did not itself yield a counted move.
    pub fn record_generation_time(&mut self, duration: Duration) {
        self.generation_time += duration;
    }

    /// Records a single generated candidate move and the time spent generating it.
    pub fn record_generated_move(&mut self, duration: Duration) {
        self.record_generated_batch(1, duration);
    }

    /// Records a move evaluation and the time spent evaluating it.
    pub fn record_evaluated_move(&mut self, duration: Duration) {
        self.moves_evaluated += 1;
        self.evaluation_time += duration;
    }

    /// Records an accepted move.
    pub fn record_move_accepted(&mut self) {
        self.moves_accepted += 1;
    }

    /// Records a score calculation.
    pub fn record_score_calculation(&mut self) {
        self.score_calculations += 1;
    }

    pub fn generated_throughput(&self) -> Throughput {
        Throughput {
            count: self.moves_generated,
            elapsed: self.generation_time,
        }
    }

    pub fn evaluated_throughput(&self) -> Throughput {
        Throughput {
            count: self.moves_evaluated,
            elapsed: self.evaluation_time,
        }
    }

    pub fn acceptance_rate(&self) -> f64 {
        if self.moves_evaluated == 0 {
            0.0
        } else {
            self.moves_accepted as f64 / self.moves_evaluated as f64
        }
    }

    pub fn generation_time(&self) -> Duration {
        self.generation_time
    }

    pub fn evaluation_time(&self) -> Duration {
        self.evaluation_time
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn solver_snapshot_preserves_exact_counts_and_durations() {
        let mut stats = SolverStats::default();
        stats.start();
        stats.record_step();
        stats.record_generated_batch(3, Duration::from_millis(4));
        stats.record_evaluated_move(Duration::from_millis(5));
        stats.record_move_accepted();
        stats.record_score_calculation();

        let snapshot = stats.snapshot();

        assert_eq!(snapshot.step_count, 1);
        assert_eq!(snapshot.moves_generated, 3);
        assert_eq!(snapshot.moves_evaluated, 1);
        assert_eq!(snapshot.moves_accepted, 1);
        assert_eq!(snapshot.score_calculations, 1);
        assert_eq!(snapshot.generation_time, Duration::from_millis(4));
        assert_eq!(snapshot.evaluation_time, Duration::from_millis(5));
    }

    #[test]
    fn phase_stats_track_generation_and_evaluation_separately() {
        let mut stats = PhaseStats::new(2, "LocalSearch");
        stats.record_step();
        stats.record_generated_batch(7, Duration::from_millis(8));
        stats.record_evaluated_move(Duration::from_millis(9));
        stats.record_move_accepted();
        stats.record_score_calculation();

        assert_eq!(stats.phase_index, 2);
        assert_eq!(stats.phase_type, "LocalSearch");
        assert_eq!(stats.step_count, 1);
        assert_eq!(stats.moves_generated, 7);
        assert_eq!(stats.moves_evaluated, 1);
        assert_eq!(stats.moves_accepted, 1);
        assert_eq!(stats.score_calculations, 1);
        assert_eq!(stats.generation_time(), Duration::from_millis(8));
        assert_eq!(stats.evaluation_time(), Duration::from_millis(9));
    }

    #[test]
    fn throughput_helpers_use_stage_specific_durations() {
        let mut solver_stats = SolverStats::default();
        solver_stats.start();
        solver_stats.record_generated_batch(5, Duration::from_millis(7));
        solver_stats.record_evaluated_move(Duration::from_millis(11));

        let mut phase_stats = PhaseStats::new(1, "LocalSearch");
        phase_stats.record_generated_batch(3, Duration::from_millis(13));
        phase_stats.record_evaluated_move(Duration::from_millis(17));

        assert_eq!(
            solver_stats.generated_throughput(),
            Throughput {
                count: 5,
                elapsed: Duration::from_millis(7),
            }
        );
        assert_eq!(
            solver_stats.evaluated_throughput(),
            Throughput {
                count: 1,
                elapsed: Duration::from_millis(11),
            }
        );
        assert_eq!(
            phase_stats.generated_throughput(),
            Throughput {
                count: 3,
                elapsed: Duration::from_millis(13),
            }
        );
        assert_eq!(
            phase_stats.evaluated_throughput(),
            Throughput {
                count: 1,
                elapsed: Duration::from_millis(17),
            }
        );
    }

    #[test]
    fn whole_units_per_second_uses_integer_rate_math() {
        assert_eq!(whole_units_per_second(3, Duration::from_millis(2_000)), 1);
        assert_eq!(whole_units_per_second(9, Duration::from_secs(2)), 4);
        assert_eq!(whole_units_per_second(5, Duration::ZERO), 0);
    }

    #[test]
    fn format_duration_uses_exact_integer_units() {
        assert_eq!(format_duration(Duration::from_millis(750)), "750ms");
        assert_eq!(format_duration(Duration::from_millis(2_500)), "2s 500ms");
        assert_eq!(format_duration(Duration::from_secs(125)), "2m 5s");
        assert_eq!(format_duration(Duration::from_micros(42)), "42us");
    }
}