oxiproj-core 0.1.2

Foundation types for OxiProj: coordinates, errors, ellipsoids, datums, and units.
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
//! Time-dependent coordinate reference frame epochs.
//! Supports `"ITRF2020@2021.3"` notation and decimal year arithmetic.

use crate::error::ProjError;
#[cfg(feature = "no_std")]
use alloc::format;
#[cfg(feature = "no_std")]
use alloc::string::String;
#[cfg(feature = "no_std")]
use alloc::string::ToString;
use core::fmt;
use core::str::FromStr;

/// A decimal-year epoch (e.g., 2021.3 ≈ April 22, 2021).
///
/// Decimal years are the standard time representation used in geodesy and
/// tectonic plate motion models. A value of 2021.3 corresponds to
/// approximately 2021-04-22.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Epoch {
    /// Decimal year (e.g., 2021.3).
    pub year: f64,
}

impl Epoch {
    /// Construct an epoch from a decimal year value.
    ///
    /// # Errors
    ///
    /// Returns [`ProjError::IllegalArgValue`] if `year` is NaN or infinite.
    pub fn new(year: f64) -> Result<Self, ProjError> {
        if !year.is_finite() {
            return Err(ProjError::IllegalArgValue);
        }
        Ok(Self { year })
    }

    /// Alias for [`Epoch::new`] — constructs an epoch from a decimal year.
    ///
    /// # Errors
    ///
    /// Returns [`ProjError::IllegalArgValue`] if `year` is NaN or infinite.
    pub fn from_decimal_year(year: f64) -> Result<Self, ProjError> {
        Self::new(year)
    }

    /// Compute the signed number of years elapsed from `other` to `self`.
    ///
    /// A positive result means `self` is later than `other`.
    ///
    /// ```
    /// use oxiproj_core::epoch::Epoch;
    ///
    /// let e1 = Epoch::new(2020.0).unwrap();
    /// let e2 = Epoch::new(2021.5).unwrap();
    /// assert!((e2.delta_years(&e1) - 1.5).abs() < 1e-10);
    /// ```
    #[must_use]
    pub fn delta_years(&self, other: &Epoch) -> f64 {
        self.year - other.year
    }
}

impl fmt::Display for Epoch {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.year)
    }
}

impl FromStr for Epoch {
    type Err = ProjError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let year = s
            .trim()
            .parse::<f64>()
            .map_err(|_| ProjError::IllegalArgValue)?;
        Self::new(year)
    }
}

/// A reference frame identifier paired with an optional coordinate epoch.
///
/// Parsing follows the `"<frame>@<epoch>"` convention used in PROJ and ISO 19111:
/// - `"ITRF2020@2021.3"` — dynamic frame at decimal year 2021.3
/// - `"NAD83(2011)"` — static (epoch-less) realization
///
/// # Examples
///
/// ```
/// use oxiproj_core::epoch::RefFrameEpoch;
///
/// let r: RefFrameEpoch = "ITRF2020@2021.3".parse().unwrap();
/// assert_eq!(r.frame, "ITRF2020");
/// assert!(r.is_dynamic());
/// assert_eq!(r.to_string(), "ITRF2020@2021.3");
/// ```
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RefFrameEpoch {
    /// Reference frame name/identifier (e.g., `"ITRF2020"`, `"NAD83(2011)"`).
    pub frame: String,
    /// Optional epoch; `None` means "unspecified / static realization".
    pub epoch: Option<Epoch>,
}

impl RefFrameEpoch {
    /// Construct a [`RefFrameEpoch`] with an explicit frame name and optional epoch.
    pub fn new(frame: impl Into<String>, epoch: Option<Epoch>) -> Self {
        Self {
            frame: frame.into(),
            epoch,
        }
    }

    /// Construct a static (epoch-less) reference frame.
    pub fn static_frame(frame: impl Into<String>) -> Self {
        Self::new(frame, None)
    }

    /// Returns `true` if this reference frame carries an explicit epoch
    /// (i.e., it is a dynamic rather than static realization).
    #[must_use]
    pub fn is_dynamic(&self) -> bool {
        self.epoch.is_some()
    }
}

impl fmt::Display for RefFrameEpoch {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.epoch {
            None => write!(f, "{}", self.frame),
            Some(e) => write!(f, "{}@{}", self.frame, e),
        }
    }
}

