liblrs 0.5.0

Library to manipulate linear referencing systems
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
500
501
502
503
504
505
506
507
508
509
510
//! A LRM (linear reference model) is an abstract representation
//! where the geometry and real distances are not considered.

use geo::Point;
use thiserror::Error;

use crate::lrs::Properties;

/// Measurement along the `Curve`. Typically in meters.
pub type CurvePosition = f64;

/// Measurement along the `LrmScale`. Often in meters, but it could be anything.
pub type ScalePosition = f64;

/// Errors when manipulating a `LrmScale`.
#[derive(Error, Debug, PartialEq)]
pub enum LrmScaleError {
    /// Returned when building a `LrmScale` from a builder and less than 2 [NamedAnchor] objects were provided.
    #[error("a scale needs at least two named anchor")]
    NoEnoughNamedAnchor,
    /// All the [NamedAnchor] objects must be unique within a same `LrmScale`.
    #[error("duplicated anchor: {0}")]
    DuplicatedAnchorName(String),
    /// Could not find the position on the `Curve` as the [Anchor] is not known.
    #[error("anchor is unknown in the LrmScale")]
    UnknownAnchorName,
    /// Could not find an [Anchor] that matches a given offset.
    #[error("no anchor found")]
    NoAnchorFound,
}

/// An unnamed anchor is an anchor that is not a landmark, and no point will be referenced from that anchor.
///
/// It is used to match a scale position with a `Curve` position.
/// This can happen when an object between two `NamedAnchor` has a bad offset:
/// if it is said to be 300m away from the previous named anchor, but in reality it is 322m.
/// This makes sure that an object label at +310m is located after the one at +300m.
#[derive(PartialEq, Debug, Clone)]
pub struct UnnamedAnchor {
    /// Distance from the start of the scale in the scale space, can be negative.
    pub scale_position: ScalePosition,

    /// Real distance from the start of the `Curve`.
    /// The `Curve` might not start at the same 0 (e.g. the `Curve` is longer than the scale),
    /// or the `Curve` might not progress at the same rate (e.g. the `Curve` is a schematic representation that distorts distances).
    pub curve_position: CurvePosition,

    /// Position of the anchor on the `Curve`.
    pub point: Option<Point>,

    /// Metadata to describe the node
    pub properties: Properties,
}

/// A named anchor is an anchor that is a known reference point.
///
/// It often is a milestone (such a km 42), but it can be any landmark (a bridge, a notable building…)
#[derive(PartialEq, Debug, Clone)]
pub struct NamedAnchor {
    /// The name that identifies the anchor. It must be unique within the `LrmScale`.
    pub name: String,
    /// Distance from the start of the scale in the scale space, can be negative.
    pub scale_position: ScalePosition,

    /// Real distance from the start of the `Curve`.
    /// The `Curve` might not start at the same 0 (e.g. the `Curve` is longer than the scale),
    /// or the `Curve` might not progress at the same rate (e.g. the `Curve` is a schematic representation that distorts distances).
    pub curve_position: CurvePosition,

    /// Position of the anchor on the `Curve`.
    pub point: Option<Point>,

    /// Metadata to describe the node
    pub properties: Properties,
}

/// An anchor is a reference point on a `LrmScale`.
///
/// It can either be a `NamedAnchor` or an `UnnamedAnchor`.
#[derive(Debug, PartialEq, Clone)]
pub enum Anchor {
    /// A `NamedAnchor`
    Named(NamedAnchor),
    /// An `UnnamedAnchor`
    Unnamed(UnnamedAnchor),
}

impl Anchor {
    /// Builds a named `Anchor`.
    pub fn new_named(
        name: &str,
        scale_position: ScalePosition,
        curve_position: CurvePosition,
        point: Option<Point>,
        properties: Properties,
    ) -> Self {
        Self::Named(NamedAnchor {
            name: name.to_owned(),
            scale_position,
            curve_position,
            point,
            properties,
        })
    }

    /// Create an unnamed anchor.
    pub fn new_unnamed(
        scale_position: ScalePosition,
        curve_position: CurvePosition,
        point: Option<Point>,
        properties: Properties,
    ) -> Self {
        Self::Unnamed(UnnamedAnchor {
            scale_position,
            curve_position,
            point,
            properties,
        })
    }

    /// Position of the anchor on the scale.
    ///
    /// This value is arbitrary. It typically is expressed in meters, but can be any unit.
    /// It is common, but not necessary that the scale starts at 0 at the start of the curve.
    pub fn scale_position(&self) -> ScalePosition {
        match self {
            Anchor::Named(anchor) => anchor.scale_position,
            Anchor::Unnamed(anchor) => anchor.scale_position,
        }
    }

