affn 0.6.0

Affine geometry primitives: strongly-typed coordinate systems, reference frames, and centers for scientific computing.
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
//! # Cartesian Free Vector
//!
//! This module defines [`Vector<F, U>`], a **free vector** in 3D Cartesian space.
//!
//! ## Mathematical Model
//!
//! A free vector represents a directed magnitude in space. It is:
//! - **Frame-dependent**: The orientation is relative to a reference frame `F`
//! - **Center-independent**: Free vectors are translation-invariant
//! - **Dimensioned**: Has a unit `U` (length, velocity, acceleration, etc.)
//!
//! Free vectors form a vector space and support:
//! - Addition: `Vector + Vector -> Vector`
//! - Subtraction: `Vector - Vector -> Vector`
//! - Scalar multiplication: `Vector * f64 -> Vector`
//! - Normalization (for length units): `normalize(Vector) -> Option<Direction>`
//!
//! ## Semantic Type Aliases
//!
//! This module provides semantic aliases for clarity:
//! - [`Displacement<F, U>`] — displacement vector with length unit
//! - [`Velocity<F, U>`] — velocity vector with velocity unit
//!
//! ## Example
//!
//! ```rust
//! use affn::cartesian::{Vector, Displacement, Velocity};
//! use affn::frames::ReferenceFrame;
//! use qtty::*;
//!
//! // Define a custom frame (astronomy frames are defined in downstream crates)
//! #[derive(Debug, Copy, Clone)]
//! struct MyFrame;
//! impl ReferenceFrame for MyFrame {
//!     fn frame_name() -> &'static str { "MyFrame" }
//! }
//!
//! // Displacement with length unit
//! let displacement = Displacement::<MyFrame, AstronomicalUnit>::new(1.0, 2.0, 3.0);
//!
//! // Velocity with velocity unit
//! type AuPerDay = Per<AstronomicalUnit, Day>;
//! let velocity = Velocity::<MyFrame, AuPerDay>::new(0.01, 0.02, 0.0);
//!
//! // Both are just Vector<F, U> with different units
//! let v: Vector<MyFrame, AuPerDay> = velocity;
//! ```

use super::xyz::XYZ;
use crate::frames::ReferenceFrame;
use qtty::{LengthUnit, Quantity, Unit};

use std::marker::PhantomData;
use std::ops::{Add, Neg, Sub};

/// A free vector in 3D Cartesian coordinates.
///
/// Free vectors are frame-dependent but center-independent. They represent
/// directed magnitudes (displacement, velocity, acceleration, etc.) in space.
///
/// # Type Parameters
/// - `F`: The reference frame (e.g., `ICRS`, `EclipticMeanJ2000`, `Equatorial`)
/// - `U`: The unit (e.g., `AstronomicalUnit`, `Per<Kilometer, Second>`)
///
/// # Zero-Cost Abstraction
///
/// This type uses `#[repr(transparent)]` over the internal storage,
/// ensuring no runtime overhead compared to raw `Vector3<Quantity<U>>`.
#[repr(transparent)]
#[derive(Debug, Clone, Copy)]
pub struct Vector<F: ReferenceFrame, U: Unit> {
    pub(in crate::cartesian) xyz: XYZ<Quantity<U>>,
    _frame: PhantomData<F>,
}

// =============================================================================
// Constructors
// =============================================================================

impl<F: ReferenceFrame, U: Unit> Vector<F, U> {
    /// Creates a new vector from component values.
    ///
    /// # Arguments
    /// - `x`, `y`, `z`: Component values (converted to `Quantity<U>`)
    #[inline]
    pub fn new<T: Into<Quantity<U>>>(x: T, y: T, z: T) -> Self {
        Self {
            xyz: XYZ::new(x.into(), y.into(), z.into()),
            _frame: PhantomData,
        }
    }

    /// Creates a vector from a nalgebra Vector3.
    #[inline]
    pub fn from_vec3(vec3: nalgebra::Vector3<Quantity<U>>) -> Self {
        Self {
            xyz: XYZ::from_vec3(vec3),
            _frame: PhantomData,
        }
    }

