brahe 1.4.0

Brahe is a modern satellite dynamics library for research and engineering applications designed to be easy-to-learn, high-performance, and quick-to-deploy. The north-star of the development is enabling users to solve meaningful problems and answer questions quickly, easily, and correctly.
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
/*!
 * Numerical orbit propagation configuration
 *
 * This module provides configuration for the numerical integrator settings
 * used in numerical orbit propagation, including:
 * - Integrator selection (RK4, RKF45, DP54, RKN1210)
 * - Integrator tolerances and step sizes
 * - Jacobian and sensitivity computation methods
 *
 * Note: Force model configuration is handled separately in `force_model_config.rs`.
 *
 * # Example
 *
 * ```rust,ignore
 * use brahe::propagators::{NumericalPropagationConfig, IntegratorMethod};
 *
 * // Default configuration (DP54 integrator with standard tolerances)
 * let config = NumericalPropagationConfig::default();
 *
 * // Custom configuration with specific integrator
 * let config = NumericalPropagationConfig::with_method(IntegratorMethod::RKF45);
 * ```
 */

use serde::{Deserialize, Serialize};

use crate::integrators::IntegratorConfig;
use crate::math::interpolation::InterpolationMethod;
use crate::math::jacobian::DifferenceMethod;

// =============================================================================
// Integrator Method Selection
// =============================================================================

/// Integration method for numerical orbit propagation
///
/// Specifies which numerical integrator to use. Different methods trade off
/// accuracy, efficiency, and applicability.
///
/// # Available Methods
///
/// | Method   | Order | Adaptive | Function Evals | Best For |
/// |----------|-------|----------|----------------|----------|
/// | RK4      | 4     | No       | 4              | Simple problems, debugging |
/// | RKF45    | 4(5)  | Yes      | 6              | General purpose |
/// | DP54     | 5(4)  | Yes      | 7 (6 w/FSAL)   | General purpose (default) |
/// | RKN1210  | 12(10)| Yes      | 17             | High precision |
///
/// # Example
///
/// ```rust
/// use brahe::propagators::IntegratorMethod;
///
/// // Use default (DP54)
/// let method = IntegratorMethod::default();
///
/// // Check if method uses adaptive stepping
/// assert!(method.is_adaptive());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum IntegratorMethod {
    /// Classical 4th-order Runge-Kutta (fixed-step)
    ///
    /// The "standard" RK4 method. Fixed step size only.
    /// Good for simple problems or when you want to control step size manually.
    RK4,

    /// Runge-Kutta-Fehlberg 4(5) adaptive
    ///
    /// Uses 4th and 5th order solutions for error estimation.
    /// 6 function evaluations per step.
    RKF45,

    /// Dormand-Prince 5(4) adaptive (default)
    ///
    /// MATLAB's ode45. Uses FSAL (First-Same-As-Last) optimization
    /// for only 6 effective function evaluations per accepted step.
    /// Generally preferred over RKF45.
    #[default]
    DP54,

    /// Runge-Kutta-Nystrom 12(10) adaptive
    ///
    /// Very high-order integrator optimized for second-order ODEs.
    /// 17 function evaluations per step but achieves extreme accuracy.
    /// Best for high-precision applications with tight tolerances.
    ///
    /// **Note**: This integrator is experimental.
    RKN1210,
}

impl IntegratorMethod {
    /// Returns true if this integrator uses adaptive step size control.
    ///
    /// Adaptive integrators automatically adjust step size to maintain
    /// error tolerances.
    ///
    /// # Returns
    /// `true` for RKF45, DP54, and RKN1210; `false` for RK4.
    pub fn is_adaptive(&self) -> bool {
        !matches!(self, IntegratorMethod::RK4)
    }
}

// =============================================================================
// Trajectory Mode
// =============================================================================

/// Trajectory storage mode for numerical propagators
///
/// Controls when and whether state data is stored in the trajectory during propagation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum TrajectoryMode {
    /// Store state at requested output epochs only (default)
    ///
    /// Most memory-efficient. Only stores at times explicitly requested
    /// via `propagate_to_epochs()` or similar methods.
    #[default]
    OutputStepsOnly,

    /// Store state at every integration step
    ///
    /// Useful for debugging or high-resolution trajectory analysis.
    /// May use significantly more memory for long propagations.
    AllSteps,

    /// Disable trajectory storage entirely
    ///
    /// Only the current state is maintained. Useful when only the
    /// final state matters and memory is constrained.
    Disabled,
}