    /// Position of the anchor on the curve.
    ///
    /// The value is between 0 and 1 and represents a fraction of the curve.
    /// The can sometimes be negative to represent an anchor located before the curve starts.
    pub fn curve_position(&self) -> ScalePosition {
        match self {
            Anchor::Named(anchor) => anchor.curve_position,
            Anchor::Unnamed(anchor) => anchor.curve_position,
        }
    }

    /// Properties of the anchor
    pub fn properties(&self) -> &Properties {
        match self {
            Anchor::Named(anchor) => &anchor.properties,
            Anchor::Unnamed(anchor) => &anchor.properties,
        }
    }

    /// Geographical position of the anchor
    ///
    /// The location can be outside of the curve (a landmark visible from the curve)
    /// It is optional as it might be defined only with the curve position
    pub fn point(&self) -> Option<Point> {
        match self {
            Anchor::Named(anchor) => anchor.point,
            Anchor::Unnamed(anchor) => anchor.point,
        }
    }
}

/// A measure defines a location on the [LrmScale].
/// It is given as an [Anchor] name and an `offset` on that scale.
/// It is often represented as `12+100` to say `“100 scale units after the Anchor 12`”.
#[derive(Clone, Debug)]
pub struct LrmScaleMeasure {
    /// `Name` of the [Anchor]. While it is often named after a kilometer position,
    /// it can be anything (a letter, a landmark).
    pub anchor_name: String,
    /// The `offset` from the anchor in the scale units.
    /// there is no guarantee that its value matches actual distance on the `Curve` and is defined in scale units.
    pub scale_offset: ScalePosition,
}

impl LrmScaleMeasure {
    /// Builds a new `LrmMeasure` from an [Anchor] `name` and the `offset` on the [LrmScale].
    pub fn new(anchor_name: &str, scale_offset: ScalePosition) -> Self {
        Self {
            anchor_name: anchor_name.to_owned(),
            scale_offset,
        }
    }
}

/// Represents an `LrmScale` and allows to map [Measure] to a position along a `Curve`.
#[derive(PartialEq, Debug, Clone)]
pub struct LrmScale {
    /// Unique identifier.
    pub id: String,
    /// The [Anchor] objects are reference points on the scale from which relative distances are used.
    pub anchors: Vec<Anchor>,
}

impl LrmScale {
    /// Locates a point along a `Curve` given an [Anchor] and an `offset`,
    /// which might be negative.
    /// The `[CurvePosition]` is between 0.0 and 1.0, both included
    pub fn locate_point(&self, measure: &LrmScaleMeasure) -> Result<CurvePosition, LrmScaleError> {
        let named_anchor = self
            .iter_named()
            .find(|anchor| anchor.name == measure.anchor_name)
            .ok_or(LrmScaleError::UnknownAnchorName)?;

        let scale_position = named_anchor.scale_position + measure.scale_offset;
        let anchors = self
            .anchors
            .windows(2)
            .find(|window| window[1].scale_position() >= scale_position)
            .or_else(|| self.anchors.windows(2).last())
            .ok_or(LrmScaleError::NoAnchorFound)?;

        let scale_interval = anchors[0].scale_position() - anchors[1].scale_position();
        let curve_interval = anchors[0].curve_position() - anchors[1].curve_position();
        Ok(anchors[0].curve_position()
            + curve_interval * (scale_position - anchors[0].scale_position()) / scale_interval)
    }

    /// Returns a [LrmScaleMeasure] given a distance along the `Curve`.
    ///
    /// The corresponding [Anchor] is the named `Anchor` that gives the smallest positive `offset`.
    /// If such an `Anchor` does not exists, the first named `Anchor` is used and the offset can be negative.
    pub fn locate_anchor(
        &self,
        curve_position: CurvePosition,
    ) -> Result<LrmScaleMeasure, LrmScaleError> {
        // First, we find the nearest named Anchor to the Curve.
        // It will be the reference point from which we will compute the offset to the point on the curve
        let named_anchor = self
            .nearest_named(curve_position)
            .ok_or(LrmScaleError::NoAnchorFound)?;

        // We need the anchor just before and just after the position to interpolate the scale position
        // If we are looking for a curve position that is after the last anchor, we extrapolate from the last two
        let anchors = self
            .anchors
            .windows(2)
            .find(|window| window[1].curve_position() >= curve_position)
            .or_else(|| self.anchors.windows(2).last())
            .ok_or(LrmScaleError::NoAnchorFound)?;

        // We compute a ratio to know how much the scale increases per unit of curve.
        // This ratio isn’t always constant due to irregularities in anchor measurements
        let ratio = (anchors[0].scale_position() - anchors[1].scale_position())
            / (anchors[0].curve_position() - anchors[1].curve_position());

        Ok(LrmScaleMeasure {
            anchor_name: named_anchor.name.clone(),
            scale_offset: (anchors[0].scale_position() - named_anchor.scale_position)
                + (curve_position - anchors[0].curve_position()) * ratio,
        })
    }

