sumo-types 0.2.2

Reads and writes SUMO (Eclipse SUMO) .net.xml, .rou.xml and .add.xml files as well-typed Rust structs
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
//! Layer 2: this crate's own domain types.
//!
//! These types are independent of SUMO/XSD (unlike the private `schema`
//! module, layer
//! 1, which is an almost literal mirror of the `.xsd` files) and are
//! produced from it by [`crate::schema_mapper`]. Consumers of this crate
//! should work on these types, not on the ones generated by xsd-parser.

use derive_more::{AsRef, Display, From};
use uom::si::f64::{Length, Time, Velocity};
use uom::si::length::meter;

/// SUMO's default lane width (`SUMO_const_laneWidth`), used by netconvert
/// whenever a lane's `width` attribute is omitted from `.net.xml`.
///
/// This is the value SUMO itself has used across recent versions; it isn't
/// derived from anything in this repo, so double-check it against the SUMO
/// version producing your input if precision matters.
#[must_use]
pub fn default_lane_width() -> Length {
    Length::new::<meter>(3.2)
}

/// SUMO's default lane end offset: `0`, meaning the lane extends the full
/// length of its edge. Used whenever a lane's `endOffset` attribute is
/// omitted from `.net.xml`.
#[must_use]
pub fn default_lane_end_offset() -> Length {
    Length::new::<meter>(0.0)
}

/// Identifier of an [`Edge`]. A distinct type from a bare `String` so it
/// can't be passed where a [`LaneId`] is expected — a mistake that would
/// silently compile (and silently misbehave, e.g. as a wrong `HashMap`
/// lookup) if every id were just a `String`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Display, From, AsRef)]
pub struct EdgeId(#[as_ref(forward)] pub String);

/// Identifier of a [`Lane`]. See [`EdgeId`] for why this isn't a bare `String`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Display, From, AsRef)]
pub struct LaneId(#[as_ref(forward)] pub String);

/// Identifier of a [`Junction`]. See [`EdgeId`] for why this isn't a bare `String`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Display, From, AsRef)]
pub struct JunctionId(#[as_ref(forward)] pub String);

/// Identifier of a traffic light program (`tlLogic`). See [`EdgeId`] for why
/// this isn't a bare `String`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Display, From, AsRef)]
pub struct TrafficLightId(#[as_ref(forward)] pub String);

/// Index of a [`Lane`] within its parent [`Edge`] (`0` is the rightmost lane
/// in SUMO's convention). A distinct type from a bare `usize` so it can't be
/// confused with unrelated counts (e.g. a traffic light link index).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Display, From)]
pub struct LaneIndex(pub usize);

/// Relative right-of-way ranking of an [`Edge`] (higher wins), derived by
/// netconvert from the road classification. Can be negative (e.g. `-1` for
/// internal/connector edges). A distinct type from a bare `i32` so it can't
/// be confused with unrelated integers (e.g. a traffic light link index).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Display, From)]
pub struct Priority(pub i32);

/// Index of a [`Connection`] within its traffic light's signal group
/// (`tlLogic/@state` / `phase/@state` character position). A distinct type
/// from a bare `i32` so it can't be confused with unrelated integers (e.g.
/// an edge's [`Priority`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Display, From)]
pub struct LinkIndex(pub i32);

/// A point in the network's coordinate system, re-exported at this format's
/// own path. Defined once for the whole crate — see the type's own docs for
/// why this one is shared while the id newtypes above are not.
pub use crate::sumo::Point;

/// Polyline that defines the geometry of an edge, lane, or junction.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Shape(pub Vec<Point>);

/// Bounding box (bottom-left corner, top-right corner). Each corner is a
/// [`Point`] rather than a bare `(f64, f64)`: SUMO's `locationType` boundary
/// is inherently 2D (no `z`), but reusing the type already shared by every
/// other coordinate in this crate beats introducing a second, boundary-only
/// pair type for the same two numbers.
///
/// [`Default`] is the degenerate box at the origin.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Boundary {
    pub min: Point,
    pub max: Point,
}

/// How a network's coordinates relate to real-world geographic coordinates,
/// as declared by SUMO's `location/@projParameter`.
#[derive(Debug, Clone, Default, PartialEq)]
pub enum Projection {
    /// SUMO's `"!"` sentinel: the network isn't georeferenced, its
    /// coordinates are already local/Cartesian. Also the [`Default`]:
    /// assuming plain Cartesian coordinates is the assumption that can't
    /// silently misplace a network on the globe.
    #[default]
    None,
    /// A PROJ definition string, e.g. `"+proj=utm +zone=32 +ellps=WGS84"`.
    Proj4(String),
}

/// Geographic metadata of the network, as exported by netconvert. Unlike
/// the XSD (which marks these attributes optional), a real `netconvert`
/// output always populates all of them, so a missing one here is treated as
/// a malformed input rather than modeled with `Option`.
///
/// [`Default`] is a non-georeferenced network at the origin with an empty
/// bounding box — what an empty `.net.xml` would describe. It exists so
/// [`Network`] can keep its own [`Default`] for test fixtures
/// (`Network { edges, ..Default::default() }`) now that `location` is no
/// longer an `Option`; it is not something [`crate::read_network`] ever
/// produces.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Location {
    pub net_offset: Point,
    pub converted_boundary: Boundary,
    pub original_boundary: Boundary,
    pub projection: Projection,
}

/// The role an edge plays within the network.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EdgeFunction {
    Normal,
    Internal,
    Connector,
    Crossing,
    Walkingarea,
}

/// How the edge's width is distributed relative to its axis.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpreadType {
    Center,
    RoadCenter,
    Right,
}

