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_is_useful};
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`](super::pair_can_do_work);
81 /// lets you prefer 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 ///
105 /// This is the **additive-composition baseline** — every penalty
106 /// and bonus is zero, so the rank reduces to
107 /// [`NearestCarDispatch`](super::NearestCarDispatch) on distance
108 /// alone. Useful for tests that want to measure a single term in
109 /// isolation (`RsrDispatch::new().with_wrong_direction_penalty(…)`).
110 ///
111 /// For the opinionated "out-of-the-box RSR" configuration used by
112 /// [`BuiltinStrategy::Rsr`](super::BuiltinStrategy::Rsr) and the
113 /// playground, use [`RsrDispatch::default`] instead. `Default` ships
114 /// with the full penalty stack turned on; `new()` is the empty
115 /// canvas you build on top of.
116 #[must_use]
117 pub const fn new() -> Self {
118 Self {
119 eta_weight: 1.0,
120 wrong_direction_penalty: 0.0,
121 coincident_car_call_bonus: 0.0,
122 load_penalty_coeff: 0.0,
123 peak_direction_multiplier: 1.0,
124 }
125 }
126
127 /// Return the opinionated tuned configuration — equivalent to
128 /// [`Default::default`] but usable in `const` contexts.
129 ///
130 /// See [`RsrDispatch::default`] for the rationale behind each
131 /// weight. The tuned stack ships with every penalty/bonus turned
132 /// on so picking RSR out of the box is strictly richer than
133 /// `NearestCar`, not identical to it.
134 #[must_use]
135 pub const fn tuned() -> Self {
136 Self {
137 eta_weight: 1.0,
138 // Chosen ≈ one shaft-length travel time on a typical 20-stop
139 // commercial bank (≈15s), so a backward pickup costs as much
140 // as the trip to serve it. Large enough to dominate the ETA
141 // term for a close-but-wrong-direction candidate; small
142 // enough that off-peak inter-floor reversals still flip when
143 // the demand strongly favours them.
144 wrong_direction_penalty: 15.0,
145 // Small merge bonus — prefer a car with a matching car-call
146 // over spawning a new trip, but not so large it overrides a
147 // much closer empty car.
148 coincident_car_call_bonus: 5.0,
149 // Light load-balancing — prefer empty cars for new work
150 // when cars are otherwise tied.
151 load_penalty_coeff: 3.0,
152 // Strong directional commitment during up-peak / down-peak
153 // (lobby-bound loads shouldn't reverse for new pickups).
154 // Off-peak stays unscaled for cheap inter-floor reversals.
155 peak_direction_multiplier: 2.0,
156 }
157 }
158
159 /// Set the wrong-direction penalty.
160 ///
161 /// # Panics
162 /// Panics on non-finite or negative weights — a negative penalty
163 /// would invert the direction ordering, silently preferring
164 /// wrong-direction candidates.
165 #[must_use]
166 pub fn with_wrong_direction_penalty(mut self, weight: f64) -> Self {
167 assert!(
168 weight.is_finite() && weight >= 0.0,
169 "wrong_direction_penalty must be finite and non-negative, got {weight}"
170 );
171 self.wrong_direction_penalty = weight;
172 self
173 }
174
175 /// Set the coincident-car-call bonus.
176 ///
177 /// # Panics
178 /// Panics on non-finite or negative weights — the bonus is
179 /// subtracted, so a negative value would become a penalty.
180 #[must_use]
181 pub fn with_coincident_car_call_bonus(mut self, weight: f64) -> Self {
182 assert!(
183 weight.is_finite() && weight >= 0.0,
184 "coincident_car_call_bonus must be finite and non-negative, got {weight}"
185 );
186 self.coincident_car_call_bonus = weight;
187 self
188 }
189
190 /// Set the load-penalty coefficient.
191 ///
192 /// # Panics
193 /// Panics on non-finite or negative weights.
194 #[must_use]
195 pub fn with_load_penalty_coeff(mut self, weight: f64) -> Self {
196 assert!(
197 weight.is_finite() && weight >= 0.0,
198 "load_penalty_coeff must be finite and non-negative, got {weight}"
199 );
200 self.load_penalty_coeff = weight;
201 self
202 }
203
204 /// Set the ETA weight.
205 ///
206 /// # Panics
207 /// Panics on non-finite or negative weights. Zero is allowed and
208 /// reduces the strategy to penalty/bonus tiebreaking alone.
209 #[must_use]
210 pub fn with_eta_weight(mut self, weight: f64) -> Self {
211 assert!(
212 weight.is_finite() && weight >= 0.0,
213 "eta_weight must be finite and non-negative, got {weight}"
214 );
215 self.eta_weight = weight;
216 self
217 }
218
219 /// Set the peak-direction multiplier.
220 ///
221 /// # Panics
222 /// Panics on non-finite or sub-1.0 values. A multiplier below `1.0`
223 /// would *weaken* the direction penalty during peaks (the opposite
224 /// of the intent) — explicitly disallowed so a typo doesn't silently
225 /// invert the tuning.
226 #[must_use]
227 pub fn with_peak_direction_multiplier(mut self, factor: f64) -> Self {
228 assert!(
229 factor.is_finite() && factor >= 1.0,
230 "peak_direction_multiplier must be finite and ≥ 1.0, got {factor}"
231 );
232 self.peak_direction_multiplier = factor;
233 self
234 }
235}
236
237impl Default for RsrDispatch {
238 /// The opinionated "pick RSR from the dropdown" configuration.
239 ///
240 /// Defaults to [`RsrDispatch::tuned`] — every penalty and bonus
241 /// turned on with values calibrated to a 20-stop commercial bank.
242 /// Before this default was tuned, `RsrDispatch::default()`
243 /// reduced to the raw [`NearestCarDispatch`](super::NearestCarDispatch)
244 /// baseline: picking "RSR" in the playground produced worse
245 /// behaviour than picking "Nearest Car" (no direction discipline,
246 /// no load balancing, no car-call merging). The tuned default
247 /// fixes that without making any term mandatory — consumers
248 /// wanting the zero baseline can still call
249 /// [`RsrDispatch::new`].
250 fn default() -> Self {
251 Self::tuned()
252 }
253}
254
255impl DispatchStrategy for RsrDispatch {
256 fn rank(&mut self, ctx: &RankContext<'_>) -> Option<f64> {
257 // `pair_is_useful` subsumes `pair_can_do_work` and adds the
258 // aboard-rider path guard. Without it, a loaded RSR car gets
259 // pulled off the path to its aboard riders' destinations by
260 // closer pickups — the same "never reaches the passenger's
261 // desired stop" loop that NearestCar specifically fixes. RSR's
262 // `wrong_direction_penalty` can mitigate this when configured,
263 // but the guard is a correctness floor independent of tuning.
264 if !pair_is_useful(ctx) {
265 return None;
266 }
267 let car = ctx.world.elevator(ctx.car)?;
268
269 // ETA — travel time to the candidate stop.
270 let distance = (ctx.car_position - ctx.stop_position).abs();
271 let max_speed = car.max_speed.value();
272 if max_speed <= 0.0 {
273 return None;
274 }
275 let travel_time = distance / max_speed;
276 let mut cost = self.eta_weight * travel_time;
277
278 // Wrong-direction penalty. Only applies when the car has a
279 // committed direction (not Idle / Stopped) — an idle car can
280 // accept any candidate without "reversing" anything.
281 if self.wrong_direction_penalty > 0.0
282 && let Some(target) = car.phase.moving_target()
283 && let Some(target_pos) = ctx.world.stop_position(target)
284 {
285 let car_going_up = target_pos > ctx.car_position;
286 let car_going_down = target_pos < ctx.car_position;
287 let cand_above = ctx.stop_position > ctx.car_position;
288 let cand_below = ctx.stop_position < ctx.car_position;
289 if (car_going_up && cand_below) || (car_going_down && cand_above) {
290 // During up-peak/down-peak the directional invariant
291 // is load-bearing (a committed car shouldn't reverse
292 // to grab a new pickup), so scale the penalty up.
293 // Off-peak, the base value still rules — inter-floor
294 // traffic wants cheap reversals.
295 let scaled = self.wrong_direction_penalty
296 * peak_scaling(ctx, self.peak_direction_multiplier);
297 cost += scaled;
298 }
299 }
300
301 // Coincident-car-call bonus — the candidate stop is already a
302 // committed dropoff for this car.
303 if self.coincident_car_call_bonus > 0.0
304 && ctx
305 .manifest
306 .car_calls_for(ctx.car)
307 .iter()
308 .any(|c: &CarCall| c.floor == ctx.stop)
309 {
310 cost -= self.coincident_car_call_bonus;
311 }
312
313 // Smooth load-fraction penalty. `pair_can_do_work` has already
314 // filtered over-capacity and bypass-threshold cases; this term
315 // shapes preference among the survivors so emptier cars win
316 // pickups when all else is equal. Idle cars contribute zero.
317 if self.load_penalty_coeff > 0.0 && car.phase() != ElevatorPhase::Idle {
318 let capacity = car.weight_capacity().value();
319 if capacity > 0.0 {
320 let load_ratio = (car.current_load().value() / capacity).clamp(0.0, 1.0);
321 cost += self.load_penalty_coeff * load_ratio;
322 }
323 }
324
325 let cost = cost.max(0.0);
326 if cost.is_finite() { Some(cost) } else { None }
327 }
328
329 fn builtin_id(&self) -> Option<super::BuiltinStrategy> {
330 Some(super::BuiltinStrategy::Rsr)
331 }
332
333 fn snapshot_config(&self) -> Option<String> {
334 ron::to_string(self).ok()
335 }
336
337 fn restore_config(&mut self, serialized: &str) -> Result<(), String> {
338 let restored: Self = ron::from_str(serialized).map_err(|e| e.to_string())?;
339 *self = restored;
340 Ok(())
341 }
342}