// =============================================================================
// Variational Configuration
// =============================================================================

/// Configuration for STM and sensitivity matrix propagation
///
/// Controls whether the propagator computes and stores variational matrices
/// (State Transition Matrix and Sensitivity Matrix) during propagation.
///
/// # Example
///
/// ```rust
/// use brahe::propagators::VariationalConfig;
/// use brahe::math::jacobian::DifferenceMethod;
///
/// // Default: no variational matrices
/// let config = VariationalConfig::default();
///
/// // Enable STM and sensitivity with history storage
/// let config = VariationalConfig::new(
///     true, true, true, true,
///     DifferenceMethod::Central, DifferenceMethod::Central,
/// );
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VariationalConfig {
    /// Enable State Transition Matrix (STM) propagation
    ///
    /// When enabled, the propagator computes the STM (Φ) which maps
    /// initial state perturbations to final state perturbations:
    /// δx(t) = Φ(t, t₀) · δx(t₀)
    ///
    /// Default: `false`
    /// Note: Automatically enabled if `initial_covariance` is provided to constructor.
    pub enable_stm: bool,

    /// Enable sensitivity matrix propagation
    ///
    /// When enabled, the propagator computes the sensitivity matrix (S)
    /// which maps parameter perturbations to state perturbations:
    /// δx(t) = S(t) · δp
    ///
    /// Default: `false`
    /// Note: Requires `params` to be provided to constructor when enabled.
    pub enable_sensitivity: bool,

    /// Store STM at output times in trajectory
    ///
    /// When enabled, the STM is stored at requested output epochs
    /// and can be retrieved from the trajectory.
    ///
    /// Default: `false`
    pub store_stm_history: bool,

    /// Store sensitivity matrix at output times in trajectory
    ///
    /// When enabled, the sensitivity matrix is stored at requested
    /// output epochs and can be retrieved from the trajectory.
    ///
    /// Default: `false`
    pub store_sensitivity_history: bool,

    /// Finite difference method for Jacobian computation
    ///
    /// Used when computing the state transition matrix (STM) numerically.
    ///
    /// Default: `DifferenceMethod::Central`
    pub jacobian_method: DifferenceMethod,

    /// Finite difference method for sensitivity matrix computation
    ///
    /// Used when computing parameter sensitivities numerically.
    ///
    /// Default: `DifferenceMethod::Central`
    pub sensitivity_method: DifferenceMethod,
}

impl Default for VariationalConfig {
    fn default() -> Self {
        Self {
            enable_stm: false,
            enable_sensitivity: false,
            store_stm_history: false,
            store_sensitivity_history: false,
            jacobian_method: DifferenceMethod::Central,
            sensitivity_method: DifferenceMethod::Central,
        }
    }
}

impl VariationalConfig {
    /// Create configuration with specified STM and sensitivity settings
    ///
    /// # Arguments
    /// * `enable_stm` - Enable STM propagation
    /// * `enable_sensitivity` - Enable sensitivity matrix propagation
    /// * `store_stm_history` - Store STM at each step in trajectory
    /// * `store_sensitivity_history` - Store sensitivity at each step in trajectory
    /// * `jacobian_method` - Finite difference method for Jacobian computation
    /// * `sensitivity_method` - Finite difference method for sensitivity computation
    ///
    /// # Example
    ///
    /// ```rust
    /// use brahe::propagators::VariationalConfig;
    /// use brahe::math::jacobian::DifferenceMethod;
    ///
    /// // Full uncertainty quantification with history
    /// let config = VariationalConfig::new(
    ///     true, true, true, true,
    ///     DifferenceMethod::Central, DifferenceMethod::Central,
    /// );
    /// ```
    pub fn new(
        enable_stm: bool,
        enable_sensitivity: bool,
        store_stm_history: bool,
        store_sensitivity_history: bool,
        jacobian_method: DifferenceMethod,
        sensitivity_method: DifferenceMethod,
    ) -> Self {
        Self {
            enable_stm,
            enable_sensitivity,
            store_stm_history,
            store_sensitivity_history,
            jacobian_method,
            sensitivity_method,
        }
    }
}