impl FromStr for RefFrameEpoch {
    type Err = ProjError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let s = s.trim();
        if let Some((frame, epoch_str)) = s.split_once('@') {
            let epoch = Epoch::from_str(epoch_str)?;
            Ok(Self::new(frame.trim(), Some(epoch)))
        } else {
            Ok(Self::static_frame(s))
        }
    }
}

/// A 4D coordinate tagged with a reference frame and epoch.
///
/// Ties a [`crate::coord::Coord`] to its geodetic provenance — the reference
/// frame and the coordinate epoch at which the position was measured or
/// computed.
///
/// # Examples
///
/// ```
/// use oxiproj_core::epoch::{EpochCoord, RefFrameEpoch};
///
/// let frame: RefFrameEpoch = "ITRF2020@2021.3".parse().unwrap();
/// let ec = EpochCoord::from_lonlat(10.0, 51.0, frame);
/// assert!((ec.coord[0] - 10.0).abs() < 1e-12);
/// ```
#[derive(Debug, Clone)]
pub struct EpochCoord {
    /// Coordinate values `[x/λ, y/φ, z/h, t]`; `t` may encode the epoch year.
    pub coord: crate::coord::Coord,
    /// The reference frame and epoch this coordinate belongs to.
    pub frame: RefFrameEpoch,
}

impl EpochCoord {
    /// Construct an [`EpochCoord`] from a raw [`crate::coord::Coord`] and frame.
    pub fn new(coord: crate::coord::Coord, frame: RefFrameEpoch) -> Self {
        Self { coord, frame }
    }

    /// Construct an [`EpochCoord`] from longitude/latitude in decimal degrees.
    ///
    /// The `z` slot is zeroed and the `t` slot is set to
    /// [`f64::INFINITY`] (the PROJ "unspecified" sentinel).
    pub fn from_lonlat(lon: f64, lat: f64, frame: RefFrameEpoch) -> Self {
        Self::new(
            crate::coord::Coord::new(lon, lat, 0.0, f64::INFINITY),
            frame,
        )
    }
}

/// A CRS identifier with an optional epoch, following the `"<crs>@<epoch>"` notation.
///
/// This is a higher-level convenience type over [`RefFrameEpoch`] that exposes
/// the epoch directly as `f64` (decimal year) rather than the [`Epoch`] newtype.
/// It enforces the epoch range [1900, 2200].
///
/// # Examples
///
/// ```
/// use oxiproj_core::epoch::EpochTaggedCrs;
///
/// let e = EpochTaggedCrs::parse("ITRF2020@2021.3").unwrap();
/// assert_eq!(e.crs_id, "ITRF2020");
/// assert!((e.epoch.unwrap() - 2021.3).abs() < 1e-10);
/// assert_eq!(e.to_string_repr(), "ITRF2020@2021.3");
/// ```
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct EpochTaggedCrs {
    /// Base CRS identifier (e.g., `"ITRF2020"`, `"EPSG:4326"`).
    pub crs_id: String,
    /// Epoch in decimal years (e.g., 2021.3). `None` = use current epoch / static frame.
    pub epoch: Option<f64>,
}

impl EpochTaggedCrs {
    /// Parse an epoch-tagged CRS string.
    ///
    /// Formats supported:
    /// - `"ITRF2020@2021.3"` → `crs_id="ITRF2020"`, `epoch=Some(2021.3)`
    /// - `"ITRF2020"` → `crs_id="ITRF2020"`, `epoch=None`
    /// - `"EPSG:4326@2020.0"` → `crs_id="EPSG:4326"`, `epoch=Some(2020.0)`
    ///
    /// # Errors
    ///
    /// Returns [`EpochParseError`] if the string is empty, the epoch cannot be
    /// parsed as a decimal year, or the epoch falls outside [1900, 2200].
    pub fn parse(s: &str) -> Result<Self, EpochParseError> {
        if let Some((before, after)) = s.split_once('@') {
            let crs_id = before.trim().to_string();
            if crs_id.is_empty() {
                return Err(EpochParseError::EmptyCrsId);
            }
            let epoch_str = after.trim();
            let epoch: f64 = epoch_str
                .parse()
                .map_err(|_| EpochParseError::InvalidEpoch(epoch_str.to_string()))?;
            if !(1900.0..=2200.0).contains(&epoch) {
                return Err(EpochParseError::EpochOutOfRange);
            }
            Ok(Self {
                crs_id,
                epoch: Some(epoch),
            })
        } else {
            let crs_id = s.trim().to_string();
            if crs_id.is_empty() {
                return Err(EpochParseError::EmptyCrsId);
            }
            Ok(Self {
                crs_id,
                epoch: None,
            })
        }
    }

