elevator-core 15.14.0

Engine-agnostic elevator simulation library with pluggable dispatch strategies
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
//! Aggregate simulation metrics (wait times, throughput, distance).

use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::collections::VecDeque;
use std::fmt;

/// Aggregated simulation metrics, updated each tick from events.
///
/// Games query this via `sim.metrics()` for HUD display, scoring,
/// or scenario evaluation.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Metrics {
    // -- Queryable metrics (accessed via getters) --
    /// Average wait time in ticks (spawn to board).
    pub(crate) avg_wait_time: f64,
    /// Average ride time in ticks (board to exit).
    pub(crate) avg_ride_time: f64,
    /// Maximum wait time observed (ticks).
    pub(crate) max_wait_time: u64,
    /// Riders delivered in the current throughput window.
    pub(crate) throughput: u64,
    /// Riders delivered total.
    pub(crate) total_delivered: u64,
    /// Riders who abandoned.
    pub(crate) total_abandoned: u64,
    /// Total riders spawned.
    pub(crate) total_spawned: u64,
    /// Abandonment rate (0.0 - 1.0).
    pub(crate) abandonment_rate: f64,
    /// Total distance traveled by all elevators.
    pub(crate) total_distance: f64,
    /// Per-group instantaneous elevator utilization: fraction of elevators
    /// currently moving (either `MovingToStop` or `Repositioning`) vs total
    /// enabled elevators. Overwritten each tick. Key is group name (String
    /// for serialization).
    #[serde(default)]
    pub(crate) utilization_by_group: BTreeMap<String, f64>,
    /// Total distance traveled by elevators while repositioning.
    #[serde(default)]
    pub(crate) reposition_distance: f64,
    /// Total rounded-floor transitions across all elevators
    /// (passing-floor crossings plus arrivals).
    #[serde(default)]
    pub(crate) total_moves: u64,
    /// Total riders settled as residents.
    pub(crate) total_settled: u64,
    /// Total riders rerouted from resident phase.
    pub(crate) total_rerouted: u64,

    /// Total energy consumed by all elevators.
    #[cfg(feature = "energy")]
    #[serde(default)]
    pub(crate) total_energy_consumed: f64,
    /// Total energy regenerated by all elevators.
    #[cfg(feature = "energy")]
    #[serde(default)]
    pub(crate) total_energy_regenerated: f64,

    // -- Internal accumulators --
    /// Running sum of wait ticks across all boarded riders.
    sum_wait_ticks: u64,
    /// Running sum of ride ticks across all delivered riders.
    sum_ride_ticks: u64,
    /// Number of riders that have boarded.
    boarded_count: u64,
    /// Number of riders that have been delivered.
    delivered_count: u64,
    /// Sliding window of delivery ticks, sorted ascending.
    delivery_window: VecDeque<u64>,
    /// Window size for throughput calculation.
    pub(crate) throughput_window_ticks: u64,
    /// Ring buffer of the most-recent wait samples (spawn-to-board ticks).
    /// Powers [`percentile_wait_time`](Metrics::percentile_wait_time). Capped
    /// by [`wait_sample_capacity`](Self::wait_sample_capacity); oldest samples
    /// are evicted when full.
    #[serde(default)]
    wait_samples: VecDeque<u64>,
    /// Maximum number of wait samples retained. `0` disables sampling; the
    /// default matches [`default_wait_sample_capacity`], ~80 KB of RAM.
    #[serde(default = "default_wait_sample_capacity")]
    pub(crate) wait_sample_capacity: usize,
}

/// Default capacity for the wait-sample ring buffer. 10 000 samples is
/// enough to keep a stable p95 over multi-hour simulations while bounding
/// memory at ~80 KB. Exposed as a named function so serde's
/// `#[serde(default = "...")]` can reference it for schema evolution.
const fn default_wait_sample_capacity() -> usize {
    10_000
}

