oxiproj-transformations 0.1.2

Datum transformations and coordinate conversions for OxiProj.
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
//! ITRF/ETRF/NAD83/GDA frame-chain pathfinding and epoch-aware Helmert application.
//!
//! Provides a catalogue of 7-parameter (14-parameter with rates) Helmert
//! transforms between reference-frame realisations, plus utilities to
//!
//! * find a *direct* transform ([`find_frame_transform`]),
//! * find a *multi-hop* path through the transform graph
//!   ([`find_frame_path`]) using breadth-first search, and
//! * apply a transform (or a whole path) forward and inverse at an arbitrary
//!   decimal-year epoch ([`apply_frame_transform`], [`apply_frame_path`]).
//!
//! All numeric parameters are taken verbatim from the IERS/EPSG published
//! transformation tables that PROJ 9.8 ships in its `data/ITRF*` init files and
//! `proj.db`, so every entry can be cross-checked against the `cct`/`cs2cs`
//! binaries. Two rotation-sign conventions coexist in those sources
//! ([`RotationConvention`]); each catalogue entry records the convention of its
//! source so the values can be compared to PROJ 1:1.

use oxiproj_core::ProjResult;

/// Rotation-sign convention of a Helmert transform.
///
/// The two conventions differ only in the sign of the three rotation
/// parameters (and their rates); the rotation matrices are transposes of one
/// another. IERS ITRF↔ITRF and ITRF↔ETRF transforms are published in the
/// *position-vector* convention, whereas the EPSG ITRF↔NAD83 and ITRF↔GDA2020
/// operations use the *coordinate-frame* convention.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RotationConvention {
    /// Position-vector (a.k.a. "Helmert", IERS) convention.
    ///
    /// ```text
    /// R = [  1  -rz   ry ]
    ///     [ rz    1  -rx ]
    ///     [-ry   rx    1  ]
    /// ```
    PositionVector,
    /// Coordinate-frame (a.k.a. "Bursa-Wolf", EPSG geocentric) convention —
    /// the transpose of [`RotationConvention::PositionVector`] (rotations of
    /// opposite sign).
    CoordinateFrame,
}

/// A 7-parameter Helmert transform (with temporal rates) between two frames.
///
/// All parameters follow the IERS/EPSG conventions:
/// - translations in mm (rate in mm/yr)
/// - scale in parts per billion (rate in ppb/yr)
/// - rotations in milli-arc-seconds (rate in mas/yr), interpreted in
///   [`FrameTransform::convention`].
#[derive(Debug, Clone, Copy)]
pub struct FrameTransform {
    /// Source frame name (e.g. `"ITRF2020"`).
    pub from: &'static str,
    /// Target frame name (e.g. `"ITRF2014"`).
    pub to: &'static str,
    /// Reference epoch (decimal year) at which the published parameters apply.
    pub ref_epoch: f64,
    // Translations (mm)
    pub tx_mm: f64,
    pub ty_mm: f64,
    pub tz_mm: f64,
    // Translation rates (mm/yr)
    pub dtx_mm: f64,
    pub dty_mm: f64,
    pub dtz_mm: f64,
    // Scale (ppb) and rate (ppb/yr)
    pub scale_ppb: f64,
    pub dscale_ppb: f64,
    // Rotations (mas) and rates (mas/yr)
    pub rx_mas: f64,
    pub ry_mas: f64,
    pub rz_mas: f64,
    pub drx_mas: f64,
    pub dry_mas: f64,
    pub drz_mas: f64,
    /// Sign convention the rotation parameters are expressed in.
    pub convention: RotationConvention,
}

use RotationConvention::{CoordinateFrame, PositionVector};