// =============================================================================
// Numerical Propagation Configuration
// =============================================================================

/// Configuration for the numerical integrator
///
/// This struct contains the integrator-specific configuration options:
/// - Integration method selection
/// - Integrator tolerances and step sizes
/// - Variational equation settings (STM, sensitivity, finite difference methods)
///
/// Note: Force model configuration (gravity, drag, SRP, etc.) is handled
/// separately via `ForceModelConfig`.
///
/// # Example
///
/// ```rust,ignore
/// use brahe::propagators::{NumericalPropagationConfig, IntegratorMethod};
/// use brahe::integrators::IntegratorConfig;
///
/// // Create custom configuration
/// let config = NumericalPropagationConfig {
///     method: IntegratorMethod::RKF45,
///     integrator: IntegratorConfig::adaptive(1e-10, 1e-8),
///     ..Default::default()
/// };
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NumericalPropagationConfig {
    /// Integration method to use
    pub method: IntegratorMethod,

    /// Integrator configuration (tolerances, step sizes)
    pub integrator: IntegratorConfig,

    /// STM and sensitivity propagation configuration
    pub variational: VariationalConfig,

    /// Whether to store accelerations in trajectory
    ///
    /// When enabled, the propagator computes and stores acceleration vectors
    /// at each trajectory point. This enables higher-order interpolation
    /// methods like Hermite quintic that use acceleration data.
    ///
    /// Default: `true`
    pub store_accelerations: bool,

    /// Interpolation method for trajectory queries
    ///
    /// Controls how states are interpolated between stored trajectory points.
    /// Higher-order methods (Lagrange, Hermite) provide better accuracy but
    /// may require more stored points or acceleration data.
    ///
    /// **Note**: Hermite interpolation methods (`HermiteCubic`, `HermiteQuintic`)
    /// require 6D state vectors with position/velocity structure `[x, y, z, vx, vy, vz]`.
    /// For non-6D systems, use `Linear` or `Lagrange` interpolation.
    ///
    /// Default: `InterpolationMethod::Linear`
    pub interpolation_method: InterpolationMethod,
}

impl Default for NumericalPropagationConfig {
    /// Default configuration suitable for most applications
    ///
    /// Uses:
    /// - Dormand-Prince 5(4) integrator
    /// - Default tolerances (abs=1e-6, rel=1e-3)
    /// - No variational matrix propagation (central differences when enabled)
    /// - Acceleration storage enabled
    /// - Linear interpolation (safe for any state dimension)
    fn default() -> Self {
        Self {
            method: IntegratorMethod::default(),
            integrator: IntegratorConfig::default(),
            variational: VariationalConfig::default(),
            store_accelerations: true,
            interpolation_method: InterpolationMethod::Linear,
        }
    }
}

impl NumericalPropagationConfig {
    /// Create configuration with a specific integrator method
    ///
    /// # Arguments
    /// * `method` - The integrator method to use
    ///
    /// # Returns
    /// Configuration with the specified method and default settings
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use brahe::propagators::{NumericalPropagationConfig, IntegratorMethod};
    ///
    /// let config = NumericalPropagationConfig::with_method(IntegratorMethod::RKF45);
    /// ```
    pub fn with_method(method: IntegratorMethod) -> Self {
        Self {
            method,
            ..Default::default()
        }
    }