    /// Returns a measure given a distance along the `LrmScale`.
    /// The corresponding [Anchor] is the named `Anchor` that gives the smallest positive `offset`.
    /// If such an `Anchor` does not exists, the first named `Anchor` is used.
    pub fn get_measure(
        &self,
        scale_position: ScalePosition,
    ) -> Result<LrmScaleMeasure, LrmScaleError> {
        let named_anchor = self
            .scale_nearest_named(scale_position)
            .ok_or(LrmScaleError::NoAnchorFound)?;

        Ok(LrmScaleMeasure {
            anchor_name: named_anchor.name.clone(),
            scale_offset: scale_position - named_anchor.scale_position,
        })
    }

    /// Locates a point along the scale given an [Anchor] and an `offset`,
    /// which might be negative.
    pub fn get_position(&self, measure: LrmScaleMeasure) -> Result<ScalePosition, LrmScaleError> {
        let named_anchor = self
            .iter_named()
            .find(|anchor| anchor.name == measure.anchor_name)
            .ok_or(LrmScaleError::UnknownAnchorName)?;

        Ok(named_anchor.scale_position + measure.scale_offset)
    }

    fn nearest_named(&self, curve_position: CurvePosition) -> Option<&NamedAnchor> {
        // Tries to find the Anchor whose curve_position is the biggest possible, yet smaller than Curve position
        // Otherwise take the first named
        // Anchor names   ----A----B----
        // Curve positions    2    3
        // With Curve position = 2.1, we want A
        // With Curve position = 2.9, we want A
        //                       3.5, we want B
        //                       1.5, we want A
        self.iter_named()
            .rev()
            .find(|anchor| anchor.curve_position <= curve_position)
            .or_else(|| self.iter_named().next())
    }

    fn scale_nearest_named(&self, scale_position: ScalePosition) -> Option<&NamedAnchor> {
        // Like nearest_named, but our position is along the scale
        self.iter_named()
            .rev()
            .find(|anchor| anchor.scale_position <= scale_position)
            .or_else(|| self.iter_named().next())
    }

    // Iterates only on named Anchor objects
    fn iter_named(&self) -> impl DoubleEndedIterator<Item = &NamedAnchor> + '_ {
        self.anchors.iter().filter_map(|anchor| match anchor {
            Anchor::Named(anchor) => Some(anchor),
            Anchor::Unnamed(_) => None,
        })
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use crate::properties;

    use super::*;

    pub(crate) fn scale() -> LrmScale {
        LrmScale {
            id: "id".to_owned(),
            anchors: vec![
                Anchor::new_named("a", 0., 0., None, properties!()),
                Anchor::new_named("b", 10., 0.5, None, properties!()),
            ],
        }
    }

    #[test]
    fn locate_point() {
        // Everything a usual
        assert_eq!(
            scale().locate_point(&LrmScaleMeasure::new("a", 5.)),
            Ok(0.25)
        );
        assert_eq!(
            scale().locate_point(&LrmScaleMeasure::new("b", 5.)),
            Ok(0.75)
        );

        // Negative offsets
        assert_eq!(
            scale().locate_point(&LrmScaleMeasure::new("a", -5.)),
            Ok(-0.25)
        );

        // Unknown Anchor
        assert_eq!(
            scale().locate_point(&LrmScaleMeasure::new("c", 5.)),
            Err(LrmScaleError::UnknownAnchorName)
        );
    }

    #[test]
    fn nearest_named() {
        let scale = LrmScale {
            id: "id".to_owned(),
            anchors: vec![
                Anchor::new_named("a", 0., 2., None, properties!()),
                Anchor::new_named("b", 10., 3., None, properties!()),
            ],
        };

        assert_eq!(scale.nearest_named(2.1).unwrap().name, "a");
        assert_eq!(scale.nearest_named(2.9).unwrap().name, "a");
        assert_eq!(scale.nearest_named(1.5).unwrap().name, "a");
        assert_eq!(scale.nearest_named(3.5).unwrap().name, "b");
    }

    #[test]
    fn locate_anchor() {
        let measure = scale().locate_anchor(0.2).unwrap();
        assert_eq!(measure.anchor_name, "a");
        assert_eq!(measure.scale_offset, 4.);

        let measure = scale().locate_anchor(0.75).unwrap();
        assert_eq!(measure.anchor_name, "b");
        assert_eq!(measure.scale_offset, 5.);

        let measure = scale().locate_anchor(-0.05).unwrap();
        assert_eq!(measure.anchor_name, "a");
        assert_eq!(measure.scale_offset, -1.);
    }