/// SUMO's own named vehicle/traffic-participant classes. Defined in the
/// shared `crate::sumo` module, not here — `routes::domain::VehicleType`
/// needs it too (`vClass` is a plain vehicle-class token there as well),
/// and `routes` doesn't depend on `net` (see that module's own docs) — and
/// re-exported at this path so `domain::VClass` stays the public spelling
/// this crate has always used.
pub use crate::sumo::{UnknownVClass, VClass};

/// A lane within an edge.
#[derive(Debug, Clone, PartialEq)]
pub struct Lane {
    pub id: LaneId,
    pub index: LaneIndex,
    pub speed: Velocity,
    pub length: Length,
    pub width: Length,
    pub end_offset: Length,
    pub shape: Shape,
    pub allow: Vec<String>,
    pub disallow: Vec<String>,
}

impl Lane {
    /// Shorthand for `class.permitted_on(&self.allow, &self.disallow)` —
    /// see [`VClass::permitted_on`] for the actual rule.
    #[must_use]
    pub fn permits(&self, class: VClass) -> bool {
        class.permitted_on(&self.allow, &self.disallow)
    }

    /// Whether this lane is restricted to pedestrians only
    /// (`allow="pedestrian"` in `.net.xml`, e.g. crossings and
    /// walkingareas) — straight from SUMO's own vClass permissions, not
    /// from the edge's `function` label. Distinct from
    /// `self.permits(VClass::Pedestrian)`: that asks "may a pedestrian use
    /// this lane", true for e.g. `allow="pedestrian bicycle"` too, while
    /// this asks "is a pedestrian the *only* thing that may".
    #[must_use]
    pub fn is_pedestrian_only(&self) -> bool {
        !self.allow.is_empty() && self.allow.iter().all(|vclass| vclass == "pedestrian")
    }
}

/// A directed edge (arc) of the network.
#[derive(Debug, Clone, PartialEq)]
pub struct Edge {
    pub id: EdgeId,
    pub function: EdgeFunction,
    pub from: Option<JunctionId>,
    pub to: Option<JunctionId>,
    pub name: Option<String>,
    pub priority: Option<Priority>,
    pub length: Option<Length>,
    pub shape: Option<Shape>,
    pub spread_type: Option<SpreadType>,
    pub lanes: Vec<Lane>,
}

/// The kind of right-of-way control a junction has (traffic light, priority,
/// yield, ...).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JunctionKind {
    TrafficLight,
    TrafficLightUnregulated,
    TrafficLightRightOnRed,
    RailSignal,
    RailCrossing,
    Priority,
    PriorityStop,
    LeftBeforeRight,
    RightBeforeLeft,
    AllWayStop,
    Zipper,
    District,
    Unregulated,
    Internal,
    DeadEnd,
}

/// A network node where one or more edges meet.
#[derive(Debug, Clone, PartialEq)]
pub struct Junction {
    pub id: JunctionId,
    pub position: Point,
    pub kind: JunctionKind,
    pub incoming_lanes: Vec<LaneId>,
    pub internal_lanes: Vec<LaneId>,
    pub shape: Option<Shape>,
    pub name: Option<String>,
}

/// Turning direction of a connection, following SUMO's convention
/// (`SUMOXMLDefinitions::LinkDirection`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum ConnectionDirection {
    Straight,
    Turn,
    TurnLeftHand,
    Left,
    Right,
    PartialLeft,
    PartialRight,
}