/// Static catalogue of inter-frame Helmert transforms.
///
/// Each entry represents the transform FROM `from` TO `to` at `ref_epoch`,
/// and is taken verbatim (converted to mm/ppb/mas units) from the PROJ 9.8
/// `data/ITRF2020`, `data/ITRF2014` init files and `proj.db` EPSG operations:
///
/// | Entry | Source | PROJ cross-check |
/// |-------|--------|------------------|
/// | ITRF2020→ITRF2014/2008/2005/2000 | `data/ITRF2020` (Altamimi et al. 2023) | `cct +init=ITRF2020:ITRF20xx` |
/// | ITRF2014→ITRF2008 | `data/ITRF2014` (Altamimi et al. 2016) | `cct +init=ITRF2014:ITRF2008` |
/// | ITRF2000→ETRF2000 | EPSG "ITRF2000 to ETRF2000 (1)" | `projinfo -s ETRF2000 -t ITRF2000` |
/// | ITRF2014→ETRF2014 | EPSG "ITRF2014 to ETRF2014 (1)" | `projinfo -s ETRF2014 -t ITRF2014` |
/// | ITRF2014→NAD83(2011) | EPSG "ITRF2014 to NAD83(2011) (1)" | `projinfo -s NAD83(2011) -t ITRF2014` |
/// | ITRF2014→GDA2020 | EPSG "ITRF2014 to GDA2020 (1)" | `projinfo -s GDA2020 -t ITRF2014` |
///
/// The graph is connected via the ITRF2020 hub (ITRF2020↔{2014,2008,2005,2000})
/// plus ITRF2014→{2008, ETRF2014, NAD83(2011), GDA2020} and ITRF2000→ETRF2000,
/// so [`find_frame_path`] can reach every frame (multi-hop where required).
pub const FRAME_TRANSFORMS: &[FrameTransform] = &[
    // ITRF2020 → ITRF2014  (ref_epoch = 2015.0)
    // Source: PROJ data/ITRF2020, +x=-0.0014 +y=-0.0009 +z=0.0014 +s=-0.00042
    //         +dy=-0.0001 +dz=0.0002 +t_epoch=2015 +convention=position_vector
    FrameTransform {
        from: "ITRF2020",
        to: "ITRF2014",
        ref_epoch: 2015.0,
        tx_mm: -1.4,
        ty_mm: -0.9,
        tz_mm: 1.4,
        dtx_mm: 0.0,
        dty_mm: -0.1,
        dtz_mm: 0.2,
        scale_ppb: -0.42,
        dscale_ppb: 0.0,
        rx_mas: 0.0,
        ry_mas: 0.0,
        rz_mas: 0.0,
        drx_mas: 0.0,
        dry_mas: 0.0,
        drz_mas: 0.0,
        convention: PositionVector,
    },
    // ITRF2020 → ITRF2008  (ref_epoch = 2015.0)
    // Source: PROJ data/ITRF2020, +x=0.0002 +y=0.001 +z=0.0033 +s=-0.00029
    //         +dy=-0.0001 +dz=0.0001 +ds=3e-05 +t_epoch=2015 +convention=position_vector
    FrameTransform {
        from: "ITRF2020",
        to: "ITRF2008",
        ref_epoch: 2015.0,
        tx_mm: 0.2,
        ty_mm: 1.0,
        tz_mm: 3.3,
        dtx_mm: 0.0,
        dty_mm: -0.1,
        dtz_mm: 0.1,
        scale_ppb: -0.29,
        dscale_ppb: 0.03,
        rx_mas: 0.0,
        ry_mas: 0.0,
        rz_mas: 0.0,
        drx_mas: 0.0,
        dry_mas: 0.0,
        drz_mas: 0.0,
        convention: PositionVector,
    },
    // ITRF2020 → ITRF2005  (ref_epoch = 2015.0)
    // Source: PROJ data/ITRF2020, +x=0.0027 +y=0.0001 +z=-0.0014 +s=0.00065
    //         +dx=0.0003 +dy=-0.0001 +dz=0.0001 +ds=3e-05 +t_epoch=2015 +convention=position_vector
    FrameTransform {
        from: "ITRF2020",
        to: "ITRF2005",
        ref_epoch: 2015.0,
        tx_mm: 2.7,
        ty_mm: 0.1,
        tz_mm: -1.4,
        dtx_mm: 0.3,
        dty_mm: -0.1,
        dtz_mm: 0.1,
        scale_ppb: 0.65,
        dscale_ppb: 0.03,
        rx_mas: 0.0,
        ry_mas: 0.0,
        rz_mas: 0.0,
        drx_mas: 0.0,
        dry_mas: 0.0,
        drz_mas: 0.0,
        convention: PositionVector,
    },
    // ITRF2020 → ITRF2000  (ref_epoch = 2015.0)
    // Source: PROJ data/ITRF2020, +x=-0.0002 +y=0.0008 +z=-0.0342 +s=0.00225
    //         +dx=0.0001 +dz=-0.0017 +ds=0.00011 +t_epoch=2015 +convention=position_vector
    FrameTransform {
        from: "ITRF2020",
        to: "ITRF2000",
        ref_epoch: 2015.0,
        tx_mm: -0.2,
        ty_mm: 0.8,
        tz_mm: -34.2,
        dtx_mm: 0.1,
        dty_mm: 0.0,
        dtz_mm: -1.7,
        scale_ppb: 2.25,
        dscale_ppb: 0.11,
        rx_mas: 0.0,
        ry_mas: 0.0,
        rz_mas: 0.0,
        drx_mas: 0.0,
        dry_mas: 0.0,
        drz_mas: 0.0,
        convention: PositionVector,
    },
    // ITRF2014 → ITRF2008  (ref_epoch = 2010.0)
    // Source: PROJ data/ITRF2014 (Altamimi et al. 2016, Table 2),
    //         +x=0.0016 +y=0.0019 +z=0.0024 +s=-0.00002 +dz=-0.0001 +ds=3e-05
    //         +t_epoch=2010 +convention=position_vector
    FrameTransform {
        from: "ITRF2014",
        to: "ITRF2008",
        ref_epoch: 2010.0,
        tx_mm: 1.6,
        ty_mm: 1.9,
        tz_mm: 2.4,
        dtx_mm: 0.0,
        dty_mm: 0.0,
        dtz_mm: -0.1,
        scale_ppb: -0.02,
        dscale_ppb: 0.03,
        rx_mas: 0.0,
        ry_mas: 0.0,
        rz_mas: 0.0,
        drx_mas: 0.0,
        dry_mas: 0.0,
        drz_mas: 0.0,
        convention: PositionVector,
    },
    // ITRF2000 → ETRF2000  (ref_epoch = 2000.0)
    // Source: EPSG "ITRF2000 to ETRF2000 (1)", position-vector,
    //         +x=0.054 +y=0.051 +z=-0.048 +rx=0.000891 +ry=0.00539 +rz=-0.008712
    //         +drx=8.1e-05 +dry=0.00049 +drz=-0.000792 +t_epoch=2000
    FrameTransform {
        from: "ITRF2000",
        to: "ETRF2000",
        ref_epoch: 2000.0,
        tx_mm: 54.0,
        ty_mm: 51.0,
        tz_mm: -48.0,
        dtx_mm: 0.0,
        dty_mm: 0.0,
        dtz_mm: 0.0,
        scale_ppb: 0.0,
        dscale_ppb: 0.0,
        rx_mas: 0.891,
        ry_mas: 5.39,
        rz_mas: -8.712,
        drx_mas: 0.081,
        dry_mas: 0.49,
        drz_mas: -0.792,
        convention: PositionVector,
    },
    // ITRF2014 → ETRF2014  (ref_epoch = 2010.0)
    // Source: EPSG "ITRF2014 to ETRF2014 (1)", position-vector,
    //         +rx=0.001785 +ry=0.011151 +rz=-0.01617 +drx=8.5e-05 +dry=0.000531
    //         +drz=-0.00077 +t_epoch=2010
    FrameTransform {
        from: "ITRF2014",
        to: "ETRF2014",
        ref_epoch: 2010.0,
        tx_mm: 0.0,
        ty_mm: 0.0,
        tz_mm: 0.0,
        dtx_mm: 0.0,
        dty_mm: 0.0,
        dtz_mm: 0.0,
        scale_ppb: 0.0,
        dscale_ppb: 0.0,
        rx_mas: 1.785,
        ry_mas: 11.151,
        rz_mas: -16.17,
        drx_mas: 0.085,
        dry_mas: 0.531,
        drz_mas: -0.77,
        convention: PositionVector,
    },
    // ITRF2014 → NAD83(2011)  (ref_epoch = 2010.0)
    // Source: EPSG "ITRF2014 to NAD83(2011) (1)", coordinate-frame,
    //         +x=1.0053 +y=-1.90921 +z=-0.54157 +rx=0.02678138 +ry=-0.00042027
    //         +rz=0.01093206 +s=0.00036891 +dx=0.00079 +dy=-0.0006 +dz=-0.00144
    //         +drx=6.667e-05 +dry=-0.00075744 +drz=-5.133e-05 +ds=-7.201e-05 +t_epoch=2010
    FrameTransform {
        from: "ITRF2014",
        to: "NAD83(2011)",
        ref_epoch: 2010.0,
        tx_mm: 1005.3,
        ty_mm: -1909.21,
        tz_mm: -541.57,
        dtx_mm: 0.79,
        dty_mm: -0.6,
        dtz_mm: -1.44,
        scale_ppb: 0.36891,
        dscale_ppb: -0.07201,
        rx_mas: 26.78138,
        ry_mas: -0.42027,
        rz_mas: 10.93206,
        drx_mas: 0.06667,
        dry_mas: -0.75744,
        drz_mas: -0.05133,
        convention: CoordinateFrame,
    },
    // ITRF2014 → GDA2020  (ref_epoch = 2020.0)
    // Source: EPSG "ITRF2014 to GDA2020 (1)", coordinate-frame,
    //         +drx=0.00150379 +dry=0.00118346 +drz=0.00120716 +t_epoch=2020
    //         (all static parameters zero — GDA2020 ≡ ITRF2014 @ 2020.0, plate rotation only)
    FrameTransform {
        from: "ITRF2014",
        to: "GDA2020",
        ref_epoch: 2020.0,
        tx_mm: 0.0,
        ty_mm: 0.0,
        tz_mm: 0.0,
        dtx_mm: 0.0,
        dty_mm: 0.0,
        dtz_mm: 0.0,
        scale_ppb: 0.0,
        dscale_ppb: 0.0,
        rx_mas: 0.0,
        ry_mas: 0.0,
        rz_mas: 0.0,
        drx_mas: 1.50379,
        dry_mas: 1.18346,
        drz_mas: 1.20716,
        convention: CoordinateFrame,
    },
];

