Skip to main content

spacelab_frames/
rotation.rs

1//! The frame algebra.
2//!
3//! The angles in this crate are checked against ERFA numerically; the algebra wrapped around them is
4//! proved in `derivations/frame_transform.mac`, because a number at one epoch cannot tell a correct
5//! composition law from a lucky one. What that file establishes: [`Transform::inverse`] followed by
6//! [`Transform::state`] is the identity on `(r, v)` for **any** proper rotation and **any** angular
7//! velocity — no small-angle, no alignment assumption — and it rests on `det R = +1` and nothing
8//! else. Feed the same code an *improper* orthogonal matrix and the round trip comes back wrong by
9//! exactly `−2 ω × r`, which at LEO is a kilometre per second. [`Rotation::from_matrix`] is where
10//! that precondition is asserted and never checked.
11
12use core::marker::PhantomData;
13use core::ops::Mul;
14
15use spacelab_core::{Mat3, Vec3};
16
17/// A reference frame.
18///
19/// Implemented only by the tag types in this module. A frame is never
20/// instantiated; it exists to label a type parameter and then vanish.
21///
22/// The supertraits exist so that `#[derive(Copy)]` on the frame-tagged types does
23/// not demand them all over again: a derive on a struct holding
24/// `PhantomData<fn(F) -> F>` adds a spurious `F: Copy` bound, even though
25/// `PhantomData` is `Copy` unconditionally.
26pub trait Frame: Copy + core::fmt::Debug + PartialEq + Eq + 'static {
27    /// Short name, for diagnostics.
28    const NAME: &'static str;
29}
30
31macro_rules! frame {
32    ($(#[$m:meta])* $name:ident, $s:literal) => {
33        $(#[$m])*
34        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
35        pub struct $name;
36        impl Frame for $name {
37            const NAME: &'static str = $s;
38        }
39    };
40}
41
42frame!(
43    /// Geocentric Celestial Reference Frame. Quasi-inertial, the IAU's answer to
44    /// "what does not rotate".
45    ///
46    /// Its axes are ICRF3's, reached through the IAU 2006/2000A precession-nutation
47    /// model plus the observed celestial-pole offsets `dX, dY` — nothing here fixes
48    /// a radio-source position, so the catalogue realization arrives with the EOP
49    /// series, as it does for [`Itrf`].
50    Gcrf, "GCRF"
51);
52frame!(
53    /// Celestial Intermediate Reference System. GCRF, with precession and nutation
54    /// applied.
55    Cirs, "CIRS"
56);
57frame!(
58    /// Terrestrial Intermediate Reference System. CIRS, spun by the Earth Rotation
59    /// Angle. Differs from [`Pef`] only by the TIO locator, some tens of
60    /// microarcseconds.
61    Tirs, "TIRS"
62);
63frame!(
64    /// Pseudo-Earth-Fixed. The classical equinox-based counterpart of [`Tirs`]:
65    /// what you get after rotating by sidereal time, before polar motion.
66    Pef, "PEF"
67);
68frame!(
69    /// International Terrestrial Reference Frame. Bolted to the crust.
70    ///
71    /// *Which* realization is not this type's to say: it is the one the supplied
72    /// Earth-orientation series realizes. Station coordinates must come from the
73    /// matching realization — they differ at the centimetre level, which is the
74    /// whole budget of an SLR residual.
75    ///
76    /// **It is the file's vintage that fixes this, not the row's date.** The IERS
77    /// replaced 14 C04 with 20 C04 on 2023-02-14 and *reprocessed the whole series*
78    /// in ITRF2020: the current product's own header reads "EOP (IERS) 20 C04 TIME
79    /// SERIES consistent with ITRF 2020" and its first row is 1962-01-01. So a 2026
80    /// download realizes ITRF2020 back to 1962, and a file archived in 2022 realizes
81    /// ITRF2014 all the way forward — the opposite of splitting a series by epoch.
82    ///
83    /// `finals2000A`, which this workspace reads, states none of that: it has no
84    /// header at all, every line is a data row, so the realization cannot be
85    /// recovered from the bytes. Naming the chain's frame therefore needs the C04
86    /// product, which does say it. Where a *product* names its frame the workspace
87    /// now reads it — see `spacelab_gnss::ReferenceFrame` for SP3, not linked
88    /// because that crate is not a dependency here — and the agreement is checked
89    /// where two products' coordinates are differenced.
90    Itrf, "ITRF"
91);
92frame!(
93    /// True Equator, Mean Equinox. What SGP4 emits, and what no standard defines
94    /// precisely. Neither SOFA nor ERFA offers it.
95    Teme, "TEME"
96);
97
98/// A rotation from one frame to another.
99///
100/// `PhantomData<fn(From) -> To>` rather than `PhantomData<(From, To)>`: it gives
101/// the correct variance and keeps `Rotation` unconditionally `Send + Sync`
102/// regardless of the tag types, which are never values anyway.
103#[derive(Debug, Clone, Copy, PartialEq)]
104pub struct Rotation<From: Frame, To: Frame> {
105    matrix: Mat3,
106    _frames: PhantomData<fn(From) -> To>,
107}
108
109impl<From: Frame, To: Frame> Rotation<From, To> {
110    /// Wrap a matrix, asserting by construction which frames it connects.
111    ///
112    /// The only place a frame claim is made rather than checked. Everything
113    /// downstream is then checked by the compiler.
114    ///
115    /// Two things are asserted here and not checked: the frames, and that the matrix
116    /// is a *proper* rotation. The second is not decoration —
117    /// `derivations/frame_transform.mac` shows [`Transform::inverse`] inverts
118    /// [`Transform::state`] only when `det = +1`, and misses by `−2 ω × r` when it is
119    /// `−1`. A reflection would typecheck.
120    #[must_use]
121    pub const fn from_matrix(matrix: Mat3) -> Self {
122        Self {
123            matrix,
124            _frames: PhantomData,
125        }
126    }
127
128    /// The underlying matrix.
129    #[must_use]
130    pub const fn matrix(self) -> Mat3 {
131        self.matrix
132    }
133
134    /// The inverse rotation. For a proper rotation, the transpose.
135    #[must_use]
136    pub fn inverse(self) -> Rotation<To, From> {
137        Rotation::from_matrix(self.matrix.transpose())
138    }
139}
140
141impl<A: Frame, B: Frame, C: Frame> Mul<Rotation<A, B>> for Rotation<B, C> {
142    type Output = Rotation<A, C>;
143
144    /// Compose: apply the right operand first.
145    ///
146    /// `b_to_c * a_to_b` is `a_to_c`. Any other pairing fails to typecheck, which
147    /// is the entire point of this module.
148    fn mul(self, rhs: Rotation<A, B>) -> Rotation<A, C> {
149        Rotation::from_matrix(self.matrix * rhs.matrix)
150    }
151}
152
153/// A position, in a known frame.
154#[derive(Debug, Clone, Copy, PartialEq)]
155pub struct Position<F: Frame> {
156    /// Metres, in frame `F`.
157    pub vector: Vec3,
158    _frame: PhantomData<fn(F) -> F>,
159}
160
161/// A velocity, in a known frame.
162#[derive(Debug, Clone, Copy, PartialEq)]
163pub struct Velocity<F: Frame> {
164    /// Metres per second, in frame `F`.
165    pub vector: Vec3,
166    _frame: PhantomData<fn(F) -> F>,
167}
168
169macro_rules! tagged_vector {
170    ($name:ident) => {
171        impl<F: Frame> $name<F> {
172            /// Tag a raw vector with the frame it is expressed in.
173            #[must_use]
174            pub const fn new(vector: Vec3) -> Self {
175                Self {
176                    vector,
177                    _frame: PhantomData,
178                }
179            }
180        }
181
182        impl<A: Frame, B: Frame> Mul<$name<A>> for Rotation<A, B> {
183            type Output = $name<B>;
184            fn mul(self, v: $name<A>) -> $name<B> {
185                $name::new(self.matrix * v.vector)
186            }
187        }
188    };
189}
190
191tagged_vector!(Position);
192tagged_vector!(Velocity);
193
194/// Position and velocity, in a known frame, at an implied instant.
195#[derive(Debug, Clone, Copy, PartialEq)]
196pub struct StateVector<F: Frame> {
197    /// Position.
198    pub position: Position<F>,
199    /// Velocity.
200    pub velocity: Velocity<F>,
201}
202
203impl<F: Frame> StateVector<F> {
204    /// Tag a raw pair with the frame it is expressed in.
205    #[must_use]
206    pub const fn new(position: Vec3, velocity: Vec3) -> Self {
207        Self {
208            position: Position::new(position),
209            velocity: Velocity::new(velocity),
210        }
211    }
212}
213
214/// A rotation between frames that turn relative to one another.
215///
216/// Carries the angular velocity of `To` with respect to `From`, expressed in
217/// `From`. A [`Rotation`] alone is enough for a [`Position`]; only this is enough
218/// for a [`StateVector`].
219#[derive(Debug, Clone, Copy, PartialEq)]
220pub struct Transform<From: Frame, To: Frame> {
221    /// The rotation part.
222    pub rotation: Rotation<From, To>,
223    /// Angular velocity of `To` relative to `From`, expressed in `From`, rad/s.
224    pub omega: Vec3,
225}
226
227impl<A: Frame, B: Frame> Transform<A, B> {
228    /// Assemble from a rotation and the angular velocity between the frames.
229    #[must_use]
230    pub const fn new(rotation: Rotation<A, B>, omega: Vec3) -> Self {
231        Self { rotation, omega }
232    }
233
234    /// Apply to a position. The angular velocity plays no part.
235    #[must_use]
236    pub fn position(self, p: Position<A>) -> Position<B> {
237        self.rotation * p
238    }
239
240    /// Apply to a full state.
241    ///
242    /// ```text
243    /// r_B = R · r_A
244    /// v_B = R · (v_A − ω × r_A)
245    /// ```
246    ///
247    /// The second term is the one everyone forgets. For GCRF→ITRF at the equator it
248    /// is 465 m/s: a satellite at rest on the ground would appear to be moving at
249    /// Mach 1.4, and a satellite in orbit would have its velocity wrong by six
250    /// percent. The result still *looks* like a plausible orbit.
251    #[must_use]
252    pub fn state(self, s: StateVector<A>) -> StateVector<B> {
253        let r = s.position.vector;
254        let v = s.velocity.vector;
255        StateVector::new(
256            self.rotation.matrix() * r,
257            self.rotation.matrix() * (v - self.omega.cross(r)),
258        )
259    }
260
261    /// The inverse transform.
262    ///
263    /// The angular velocity of `From` relative to `To` is `−ω`, re-expressed in
264    /// `To`.
265    #[must_use]
266    pub fn inverse(self) -> Transform<B, A> {
267        Transform::new(
268            self.rotation.inverse(),
269            self.rotation.matrix() * (-self.omega),
270        )
271    }
272}