rustsim-traffic 0.0.1

Transport-domain semantics for rustsim: multimodal movement, controls, and routing metadata
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
//! Transport-domain semantics layered on top of `rustsim-core` and `rustsim-spaces`.
//!
//! This module provides reusable transport metadata plus transport operations
//! over `LinkSpace<LinkProperties>`.
//!
//! Current semantic position:
//! - topology and occupancy primitives come from `LinkSpace<P>`
//! - this module adds transport-specific calculations and convenience presets
//! - queue and control decisions are explicit policies in [`crate::policy`]
//!
//! In particular:
//! - `link_density`, `link_speed`, and travel-time helpers are per-link snapshot calculations
//! - `agent_speed` uses the default FIFO/gap policy for current ordering and downstream blocking
//! - no lane-changing, merge-resolution, signal-phase engine, or network-equilibrium model is implied

use crate::policy::{FifoGapPolicy, QueuePolicy, SpeedDecision};
use rustsim_core::types::{EdgeId, LevelRelation, NodeId, SemanticEntity, ZoneId};
use rustsim_modes::AllowedModes;
use rustsim_spaces::link::{LinkGeometry, LinkGeometryError, LinkId, LinkSpace, LinkSpaceError};

/// Coarse traffic control semantics at a node, movement, or approach.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum TrafficControlType {
    #[default]
    Uncontrolled,
    Yield,
    Stop,
    Signal,
}

/// Coarse turning movement semantics.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TurnType {
    Left,
    Through,
    Right,
    UTurn,
}

/// Coarse classification for transport links.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum LinkClass {
    #[default]
    Road,
    Walkway,
    Cycleway,
    Transitway,
    Rail,
    Shared,
}

/// Speed-density relationship (fundamental diagram) for a transport link.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum FundamentalDiagram {
    Greenshields,
    Underwood {
        k_opt: Option<f64>,
    },
    Triangular,
    FreeFlow,
    /// Weidmann (1993) pedestrian speed-density relationship.
    ///
    /// Uses density in ped/m² (not veh/km/lane). The `jam_density` parameter
    /// passed to [`speed()`](FundamentalDiagram::speed) is ignored; the
    /// Weidmann jam density of 5.4 ped/m² is used instead.
    ///
    /// **Important:** when using this variant, `density_per_km` is
    /// reinterpreted as density in ped/m².
    Weidmann,
}

impl FundamentalDiagram {
    /// Compute speed (m/s) given density (veh/km/lane), free-flow speed (m/s), and jam density.
    pub fn speed(&self, density_per_km: f64, free_flow_speed: f64, jam_density: f64) -> f64 {
        if density_per_km <= 0.0 || jam_density <= 0.0 {
            return free_flow_speed;
        }

        let speed = match self {
            FundamentalDiagram::Greenshields => {
                free_flow_speed * (1.0 - density_per_km / jam_density).max(0.0)
            }
            FundamentalDiagram::Underwood { k_opt } => {
                let k_opt_val = k_opt.unwrap_or(jam_density / std::f64::consts::E);
                if k_opt_val <= 0.0 {
                    free_flow_speed
                } else {
                    free_flow_speed * (-density_per_km / k_opt_val).exp()
                }
            }
            FundamentalDiagram::Triangular => {
                let k_c = jam_density / 2.0;
                if density_per_km <= k_c {
                    free_flow_speed
                } else {
                    free_flow_speed * (jam_density - density_per_km) / (jam_density - k_c)
                }
                .max(0.0)
            }
            FundamentalDiagram::FreeFlow => free_flow_speed,
            FundamentalDiagram::Weidmann => {
                crate::pedestrian_links::weidmann_speed(free_flow_speed, density_per_km)
            }
        };

        speed.max(0.0)
    }
}

/// Transport-specific physical properties of a link.
///
/// This type stores the transport behavior parameters attached to a
/// `LinkSpace<LinkProperties>` link.
///
/// The associated constructors such as [`LinkProperties::urban`],
/// [`LinkProperties::freeway`], and [`LinkProperties::pedestrian`] are
/// **convenience presets** for common real-world link types. They are not
/// a fixed catalog enforced by the engine - users can either use these
/// helpers as starting points or construct/customize values directly.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LinkProperties {
    /// Free-flow speed in m/s.
    pub free_flow_speed: f64,
    /// Capacity in units/hour across all lanes.
    pub capacity: f64,
    /// Number of lanes or effective parallel channels.
    pub lanes: u32,
    /// Jam density in units/km/lane.
    pub jam_density: f64,
    /// Speed-density relationship applied to the link.
    pub diagram: FundamentalDiagram,
}