/// Search [`FRAME_TRANSFORMS`] for a direct transform between two frames.
///
/// Comparison is case-insensitive. Returns `None` when no entry matches.
pub fn find_frame_transform<'a>(from: &str, to: &str) -> Option<&'a FrameTransform> {
    FRAME_TRANSFORMS
        .iter()
        .find(|ft| ft.from.eq_ignore_ascii_case(from) && ft.to.eq_ignore_ascii_case(to))
}

/// One hop in a multi-hop frame-transform path.
#[derive(Debug, Clone, Copy)]
pub struct FramePathStep {
    /// The catalogue transform to apply.
    pub transform: &'static FrameTransform,
    /// When `true`, apply the transform in the inverse direction.
    pub inverse: bool,
}

/// Find a path of Helmert transforms connecting `from` to `to`.
///
/// Performs a breadth-first search over the undirected transform graph induced
/// by [`FRAME_TRANSFORMS`] (each catalogue entry contributes a forward edge
/// `from→to` and an inverse edge `to→from`). Returns the shortest chain of
/// [`FramePathStep`]s, or `None` when the two frames are not connected.
///
/// A request where `from` and `to` name the same frame (case-insensitively)
/// returns `Some(empty path)`.
///
/// # Examples
///
/// ```
/// use oxiproj_transformations::frame_chain::find_frame_path;
///
/// // Direct edge (1 hop).
/// assert_eq!(find_frame_path("ITRF2020", "ITRF2014").map(|p| p.len()), Some(1));
/// // Requires composing two hops through the ITRF2020 hub.
/// assert_eq!(find_frame_path("ITRF2014", "ITRF2000").map(|p| p.len()), Some(2));
/// ```
#[must_use]
pub fn find_frame_path(from: &str, to: &str) -> Option<Vec<FramePathStep>> {
    if from.eq_ignore_ascii_case(to) {
        return Some(Vec::new());
    }

    // BFS. The graph is tiny (a handful of nodes), so a linear-scan visited
    // list and path-carrying queue are more than adequate and keep the code
    // allocation-simple and `no_std`-friendly.
    let mut visited: Vec<&str> = Vec::new();
    let mut queue: Vec<(&str, Vec<FramePathStep>)> = Vec::new();

    visited.push(from);
    queue.push((from, Vec::new()));

    let mut head = 0usize;
    while head < queue.len() {
        let (node, path) = queue[head].clone();
        head += 1;

        for ft in FRAME_TRANSFORMS {
            // Forward edge: node == ft.from  → neighbour ft.to
            // Inverse edge: node == ft.to    → neighbour ft.from
            let (neighbour, inverse) = if ft.from.eq_ignore_ascii_case(node) {
                (ft.to, false)
            } else if ft.to.eq_ignore_ascii_case(node) {
                (ft.from, true)
            } else {
                continue;
            };

            if visited.iter().any(|v| v.eq_ignore_ascii_case(neighbour)) {
                continue;
            }

            let mut next_path = path.clone();
            next_path.push(FramePathStep {
                transform: ft,
                inverse,
            });

            if neighbour.eq_ignore_ascii_case(to) {
                return Some(next_path);
            }

            visited.push(neighbour);
            queue.push((neighbour, next_path));
        }
    }

    None
}