    /// Creates a vector from the internal XYZ storage.
    #[inline]
    pub(crate) fn from_xyz(xyz: XYZ<Quantity<U>>) -> Self {
        Self {
            xyz,
            _frame: PhantomData,
        }
    }

    /// The zero vector.
    pub const ZERO: Self = Self {
        xyz: XYZ::new(
            Quantity::<U>::new(0.0),
            Quantity::<U>::new(0.0),
            Quantity::<U>::new(0.0),
        ),
        _frame: PhantomData,
    };
}

// =============================================================================
// Component Access
// =============================================================================

impl<F: ReferenceFrame, U: Unit> Vector<F, U> {
    /// Returns the x-component.
    #[inline]
    pub fn x(&self) -> Quantity<U> {
        self.xyz.x()
    }

    /// Returns the y-component.
    #[inline]
    pub fn y(&self) -> Quantity<U> {
        self.xyz.y()
    }

    /// Returns the z-component.
    #[inline]
    pub fn z(&self) -> Quantity<U> {
        self.xyz.z()
    }

    /// Returns the underlying nalgebra Vector3.
    #[inline]
    pub fn as_vec3(&self) -> &nalgebra::Vector3<Quantity<U>> {
        self.xyz.as_vec3()
    }

    /// Converts this vector to another unit of the same dimension.
    ///
    /// The frame is preserved and each component is converted independently
    /// via `qtty::Quantity::to`.
    #[inline]
    pub fn to_unit<U2: Unit<Dim = U::Dim>>(&self) -> Vector<F, U2> {
        Vector::<F, U2>::new(
            self.x().to::<U2>(),
            self.y().to::<U2>(),
            self.z().to::<U2>(),
        )
    }

    /// Reinterprets this vector as belonging to a different reference frame.
    ///
    /// This is a **zero-cost** operation: the components are preserved
    /// unchanged; only the compile-time frame tag `F` is replaced by `F2`.
    ///
    /// Use after applying a mathematical rotation whose result still carries
    /// the original frame tag.
    #[inline]
    pub fn reinterpret_frame<F2: ReferenceFrame>(self) -> Vector<F2, U> {
        Vector::new(self.x(), self.y(), self.z())
    }
}

// =============================================================================
// Vector Space Operations (for all units)
// =============================================================================

impl<F: ReferenceFrame, U: Unit> Vector<F, U> {
    /// Computes the Euclidean magnitude of the vector.
    #[inline]
    pub fn magnitude(&self) -> Quantity<U> {
        self.xyz.magnitude()
    }

    /// Computes the squared magnitude (avoids sqrt, useful for comparisons).
    #[inline]
    pub fn magnitude_squared(&self) -> f64 {
        self.xyz.magnitude_squared()
    }

    /// Scales the vector by a scalar factor.
    #[inline]
    pub fn scale(&self, factor: f64) -> Self {
        Self::from_xyz(XYZ::from_raw(self.xyz.to_raw().scale(factor)))
    }

    /// Computes the dot product with another vector (returns dimensionless f64).
    ///
    /// Note: For proper dimensional analysis, the result would be U²,
    /// but we return the raw f64 value for convenience.
    #[inline]
    pub fn dot(&self, other: &Self) -> f64 {
        self.xyz.to_raw().dot(&other.xyz.to_raw())
    }

    /// Computes the cross product with another vector.
    #[inline]
    pub fn cross(&self, other: &Self) -> Self {
        Self::from_xyz(XYZ::from_raw(self.xyz.to_raw().cross(&other.xyz.to_raw())))
    }

    /// Returns the negation of this vector.
    #[inline]
    pub fn negate(&self) -> Self {
        Self::from_xyz(-self.xyz)
    }
}

// =============================================================================
// Length-Specific Operations (only for LengthUnit)
// =============================================================================