impl LinkProperties {
    /// Convenience preset for a typical urban road segment.
    ///
    /// Returns `(LinkGeometry, LinkProperties)` so the result can be passed
    /// directly into `LinkSpace<LinkProperties>::add_link(...)`.
    ///
    /// Arguments:
    /// - `length`: link length in meters
    /// - `speed_kmh`: free-flow speed in km/h
    /// - `lanes`: number of lanes
    ///
    /// This is an example/default profile, not a mandatory schema.
    pub fn urban(
        length: f64,
        speed_kmh: f64,
        lanes: u32,
    ) -> Result<(LinkGeometry, Self), LinkGeometryError> {
        Ok((
            LinkGeometry::new(length)?,
            Self {
                free_flow_speed: speed_kmh / 3.6,
                capacity: 900.0 * lanes as f64,
                lanes,
                jam_density: 150.0,
                diagram: FundamentalDiagram::Greenshields,
            },
        ))
    }

    /// Convenience preset for a typical freeway segment.
    ///
    /// Returns `(LinkGeometry, LinkProperties)` so the result can be passed
    /// directly into `LinkSpace<LinkProperties>::add_link(...)`.
    ///
    /// Arguments:
    /// - `length`: link length in meters
    /// - `speed_kmh`: free-flow speed in km/h
    /// - `lanes`: number of lanes
    ///
    /// This is an example/default profile, not a mandatory schema.
    pub fn freeway(
        length: f64,
        speed_kmh: f64,
        lanes: u32,
    ) -> Result<(LinkGeometry, Self), LinkGeometryError> {
        Ok((
            LinkGeometry::new(length)?,
            Self {
                free_flow_speed: speed_kmh / 3.6,
                capacity: 2200.0 * lanes as f64,
                lanes,
                jam_density: 120.0,
                diagram: FundamentalDiagram::Underwood { k_opt: None },
            },
        ))
    }

    /// Convenience preset for a pedestrian corridor or walkway.
    ///
    /// Returns `(LinkGeometry, LinkProperties)` so the result can be passed
    /// directly into `LinkSpace<LinkProperties>::add_link(...)`.
    ///
    /// Arguments:
    /// - `length`: link length in meters
    /// - `width`: effective corridor width in meters
    ///
    /// Width is converted into an approximate number of parallel channels.
    /// This is an example/default profile, not a mandatory schema.
    pub fn pedestrian(length: f64, width: f64) -> Result<(LinkGeometry, Self), LinkGeometryError> {
        Ok((
            LinkGeometry::new(length)?,
            Self {
                free_flow_speed: 1.3,
                capacity: 4800.0 * width,
                lanes: (width.ceil() as u32).max(1),
                jam_density: 5000.0,
                diagram: FundamentalDiagram::Greenshields,
            },
        ))
    }
}

/// Minimal reusable transport metadata for a link or edge.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TransportLinkMetadata {
    /// Stable edge identifier.
    pub edge_id: EdgeId,
    /// Source topology node.
    pub from_node: NodeId,
    /// Destination topology node.
    pub to_node: NodeId,
    /// Coarse link classification.
    pub link_class: LinkClass,
    /// Which modes may use this link.
    pub allowed_modes: AllowedModes,
    /// Optional traffic control semantics.
    pub traffic_control: Option<TrafficControlType>,
    /// Optional turn semantics.
    pub turn_type: Option<TurnType>,
    /// Optional speed limit in km/h.
    pub speed_limit_kph: Option<f64>,
}

impl TransportLinkMetadata {
    /// Create link metadata with a required topology and mode definition.
    pub fn new(
        edge_id: EdgeId,
        from_node: NodeId,
        to_node: NodeId,
        link_class: LinkClass,
        allowed_modes: AllowedModes,
    ) -> Self {
        Self {
            edge_id,
            from_node,
            to_node,
            link_class,
            allowed_modes,
            traffic_control: None,
            turn_type: None,
            speed_limit_kph: None,
        }
    }