/// Apply a Helmert frame transform at a given decimal-year `epoch`.
///
/// Uses a linearised (small-angle) Helmert model in the *position-vector*
/// convention:
///
/// ```text
/// [xout]   [tx]         [  1  -rz  ry ] [x]
/// [yout] = [ty] + scale·[ rz   1  -rx ]·[y]
/// [zout]   [tz]         [-ry  rx   1  ] [z]
/// ```
///
/// When [`FrameTransform::convention`] is
/// [`RotationConvention::CoordinateFrame`], the three rotation angles are
/// negated first (turning the coordinate-frame rotation matrix into its
/// position-vector transpose) before this matrix is applied, so the same
/// evaluation kernel serves both conventions.
///
/// Parameters are propagated from `transform.ref_epoch` to `epoch` using the
/// published rates before the transform is applied.
///
/// # Errors
///
/// This function always succeeds; the return type is `ProjResult` for API
/// consistency with the rest of the pipeline.
pub fn apply_frame_transform(
    transform: &FrameTransform,
    x: f64,
    y: f64,
    z: f64,
    epoch: f64,
) -> ProjResult<(f64, f64, f64)> {
    let dt = epoch - transform.ref_epoch;

    let tx = (transform.tx_mm + transform.dtx_mm * dt) * 1e-3;
    let ty = (transform.ty_mm + transform.dty_mm * dt) * 1e-3;
    let tz = (transform.tz_mm + transform.dtz_mm * dt) * 1e-3;

    let scale = 1.0 + (transform.scale_ppb + transform.dscale_ppb * dt) * 1e-9;

    // 1 mas = π / (180 × 3_600_000) radians
    const MAS_TO_RAD: f64 = core::f64::consts::PI / (180.0 * 3_600_000.0);

    // Sign that converts the stored convention into position-vector rotations.
    let conv_sign = match transform.convention {
        RotationConvention::PositionVector => 1.0,
        RotationConvention::CoordinateFrame => -1.0,
    };

    let rx = conv_sign * (transform.rx_mas + transform.drx_mas * dt) * MAS_TO_RAD;
    let ry = conv_sign * (transform.ry_mas + transform.dry_mas * dt) * MAS_TO_RAD;
    let rz = conv_sign * (transform.rz_mas + transform.drz_mas * dt) * MAS_TO_RAD;

    let xout = tx + scale * (x - rz * y + ry * z);
    let yout = ty + scale * (rz * x + y - rx * z);
    let zout = tz + scale * (-ry * x + rx * y + z);

    Ok((xout, yout, zout))
}

