lox-core 0.1.0-alpha.11

Common data types and utilities for the Lox ecosystem
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
// SPDX-FileCopyrightText: 2025 Helge Eichhorn <git@helgeeichhorn.de>
//
// SPDX-License-Identifier: MPL-2.0

//! Data types for representing orbital elements.

use std::f64::consts::PI;
use std::f64::consts::TAU;
use std::fmt::Display;

use glam::DVec3;
use lox_test_utils::ApproxEq;
use lox_test_utils::approx_eq;
use thiserror::Error;

use crate::anomalies::AnomalyError;
use crate::anomalies::MeanAnomaly;
use crate::anomalies::{EccentricAnomaly, TrueAnomaly};
use crate::time::deltas::TimeDelta;
use crate::utils::Linspace;
use crate::{
    coords::Cartesian,
    glam::Azimuth,
    units::{Angle, AngleUnits, Distance, DistanceUnits},
};

/// The standard gravitational parameter of a celestial body µ = GM.
#[derive(Debug, Default, Clone, Copy, PartialEq, PartialOrd, ApproxEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(transparent)]
pub struct GravitationalParameter(f64);

impl GravitationalParameter {
    /// Creates a new gravitational parameter from an `f64` value in m³/s².
    pub const fn m3_per_s2(mu: f64) -> Self {
        Self(mu)
    }

    /// Creates a new gravitational parameter from an `f64` value in km³/s².
    pub const fn km3_per_s2(mu: f64) -> Self {
        Self(1e9 * mu)
    }

    /// Returns the value of the gravitational parameters as an `f64`.
    pub const fn as_f64(&self) -> f64 {
        self.0
    }
}

impl Display for GravitationalParameter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        (self.0 * 1e-9).fmt(f)?;
        write!(f, " km³/s²")
    }
}

/// Type alias for the semi-major axis of an orbit, stored as a [`Distance`].
pub type SemiMajorAxis = Distance;

/// The Keplerian orbit types or conic sections.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum OrbitType {
    /// Circular orbit (e ≈ 0).
    Circular,
    /// Elliptic orbit (0 < e < 1).
    Elliptic,
    /// Parabolic orbit (e ≈ 1).
    Parabolic,
    /// Hyperbolic orbit (e > 1).
    Hyperbolic,
}

impl Display for OrbitType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            OrbitType::Circular => "circular".fmt(f),
            OrbitType::Elliptic => "elliptic".fmt(f),
            OrbitType::Parabolic => "parabolic".fmt(f),
            OrbitType::Hyperbolic => "hyperbolic".fmt(f),
        }
    }
}

/// Error returned when attempting to create an [`Eccentricity`] with a negative value.
#[derive(Debug, Clone, Error)]
#[error("eccentricity cannot be negative but was {0}")]
pub struct NegativeEccentricityError(f64);

/// Orbital eccentricity.
#[derive(Debug, Default, Clone, Copy, PartialEq, PartialOrd, ApproxEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(transparent)]
pub struct Eccentricity(f64);

impl Eccentricity {
    /// Tries to create a new [`Eccentricity`] instance from an `f64` value.
    ///
    /// # Errors
    ///
    /// Returns a [`NegativeEccentricityError`] if the value is smaller than zero.
    pub const fn try_new(ecc: f64) -> Result<Eccentricity, NegativeEccentricityError> {
        if ecc < 0.0 {
            return Err(NegativeEccentricityError(ecc));
        }
        Ok(Eccentricity(ecc))
    }

    /// Returns the value of the eccentricity as an `f64`.
    pub const fn as_f64(&self) -> f64 {
        self.0
    }

    /// Returns the [`OrbitType`] based on the eccentricity.
    pub fn orbit_type(&self) -> OrbitType {
        match self.0 {
            ecc if approx_eq!(ecc, 0.0, atol <= 1e-8) => OrbitType::Circular,
            ecc if approx_eq!(ecc, 1.0, rtol <= 1e-8) => OrbitType::Parabolic,
            ecc if ecc > 0.0 && ecc < 1.0 => OrbitType::Elliptic,
            _ => OrbitType::Hyperbolic,
        }
    }