impl<F: ReferenceFrame, U: LengthUnit> Vector<F, U> {
    /// Normalizes this vector to a unit direction.
    ///
    /// Returns `None` if the vector has zero (or near-zero) magnitude.
    ///
    /// # Example
    /// ```rust
    /// use affn::cartesian::Displacement;
    /// use affn::frames::ReferenceFrame;
    /// use qtty::*;
    ///
    /// #[derive(Debug, Copy, Clone)]
    /// struct MyFrame;
    /// impl ReferenceFrame for MyFrame {
    ///     fn frame_name() -> &'static str { "MyFrame" }
    /// }
    ///
    /// let v = Displacement::<MyFrame, AstronomicalUnit>::new(3.0, 4.0, 0.0);
    /// let dir = v.normalize().expect("non-zero vector");
    /// // dir is now a unit Direction<MyFrame>
    /// ```
    #[inline]
    pub fn normalize(&self) -> Option<super::Direction<F>> {
        self.xyz
            .to_raw()
            .try_normalize()
            .map(super::Direction::from_xyz_unchecked)
    }

    /// Returns a unit direction, assuming non-zero magnitude.
    ///
    /// # Panics
    /// May produce NaN if the vector has zero magnitude.
    #[inline]
    pub fn normalize_unchecked(&self) -> super::Direction<F> {
        super::Direction::from_xyz_unchecked(self.xyz.to_raw().normalize_unchecked())
    }
}

// =============================================================================
// Operator Implementations
// =============================================================================

impl<F: ReferenceFrame, U: Unit> Add for Vector<F, U> {
    type Output = Self;

    /// Vector + Vector -> Vector
    #[inline]
    fn add(self, other: Self) -> Self::Output {
        Self::from_xyz(self.xyz + other.xyz)
    }
}

impl<F: ReferenceFrame, U: Unit> Sub for Vector<F, U> {
    type Output = Self;

    /// Vector - Vector -> Vector
    #[inline]
    fn sub(self, other: Self) -> Self::Output {
        Self::from_xyz(self.xyz - other.xyz)
    }
}

impl<F: ReferenceFrame, U: Unit> Neg for Vector<F, U> {
    type Output = Self;

    #[inline]
    fn neg(self) -> Self::Output {
        self.negate()
    }
}

// =============================================================================
// PartialEq
// =============================================================================

impl<F: ReferenceFrame, U: Unit> PartialEq for Vector<F, U> {
    fn eq(&self, other: &Self) -> bool {
        self.xyz == other.xyz
    }
}

// =============================================================================
// Display
// =============================================================================

impl<F: ReferenceFrame, U: Unit> std::fmt::Display for Vector<F, U>
where
    Quantity<U>: std::fmt::Display,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Vector<{}> X: ", F::frame_name())?;
        std::fmt::Display::fmt(&self.x(), f)?;
        write!(f, ", Y: ")?;
        std::fmt::Display::fmt(&self.y(), f)?;
        write!(f, ", Z: ")?;
        std::fmt::Display::fmt(&self.z(), f)
    }
}

impl<F: ReferenceFrame, U: Unit> std::fmt::LowerExp for Vector<F, U>
where
    Quantity<U>: std::fmt::LowerExp,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Vector<{}> X: ", F::frame_name())?;
        std::fmt::LowerExp::fmt(&self.x(), f)?;
        write!(f, ", Y: ")?;
        std::fmt::LowerExp::fmt(&self.y(), f)?;
        write!(f, ", Z: ")?;
        std::fmt::LowerExp::fmt(&self.z(), f)
    }
}

impl<F: ReferenceFrame, U: Unit> std::fmt::UpperExp for Vector<F, U>
where
    Quantity<U>: std::fmt::UpperExp,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Vector<{}> X: ", F::frame_name())?;
        std::fmt::UpperExp::fmt(&self.x(), f)?;
        write!(f, ", Y: ")?;
        std::fmt::UpperExp::fmt(&self.y(), f)?;
        write!(f, ", Z: ")?;
        std::fmt::UpperExp::fmt(&self.z(), f)
    }
}