impl Default for Metrics {
    /// Delegates to [`Metrics::new`] so `#[derive(Default)]`-on-holders and
    /// direct `Metrics::default()` callers get the same 3600-tick throughput
    /// window and 10 000-sample wait buffer that `new()` wires up. Without
    /// this, the derived `Default` would zero every field — silently
    /// disabling `p95_wait_time` sampling and collapsing the throughput
    /// window to an empty range (greptile review of #347).
    fn default() -> Self {
        Self::new()
    }
}

impl Metrics {
    /// Create a new `Metrics` with default throughput window (3600 ticks)
    /// and default wait-sample capacity (10 000).
    #[must_use]
    pub const fn new() -> Self {
        Self {
            avg_wait_time: 0.0,
            avg_ride_time: 0.0,
            max_wait_time: 0,
            throughput: 0,
            total_delivered: 0,
            total_abandoned: 0,
            total_spawned: 0,
            abandonment_rate: 0.0,
            total_distance: 0.0,
            utilization_by_group: BTreeMap::new(),
            reposition_distance: 0.0,
            total_moves: 0,
            total_settled: 0,
            total_rerouted: 0,
            #[cfg(feature = "energy")]
            total_energy_consumed: 0.0,
            #[cfg(feature = "energy")]
            total_energy_regenerated: 0.0,
            sum_wait_ticks: 0,
            sum_ride_ticks: 0,
            boarded_count: 0,
            delivered_count: 0,
            delivery_window: VecDeque::new(),
            throughput_window_ticks: 3600, // default: 1 minute at 60 tps
            wait_samples: VecDeque::new(),
            wait_sample_capacity: default_wait_sample_capacity(),
        }
    }

    /// Set the throughput window size (builder pattern).
    #[must_use]
    pub const fn with_throughput_window(mut self, window_ticks: u64) -> Self {
        self.throughput_window_ticks = window_ticks;
        self
    }

    /// Set the wait-sample ring buffer capacity (builder pattern). `0`
    /// disables wait sampling entirely; [`percentile_wait_time`](Self::percentile_wait_time)
    /// will return 0 once the buffer is empty.
    ///
    /// Shrinking below the current sample count truncates from the front
    /// (oldest samples evicted first) so the retained window always
    /// represents the most recent waits.
    #[must_use]
    pub fn with_wait_sample_capacity(mut self, capacity: usize) -> Self {
        self.wait_sample_capacity = capacity;
        while self.wait_samples.len() > capacity {
            self.wait_samples.pop_front();
        }
        self
    }

    // ── Getters ──────────────────────────────────��───────────────────

    /// Average wait time in ticks (spawn to board).
    #[must_use]
    pub const fn avg_wait_time(&self) -> f64 {
        self.avg_wait_time
    }

    /// Average ride time in ticks (board to exit).
    #[must_use]
    pub const fn avg_ride_time(&self) -> f64 {
        self.avg_ride_time
    }

    /// Maximum wait time observed (ticks).
    #[must_use]
    pub const fn max_wait_time(&self) -> u64 {
        self.max_wait_time
    }

    /// 95th-percentile wait time over the last `wait_sample_capacity`
    /// boardings (ticks). Shorthand for `percentile_wait_time(95.0)`.
    /// Returns `0` when no samples have been recorded.
    ///
    /// CIBSE and community-benchmark traffic studies score against
    /// percentiles rather than the `(avg, max)` pair alone — max is
    /// dominated by rare outliers, avg hides the tail.
    #[must_use]
    pub fn p95_wait_time(&self) -> u64 {
        self.percentile_wait_time(95.0)
    }