    /// Checks if the orbit is circular.
    pub fn is_circular(&self) -> bool {
        matches!(self.orbit_type(), OrbitType::Circular)
    }

    /// Checks if the orbit is elliptic.
    pub fn is_elliptic(&self) -> bool {
        matches!(self.orbit_type(), OrbitType::Elliptic)
    }

    /// Checks if the orbit is parabolic.
    pub fn is_parabolic(&self) -> bool {
        matches!(self.orbit_type(), OrbitType::Parabolic)
    }

    /// Checks if the orbit is hyperbolic.
    pub fn is_hyperbolic(&self) -> bool {
        matches!(self.orbit_type(), OrbitType::Hyperbolic)
    }

    /// Checks if the orbit is circular or elliptic.
    pub fn is_circular_or_elliptic(&self) -> bool {
        matches!(self.orbit_type(), OrbitType::Circular | OrbitType::Elliptic)
    }
}

impl Display for Eccentricity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

/// Error returned when an [`Inclination`] is outside the valid range [0°, 180°].
#[derive(Debug, Clone, Error)]
#[error("inclination must be between 0 and 180 deg but was {0}")]
pub struct InclinationError(Angle);

/// Orbital inclination.
#[derive(Debug, Default, Clone, Copy, PartialEq, PartialOrd, ApproxEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(transparent)]
pub struct Inclination(Angle);

impl Inclination {
    /// Tries to create a new [`Inclination`] from an angle. Must be between 0 and π.
    pub const fn try_new(inclination: Angle) -> Result<Inclination, InclinationError> {
        let inc = inclination.as_f64();
        if inc < 0.0 || inc > PI {
            return Err(InclinationError(inclination));
        }
        Ok(Inclination(inclination))
    }

    /// Returns the inclination in radians as an `f64`.
    pub const fn as_f64(&self) -> f64 {
        self.0.as_f64()
    }
}

impl Display for Inclination {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

/// Error returned when a [`LongitudeOfAscendingNode`] is outside the valid range [0°, 360°].
#[derive(Debug, Clone, Error)]
#[error("longitude of ascending node must be between 0 and 360 deg but was {0}")]
pub struct LongitudeOfAscendingNodeError(Angle);

/// Longitude of ascending node.
#[derive(Debug, Default, Clone, Copy, PartialEq, PartialOrd, ApproxEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(transparent)]
pub struct LongitudeOfAscendingNode(Angle);

impl LongitudeOfAscendingNode {
    /// Tries to create a new [`LongitudeOfAscendingNode`]. Must be between 0 and 2π.
    pub const fn try_new(
        longitude_of_ascending_node: Angle,
    ) -> Result<LongitudeOfAscendingNode, LongitudeOfAscendingNodeError> {
        let node = longitude_of_ascending_node.as_f64();
        if node < 0.0 || node > TAU {
            return Err(LongitudeOfAscendingNodeError(longitude_of_ascending_node));
        }
        Ok(LongitudeOfAscendingNode(longitude_of_ascending_node))
    }

    /// Returns the longitude of ascending node in radians as an `f64`.
    pub const fn as_f64(&self) -> f64 {
        self.0.as_f64()
    }
}

impl Display for LongitudeOfAscendingNode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

/// Error returned when an [`ArgumentOfPeriapsis`] is outside the valid range [0°, 360°].
#[derive(Debug, Clone, Error)]
#[error("argument of periapsis must be between 0 and 360 deg but was {0}")]
pub struct ArgumentOfPeriapsisError(Angle);

/// Argument of periapsis.
#[derive(Debug, Default, Clone, Copy, PartialEq, PartialOrd, ApproxEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(transparent)]
pub struct ArgumentOfPeriapsis(Angle);

impl ArgumentOfPeriapsis {
    /// Tries to create a new [`ArgumentOfPeriapsis`]. Must be between 0 and 2π.
    pub const fn try_new(
        argument_of_periapsis: Angle,
    ) -> Result<ArgumentOfPeriapsis, ArgumentOfPeriapsisError> {
        let arg = argument_of_periapsis.as_f64();
        if arg < 0.0 || arg > TAU {
            return Err(ArgumentOfPeriapsisError(argument_of_periapsis));
        }
        Ok(ArgumentOfPeriapsis(argument_of_periapsis))
    }