/// Apply the inverse of a Helmert frame transform at a given decimal-year `epoch`.
///
/// Constructs an inverted [`FrameTransform`] by negating all translation,
/// scale, and rotation parameters (and their rates) while keeping the same
/// [`RotationConvention`], then delegates to [`apply_frame_transform`]. This is
/// the standard small-angle inverse (`X = -T + (1−s)·R(−θ)·X'`), accurate to
/// well below a micrometre for all catalogue entries.
pub fn apply_frame_transform_inverse(
    transform: &FrameTransform,
    x: f64,
    y: f64,
    z: f64,
    epoch: f64,
) -> ProjResult<(f64, f64, f64)> {
    let inv = FrameTransform {
        from: transform.from,
        to: transform.to,
        ref_epoch: transform.ref_epoch,
        tx_mm: -transform.tx_mm,
        ty_mm: -transform.ty_mm,
        tz_mm: -transform.tz_mm,
        dtx_mm: -transform.dtx_mm,
        dty_mm: -transform.dty_mm,
        dtz_mm: -transform.dtz_mm,
        scale_ppb: -transform.scale_ppb,
        dscale_ppb: -transform.dscale_ppb,
        rx_mas: -transform.rx_mas,
        ry_mas: -transform.ry_mas,
        rz_mas: -transform.rz_mas,
        drx_mas: -transform.drx_mas,
        dry_mas: -transform.dry_mas,
        drz_mas: -transform.drz_mas,
        convention: transform.convention,
    };
    apply_frame_transform(&inv, x, y, z, epoch)
}