// =============================================================================
// Type Aliases
// =============================================================================

/// A displacement vector (free vector with length unit).
///
/// This is a semantic alias for [`Vector<F, U>`] where `U` is a length unit.
/// Displacements represent directed distances in space.
pub type Displacement<F, U> = Vector<F, U>;

/// A velocity vector (free vector with velocity unit).
///
/// This is a semantic alias for [`Vector<F, U>`] where `U` is a velocity unit.
/// Velocities represent rates of change of position.
pub type Velocity<F, U> = Vector<F, U>;

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    // Import the derive
    use crate::DeriveReferenceFrame as ReferenceFrame;
    use qtty::{AstronomicalUnit, Day, Kilometer, Meter, Per, Quantity};

    // Define a test frame using the macro
    #[derive(Debug, Copy, Clone, ReferenceFrame)]
    struct TestFrame;

    type DispAu = Displacement<TestFrame, AstronomicalUnit>;
    type AuPerDay = Per<AstronomicalUnit, Day>;
    type VelAuDay = Velocity<TestFrame, AuPerDay>;

    #[test]
    fn test_vector_add_sub() {
        let a = DispAu::new(1.0, 2.0, 3.0);
        let b = DispAu::new(4.0, 5.0, 6.0);

        let sum = a + b;
        assert!((sum.x().value() - 5.0).abs() < 1e-12);
        assert!((sum.y().value() - 7.0).abs() < 1e-12);
        assert!((sum.z().value() - 9.0).abs() < 1e-12);

        let diff = b - a;
        assert!((diff.x().value() - 3.0).abs() < 1e-12);
        assert!((diff.y().value() - 3.0).abs() < 1e-12);
        assert!((diff.z().value() - 3.0).abs() < 1e-12);
    }

    #[test]
    fn test_vector_magnitude() {
        let v = DispAu::new(3.0, 4.0, 0.0);
        assert!((v.magnitude().value() - 5.0).abs() < 1e-12);
    }

    #[test]
    fn test_displacement_normalize() {
        let v = DispAu::new(3.0, 4.0, 0.0);
        let dir = v.normalize().expect("non-zero displacement");
        let norm = (dir.x() * dir.x() + dir.y() * dir.y() + dir.z() * dir.z()).sqrt();
        assert!((norm - 1.0).abs() < 1e-12);
    }

    #[test]
    fn test_zero_displacement_normalize() {
        let zero = DispAu::ZERO;
        assert!(zero.normalize().is_none());
    }

    #[test]
    fn test_velocity_add_sub() {
        let v1 = VelAuDay::new(
            Quantity::<AuPerDay>::new(1.0),
            Quantity::<AuPerDay>::new(2.0),
            Quantity::<AuPerDay>::new(3.0),
        );
        let v2 = VelAuDay::new(
            Quantity::<AuPerDay>::new(0.5),
            Quantity::<AuPerDay>::new(1.0),
            Quantity::<AuPerDay>::new(1.5),
        );

        let sum = v1 + v2;
        assert!((sum.x().value() - 1.5).abs() < 1e-12);
        assert!((sum.y().value() - 3.0).abs() < 1e-12);
        assert!((sum.z().value() - 4.5).abs() < 1e-12);

        let diff = v1 - v2;
        assert!((diff.x().value() - 0.5).abs() < 1e-12);
        assert!((diff.y().value() - 1.0).abs() < 1e-12);
        assert!((diff.z().value() - 1.5).abs() < 1e-12);
    }

    #[test]
    fn test_velocity_magnitude() {
        let v = VelAuDay::new(
            Quantity::<AuPerDay>::new(3.0),
            Quantity::<AuPerDay>::new(4.0),
            Quantity::<AuPerDay>::new(0.0),
        );
        assert!((v.magnitude().value() - 5.0).abs() < 1e-12);
    }

    #[test]
    fn test_vector_misc_ops() {
        let v = DispAu::new(1.0, 2.0, 3.0);
        let scaled = v.scale(2.0);
        assert_eq!(scaled, DispAu::new(2.0, 4.0, 6.0));

        let neg = v.negate();
        assert!((neg.x().value() + 1.0).abs() < 1e-12);
        assert!((neg.y().value() + 2.0).abs() < 1e-12);

        let dot = v.dot(&DispAu::new(0.0, 1.0, 0.0));
        assert!((dot - 2.0).abs() < 1e-12);

        let cross = v.cross(&DispAu::new(0.0, 1.0, 0.0));
        assert!((cross.x().value() + 3.0).abs() < 1e-12);
        assert!(cross.y().value().abs() < 1e-12);
        assert!((cross.z().value() - 1.0).abs() < 1e-12);

        let magnitude_sq = v.magnitude_squared();
        assert!((magnitude_sq - 14.0).abs() < 1e-12);

        let from_vec3 = DispAu::from_vec3(nalgebra::Vector3::new(
            Quantity::<AstronomicalUnit>::new(1.0),
            Quantity::<AstronomicalUnit>::new(2.0),
            Quantity::<AstronomicalUnit>::new(3.0),
        ));
        assert_eq!(from_vec3, v);

        let dir = v.normalize_unchecked();
        let norm = (dir.x() * dir.x() + dir.y() * dir.y() + dir.z() * dir.z()).sqrt();
        assert!((norm - 1.0).abs() < 1e-12);

        let neg_op = -v;
        assert_eq!(neg_op, neg);
    }

    #[test]
    fn test_vector_display_and_accessors() {
        let v = Displacement::<TestFrame, Meter>::new(1.0, 2.0, 3.0);
        let vec3 = v.as_vec3();
        assert!((vec3[0].value() - 1.0).abs() < 1e-12);
        assert!((vec3[1].value() - 2.0).abs() < 1e-12);
        assert!((vec3[2].value() - 3.0).abs() < 1e-12);

        let text = v.to_string();
        assert!(text.contains("Vector<TestFrame>"));

        let text_prec = format!("{:.1}", v);
        let expected_x_prec = format!("{:.1}", v.x());
        assert!(text_prec.contains(&format!("X: {expected_x_prec}")));

        let text_exp = format!("{:.2e}", v);
        let expected_y_exp = format!("{:.2e}", v.y());
        assert!(text_exp.contains(&format!("Y: {expected_y_exp}")));
    }

    #[test]
    fn test_vector_to_unit_roundtrip() {
        let v_au = DispAu::new(1.0, -2.0, 0.5);
        let v_km: Displacement<TestFrame, Kilometer> = v_au.to_unit();
        let back: DispAu = v_km.to_unit();

        assert!((back.x().value() - v_au.x().value()).abs() < 1e-12);
        assert!((back.y().value() - v_au.y().value()).abs() < 1e-12);
        assert!((back.z().value() - v_au.z().value()).abs() < 1e-12);
    }

    #[test]
    fn test_velocity_to_unit_roundtrip() {
        type KmPerDay = Per<Kilometer, Day>;

        let v_au_day = VelAuDay::new(
            Quantity::<AuPerDay>::new(0.01),
            Quantity::<AuPerDay>::new(-0.02),
            Quantity::<AuPerDay>::new(0.03),
        );
        let v_km_day: Velocity<TestFrame, KmPerDay> = v_au_day.to_unit();
        let back: VelAuDay = v_km_day.to_unit();

        assert!((back.x().value() - v_au_day.x().value()).abs() < 1e-12);
        assert!((back.y().value() - v_au_day.y().value()).abs() < 1e-12);
        assert!((back.z().value() - v_au_day.z().value()).abs() < 1e-12);
    }

    #[test]
    fn vector_has_xyz_layout() {
        assert_eq!(
            core::mem::size_of::<DispAu>(),
            core::mem::size_of::<XYZ<Quantity<AstronomicalUnit>>>()
        );
        assert_eq!(
            core::mem::align_of::<DispAu>(),
            core::mem::align_of::<XYZ<Quantity<AstronomicalUnit>>>()
        );
    }
}