/// Right-of-way state of a connection, following SUMO's convention
/// (`SUMOXMLDefinitions::LinkState`) for the `state` attribute in `.net.xml`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LinkState {
    /// Has the right of way ("major").
    Major,
    /// Does not have the right of way ("minor"), must yield.
    Minor,
    /// Controlled by a traffic light that is off, with no visible signal.
    TlsOffNoSignal,
    /// Controlled by a traffic light that is off, in blinking mode.
    TlsOffBlinking,
    /// Shared right of way (everyone yields equally).
    Equal,
    /// Must come to a full stop.
    Stop,
    /// "All-way stop" style intersection.
    AllWayStop,
    /// "Zipper" merge.
    Zipper,
    /// No real connection (dead end).
    DeadEnd,
}

/// A connection between two lanes (possibly from different edges).
#[derive(Debug, Clone, PartialEq)]
pub struct Connection {
    pub from_edge: EdgeId,
    pub to_edge: EdgeId,
    pub from_lane: LaneIndex,
    pub to_lane: LaneIndex,
    pub direction: ConnectionDirection,
    pub state: LinkState,
    pub via: Option<LaneId>,
    pub traffic_light: Option<TrafficLightId>,
    pub link_index: Option<LinkIndex>,
    pub pass: bool,
    pub keep_clear: bool,
}

/// A roundabout in the network.
#[derive(Debug, Clone, PartialEq)]
pub struct Roundabout {
    pub nodes: Vec<JunctionId>,
    pub edges: Vec<EdgeId>,
}

/// A traffic light program's control strategy (`tlLogic/@type`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TrafficLightKind {
    Actuated,
    DelayBased,
    Static,
    Nema,
}

/// When a traffic light program's cycle starts, relative to the simulation
/// clock (`tlLogic/@offset`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TrafficLightOffset {
    /// A fixed offset into the program's cycle.
    Fixed(Time),
    /// SUMO's `"begin"` sentinel: the cycle starts at the simulation's own
    /// begin time rather than at a fixed offset.
    Begin,
}

/// One phase of a [`TrafficLightProgram`] (`phaseType`): how long it lasts
/// and the `state` string every [`Connection`] it controls reads from at
/// that phase — see the program's own docs for how the two connect.
///
/// Only `duration` and `state` are modelled. `phaseType` also has a group of
/// actuated/NEMA-controller attributes this crate doesn't read yet —
/// `minDur`, `maxDur`, `earliestEnd`, `latestEnd`, `earlyTarget`,
/// `finalTarget`, `yellow`, `red`, `vehext`, `next`, `name` — meaningful
/// only for a [`TrafficLightProgram`] whose `kind` is
/// [`TrafficLightKind::Actuated`] or [`TrafficLightKind::Nema`], and absent
/// or ignored for the plain [`TrafficLightKind::Static`] case this crate was
/// first built to round-trip.
#[derive(Debug, Clone, PartialEq)]
pub struct Phase {
    pub duration: Time,
    pub state: String,
}

/// A traffic light program (`tlLogic`): an ordered list of [`Phase`]s. The
/// character at index `i` of every phase's `state` governs the
/// [`Connection`] whose `link_index == i` — two links that always share the
/// same character, in every phase, are controlled by the same physical
/// signal head and should be treated as one group, even if SUMO assigns
/// them different `link_index`es.
///
/// A `tlLogic` id can appear more than once in `.net.xml` (multiple
/// programs sharing one junction, e.g. a normal one and a night-time one) —
/// [`Self::program_id`] is what tells them apart; which one is "the" active
/// program for a junction is left to the caller. This type only models a
/// single program as parsed.
#[derive(Debug, Clone, PartialEq)]
pub struct TrafficLightProgram {
    pub id: TrafficLightId,
    /// `programID`: SUMO requires this, so unlike [`Self::kind`] and
    /// [`Self::offset`] it can't be `None` — a `.net.xml` omitting it fails
    /// to parse rather than yielding a program with no `program_id`.
    pub program_id: String,
    pub kind: Option<TrafficLightKind>,
    pub offset: Option<TrafficLightOffset>,
    pub phases: Vec<Phase>,
}

/// Complete model of a SUMO network (`.net.xml`), already converted to the
/// project's own types and decoupled from the original XSD schema.
///
/// [`Default`] is an empty network with a default [`Location`], which is
/// useful for building test fixtures but is never what
/// [`crate::read_network`] returns: `net_file.xsd` requires `<location>`
/// (`minOccurs="1"`), so a parsed `Network` always carries the real one.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Network {
    /// Always present: `net_file.xsd` declares `<location>` as
    /// `minOccurs="1"`, so a `.net.xml` without one fails to parse rather
    /// than yielding a `Network` with no location.
    pub location: Location,
    pub edges: Vec<Edge>,
    pub junctions: Vec<Junction>,
    pub connections: Vec<Connection>,
    pub roundabouts: Vec<Roundabout>,
    pub traffic_light_programs: Vec<TrafficLightProgram>,
}