    /// Returns the argument of periapsis in radians as an `f64`.
    pub const fn as_f64(&self) -> f64 {
        self.0.as_f64()
    }
}

impl Display for ArgumentOfPeriapsis {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

/// A set of Keplerian orbital elements.
#[derive(Debug, Clone, Copy, PartialEq, ApproxEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Keplerian {
    semi_major_axis: SemiMajorAxis,
    eccentricity: Eccentricity,
    inclination: Inclination,
    longitude_of_ascending_node: LongitudeOfAscendingNode,
    argument_of_periapsis: ArgumentOfPeriapsis,
    true_anomaly: TrueAnomaly,
}

impl Keplerian {
    /// Creates a new set of Keplerian elements from pre-validated components.
    pub fn new(
        semi_major_axis: SemiMajorAxis,
        eccentricity: Eccentricity,
        inclination: Inclination,
        longitude_of_ascending_node: LongitudeOfAscendingNode,
        argument_of_periapsis: ArgumentOfPeriapsis,
        true_anomaly: TrueAnomaly,
    ) -> Self {
        Self {
            semi_major_axis,
            eccentricity,
            inclination,
            longitude_of_ascending_node,
            argument_of_periapsis,
            true_anomaly,
        }
    }

    /// Returns a new [`KeplerianBuilder`].
    pub fn builder() -> KeplerianBuilder {
        KeplerianBuilder::default()
    }

    /// Returns the semi-major axis.
    pub fn semi_major_axis(&self) -> SemiMajorAxis {
        self.semi_major_axis
    }

    /// Returns the eccentricity.
    pub fn eccentricity(&self) -> Eccentricity {
        self.eccentricity
    }

    /// Returns the inclination.
    pub fn inclination(&self) -> Inclination {
        self.inclination
    }

    /// Returns the longitude of ascending node.
    pub fn longitude_of_ascending_node(&self) -> LongitudeOfAscendingNode {
        self.longitude_of_ascending_node
    }

    /// Returns the argument of periapsis.
    pub fn argument_of_periapsis(&self) -> ArgumentOfPeriapsis {
        self.argument_of_periapsis
    }

    /// Returns the true anomaly.
    pub fn true_anomaly(&self) -> TrueAnomaly {
        self.true_anomaly
    }

    /// Returns the semi-parameter (semi-latus rectum) of the orbit.
    pub fn semi_parameter(&self) -> Distance {
        if self.eccentricity.is_circular() {
            self.semi_major_axis
        } else {
            Distance::new(self.semi_major_axis.as_f64() * (1.0 - self.eccentricity.0.powi(2)))
        }
    }

    /// Converts the orbital elements to position and velocity in the perifocal frame.
    pub fn to_perifocal(&self, grav_param: GravitationalParameter) -> (DVec3, DVec3) {
        let ecc = self.eccentricity.as_f64();
        let mu = grav_param.as_f64();
        let semiparameter = self.semi_parameter().as_f64();
        let (sin_nu, cos_nu) = self.true_anomaly.as_angle().sin_cos();
        let sqrt_mu_p = (mu / semiparameter).sqrt();

        let pos = DVec3::new(cos_nu, sin_nu, 0.0) * (semiparameter / (1.0 + ecc * cos_nu));
        let vel = DVec3::new(-sin_nu, ecc + cos_nu, 0.0) * sqrt_mu_p;

        (pos, vel)
    }

    /// Converts the orbital elements to a Cartesian state vector.
    pub fn to_cartesian(&self, grav_param: GravitationalParameter) -> Cartesian {
        let (pos, vel) = self.to_perifocal(grav_param);
        let rot = self.longitude_of_ascending_node.0.rotation_z().transpose()
            * self.inclination.0.rotation_x().transpose()
            * self.argument_of_periapsis.0.rotation_z().transpose();
        Cartesian::from_vecs(rot * pos, rot * vel)
    }