/// Apply a whole [`find_frame_path`] result to a coordinate at `epoch`.
///
/// Each hop is evaluated at the same coordinate `epoch` (the observation
/// epoch); a frame change never alters the coordinate epoch. An empty path
/// (same source and target frame) returns the input unchanged.
pub fn apply_frame_path(
    path: &[FramePathStep],
    x: f64,
    y: f64,
    z: f64,
    epoch: f64,
) -> ProjResult<(f64, f64, f64)> {
    let mut cur = (x, y, z);
    for step in path {
        cur = if step.inverse {
            apply_frame_transform_inverse(step.transform, cur.0, cur.1, cur.2, epoch)?
        } else {
            apply_frame_transform(step.transform, cur.0, cur.1, cur.2, epoch)?
        };
    }
    Ok(cur)
}

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

    #[test]
    fn frame_transform_itrf2020_to_itrf2014_found() {
        let ft = find_frame_transform("ITRF2020", "ITRF2014");
        assert!(ft.is_some(), "ITRF2020->ITRF2014 transform not found");
    }

    /// The catalogue entries must match the IERS/EPSG published values exactly
    /// (as shipped in PROJ 9.8 `data/ITRF2020`, converted mm/ppb/mas).
    #[test]
    fn catalogue_itrf2020_to_itrf2014_matches_published_iers() {
        let ft = find_frame_transform("ITRF2020", "ITRF2014").unwrap();
        assert_eq!(ft.ref_epoch, 2015.0);
        assert_eq!(ft.tx_mm, -1.4);
        // Regression guard for the historical sign bug: IERS/PROJ give T2 = −0.9 mm.
        assert_eq!(ft.ty_mm, -0.9, "ITRF2020->ITRF2014 T2 must be -0.9 mm");
        assert_eq!(ft.tz_mm, 1.4);
        assert_eq!(ft.dty_mm, -0.1);
        assert_eq!(ft.dtz_mm, 0.2);
        assert_eq!(ft.scale_ppb, -0.42);
        assert_eq!(ft.convention, RotationConvention::PositionVector);
    }

    /// Empirical cross-check of the ITRF2020→ITRF2014 transform at the reference
    /// epoch (2015.0) against `cct +init=ITRF2020:ITRF2014` from Homebrew PROJ:
    ///   in : 4627798.0 119795.0 4369668.0 @2015
    ///   out: 4627797.996656 119794.999050 4369667.999565
    #[test]
    fn frame_transform_itrf2020_to_itrf2014_matches_cct() {
        let ft = find_frame_transform("ITRF2020", "ITRF2014").unwrap();
        let (x, y, z) =
            apply_frame_transform(ft, 4_627_798.0, 119_795.0, 4_369_668.0, 2015.0).expect("apply");
        assert!((x - 4_627_797.996_656).abs() < 5e-6, "x={x}");
        assert!((y - 119_794.999_050).abs() < 5e-6, "y={y}");
        assert!((z - 4_369_667.999_565).abs() < 5e-6, "z={z}");
    }

    /// ITRF2020→ITRF2008/2005/2000 direct hops vs `cct +init=ITRF2020:ITRF20xx`.
    #[test]
    fn frame_transform_itrf2020_star_matches_cct() {
        let cases: &[(&str, (f64, f64, f64))] = &[
            (
                "ITRF2008",
                (4_627_797.998_858, 119_795.000_965, 4_369_668.002_033),
            ),
            (
                "ITRF2005",
                (4_627_798.005_708, 119_795.000_178, 4_369_668.001_440),
            ),
            (
                "ITRF2000",
                (4_627_798.010_213, 119_795.001_070, 4_369_667.975_632),
            ),
        ];
        for (target, (ex, ey, ez)) in cases {
            let ft = find_frame_transform("ITRF2020", target).unwrap();
            let (x, y, z) =
                apply_frame_transform(ft, 4_627_798.0, 119_795.0, 4_369_668.0, 2015.0).unwrap();
            assert!((x - ex).abs() < 5e-6, "{target} x={x}");
            assert!((y - ey).abs() < 5e-6, "{target} y={y}");
            assert!((z - ez).abs() < 5e-6, "{target} z={z}");
        }
    }

    #[test]
    fn frame_transform_inverse_reverses_forward() {
        let ft = find_frame_transform("ITRF2020", "ITRF2014").unwrap();
        let x0 = 4_627_798.0_f64;
        let y0 = 119_795.0_f64;
        let z0 = 4_369_668.0_f64;
        let (xf, yf, zf) = apply_frame_transform(ft, x0, y0, z0, 2015.0).unwrap();
        let (xr, yr, zr) = apply_frame_transform_inverse(ft, xf, yf, zf, 2015.0).unwrap();
        assert!(
            (xr - x0).abs() < 0.001,
            "x roundtrip error: {}",
            (xr - x0).abs()
        );
        assert!(
            (yr - y0).abs() < 0.001,
            "y roundtrip error: {}",
            (yr - y0).abs()
        );
        assert!(
            (zr - z0).abs() < 0.001,
            "z roundtrip error: {}",
            (zr - z0).abs()
        );
    }

    #[test]
    fn frame_transform_unknown_returns_none() {
        assert!(find_frame_transform("ITRF1900", "ITRF2014").is_none());
    }

    #[test]
    fn find_frame_path_same_frame_is_empty() {
        let p = find_frame_path("ITRF2020", "itrf2020").expect("same frame path");
        assert!(p.is_empty());
    }

    #[test]
    fn find_frame_path_direct_is_one_hop() {
        let p = find_frame_path("ITRF2020", "ITRF2014").expect("direct");
        assert_eq!(p.len(), 1);
        assert!(!p[0].inverse);
        assert_eq!(p[0].transform.to, "ITRF2014");
    }

    #[test]
    fn find_frame_path_inverse_direct() {
        let p = find_frame_path("ITRF2014", "ITRF2020").expect("inverse direct");
        assert_eq!(p.len(), 1);
        assert!(p[0].inverse);
        assert_eq!(p[0].transform.from, "ITRF2020");
    }

    #[test]
    fn find_frame_path_two_hop_itrf2014_to_itrf2000() {
        // No direct ITRF2014→ITRF2000 edge: must go via the ITRF2020 hub.
        let p = find_frame_path("ITRF2014", "ITRF2000").expect("2-hop");
        assert_eq!(p.len(), 2);
    }

    #[test]
    fn find_frame_path_reaches_gda2020_and_etrf_and_nad83() {
        assert!(find_frame_path("ITRF2020", "GDA2020").is_some());
        assert!(find_frame_path("ITRF2020", "NAD83(2011)").is_some());
        assert!(find_frame_path("ITRF2020", "ETRF2000").is_some());
        assert!(find_frame_path("ITRF2020", "ETRF2014").is_some());
        // NAD83(2011)→GDA2020 spans NAD83→ITRF2014→GDA2020 (2 hops).
        assert_eq!(
            find_frame_path("NAD83(2011)", "GDA2020").map(|p| p.len()),
            Some(2)
        );
    }

    #[test]
    fn find_frame_path_disconnected_returns_none() {
        assert!(find_frame_path("ITRF2020", "MADE_UP_FRAME").is_none());
    }

    /// Multi-hop composition ITRF2014→ITRF2020→ITRF2000 at 2015.0 must match the
    /// equivalent PROJ pipeline
    ///   cct +proj=pipeline +step +inv +init=ITRF2020:ITRF2014
    ///                      +step +init=ITRF2020:ITRF2000
    ///   in : 4627798.0 119795.0 4369668.0 @2015
    ///   out: 4627798.013556 119795.002020 4369667.976067
    #[test]
    fn apply_frame_path_two_hop_matches_cct_pipeline() {
        let path = find_frame_path("ITRF2014", "ITRF2000").expect("2-hop");
        let (x, y, z) =
            apply_frame_path(&path, 4_627_798.0, 119_795.0, 4_369_668.0, 2015.0).unwrap();
        assert!((x - 4_627_798.013_556).abs() < 1e-5, "x={x}");
        assert!((y - 119_795.002_020).abs() < 1e-5, "y={y}");
        assert!((z - 4_369_667.976_067).abs() < 1e-5, "z={z}");
    }

    /// ITRF2014→NAD83(2011) (coordinate-frame convention, with rates) vs
    /// `cct +proj=helmert ... +convention=coordinate_frame`:
    ///   in : -1300000 -4700000 4000000 @2010 → -1299999.236130 -4700001.322685 4000000.072801
    ///   in : -1300000 -4700000 4000000 @2020 → -1299999.068711 -4700001.315606 4000000.118451
    #[test]
    fn coordinate_frame_nad83_matches_cct() {
        let ft = find_frame_transform("ITRF2014", "NAD83(2011)").unwrap();
        let (x, y, z) =
            apply_frame_transform(ft, -1_300_000.0, -4_700_000.0, 4_000_000.0, 2010.0).unwrap();
        assert!((x - (-1_299_999.236_130)).abs() < 5e-6, "x2010={x}");
        assert!((y - (-4_700_001.322_685)).abs() < 5e-6, "y2010={y}");
        assert!((z - 4_000_000.072_801).abs() < 5e-6, "z2010={z}");

        let (x2, y2, z2) =
            apply_frame_transform(ft, -1_300_000.0, -4_700_000.0, 4_000_000.0, 2020.0).unwrap();
        assert!((x2 - (-1_299_999.068_711)).abs() < 5e-6, "x2020={x2}");
        assert!((y2 - (-4_700_001.315_606)).abs() < 5e-6, "y2020={y2}");
        assert!((z2 - 4_000_000.118_451).abs() < 5e-6, "z2020={z2}");
    }

    /// ITRF2014→GDA2020 (coordinate-frame, rotation-rate only) vs cct at 2015:
    ///   in : -4000000 2500000 -3800000 @2015 → -4000000.182170 2500000.021471 -3799999.794116
    #[test]
    fn coordinate_frame_gda2020_matches_cct() {
        let ft = find_frame_transform("ITRF2014", "GDA2020").unwrap();
        let (x, y, z) =
            apply_frame_transform(ft, -4_000_000.0, 2_500_000.0, -3_800_000.0, 2015.0).unwrap();
        assert!((x - (-4_000_000.182_170)).abs() < 5e-6, "x={x}");
        assert!((y - 2_500_000.021_471).abs() < 5e-6, "y={y}");
        assert!((z - (-3_799_999.794_116)).abs() < 5e-6, "z={z}");
    }

    /// Full 3-hop NAD83(2011)→ITRF2014→GDA2020 vs the equivalent PROJ pipeline
    /// at 2020.0:
    ///   in : -4000000 2500000 -3800000 @2020 → -4000000.993599 2500002.219715 -3799999.267721
    #[test]
    fn apply_frame_path_nad83_to_gda2020_matches_cct_pipeline() {
        let path = find_frame_path("NAD83(2011)", "GDA2020").expect("path");
        let (x, y, z) =
            apply_frame_path(&path, -4_000_000.0, 2_500_000.0, -3_800_000.0, 2020.0).unwrap();
        // Small-angle inverse of the NAD83 leg differs from PROJ's exact inverse
        // by sub-micrometre; 0.1 mm tolerance is comfortable.
        assert!((x - (-4_000_000.993_599)).abs() < 1e-4, "x={x}");
        assert!((y - 2_500_002.219_715).abs() < 1e-4, "y={y}");
        assert!((z - (-3_799_999.267_721)).abs() < 1e-4, "z={z}");
    }
}