#[cfg(test)]
mod vclass_tests {
    use super::*;

    fn lane_with(allow: &[&str], disallow: &[&str]) -> Lane {
        Lane {
            id: LaneId("e0_0".into()),
            index: LaneIndex(0),
            speed: Velocity::new::<uom::si::velocity::meter_per_second>(10.0),
            length: Length::new::<meter>(20.0),
            width: default_lane_width(),
            end_offset: default_lane_end_offset(),
            shape: Shape::default(),
            allow: allow.iter().map(|s| (*s).to_string()).collect(),
            disallow: disallow.iter().map(|s| (*s).to_string()).collect(),
        }
    }

    #[test]
    fn a_lane_with_neither_attribute_permits_every_class() {
        let lane = lane_with(&[], &[]);
        assert!(lane.permits(VClass::Passenger));
        assert!(lane.permits(VClass::Bicycle));
        assert!(lane.permits(VClass::Pedestrian));
    }

    #[test]
    fn disallow_excludes_only_the_classes_it_names() {
        let lane = lane_with(&[], &["pedestrian", "tram"]);
        assert!(!lane.permits(VClass::Pedestrian));
        assert!(!lane.permits(VClass::Tram));
        assert!(lane.permits(VClass::Passenger));
        assert!(lane.permits(VClass::Bicycle));
    }

    #[test]
    fn a_non_empty_allow_is_exhaustive_disallow_is_not_consulted() {
        // Real `.net.xml` output never sets both, but `permitted_on`'s own
        // contract is "allow wins outright" regardless.
        let lane = lane_with(&["pedestrian"], &["pedestrian"]);
        assert!(lane.permits(VClass::Pedestrian));
        assert!(!lane.permits(VClass::Passenger));
    }

    #[test]
    fn disallow_all_permits_nothing() {
        let lane = lane_with(&[], &["all"]);
        assert!(!lane.permits(VClass::Passenger));
        assert!(!lane.permits(VClass::Pedestrian));
        assert!(!lane.permits(VClass::Bicycle));
    }

    #[test]
    fn allow_all_permits_everything_the_same_as_no_allow_at_all() {
        let lane = lane_with(&["all"], &[]);
        assert!(lane.permits(VClass::Passenger));
        assert!(lane.permits(VClass::Pedestrian));
    }

    #[test]
    fn an_unknown_token_in_disallow_does_not_affect_any_known_class() {
        // Real, forward-compatible shape: a `.net.xml` from a newer SUMO
        // naming a vClass this crate doesn't have a variant for yet.
        let lane = lane_with(&[], &["some_future_vclass"]);
        assert!(lane.permits(VClass::Passenger));
        assert!(lane.permits(VClass::Bicycle));
    }

    #[test]
    fn an_unknown_token_in_a_non_empty_allow_grants_no_known_class() {
        let lane = lane_with(&["some_future_vclass"], &[]);
        assert!(!lane.permits(VClass::Passenger));
    }

    #[test]
    fn a_real_barcelona_style_vehicle_lane_permits_car_moped_and_bicycle() {
        // Mirrors `disallow="pedestrian tram rail_urban rail rail_electric
        // rail_fast ship container cable_car subway aircraft wheelchair
        // scooter drone"`, the actual attribute this crate's own Barcelona
        // fixture uses on an ordinary vehicle lane.
        let lane = lane_with(
            &[],
            &[
                "pedestrian",
                "tram",
                "rail_urban",
                "rail",
                "rail_electric",
                "rail_fast",
                "ship",
                "container",
                "cable_car",
                "subway",
                "aircraft",
                "wheelchair",
                "scooter",
                "drone",
            ],
        );
        assert!(lane.permits(VClass::Passenger));
        assert!(lane.permits(VClass::Motorcycle));
        assert!(lane.permits(VClass::Moped));
        assert!(lane.permits(VClass::Bicycle));
        assert!(!lane.permits(VClass::Pedestrian));
    }

    #[test]
    fn a_pedestrian_only_lane_permits_only_pedestrians() {
        let lane = lane_with(&["pedestrian"], &[]);
        assert!(lane.permits(VClass::Pedestrian));
        assert!(!lane.permits(VClass::Passenger));
        assert!(!lane.permits(VClass::Bicycle));
    }

    #[test]
    fn from_str_rejects_an_unknown_token() {
        let err = "spaceship".parse::<VClass>().unwrap_err();
        assert_eq!(err, UnknownVClass("spaceship".to_string()));
    }
}