    /// Format as a canonical string (`"<crs>@<epoch>"` or just `"<crs>"`).
    #[must_use]
    pub fn to_string_repr(&self) -> String {
        match self.epoch {
            Some(e) => format!("{}@{}", self.crs_id, e),
            None => self.crs_id.clone(),
        }
    }
}

impl fmt::Display for EpochTaggedCrs {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.to_string_repr())
    }
}

/// Errors during [`EpochTaggedCrs`] parsing.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum EpochParseError {
    /// The CRS identifier portion of the string was empty.
    EmptyCrsId,
    /// The epoch string after `@` could not be parsed as a decimal year.
    InvalidEpoch(String),
    /// The epoch value falls outside the accepted range [1900, 2200].
    EpochOutOfRange,
}

impl fmt::Display for EpochParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            EpochParseError::EmptyCrsId => write!(f, "CRS identifier is empty"),
            EpochParseError::InvalidEpoch(s) => write!(f, "invalid epoch: {:?}", s),
            EpochParseError::EpochOutOfRange => {
                write!(f, "epoch out of range [1900, 2200]")
            }
        }
    }
}

/// EPSG operation codes for point-motion models (PMM).
///
/// These constants correspond to entries in the `proj.db`
/// `coordinate_operation` table. Full PMM application — multiplying a
/// velocity field by `Epoch::delta_years` and accumulating the displacement —
/// is implemented in T3.4 (`oxiproj-transformations`).
pub mod epsg_pmo {
    /// ITRF2014 point-motion model (horizontal velocity + vertical component).
    ///
    /// Source: EPSG Dataset op code 1066.
    pub const ITRF2014_PMO: u32 = 1066;

    /// ITRF2020 point-motion model.
    ///
    /// Source: EPSG Dataset op code 1067.
    pub const ITRF2020_PMO: u32 = 1067;

    /// NNR-MORVEL56 angular velocities → velocity field.
    ///
    /// Source: EPSG Dataset op code 1085.
    pub const NNR_MORVEL56: u32 = 1085;