    /// Creates a new numerical propagation configuration with all components specified.
    ///
    /// # Arguments
    ///
    /// * `method` - Integration method to use (RK4, RKF45, DP54, or RKN1210)
    /// * `integrator` - Integrator configuration (tolerances, step sizes)
    /// * `variational` - Variational configuration (STM and sensitivity settings)
    ///
    /// # Returns
    ///
    /// A new `NumericalPropagationConfig` with the specified settings.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use brahe::propagators::{
    ///     NumericalPropagationConfig, IntegratorMethod, VariationalConfig
    /// };
    /// use brahe::integrators::IntegratorConfig;
    ///
    /// let config = NumericalPropagationConfig::new(
    ///     IntegratorMethod::DP54,
    ///     IntegratorConfig::adaptive(1e-10, 1e-8),
    ///     VariationalConfig::default(),
    /// );
    /// ```
    pub fn new(
        method: IntegratorMethod,
        integrator: IntegratorConfig,
        variational: VariationalConfig,
    ) -> Self {
        Self {
            method,
            integrator,
            variational,
            store_accelerations: true,
            interpolation_method: InterpolationMethod::Linear,
        }
    }

    /// Create high-precision configuration with tight tolerances
    ///
    /// Uses:
    /// - RKN1210 integrator
    /// - Tight tolerances (abs=1e-10, rel=1e-8)
    /// - No variational matrix propagation (central differences when enabled)
    /// - Acceleration storage enabled
    /// - Linear interpolation (safe for any state dimension)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use brahe::propagators::NumericalPropagationConfig;
    ///
    /// let config = NumericalPropagationConfig::high_precision();
    /// ```
    pub fn high_precision() -> Self {
        Self {
            method: IntegratorMethod::RKN1210,
            integrator: IntegratorConfig::adaptive(1e-10, 1e-8),
            variational: VariationalConfig::default(),
            store_accelerations: true,
            interpolation_method: InterpolationMethod::Linear,
        }
    }

    /// Set whether to store accelerations in trajectory
    ///
    /// # Arguments
    /// * `store` - Whether to store accelerations
    ///
    /// # Returns
    /// Self for method chaining
    pub fn with_store_accelerations(mut self, store: bool) -> Self {
        self.store_accelerations = store;
        self
    }