    /// Wait-time percentile over the retained sample window (ticks).
    ///
    /// Uses the "nearest-rank" method: `ceil(p/100 * n)`-th smallest
    /// sample, clamped into `0..n`. `p = 0.0` returns the minimum,
    /// `p = 100.0` returns the maximum. Returns `0` when the buffer
    /// is empty.
    ///
    /// # Panics
    /// Panics if `p` is NaN or outside `[0.0, 100.0]`.
    #[must_use]
    pub fn percentile_wait_time(&self, p: f64) -> u64 {
        assert!(
            p.is_finite() && (0.0..=100.0).contains(&p),
            "percentile must be finite and in [0, 100], got {p}"
        );
        if self.wait_samples.is_empty() {
            return 0;
        }
        let mut sorted: Vec<u64> = self.wait_samples.iter().copied().collect();
        sorted.sort_unstable();
        let n = sorted.len();
        #[allow(clippy::cast_precision_loss)] // n ≤ capacity, set by user
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        let rank = ((p / 100.0) * n as f64).ceil() as usize;
        let idx = rank.saturating_sub(1).min(n - 1);
        sorted[idx]
    }

    /// Number of wait samples currently retained in the ring buffer.
    /// Useful for tests and HUDs that want to display "5 000 samples
    /// over last window" style diagnostics.
    #[must_use]
    pub fn wait_sample_count(&self) -> usize {
        self.wait_samples.len()
    }

    /// Riders delivered in the current throughput window.
    #[must_use]
    pub const fn throughput(&self) -> u64 {
        self.throughput
    }

    /// Riders delivered total.
    #[must_use]
    pub const fn total_delivered(&self) -> u64 {
        self.total_delivered
    }

    /// Riders who abandoned.
    #[must_use]
    pub const fn total_abandoned(&self) -> u64 {
        self.total_abandoned
    }

    /// Total riders spawned.
    #[must_use]
    pub const fn total_spawned(&self) -> u64 {
        self.total_spawned
    }

    /// Abandonment rate (0.0 - 1.0).
    #[must_use]
    pub const fn abandonment_rate(&self) -> f64 {
        self.abandonment_rate
    }

    /// Total distance traveled by all elevators.
    #[must_use]
    pub const fn total_distance(&self) -> f64 {
        self.total_distance
    }

    /// Per-group instantaneous elevator utilization (fraction of elevators moving).
    #[must_use]
    pub const fn utilization_by_group(&self) -> &BTreeMap<String, f64> {
        &self.utilization_by_group
    }

    /// Total distance traveled by elevators while repositioning.
    #[must_use]
    pub const fn reposition_distance(&self) -> f64 {
        self.reposition_distance
    }

    /// Total rounded-floor transitions across all elevators (passing-floor
    /// crossings plus arrivals).
    #[must_use]
    pub const fn total_moves(&self) -> u64 {
        self.total_moves
    }

    /// Total riders settled as residents.
    #[must_use]
    pub const fn total_settled(&self) -> u64 {
        self.total_settled
    }

    /// Total riders rerouted from resident phase.
    #[must_use]
    pub const fn total_rerouted(&self) -> u64 {
        self.total_rerouted
    }

    /// Window size for throughput calculation (ticks).
    #[must_use]
    pub const fn throughput_window_ticks(&self) -> u64 {
        self.throughput_window_ticks
    }

    /// Total energy consumed by all elevators (requires `energy` feature).
    #[cfg(feature = "energy")]
    #[must_use]
    pub const fn total_energy_consumed(&self) -> f64 {
        self.total_energy_consumed
    }

    /// Total energy regenerated by all elevators (requires `energy` feature).
    #[cfg(feature = "energy")]
    #[must_use]
    pub const fn total_energy_regenerated(&self) -> f64 {
        self.total_energy_regenerated
    }

    /// Net energy: consumed minus regenerated (requires `energy` feature).
    #[cfg(feature = "energy")]
    #[must_use]
    pub const fn net_energy(&self) -> f64 {
        self.total_energy_consumed - self.total_energy_regenerated
    }

    // ── Recording ───────────────────���────────────────────────────────