    /// NOAM plate rotation model.
    ///
    /// Source: EPSG Dataset op code 1086.
    pub const NOAM_PLATE: u32 = 1086;
}

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(feature = "no_std")]
    use alloc::string::ToString;

    #[test]
    fn parse_epoch() {
        let e: Epoch = "2021.3".parse().unwrap();
        assert!((e.year - 2021.3).abs() < 1e-10);
    }

    #[test]
    fn parse_ref_frame_epoch_with_at() {
        let r: RefFrameEpoch = "ITRF2020@2021.3".parse().unwrap();
        assert_eq!(r.frame, "ITRF2020");
        assert!(r.epoch.is_some());
        assert!((r.epoch.unwrap().year - 2021.3).abs() < 1e-10);
        assert!(r.is_dynamic());
    }

    #[test]
    fn parse_ref_frame_epoch_static() {
        let r: RefFrameEpoch = "NAD83(2011)".parse().unwrap();
        assert_eq!(r.frame, "NAD83(2011)");
        assert!(r.epoch.is_none());
        assert!(!r.is_dynamic());
    }

    #[test]
    fn display_round_trips() {
        let r: RefFrameEpoch = "ITRF2020@2021.3".parse().unwrap();
        assert_eq!(r.to_string(), "ITRF2020@2021.3");

        let s = RefFrameEpoch::static_frame("WGS84");
        assert_eq!(s.to_string(), "WGS84");
    }

    #[test]
    fn delta_years() {
        let e1 = Epoch::new(2020.0).unwrap();
        let e2 = Epoch::new(2021.5).unwrap();
        assert!((e2.delta_years(&e1) - 1.5).abs() < 1e-10);
    }

    #[test]
    fn epoch_coord_construction() {
        let frame: RefFrameEpoch = "ITRF2020@2021.3".parse().unwrap();
        let ec = EpochCoord::from_lonlat(10.0, 51.0, frame);
        assert!((ec.coord[0] - 10.0).abs() < 1e-12);
        assert!((ec.coord[1] - 51.0).abs() < 1e-12);
    }

    #[test]
    fn epoch_invalid_nan() {
        assert!(Epoch::new(f64::NAN).is_err());
    }

    #[test]
    fn epoch_invalid_infinite() {
        assert!(Epoch::new(f64::INFINITY).is_err());
    }

    #[test]
    fn epoch_from_decimal_year() {
        let e = Epoch::from_decimal_year(2024.0).unwrap();
        assert!((e.year - 2024.0).abs() < 1e-10);
    }

    #[test]
    fn epoch_parse_error_on_garbage() {
        let result = "not_a_number".parse::<Epoch>();
        assert!(result.is_err());
    }

    #[test]
    fn ref_frame_epoch_new_with_epoch() {
        let e = Epoch::new(2020.0).unwrap();
        let r = RefFrameEpoch::new("ITRF2014", Some(e));
        assert_eq!(r.frame, "ITRF2014");
        assert!(r.is_dynamic());
    }

    #[test]
    fn epsg_pmo_constants() {
        assert_eq!(epsg_pmo::ITRF2014_PMO, 1066);
        assert_eq!(epsg_pmo::ITRF2020_PMO, 1067);
        assert_eq!(epsg_pmo::NNR_MORVEL56, 1085);
        assert_eq!(epsg_pmo::NOAM_PLATE, 1086);
    }

    #[test]
    fn delta_years_negative() {
        let earlier = Epoch::new(2022.0).unwrap();
        let later = Epoch::new(2019.5).unwrap();
        assert!((later.delta_years(&earlier) - (-2.5)).abs() < 1e-10);
    }

    #[test]
    fn epoch_display() {
        let e = Epoch::new(2021.5).unwrap();
        assert_eq!(e.to_string(), "2021.5");
    }

    #[test]
    fn epoch_coord_new() {
        let frame = RefFrameEpoch::static_frame("WGS84");
        let coord = crate::coord::Coord::new(1.0, 2.0, 3.0, 4.0);
        let ec = EpochCoord::new(coord, frame.clone());
        assert_eq!(ec.frame, frame);
        assert!((ec.coord[2] - 3.0).abs() < 1e-12);
    }

    #[test]
    fn epoch_negative_year_valid() {
        // BCE dates encoded as negative decimal years are valid
        let e = Epoch::new(-500.0).unwrap();
        assert!((e.year - (-500.0)).abs() < 1e-10);
    }

    #[test]
    fn from_str_whitespace_trimmed() {
        let e: Epoch = "  2023.75  ".parse().unwrap();
        assert!((e.year - 2023.75).abs() < 1e-10);

        let r: RefFrameEpoch = "  ITRF2020@2023.75  ".parse().unwrap();
        assert_eq!(r.frame, "ITRF2020");
        assert!((r.epoch.unwrap().year - 2023.75).abs() < 1e-10);
    }

    #[test]
    fn epoch_tagged_crs_parse_basic() {
        let e = EpochTaggedCrs::parse("ITRF2020@2021.3").unwrap();
        assert_eq!(e.crs_id, "ITRF2020");
        assert!((e.epoch.unwrap() - 2021.3).abs() < 1e-10);
    }

    #[test]
    fn epoch_tagged_crs_parse_no_epoch() {
        let e = EpochTaggedCrs::parse("ITRF2020").unwrap();
        assert_eq!(e.crs_id, "ITRF2020");
        assert!(e.epoch.is_none());
    }

    #[test]
    fn epoch_tagged_crs_parse_epsg() {
        let e = EpochTaggedCrs::parse("EPSG:4326@2020.0").unwrap();
        assert_eq!(e.crs_id, "EPSG:4326");
        assert_eq!(e.epoch, Some(2020.0));
    }

    #[test]
    fn epoch_tagged_crs_roundtrip() {
        let s = "ITRF2020@2021.3";
        let e = EpochTaggedCrs::parse(s).unwrap();
        assert_eq!(e.to_string_repr(), s);
    }

    #[test]
    fn epoch_tagged_crs_out_of_range() {
        assert!(EpochTaggedCrs::parse("X@1800.0").is_err());
    }

    #[test]
    fn epoch_tagged_crs_empty_crs_id_error() {
        assert!(EpochTaggedCrs::parse("").is_err());
        assert!(EpochTaggedCrs::parse("@2021.3").is_err());
    }

    #[test]
    fn epoch_tagged_crs_invalid_epoch_error() {
        assert!(EpochTaggedCrs::parse("ITRF2020@not_a_number").is_err());
    }

    #[test]
    fn epoch_tagged_crs_display() {
        let e = EpochTaggedCrs::parse("ITRF2020@2021.3").unwrap();
        assert_eq!(e.to_string(), "ITRF2020@2021.3");
    }
}