    /// Set the interpolation method for trajectory queries
    ///
    /// # Arguments
    /// * `method` - The interpolation method to use
    ///
    /// # Returns
    /// Self for method chaining
    pub fn with_interpolation_method(mut self, method: InterpolationMethod) -> Self {
        self.interpolation_method = method;
        self
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use super::*;

    #[test]
    fn test_integrator_method_default() {
        let method = IntegratorMethod::default();
        assert_eq!(method, IntegratorMethod::DP54);
    }

    #[test]
    fn test_integrator_method_is_adaptive() {
        assert!(!IntegratorMethod::RK4.is_adaptive());
        assert!(IntegratorMethod::RKF45.is_adaptive());
        assert!(IntegratorMethod::DP54.is_adaptive());
        assert!(IntegratorMethod::RKN1210.is_adaptive());
    }

    #[test]
    fn test_numerical_propagation_config_default() {
        let config = NumericalPropagationConfig::default();

        assert_eq!(config.method, IntegratorMethod::DP54);
        assert_eq!(
            config.variational.jacobian_method,
            DifferenceMethod::Central
        );
        assert_eq!(
            config.variational.sensitivity_method,
            DifferenceMethod::Central
        );
    }

    #[test]
    fn test_numerical_propagation_config_with_method() {
        let config = NumericalPropagationConfig::with_method(IntegratorMethod::RKF45);
        assert_eq!(config.method, IntegratorMethod::RKF45);
    }

    #[test]
    fn test_numerical_propagation_config_high_precision() {
        let config = NumericalPropagationConfig::high_precision();

        assert_eq!(config.method, IntegratorMethod::RKN1210);
        // Tolerances are set tighter
        assert!(config.integrator.abs_tol <= 1e-9);
        assert!(config.integrator.rel_tol <= 1e-7);
    }

    #[test]
    fn test_variational_config_default() {
        let config = VariationalConfig::default();

        assert!(!config.enable_stm);
        assert!(!config.enable_sensitivity);
        assert!(!config.store_stm_history);
        assert!(!config.store_sensitivity_history);
        assert_eq!(config.jacobian_method, DifferenceMethod::Central);
        assert_eq!(config.sensitivity_method, DifferenceMethod::Central);
    }

    #[test]
    fn test_variational_config_new() {
        let config = VariationalConfig::new(
            true,
            true,
            true,
            true,
            DifferenceMethod::Forward,
            DifferenceMethod::Backward,
        );

        assert!(config.enable_stm);
        assert!(config.enable_sensitivity);
        assert!(config.store_stm_history);
        assert!(config.store_sensitivity_history);
        assert_eq!(config.jacobian_method, DifferenceMethod::Forward);
        assert_eq!(config.sensitivity_method, DifferenceMethod::Backward);
    }

    #[test]
    fn test_variational_config_partial() {
        let config = VariationalConfig::new(
            true,
            false,
            true,
            false,
            DifferenceMethod::Central,
            DifferenceMethod::Central,
        );

        assert!(config.enable_stm);
        assert!(!config.enable_sensitivity);
        assert!(config.store_stm_history);
        assert!(!config.store_sensitivity_history);
        assert_eq!(config.jacobian_method, DifferenceMethod::Central);
        assert_eq!(config.sensitivity_method, DifferenceMethod::Central);
    }

    #[test]
    fn test_numerical_propagation_config_default_variational() {
        let config = NumericalPropagationConfig::default();

        assert!(!config.variational.enable_stm);
        assert!(!config.variational.enable_sensitivity);
    }

    #[test]
    fn test_numerical_propagation_config_new() {
        let config = NumericalPropagationConfig::new(
            IntegratorMethod::RKN1210,
            IntegratorConfig::adaptive(1e-12, 1e-10),
            VariationalConfig {
                enable_stm: true,
                ..Default::default()
            },
        );

        assert_eq!(config.method, IntegratorMethod::RKN1210);
        assert_eq!(config.integrator.abs_tol, 1e-12);
        assert_eq!(config.integrator.rel_tol, 1e-10);
        assert!(config.variational.enable_stm);
        assert!(!config.variational.enable_sensitivity);
        // New fields should have defaults
        assert!(config.store_accelerations);
        assert_eq!(config.interpolation_method, InterpolationMethod::Linear);
    }

    #[test]
    fn test_numerical_propagation_config_default_accelerations() {
        let config = NumericalPropagationConfig::default();

        // Acceleration storage should be enabled by default
        assert!(config.store_accelerations);
        // Default interpolation is Linear (safe for any state dimension)
        assert_eq!(config.interpolation_method, InterpolationMethod::Linear);
    }

    #[test]
    fn test_numerical_propagation_config_with_store_accelerations() {
        let config = NumericalPropagationConfig::default().with_store_accelerations(false);
        assert!(!config.store_accelerations);

        let config = NumericalPropagationConfig::default().with_store_accelerations(true);
        assert!(config.store_accelerations);
    }

    #[test]
    fn test_numerical_propagation_config_with_interpolation_method() {
        let config = NumericalPropagationConfig::default()
            .with_interpolation_method(InterpolationMethod::Lagrange { degree: 5 });
        assert_eq!(
            config.interpolation_method,
            InterpolationMethod::Lagrange { degree: 5 }
        );

        let config = NumericalPropagationConfig::default()
            .with_interpolation_method(InterpolationMethod::HermiteCubic);
        assert_eq!(
            config.interpolation_method,
            InterpolationMethod::HermiteCubic
        );

        let config = NumericalPropagationConfig::default()
            .with_interpolation_method(InterpolationMethod::HermiteQuintic);
        assert_eq!(
            config.interpolation_method,
            InterpolationMethod::HermiteQuintic
        );
    }

    #[test]
    fn test_numerical_propagation_config_builder_chaining() {
        let config = NumericalPropagationConfig::default()
            .with_store_accelerations(false)
            .with_interpolation_method(InterpolationMethod::Lagrange { degree: 7 });

        assert!(!config.store_accelerations);
        assert_eq!(
            config.interpolation_method,
            InterpolationMethod::Lagrange { degree: 7 }
        );
    }

    #[test]
    fn test_numerical_propagation_config_high_precision_new_fields() {
        let config = NumericalPropagationConfig::high_precision();

        // High precision should also have defaults for new fields
        assert!(config.store_accelerations);
        // Default interpolation is Linear (safe for any state dimension)
        assert_eq!(config.interpolation_method, InterpolationMethod::Linear);
    }
}