    /// Returns the orbital period, or `None` for non-elliptic orbits.
    pub fn orbital_period(&self, grav_param: GravitationalParameter) -> Option<TimeDelta> {
        if !self.eccentricity().is_circular_or_elliptic() {
            return None;
        }
        let mu = grav_param.as_f64();
        let a = self.semi_major_axis.as_f64();
        Some(TimeDelta::from_seconds_f64(TAU * (a.powf(3.0) / mu).sqrt()))
    }

    /// Returns an iterator over `n` Cartesian positions equally spaced around the orbit.
    pub fn iter_trace(
        &self,
        grav_param: GravitationalParameter,
        n: usize,
    ) -> impl Iterator<Item = Cartesian> {
        assert!(self.eccentricity().is_circular_or_elliptic());
        Linspace::new(-PI, PI, n).map(move |ecc| {
            let true_anomaly = EccentricAnomaly::new(ecc.rad()).to_true(self.eccentricity);
            Keplerian {
                true_anomaly,
                ..*self
            }
            .to_cartesian(grav_param)
        })
    }

    /// Returns `n` Cartesian positions equally spaced around the orbit, or `None` for non-elliptic orbits.
    pub fn trace(&self, grav_param: GravitationalParameter, n: usize) -> Option<Vec<Cartesian>> {
        if !self.eccentricity().is_circular_or_elliptic() {
            return None;
        }
        Some(self.iter_trace(grav_param, n).collect())
    }
}

impl Cartesian {
    /// Computes the eccentricity vector from the Cartesian state.
    pub fn eccentricity_vector(&self, grav_param: GravitationalParameter) -> DVec3 {
        let mu = grav_param.as_f64();
        let r = self.position();
        let v = self.velocity();

        let rm = r.length();
        let v2 = v.dot(v);
        let rv = r.dot(v);

        ((v2 - mu / rm) * r - rv * v) / mu
    }