    #[test]
    fn locate_anchor_with_unnamed() {
        // ----Unnamed(100)----A(200)----Unnamed(250)----B(300)----Unnamed(400)---
        let scale = LrmScale {
            id: "id".to_owned(),
            anchors: vec![
                Anchor::new_unnamed(0., 100., None, properties!()),
                Anchor::new_named("a", 1., 200., None, properties!()),
                Anchor::new_unnamed(1.2, 250., None, properties!()), // 250 is between A and B, but the scale is a voluntarily off
                Anchor::new_named("b", 3., 300., None, properties!()),
                Anchor::new_unnamed(4., 400., None, properties!()),
            ],
        };

        // Unnamed----position----Named
        let measure = scale.locate_anchor(150.).unwrap();
        assert_eq!(measure.anchor_name, "a");
        assert_eq!(measure.scale_offset, -0.5);

        // position----Unnamed----Named
        let measure = scale.locate_anchor(50.).unwrap();
        assert_eq!(measure.anchor_name, "a");
        assert_eq!(measure.scale_offset, -1.5);

        // Named----Unnamed----position----Named
        let measure = scale.locate_anchor(275.).unwrap();
        assert_eq!(measure.anchor_name, "a");
        // The first unnamed is at 0.2 from a.
        // The position to find is right in the middle of 250 and 300, so 0.9 from the first unnamed
        assert_eq!(measure.scale_offset, 0.2 + 0.9);

        // Unnamed----Named----position----Unnamed
        let measure = scale.locate_anchor(350.).unwrap();
        assert_eq!(measure.anchor_name, "b");
        assert_eq!(measure.scale_offset, 0.5);

        // Unnamed----Named----Unnamed----position
        // This tests we are also able to extrapolate when the position is not between two anchors
        let measure = scale.locate_anchor(500.).unwrap();
        assert_eq!(measure.anchor_name, "b");
        assert_eq!(measure.scale_offset, 2.);
    }

    #[test]
    fn get_measure() {
        // a(scale 0)----measure(scale 5)----b(scale 10)
        let measure = scale().get_measure(5.).unwrap();
        assert_eq!(measure.anchor_name, "a");
        assert_eq!(measure.scale_offset, 5.);

        // a(scale 0)----b(scale 10)----measure(scale 25)
        let measure = scale().get_measure(25.).unwrap();
        assert_eq!(measure.anchor_name, "b");
        assert_eq!(measure.scale_offset, 15.);
    }

    #[test]
    fn get_position() {
        // a(scale 0)----position(scale a+5)----b(scale 10)
        let position = scale()
            .get_position(LrmScaleMeasure {
                anchor_name: "a".to_string(),
                scale_offset: 5.,
            })
            .unwrap();
        assert_eq!(position, 5.);

        // a(scale 0)----b(scale 10)----position(scale b+15)
        let position = scale()
            .get_position(LrmScaleMeasure {
                anchor_name: "b".to_string(),
                scale_offset: 15.,
            })
            .unwrap();
        assert_eq!(position, 25.);
    }

    #[test]
    fn single_anchor() {
        // Scenario where the curve is to short to have an anchor
        // The scale of the curve goes from 1200 to 1300
        // The anchor corresponding to the 0 of the scale is at -2. of the curve
        // Anchor(curve: -2, scale: 1000)    [curve begin]------Unamed(curve: 0, scale: 1300)
        let scale = LrmScale {
            id: "id".to_owned(),
            anchors: vec![
                Anchor::new_named("a", 1000. + 0., -2., None, properties!()),
                Anchor::new_unnamed(1000. + 300., 1., None, properties!()),
            ],
        };

        let position = scale
            .locate_point(&LrmScaleMeasure {
                anchor_name: "a".to_string(),
                scale_offset: 200.,
            })
            .unwrap();

        assert_eq!(position, 0.);
    }

    #[test]
    fn irregular_scale() {
        // Let’s imagine a scale that growth weirdly
        // 0----1--9----10
        // If we want the position +5, it should be 0.5 on the scale
        let scale = LrmScale {
            id: "id".to_owned(),
            anchors: vec![
                Anchor::new_named("a", 0., 0., None, properties!()),
                Anchor::new_unnamed(1., 0.4, None, properties!()),
                Anchor::new_unnamed(9., 0.6, None, properties!()),
            ],
        };

        let position = scale
            .locate_point(&LrmScaleMeasure {
                anchor_name: "a".to_string(),
                scale_offset: 5.,
            })
            .unwrap();

        assert_eq!(position, 0.5);
    }
}