    /// Attach traffic control semantics.
    pub fn with_traffic_control(mut self, traffic_control: TrafficControlType) -> Self {
        self.traffic_control = Some(traffic_control);
        self
    }

    /// Attach turning movement semantics.
    pub fn with_turn_type(mut self, turn_type: TurnType) -> Self {
        self.turn_type = Some(turn_type);
        self
    }

    /// Attach a speed limit in km/h.
    pub fn with_speed_limit_kph(mut self, speed_limit_kph: f64) -> Self {
        self.speed_limit_kph = Some(speed_limit_kph);
        self
    }
}

impl SemanticEntity for TransportLinkMetadata {
    type Id = EdgeId;

    fn semantic_id(&self) -> Self::Id {
        self.edge_id
    }
}

/// Minimal reusable metadata for a transit stop/platform anchor.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TransitStopMetadata {
    /// Stable topology node identifier for the stop anchor.
    pub node_id: NodeId,
    /// Optional semantic zone containing the stop.
    pub zone_id: Option<ZoneId>,
    /// Optional level relation for the stop.
    pub level_relation: Option<LevelRelation>,
    /// Modes served or admitted at the stop.
    pub served_modes: AllowedModes,
}

impl TransitStopMetadata {
    /// Create stop metadata for a node.
    pub fn new(node_id: NodeId, served_modes: AllowedModes) -> Self {
        Self {
            node_id,
            zone_id: None,
            level_relation: None,
            served_modes,
        }
    }

    /// Attach a containing semantic zone.
    pub fn with_zone(mut self, zone_id: ZoneId) -> Self {
        self.zone_id = Some(zone_id);
        self
    }

    /// Attach a level relation.
    pub fn with_level_relation(mut self, level_relation: LevelRelation) -> Self {
        self.level_relation = Some(level_relation);
        self
    }
}

impl SemanticEntity for TransitStopMetadata {
    type Id = NodeId;

    fn semantic_id(&self) -> Self::Id {
        self.node_id
    }
}

/// Canonical transport-specialized link space.
pub type TransportLinkSpace = LinkSpace<LinkProperties>;

/// Transport-specific operations over `LinkSpace<LinkProperties>`.
///
/// These helpers define a small reusable baseline policy layer.
/// They are suitable for simple transport scenarios and examples, but they do
/// not claim calibrated or reference-grade operational realism.
pub trait TransportLinkOps {
    /// Per-link density computed from current occupancy, link length, and lane count.
    fn link_density(&self, link_id: LinkId) -> f64;
    /// Per-link snapshot speed computed from the configured fundamental diagram.
    fn link_speed(&self, link_id: LinkId) -> f64;
    /// Free-flow traversal time using static geometry and free-flow speed.
    fn link_free_flow_time(&self, link_id: LinkId) -> f64;
    /// Snapshot traversal time using current `link_speed`.
    fn link_travel_time(&self, link_id: LinkId) -> f64;
    /// Simple FIFO/gap-limited speed estimate for one agent on its current link.
    fn agent_speed(&self, id: u64) -> Result<f64, LinkSpaceError>;
    /// Speed decision for one agent using an explicit queue policy.
    fn agent_speed_decision<P: QueuePolicy>(
        &self,
        id: u64,
        policy: &P,
    ) -> Result<SpeedDecision, LinkSpaceError>;
    /// Speed estimate for one agent using an explicit queue policy.
    fn agent_speed_with_policy<P: QueuePolicy>(
        &self,
        id: u64,
        policy: &P,
    ) -> Result<f64, LinkSpaceError>;
    /// Simple volume/capacity ratio over an externally supplied time window.
    fn volume_capacity_ratio(&self, link_id: LinkId, time_window_s: f64) -> f64;
}

impl TransportLinkOps for LinkSpace<LinkProperties> {
    fn link_density(&self, link_id: LinkId) -> f64 {
        let Some(props) = self.link_properties(link_id) else {
            return 0.0;
        };
        let Some(length) = self.link_length(link_id) else {
            return 0.0;
        };
        let n = self.agents_on_link(link_id) as f64;
        let length_km = length / 1000.0;
        let lanes = props.lanes.max(1) as f64;
        if length_km <= 0.0 {
            return 0.0;
        }
        n / (length_km * lanes)
    }