    /// Converts the Cartesian state to Keplerian orbital elements.
    pub fn to_keplerian(&self, grav_param: GravitationalParameter) -> Keplerian {
        let r = self.position();
        let v = self.velocity();
        let mu = grav_param.as_f64();

        let rm = r.length();
        let vm = v.length();
        let h = r.cross(v);
        let hm = h.length();
        let node = DVec3::Z.cross(h);
        let e = self.eccentricity_vector(grav_param);
        let eccentricity = Eccentricity(e.length());
        let inclination = h.angle_between(DVec3::Z).rad();

        let equatorial = approx_eq!(inclination, Angle::ZERO, atol <= 1e-8);
        let circular = eccentricity.is_circular();

        let semi_major_axis = if circular {
            hm.powi(2) / mu
        } else {
            -mu / (2.0 * (vm.powi(2) / 2.0 - mu / rm))
        };

        let (longitude_of_ascending_node, argument_of_periapsis, true_anomaly) =
            if equatorial && !circular {
                (
                    Angle::ZERO,
                    e.azimuth(),
                    TrueAnomaly::new(Angle::from_atan2(h.dot(e.cross(r)) / hm, r.dot(e))),
                )
            } else if !equatorial && circular {
                (
                    node.azimuth(),
                    Angle::ZERO,
                    TrueAnomaly::new(Angle::from_atan2(r.dot(h.cross(node)) / hm, r.dot(node))),
                )
            } else if equatorial && circular {
                (Angle::ZERO, Angle::ZERO, TrueAnomaly::new(r.azimuth()))
            } else {
                let true_anomaly = if semi_major_axis > 0.0 {
                    let e_se = r.dot(v) / (mu * semi_major_axis).sqrt();
                    let e_ce = (rm * vm.powi(2)) / mu - 1.0;
                    EccentricAnomaly::new(Angle::from_atan2(e_se, e_ce)).to_true(eccentricity)
                } else {
                    let e_sh = r.dot(v) / (-mu * semi_major_axis).sqrt();
                    let e_ch = (rm * vm.powi(2)) / mu - 1.0;
                    EccentricAnomaly::new((((e_ch + e_sh) / (e_ch - e_sh)).ln() / 2.0).rad())
                        .to_true(eccentricity)
                };
                let px = r.dot(node);
                let py = r.dot(h.cross(node)) / hm;
                (
                    node.azimuth(),
                    Angle::from_atan2(py, px) - true_anomaly.as_angle(),
                    true_anomaly,
                )
            };

        Keplerian {
            semi_major_axis: semi_major_axis.m(),
            eccentricity,
            inclination: Inclination(inclination),
            longitude_of_ascending_node: LongitudeOfAscendingNode(
                longitude_of_ascending_node.mod_two_pi(),
            ),
            argument_of_periapsis: ArgumentOfPeriapsis(argument_of_periapsis.mod_two_pi()),
            true_anomaly,
        }
    }
}

/// Error returned when constructing a [`Keplerian`] via the builder.
#[derive(Debug, Clone, Error)]
pub enum KeplerianError {
    /// The eccentricity is negative.
    #[error(transparent)]
    NegativeEccentricity(#[from] NegativeEccentricityError),
    /// The semi-major axis sign is inconsistent with the eccentricity.
    #[error(
        "{} semi-major axis ({semi_major_axis}) for {} eccentricity ({eccentricity})",
        if .semi_major_axis.as_f64().signum() == -1.0 {"negative"} else {"positive"},
        .eccentricity.orbit_type()
    )]
    InvalidShape {
        /// The invalid semi-major axis.
        semi_major_axis: SemiMajorAxis,
        /// The eccentricity that conflicts with the semi-major axis sign.
        eccentricity: Eccentricity,
    },
    /// No shape parameters were provided.
    #[error(
        "no orbital shape parameters (semi-major axis and eccentricity, radii, or altitudes) were provided"
    )]
    MissingShape,
    /// The inclination is invalid.
    #[error(transparent)]
    InvalidInclination(#[from] InclinationError),
    /// The longitude of ascending node is invalid.
    #[error(transparent)]
    InvalidLongitudeOfAscendingNode(#[from] LongitudeOfAscendingNodeError),
    /// The argument of periapsis is invalid.
    #[error(transparent)]
    InvalidArgumentOfPeriapsis(#[from] ArgumentOfPeriapsisError),
    /// The anomaly conversion failed.
    #[error(transparent)]
    Anomaly(#[from] AnomalyError),
}

/// Builder for constructing validated [`Keplerian`] elements.
#[derive(Debug, Default, Clone)]
pub struct KeplerianBuilder {
    shape: Option<(
        SemiMajorAxis,
        Result<Eccentricity, NegativeEccentricityError>,
    )>,
    inclination: Angle,
    longitude_of_ascending_node: Angle,
    argument_of_periapsis: Angle,
    true_anomaly: Option<Angle>,
    mean_anomaly: Option<Angle>,
}

impl KeplerianBuilder {
    /// Creates a new builder with default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the semi-major axis and eccentricity.
    pub fn with_semi_major_axis(
        mut self,
        semi_major_axis: SemiMajorAxis,
        eccentricity: f64,
    ) -> Self {
        self.shape = Some((semi_major_axis, Eccentricity::try_new(eccentricity)));
        self
    }

    /// Sets the orbit shape from periapsis and apoapsis radii.
    pub fn with_radii(mut self, periapsis_radius: Distance, apoapsis_radius: Distance) -> Self {
        let rp = periapsis_radius.as_f64();
        let ra = apoapsis_radius.as_f64();
        let semi_major_axis = SemiMajorAxis::new((rp + ra) / 2.0);

        let eccentricity = Eccentricity::try_new((ra - rp) / (ra + rp));

        self.shape = Some((semi_major_axis, eccentricity));

        self
    }

    /// Sets the orbit shape from periapsis and apoapsis altitudes above a mean radius.
    pub fn with_altitudes(
        self,
        periapsis_altitude: Distance,
        apoapsis_altitude: Distance,
        mean_radius: Distance,
    ) -> Self {
        let rp = periapsis_altitude + mean_radius;
        let ra = apoapsis_altitude + mean_radius;
        self.with_radii(rp, ra)
    }

    /// Sets the inclination.
    pub fn with_inclination(mut self, inclination: Angle) -> Self {
        self.inclination = inclination;
        self
    }

    /// Sets the longitude of ascending node.
    pub fn with_longitude_of_ascending_node(mut self, longitude_of_ascending_node: Angle) -> Self {
        self.longitude_of_ascending_node = longitude_of_ascending_node;
        self
    }

    /// Sets the argument of periapsis.
    pub fn with_argument_of_periapsis(mut self, argument_of_periapsis: Angle) -> Self {
        self.argument_of_periapsis = argument_of_periapsis;
        self
    }

    /// Sets the true anomaly.
    pub fn with_true_anomaly(mut self, true_anomaly: Angle) -> Self {
        self.true_anomaly = Some(true_anomaly);
        self
    }

    /// Sets the mean anomaly (converted to true anomaly during build).
    pub fn with_mean_anomaly(mut self, mean_anomaly: Angle) -> Self {
        self.mean_anomaly = Some(mean_anomaly);
        self
    }

    /// Validates all parameters and builds the [`Keplerian`] elements.
    pub fn build(self) -> Result<Keplerian, KeplerianError> {
        let (semi_major_axis, eccentricity) = self.shape.ok_or(KeplerianError::MissingShape)?;

        let eccentricity = eccentricity?;

        Self::check_shape(semi_major_axis, eccentricity)?;

        let inclination = Inclination::try_new(self.inclination)?;
        let longitude_of_ascending_node =
            LongitudeOfAscendingNode::try_new(self.longitude_of_ascending_node)?;
        let argument_of_periapsis = ArgumentOfPeriapsis::try_new(self.argument_of_periapsis)?;

        let true_anomaly = match self.true_anomaly {
            Some(true_anomaly) => TrueAnomaly::new(true_anomaly),
            None => match self.mean_anomaly {
                Some(mean_anomaly) => MeanAnomaly::new(mean_anomaly).to_true(eccentricity)?,
                None => TrueAnomaly::new(Angle::ZERO),
            },
        };

        Ok(Keplerian {
            semi_major_axis,
            eccentricity,
            inclination,
            longitude_of_ascending_node,
            argument_of_periapsis,
            true_anomaly,
        })
    }

    fn check_shape(
        semi_major_axis: SemiMajorAxis,
        eccentricity: Eccentricity,
    ) -> Result<(), KeplerianError> {
        let ecc = eccentricity.as_f64();
        let sma = semi_major_axis.as_f64();
        if (ecc > 1.0 && sma > 0.0) || (ecc < 1.0 && sma < 0.0) {
            return Err(KeplerianError::InvalidShape {
                semi_major_axis,
                eccentricity,
            });
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use lox_test_utils::assert_approx_eq;

    use crate::units::VelocityUnits;

    use super::*;

    #[test]
    fn test_cartesian_to_keplerian_roundtrip() {
        let mu = GravitationalParameter::km3_per_s2(398600.43550702266f64);

        let cartesian = Cartesian::builder()
            .position(
                -0.107622532467967e7.m(),
                -0.676589636432773e7.m(),
                -0.332308783350379e6.m(),
            )
            .velocity(
                0.935685775154103e4.mps(),
                -0.331234775037644e4.mps(),
                -0.118801577532701e4.mps(),
            )
            .build();

        let cartesian1 = cartesian.to_keplerian(mu).to_cartesian(mu);

        assert_approx_eq!(cartesian.position(), cartesian1.position(), rtol <= 1e-8);
        assert_approx_eq!(cartesian.velocity(), cartesian1.velocity(), rtol <= 1e-6);
    }

    #[test]
    fn test_keplerian_builder() {
        let mu = GravitationalParameter::km3_per_s2(398600.43550702266f64);

        let semi_major_axis = 24464.560.km();
        let eccentricity = 0.7311;
        let inclination = 0.122138.rad();
        let ascending_node = 1.00681.rad();
        let argument_of_periapsis = 3.10686.rad();
        let true_anomaly = 0.44369564302687126.rad();

        let k = Keplerian::builder()
            .with_semi_major_axis(semi_major_axis, eccentricity)
            .with_inclination(inclination)
            .with_longitude_of_ascending_node(ascending_node)
            .with_argument_of_periapsis(argument_of_periapsis)
            .with_true_anomaly(true_anomaly)
            .build()
            .unwrap();
        let k1 = k.to_cartesian(mu).to_keplerian(mu);
        assert_approx_eq!(k, k1);
    }
}