Skip to main content

elevator_core/dispatch/
rsr.rs

1//! Relative System Response (RSR) dispatch — a composite additive
2//! cost stack.
3//!
4//! Inspired by the Otis patent lineage (Bittar US5024295A, US5146053A)
5//! and the Barney–dos Santos CGC framework. Unlike those proprietary
6//! systems, this implementation is an educational model, not a
7//! faithful reproduction of any vendor's scoring.
8//!
9//! Shape: `rank = eta_weight · travel_time + Σ penalties − Σ bonuses`.
10//! All terms are additive scalars, so they compose cleanly with the
11//! library's Kuhn–Munkres assignment. Defaults are tuned so the stack
12//! reduces to the nearest-car baseline when every weight is zero.
13//!
14//! What this deliberately leaves out: online weight tuning, fuzzy
15//! inference, and stickiness state. Those belong above the trait, not
16//! inside a strategy.
17
18use crate::components::{CarCall, ElevatorPhase};
19use crate::traffic_detector::{TrafficDetector, TrafficMode};
20
21use super::{DispatchStrategy, RankContext, pair_can_do_work};
22
23/// Look up the current [`TrafficMode`] from `ctx.world` and return the
24/// scaling factor to apply to the wrong-direction penalty.
25///
26/// Returns `multiplier` when the mode is `UpPeak` or `DownPeak`, else
27/// `1.0`. Also returns `1.0` when the detector resource is missing —
28/// keeping the strategy functional in tests that skip `Simulation::new`.
29fn peak_scaling(ctx: &RankContext<'_>, multiplier: f64) -> f64 {
30    let mode = ctx
31        .world
32        .resource::<TrafficDetector>()
33        .map_or(TrafficMode::Idle, TrafficDetector::current_mode);
34    match mode {
35        TrafficMode::UpPeak | TrafficMode::DownPeak => multiplier,
36        _ => 1.0,
37    }
38}
39
40/// Additive RSR-style cost stack. Lower scores win the Hungarian
41/// assignment.
42///
43/// See module docs for the cost shape. All weights default to `0.0`
44/// except `eta_weight` (1.0), giving a baseline that mirrors
45/// [`NearestCarDispatch`](super::NearestCarDispatch) until terms are
46/// opted in.
47///
48/// # Weight invariants
49///
50/// Every weight field must be **finite and non-negative**. The
51/// `with_*` builder methods enforce this with `assert!`; direct field
52/// mutation bypasses the check and is a caller responsibility. A `NaN` weight propagates through the multiply-add
53/// chain and silently collapses every pair's cost to zero (Rust's
54/// `NaN.max(0.0) == 0.0`), producing an arbitrary but type-valid
55/// assignment from the Hungarian solver — a hard bug to diagnose.
56#[derive(serde::Serialize, serde::Deserialize)]
57pub struct RsrDispatch {
58    /// Weight on `travel_time = distance / max_speed` (seconds).
59    /// Default `1.0`; raising it shifts the blend toward travel time.
60    pub eta_weight: f64,
61    /// Constant added when the candidate stop lies opposite the
62    /// car's committed travel direction.
63    ///
64    /// Default `0.0`; the Otis RSR lineage uses a large value so any
65    /// right-direction candidate outranks any wrong-direction one.
66    /// Ignored for cars in [`ElevatorPhase::Idle`] or stopped phases,
67    /// since an idle car has no committed direction to be opposite to.
68    pub wrong_direction_penalty: f64,
69    /// Bonus subtracted when the candidate stop is already a car-call
70    /// inside this car.
71    ///
72    /// Merges the new pickup with an existing dropoff instead of
73    /// spawning an unrelated trip. Default `0.0`. Read from
74    /// [`DispatchManifest::car_calls_for`](super::DispatchManifest::car_calls_for).
75    pub coincident_car_call_bonus: f64,
76    /// Coefficient on a smooth load-fraction penalty
77    /// (`load_penalty_coeff · load_ratio`).
78    ///
79    /// Fires for partially loaded cars below the `bypass_load_*_pct`
80    /// threshold enforced by [`pair_can_do_work`]; lets you prefer
81    /// emptier cars for new pickups without an on/off cliff.
82    /// Default `0.0`.
83    pub load_penalty_coeff: f64,
84    /// Multiplier applied to `wrong_direction_penalty` when the
85    /// [`TrafficDetector`] classifies the current tick as
86    /// [`TrafficMode::UpPeak`] or [`TrafficMode::DownPeak`].
87    ///
88    /// Default `1.0` (mode-agnostic — behaviour identical to pre-peak
89    /// tuning). Raising it strengthens directional commitment during
90    /// peaks where a car carrying a lobby-bound load shouldn't be
91    /// pulled backwards to grab a new pickup. Off-peak periods keep
92    /// the unscaled penalty, leaving inter-floor assignments free
93    /// to reverse cheaply.
94    ///
95    /// Silently reduces to `1.0` when no `TrafficDetector` resource
96    /// is installed — tests and custom sims that bypass the auto-install
97    /// stay unaffected.
98    pub peak_direction_multiplier: f64,
99}
100
101impl RsrDispatch {
102    /// Create a new `RsrDispatch` with the baseline weights
103    /// (`eta_weight = 1.0`, all penalties/bonuses disabled).
104    #[must_use]
105    pub const fn new() -> Self {
106        Self {
107            eta_weight: 1.0,
108            wrong_direction_penalty: 0.0,
109            coincident_car_call_bonus: 0.0,
110            load_penalty_coeff: 0.0,
111            peak_direction_multiplier: 1.0,
112        }
113    }
114
115    /// Set the wrong-direction penalty.
116    ///
117    /// # Panics
118    /// Panics on non-finite or negative weights — a negative penalty
119    /// would invert the direction ordering, silently preferring
120    /// wrong-direction candidates.
121    #[must_use]
122    pub fn with_wrong_direction_penalty(mut self, weight: f64) -> Self {
123        assert!(
124            weight.is_finite() && weight >= 0.0,
125            "wrong_direction_penalty must be finite and non-negative, got {weight}"
126        );
127        self.wrong_direction_penalty = weight;
128        self
129    }
130
131    /// Set the coincident-car-call bonus.
132    ///
133    /// # Panics
134    /// Panics on non-finite or negative weights — the bonus is
135    /// subtracted, so a negative value would become a penalty.
136    #[must_use]
137    pub fn with_coincident_car_call_bonus(mut self, weight: f64) -> Self {
138        assert!(
139            weight.is_finite() && weight >= 0.0,
140            "coincident_car_call_bonus must be finite and non-negative, got {weight}"
141        );
142        self.coincident_car_call_bonus = weight;
143        self
144    }
145
146    /// Set the load-penalty coefficient.
147    ///
148    /// # Panics
149    /// Panics on non-finite or negative weights.
150    #[must_use]
151    pub fn with_load_penalty_coeff(mut self, weight: f64) -> Self {
152        assert!(
153            weight.is_finite() && weight >= 0.0,
154            "load_penalty_coeff must be finite and non-negative, got {weight}"
155        );
156        self.load_penalty_coeff = weight;
157        self
158    }
159
160    /// Set the ETA weight.
161    ///
162    /// # Panics
163    /// Panics on non-finite or negative weights. Zero is allowed and
164    /// reduces the strategy to penalty/bonus tiebreaking alone.
165    #[must_use]
166    pub fn with_eta_weight(mut self, weight: f64) -> Self {
167        assert!(
168            weight.is_finite() && weight >= 0.0,
169            "eta_weight must be finite and non-negative, got {weight}"
170        );
171        self.eta_weight = weight;
172        self
173    }
174
175    /// Set the peak-direction multiplier.
176    ///
177    /// # Panics
178    /// Panics on non-finite or sub-1.0 values. A multiplier below `1.0`
179    /// would *weaken* the direction penalty during peaks (the opposite
180    /// of the intent) — explicitly disallowed so a typo doesn't silently
181    /// invert the tuning.
182    #[must_use]
183    pub fn with_peak_direction_multiplier(mut self, factor: f64) -> Self {
184        assert!(
185            factor.is_finite() && factor >= 1.0,
186            "peak_direction_multiplier must be finite and ≥ 1.0, got {factor}"
187        );
188        self.peak_direction_multiplier = factor;
189        self
190    }
191}
192
193impl Default for RsrDispatch {
194    fn default() -> Self {
195        Self::new()
196    }
197}
198
199impl DispatchStrategy for RsrDispatch {
200    fn rank(&mut self, ctx: &RankContext<'_>) -> Option<f64> {
201        if !pair_can_do_work(ctx) {
202            return None;
203        }
204        let car = ctx.world.elevator(ctx.car)?;
205
206        // ETA — travel time to the candidate stop.
207        let distance = (ctx.car_position - ctx.stop_position).abs();
208        let max_speed = car.max_speed.value();
209        if max_speed <= 0.0 {
210            return None;
211        }
212        let travel_time = distance / max_speed;
213        let mut cost = self.eta_weight * travel_time;
214
215        // Wrong-direction penalty. Only applies when the car has a
216        // committed direction (not Idle / Stopped) — an idle car can
217        // accept any candidate without "reversing" anything.
218        if self.wrong_direction_penalty > 0.0
219            && let Some(target) = car.phase.moving_target()
220            && let Some(target_pos) = ctx.world.stop_position(target)
221        {
222            let car_going_up = target_pos > ctx.car_position;
223            let car_going_down = target_pos < ctx.car_position;
224            let cand_above = ctx.stop_position > ctx.car_position;
225            let cand_below = ctx.stop_position < ctx.car_position;
226            if (car_going_up && cand_below) || (car_going_down && cand_above) {
227                // During up-peak/down-peak the directional invariant
228                // is load-bearing (a committed car shouldn't reverse
229                // to grab a new pickup), so scale the penalty up.
230                // Off-peak, the base value still rules — inter-floor
231                // traffic wants cheap reversals.
232                let scaled = self.wrong_direction_penalty
233                    * peak_scaling(ctx, self.peak_direction_multiplier);
234                cost += scaled;
235            }
236        }
237
238        // Coincident-car-call bonus — the candidate stop is already a
239        // committed dropoff for this car.
240        if self.coincident_car_call_bonus > 0.0
241            && ctx
242                .manifest
243                .car_calls_for(ctx.car)
244                .iter()
245                .any(|c: &CarCall| c.floor == ctx.stop)
246        {
247            cost -= self.coincident_car_call_bonus;
248        }
249
250        // Smooth load-fraction penalty. `pair_can_do_work` has already
251        // filtered over-capacity and bypass-threshold cases; this term
252        // shapes preference among the survivors so emptier cars win
253        // pickups when all else is equal. Idle cars contribute zero.
254        if self.load_penalty_coeff > 0.0 && car.phase() != ElevatorPhase::Idle {
255            let capacity = car.weight_capacity().value();
256            if capacity > 0.0 {
257                let load_ratio = (car.current_load().value() / capacity).clamp(0.0, 1.0);
258                cost += self.load_penalty_coeff * load_ratio;
259            }
260        }
261
262        let cost = cost.max(0.0);
263        if cost.is_finite() { Some(cost) } else { None }
264    }
265
266    fn builtin_id(&self) -> Option<super::BuiltinStrategy> {
267        Some(super::BuiltinStrategy::Rsr)
268    }
269
270    fn snapshot_config(&self) -> Option<String> {
271        ron::to_string(self).ok()
272    }
273
274    fn restore_config(&mut self, serialized: &str) -> Result<(), String> {
275        let restored: Self = ron::from_str(serialized).map_err(|e| e.to_string())?;
276        *self = restored;
277        Ok(())
278    }
279}