    fn link_speed(&self, link_id: LinkId) -> f64 {
        let Some(props) = self.link_properties(link_id) else {
            return 0.0;
        };
        props.diagram.speed(
            self.link_density(link_id),
            props.free_flow_speed,
            props.jam_density,
        )
    }

    fn link_free_flow_time(&self, link_id: LinkId) -> f64 {
        let Some(props) = self.link_properties(link_id) else {
            return f64::INFINITY;
        };
        let Some(length) = self.link_length(link_id) else {
            return f64::INFINITY;
        };
        length / props.free_flow_speed
    }

    fn link_travel_time(&self, link_id: LinkId) -> f64 {
        let speed = self.link_speed(link_id);
        if speed <= 0.0 {
            return f64::INFINITY;
        }
        let Some(length) = self.link_length(link_id) else {
            return f64::INFINITY;
        };
        length / speed
    }

    fn agent_speed(&self, id: u64) -> Result<f64, LinkSpaceError> {
        self.agent_speed_with_policy(id, &FifoGapPolicy::default())
    }

    fn agent_speed_decision<P: QueuePolicy>(
        &self,
        id: u64,
        policy: &P,
    ) -> Result<SpeedDecision, LinkSpaceError> {
        policy.speed_for(self, id)
    }

    fn agent_speed_with_policy<P: QueuePolicy>(
        &self,
        id: u64,
        policy: &P,
    ) -> Result<f64, LinkSpaceError> {
        Ok(self.agent_speed_decision(id, policy)?.speed)
    }

    fn volume_capacity_ratio(&self, link_id: LinkId, time_window_s: f64) -> f64 {
        let Some(props) = self.link_properties(link_id) else {
            return 0.0;
        };
        let count = self.agents_on_link(link_id) as f64;
        let flow_rate = count / (time_window_s / 3600.0);
        flow_rate / props.capacity
    }
}

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

    #[test]
    fn transport_link_metadata_builder_helpers() {
        let link = TransportLinkMetadata::new(7, 1, 2, LinkClass::Road, AllowedModes::vehicular())
            .with_traffic_control(TrafficControlType::Signal)
            .with_turn_type(TurnType::Through)
            .with_speed_limit_kph(50.0);

        assert_eq!(link.semantic_id(), 7);
        assert_eq!(link.from_node, 1);
        assert_eq!(link.to_node, 2);
        assert_eq!(link.link_class, LinkClass::Road);
        assert!(link.allowed_modes.allows(TravelMode::Vehicle));
        assert!(link.allowed_modes.allows(TravelMode::Transit));
        assert_eq!(link.traffic_control, Some(TrafficControlType::Signal));
        assert_eq!(link.turn_type, Some(TurnType::Through));
        assert_eq!(link.speed_limit_kph, Some(50.0));
    }

    #[test]
    fn transit_stop_metadata_builder_helpers() {
        let stop = TransitStopMetadata::new(3, AllowedModes::none().with_mode(TravelMode::Transit))
            .with_zone(10)
            .with_level_relation(LevelRelation::on(2));

        assert_eq!(stop.semantic_id(), 3);
        assert_eq!(stop.zone_id, Some(10));
        assert_eq!(stop.level_relation, Some(LevelRelation::on(2)));
        assert!(stop.served_modes.allows(TravelMode::Transit));
    }

    #[test]
    fn fundamental_diagram_and_link_ops_work() {
        let fd = FundamentalDiagram::Greenshields;
        assert!((fd.speed(75.0, 13.9, 150.0) - 6.95).abs() < 0.1);

        let mut space: TransportLinkSpace = LinkSpace::new();
        let a = space.add_node();
        let b = space.add_node();
        let (geom, props) = LinkProperties::urban(500.0, 50.0, 2).unwrap();
        let link = space.add_link(a, b, geom, props).unwrap();
        for i in 1..=15 {
            space.add_agent_to_link(i, link, (i as f64) * 30.0).unwrap();
        }

        assert!((space.link_density(link) - 15.0).abs() < 1e-6);
        assert!((space.link_speed(link) - 12.51).abs() < 0.1);
        let ff_time = space.link_free_flow_time(link);
        assert!((ff_time - 36.0).abs() < 1.0);
        assert!(space.volume_capacity_ratio(link, 3600.0) > 0.0);
    }
}