    /// Overall utilization: average across all groups.
    #[must_use]
    pub fn avg_utilization(&self) -> f64 {
        if self.utilization_by_group.is_empty() {
            return 0.0;
        }
        let sum: f64 = self.utilization_by_group.values().sum();
        sum / self.utilization_by_group.len() as f64
    }

    /// Record a rider spawning.
    pub(crate) const fn record_spawn(&mut self) {
        self.total_spawned += 1;
    }

    /// Record a rider boarding. `wait_ticks` = `tick_boarded` - `tick_spawned`.
    #[allow(clippy::cast_precision_loss)] // rider counts fit in f64 mantissa
    pub(crate) fn record_board(&mut self, wait_ticks: u64) {
        self.boarded_count += 1;
        self.sum_wait_ticks += wait_ticks;
        self.avg_wait_time = self.sum_wait_ticks as f64 / self.boarded_count as f64;
        if wait_ticks > self.max_wait_time {
            self.max_wait_time = wait_ticks;
        }
        if self.wait_sample_capacity > 0 {
            if self.wait_samples.len() == self.wait_sample_capacity {
                self.wait_samples.pop_front();
            }
            self.wait_samples.push_back(wait_ticks);
        }
    }

    /// Record a rider exiting. `ride_ticks` = `tick_exited` - `tick_boarded`.
    #[allow(clippy::cast_precision_loss)] // rider counts fit in f64 mantissa
    pub(crate) fn record_delivery(&mut self, ride_ticks: u64, tick: u64) {
        self.delivered_count += 1;
        self.total_delivered += 1;
        self.sum_ride_ticks += ride_ticks;
        self.avg_ride_time = self.sum_ride_ticks as f64 / self.delivered_count as f64;
        self.delivery_window.push_back(tick);
    }

    /// Record a rider abandoning.
    #[allow(clippy::cast_precision_loss)] // rider counts fit in f64 mantissa
    pub(crate) fn record_abandonment(&mut self) {
        self.total_abandoned += 1;
        if self.total_spawned > 0 {
            self.abandonment_rate = self.total_abandoned as f64 / self.total_spawned as f64;
        }
    }

    /// Record a rider settling as a resident.
    pub(crate) const fn record_settle(&mut self) {
        self.total_settled += 1;
    }

    /// Record a resident rider being rerouted.
    pub(crate) const fn record_reroute(&mut self) {
        self.total_rerouted += 1;
    }

    /// Record elevator distance traveled this tick.
    pub(crate) fn record_distance(&mut self, distance: f64) {
        self.total_distance += distance;
    }

    /// Record elevator distance traveled while repositioning.
    pub(crate) fn record_reposition_distance(&mut self, distance: f64) {
        self.reposition_distance += distance;
    }

    /// Record energy consumption and regeneration.
    #[cfg(feature = "energy")]
    pub(crate) fn record_energy(&mut self, consumed: f64, regenerated: f64) {
        self.total_energy_consumed += consumed;
        self.total_energy_regenerated += regenerated;
    }

    /// Update windowed throughput. Call once per tick.
    #[allow(clippy::cast_possible_truncation)] // window len always fits in u64
    pub(crate) fn update_throughput(&mut self, current_tick: u64) {
        let cutoff = current_tick.saturating_sub(self.throughput_window_ticks);
        // Delivery ticks are inserted in order, so expired entries are at the front.
        while self.delivery_window.front().is_some_and(|&t| t <= cutoff) {
            self.delivery_window.pop_front();
        }
        self.throughput = self.delivery_window.len() as u64;
    }
}

impl fmt::Display for Metrics {
    /// Compact one-line summary for HUDs and logs.
    ///
    /// ```
    /// # use elevator_core::metrics::Metrics;
    /// let m = Metrics::new();
    /// assert_eq!(format!("{m}"), "0 delivered, avg wait 0.0t, 0% util");
    /// ```
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} delivered, avg wait {:.1}t, {:.0}% util",
            self.total_delivered,
            self.avg_wait_time,
            self.avg_utilization() * 100.0,
        )
    }
}