elevator_core/dispatch/etd.rs
1//! Estimated Time to Destination (ETD) dispatch algorithm.
2//!
3//! The per-call cost-minimization approach is drawn from Barney, G. C. &
4//! dos Santos, S. M., *Elevator Traffic Analysis, Design and Control* (2nd
5//! ed., 1985). Commercial controllers (Otis Elevonic, KONE Polaris, etc.)
6//! use variants of the same idea; this implementation is a simplified
7//! educational model, not a faithful reproduction of any vendor's system.
8
9use smallvec::SmallVec;
10
11use crate::components::{ElevatorPhase, Route};
12use crate::entity::EntityId;
13use crate::world::World;
14
15use super::{DispatchManifest, DispatchStrategy, ElevatorGroup, RankContext, pair_can_do_work};
16
17/// Estimated Time to Destination (ETD) dispatch algorithm.
18///
19/// For each `(car, stop)` pair the rank is a cost estimate combining
20/// travel time, delay imposed on riders already aboard, door-overhead
21/// for intervening stops, and a small bonus for cars already heading
22/// toward the stop. The dispatch system runs an optimal assignment
23/// across all pairs so the globally best matching is chosen.
24pub struct EtdDispatch {
25 /// Weight for travel time to reach the calling stop.
26 pub wait_weight: f64,
27 /// Weight for delay imposed on existing riders.
28 pub delay_weight: f64,
29 /// Weight for door open/close overhead at intermediate stops.
30 pub door_weight: f64,
31 /// Weight for the squared-wait "group-time" fairness bonus. Each
32 /// candidate stop's cost is reduced by this weight times the sum
33 /// of `wait_ticks²` across waiting riders at the stop, so stops
34 /// hosting older calls win ties. Defaults to `0.0` (no bias);
35 /// positive values damp the long-wait tail (Aalto EJOR 2016
36 /// group-time assignment model).
37 pub wait_squared_weight: f64,
38 /// Weight for the linear waiting-age fairness term. Each candidate
39 /// stop's cost is reduced by this weight times the sum of
40 /// `wait_ticks` across waiting riders at the stop, so stops hosting
41 /// older calls win ties without the quadratic blow-up of
42 /// [`wait_squared_weight`](Self::wait_squared_weight). Defaults to
43 /// `0.0` (no bias); positive values implement the linear
44 /// collective-group-control fairness term from Lim 1983 /
45 /// Barney–dos Santos 1985 CGC.
46 ///
47 /// Composes additively with `wait_squared_weight`: users wanting
48 /// the full CGC shape can set both (`k·Σw + λ·Σw²`).
49 pub age_linear_weight: f64,
50 /// Positions of every demanded stop in the group, cached by
51 /// [`DispatchStrategy::pre_dispatch`] so `rank` avoids rebuilding the
52 /// list for every `(car, stop)` pair.
53 pending_positions: SmallVec<[f64; 16]>,
54}
55
56impl EtdDispatch {
57 /// Create a new `EtdDispatch` with default weights.
58 ///
59 /// Defaults: `wait_weight = 1.0`, `delay_weight = 1.0`,
60 /// `door_weight = 0.5`, `wait_squared_weight = 0.0`,
61 /// `age_linear_weight = 0.0`.
62 #[must_use]
63 pub fn new() -> Self {
64 Self {
65 wait_weight: 1.0,
66 delay_weight: 1.0,
67 door_weight: 0.5,
68 wait_squared_weight: 0.0,
69 age_linear_weight: 0.0,
70 pending_positions: SmallVec::new(),
71 }
72 }
73
74 /// Create with a single delay weight (backwards-compatible shorthand).
75 #[must_use]
76 pub fn with_delay_weight(delay_weight: f64) -> Self {
77 Self {
78 wait_weight: 1.0,
79 delay_weight,
80 door_weight: 0.5,
81 wait_squared_weight: 0.0,
82 age_linear_weight: 0.0,
83 pending_positions: SmallVec::new(),
84 }
85 }
86
87 /// Create with fully custom weights.
88 #[must_use]
89 pub fn with_weights(wait_weight: f64, delay_weight: f64, door_weight: f64) -> Self {
90 Self {
91 wait_weight,
92 delay_weight,
93 door_weight,
94 wait_squared_weight: 0.0,
95 age_linear_weight: 0.0,
96 pending_positions: SmallVec::new(),
97 }
98 }
99
100 /// Turn on the squared-wait fairness bonus. Higher values prefer
101 /// older waiters more aggressively; `0.0` (the default) disables.
102 ///
103 /// # Panics
104 /// Panics on non-finite or negative weights. A `NaN` weight would
105 /// propagate through `mul_add` and silently disable every dispatch
106 /// rank; a negative weight would invert the fairness ordering.
107 /// Either is a programming error rather than a valid configuration.
108 #[must_use]
109 pub fn with_wait_squared_weight(mut self, weight: f64) -> Self {
110 assert!(
111 weight.is_finite() && weight >= 0.0,
112 "wait_squared_weight must be finite and non-negative, got {weight}"
113 );
114 self.wait_squared_weight = weight;
115 self
116 }
117
118 /// Turn on the linear waiting-age fairness term. Higher values
119 /// prefer older waiters more aggressively; `0.0` (the default)
120 /// disables. Composes additively with
121 /// [`with_wait_squared_weight`](Self::with_wait_squared_weight).
122 ///
123 /// # Panics
124 /// Panics on non-finite or negative weights, for the same reasons
125 /// as [`with_wait_squared_weight`](Self::with_wait_squared_weight).
126 #[must_use]
127 pub fn with_age_linear_weight(mut self, weight: f64) -> Self {
128 assert!(
129 weight.is_finite() && weight >= 0.0,
130 "age_linear_weight must be finite and non-negative, got {weight}"
131 );
132 self.age_linear_weight = weight;
133 self
134 }
135}
136
137impl Default for EtdDispatch {
138 fn default() -> Self {
139 Self::new()
140 }
141}
142
143impl DispatchStrategy for EtdDispatch {
144 fn pre_dispatch(
145 &mut self,
146 group: &ElevatorGroup,
147 manifest: &DispatchManifest,
148 world: &mut World,
149 ) {
150 self.pending_positions.clear();
151 for &s in group.stop_entities() {
152 if manifest.has_demand(s)
153 && let Some(p) = world.stop_position(s)
154 {
155 self.pending_positions.push(p);
156 }
157 }
158 }
159
160 fn rank(&mut self, ctx: &RankContext<'_>) -> Option<f64> {
161 // Exclude `(car, stop)` pairs that can't produce any useful work.
162 // Without this guard, a full car whose only candidate stop is a
163 // pickup it lacks capacity to serve collapses to a zero-cost
164 // self-assignment (travel, detour, and door terms are all 0 when
165 // the car is already at the stop). Dispatch then re-selects that
166 // stop every tick — doors cycle open, reject, close, repeat — and
167 // the aboard riders are never carried to their destinations.
168 if !pair_can_do_work(ctx) {
169 return None;
170 }
171 let mut cost = self.compute_cost(ctx.car, ctx.car_position, ctx.stop_position, ctx.world);
172 if self.wait_squared_weight > 0.0 {
173 let wait_sq: f64 = ctx
174 .manifest
175 .waiting_riders_at(ctx.stop)
176 .iter()
177 .map(|r| {
178 let w = r.wait_ticks as f64;
179 w * w
180 })
181 .sum();
182 cost = self.wait_squared_weight.mul_add(-wait_sq, cost).max(0.0);
183 }
184 if self.age_linear_weight > 0.0 {
185 let wait_sum: f64 = ctx
186 .manifest
187 .waiting_riders_at(ctx.stop)
188 .iter()
189 .map(|r| r.wait_ticks as f64)
190 .sum();
191 cost = self.age_linear_weight.mul_add(-wait_sum, cost).max(0.0);
192 }
193 if cost.is_finite() { Some(cost) } else { None }
194 }
195}
196
197impl EtdDispatch {
198 /// Compute ETD cost for assigning an elevator to serve a stop.
199 ///
200 /// Cost = `wait_weight` * travel\_time + `delay_weight` * existing\_rider\_delay
201 /// + `door_weight` * door\_overhead + direction\_bonus
202 fn compute_cost(
203 &self,
204 elev_eid: EntityId,
205 elev_pos: f64,
206 target_pos: f64,
207 world: &World,
208 ) -> f64 {
209 let Some(car) = world.elevator(elev_eid) else {
210 return f64::INFINITY;
211 };
212
213 let distance = (elev_pos - target_pos).abs();
214 let travel_time = if car.max_speed.value() > 0.0 {
215 distance / car.max_speed.value()
216 } else {
217 return f64::INFINITY;
218 };
219
220 // Door overhead is a seconds-denominated cost so the Hungarian
221 // can compare it apples-to-apples against travel time and
222 // existing-rider delay. Pre-fix, this was summed in ticks,
223 // multiplied by `door_weight` (dimensionless), and added to
224 // seconds-valued terms — giving door cost ~60× the intended
225 // influence at 60 Hz. A single intervening stop could then
226 // outweigh a long travel time and bias ETD toward distant
227 // cars with clear shafts over closer ones with a single
228 // waypoint. Convert with the sim's tick rate (resource-
229 // provided) and fall back to 60 Hz for bare-World contexts
230 // such as unit-test fixtures.
231 let tick_rate = world
232 .resource::<crate::time::TickRate>()
233 .map_or(60.0, |r| r.0);
234 let door_overhead_per_stop =
235 f64::from(car.door_transition_ticks * 2 + car.door_open_ticks) / tick_rate;
236
237 // Intervening pending stops between car and target contribute door overhead.
238 let (lo, hi) = if elev_pos < target_pos {
239 (elev_pos, target_pos)
240 } else {
241 (target_pos, elev_pos)
242 };
243 let intervening_stops = self
244 .pending_positions
245 .iter()
246 .filter(|p| **p > lo + 1e-9 && **p < hi - 1e-9)
247 .count() as f64;
248 let door_cost = intervening_stops * door_overhead_per_stop;
249
250 let mut existing_rider_delay = 0.0_f64;
251 for &rider_eid in car.riders() {
252 if let Some(dest) = world.route(rider_eid).and_then(Route::current_destination)
253 && let Some(dest_pos) = world.stop_position(dest)
254 {
255 let direct_dist = (elev_pos - dest_pos).abs();
256 let detour_dist = (elev_pos - target_pos).abs() + (target_pos - dest_pos).abs();
257 let extra = (detour_dist - direct_dist).max(0.0);
258 if car.max_speed.value() > 0.0 {
259 existing_rider_delay += extra / car.max_speed.value();
260 }
261 }
262 }
263
264 // Direction bonus: if the car is already heading this way, subtract.
265 // Scoring model requires non-negative costs, so clamp at zero — losing
266 // a small amount of discriminative power vs. a pure free-for-all when
267 // two assignments tie.
268 let direction_bonus = match car.phase.moving_target() {
269 Some(current_target) => world.stop_position(current_target).map_or(0.0, |ctp| {
270 let moving_up = ctp > elev_pos;
271 let target_is_ahead = if moving_up {
272 target_pos > elev_pos && target_pos <= ctp
273 } else {
274 target_pos < elev_pos && target_pos >= ctp
275 };
276 if target_is_ahead {
277 -travel_time * 0.5
278 } else {
279 0.0
280 }
281 }),
282 None if car.phase == ElevatorPhase::Idle => -travel_time * 0.3,
283 _ => 0.0,
284 };
285
286 let raw = self.wait_weight.mul_add(
287 travel_time,
288 self.delay_weight.mul_add(
289 existing_rider_delay,
290 self.door_weight.mul_add(door_cost, direction_bonus),
291 ),
292 );
293 raw.max(0.0)
294 }
295}