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
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
/*!
 * ECEF-frame measurement models.
 *
 * These models represent measurements expressed in the Earth-fixed (ECEF)
 * frame. The estimator's state is assumed to be in an inertial (ECI) frame,
 * so these models internally perform the ECI→ECEF rotation when computing
 * predicted measurements.
 *
 * The Jacobians use the default finite-difference implementation since the
 * ECI→ECEF rotation matrix is epoch-dependent, making analytical Jacobians
 * complex. The adaptive perturbation strategy in the default implementation
 * handles the large state magnitudes correctly.
 *
 * For direct inertial-frame measurements, see the
 * [`inertial`](super::inertial) module.
 */

use nalgebra::{DMatrix, DVector};

use crate::estimation::traits::MeasurementModel;
use crate::frames::{position_eci_to_ecef, state_eci_to_ecef};
use crate::math::covariance::{
    covariance_from_upper_triangular, diagonal_covariance, isotropic_covariance,
    validate_covariance,
};
use crate::math::linalg::SVector6;
use crate::time::Epoch;
use crate::utils::errors::BraheError;

// =============================================================================
// EcefPositionMeasurementModel
// =============================================================================

/// GNSS position measurement model (ECEF frame).
///
/// Observes 3D position in the Earth-fixed (ECEF)
/// frame. The estimator state is assumed to be in an inertial (ECI) frame;
/// this model internally converts ECI position to ECEF for the measurement
/// prediction.
///
/// Measurement: `z = R_eci2ecef(epoch) · [x, y, z]_eci` (ECEF position)
///
/// The Jacobian is computed via finite differences (default implementation)
/// since the rotation matrix is epoch-dependent.
///
/// # Examples
///
/// ```no_run
/// use brahe::estimation::{EcefPositionMeasurementModel, MeasurementModel};
///
/// // Isotropic 5m noise (typical GNSS accuracy)
/// let model = EcefPositionMeasurementModel::new(5.0);
/// assert_eq!(model.measurement_dim(), 3);
/// ```
#[derive(Clone, Debug)]
pub struct EcefPositionMeasurementModel {
    noise_cov: DMatrix<f64>,
}

impl EcefPositionMeasurementModel {
    /// Create an ECEF position model with isotropic noise.
    ///
    /// # Arguments
    ///
    /// * `sigma` - Position noise standard deviation (meters), applied to all axes
    pub fn new(sigma: f64) -> Self {
        Self {
            noise_cov: isotropic_covariance(3, sigma),
        }
    }

    /// Create an ECEF position model with per-axis noise.
    ///
    /// # Arguments
    ///
    /// * `sigma_x` - X-axis position noise standard deviation (meters)
    /// * `sigma_y` - Y-axis position noise standard deviation (meters)
    /// * `sigma_z` - Z-axis position noise standard deviation (meters)
    pub fn new_per_axis(sigma_x: f64, sigma_y: f64, sigma_z: f64) -> Self {
        Self {
            noise_cov: diagonal_covariance(&[sigma_x, sigma_y, sigma_z]),
        }
    }

    /// Create an ECEF position model from a full 3×3 noise covariance matrix.
    ///
    /// # Arguments
    ///
    /// * `noise_cov` - 3×3 noise covariance matrix (meters²)
    pub fn from_covariance(noise_cov: DMatrix<f64>) -> Result<Self, BraheError> {
        let cov = validate_covariance(noise_cov)?;
        if cov.nrows() != 3 {
            return Err(BraheError::Error(format!(
                "EcefPositionMeasurementModel requires 3x3 covariance, got {}x{}",
                cov.nrows(),
                cov.ncols()
            )));
        }
        Ok(Self { noise_cov: cov })
    }

    /// Create an ECEF position model from upper-triangular covariance elements.
    ///
    /// Elements are in row-major packed order: `[c₀₀, c₀₁, c₀₂, c₁₁, c₁₂, c₂₂]`
    /// (6 elements for a 3×3 matrix).
    ///
    /// # Arguments
    ///
    /// * `upper` - Upper-triangular elements in row-major packed order (meters²)
    pub fn from_upper_triangular(upper: &[f64]) -> Result<Self, BraheError> {
        Ok(Self {
            noise_cov: covariance_from_upper_triangular(3, upper)?,
        })
    }
}

impl MeasurementModel for EcefPositionMeasurementModel {
    fn predict(
        &self,
        epoch: &Epoch,
        state: &DVector<f64>,
        _params: Option<&DVector<f64>>,
    ) -> Result<DVector<f64>, BraheError> {
        if state.len() < 3 {
            return Err(BraheError::Error(format!(
                "EcefPositionMeasurementModel requires state dimension >= 3, got {}",
                state.len()
            )));
        }

        // Extract ECI position and convert to ECEF
        let pos_eci = nalgebra::Vector3::new(state[0], state[1], state[2]);
        let pos_ecef = position_eci_to_ecef(*epoch, pos_eci);

        Ok(DVector::from_vec(vec![
            pos_ecef[0],
            pos_ecef[1],
            pos_ecef[2],
        ]))
    }

    // Uses default finite-difference Jacobian since ECI→ECEF rotation is epoch-dependent

    fn noise_covariance(&self) -> DMatrix<f64> {
        self.noise_cov.clone()
    }

    fn measurement_dim(&self) -> usize {
        3
    }

    fn name(&self) -> &str {
        "EcefPosition"
    }
}

// =============================================================================
// EcefVelocityMeasurementModel
// =============================================================================

/// GNSS velocity measurement model (ECEF frame).
///
/// Observes 3D velocity in the Earth-fixed (ECEF)
/// frame. The estimator state is assumed to be in an inertial (ECI) frame;
/// this model internally converts the full ECI state to ECEF (accounting for
/// Earth rotation effects on velocity) and extracts the velocity component.
///
/// Measurement: `z = v_ecef` from `state_eci_to_ecef(epoch, [x,y,z,vx,vy,vz])`
///
/// # Examples
///
/// ```no_run
/// use brahe::estimation::{EcefVelocityMeasurementModel, MeasurementModel};
///
/// // Isotropic 0.05 m/s noise
/// let model = EcefVelocityMeasurementModel::new(0.05);
/// assert_eq!(model.measurement_dim(), 3);
/// ```
#[derive(Clone, Debug)]
pub struct EcefVelocityMeasurementModel {
    noise_cov: DMatrix<f64>,
}

impl EcefVelocityMeasurementModel {
    /// Create an ECEF velocity model with isotropic noise.
    ///
    /// # Arguments
    ///
    /// * `sigma` - Velocity noise standard deviation (m/s), applied to all axes
    pub fn new(sigma: f64) -> Self {
        Self {
            noise_cov: isotropic_covariance(3, sigma),
        }
    }

    /// Create an ECEF velocity model with per-axis noise.
    ///
    /// # Arguments
    ///
    /// * `sigma_x` - X-axis velocity noise standard deviation (m/s)
    /// * `sigma_y` - Y-axis velocity noise standard deviation (m/s)
    /// * `sigma_z` - Z-axis velocity noise standard deviation (m/s)
    pub fn new_per_axis(sigma_x: f64, sigma_y: f64, sigma_z: f64) -> Self {
        Self {
            noise_cov: diagonal_covariance(&[sigma_x, sigma_y, sigma_z]),
        }
    }

    /// Create an ECEF velocity model from a full 3×3 noise covariance matrix.
    ///
    /// # Arguments
    ///
    /// * `noise_cov` - 3×3 noise covariance matrix ((m/s)²)
    pub fn from_covariance(noise_cov: DMatrix<f64>) -> Result<Self, BraheError> {
        let cov = validate_covariance(noise_cov)?;
        if cov.nrows() != 3 {
            return Err(BraheError::Error(format!(
                "EcefVelocityMeasurementModel requires 3x3 covariance, got {}x{}",
                cov.nrows(),
                cov.ncols()
            )));
        }
        Ok(Self { noise_cov: cov })
    }

    /// Create an ECEF velocity model from upper-triangular covariance elements.
    ///
    /// Elements are in row-major packed order: `[c₀₀, c₀₁, c₀₂, c₁₁, c₁₂, c₂₂]`
    /// (6 elements for a 3×3 matrix).
    ///
    /// # Arguments
    ///
    /// * `upper` - Upper-triangular elements in row-major packed order ((m/s)²)
    pub fn from_upper_triangular(upper: &[f64]) -> Result<Self, BraheError> {
        Ok(Self {
            noise_cov: covariance_from_upper_triangular(3, upper)?,
        })
    }
}

impl MeasurementModel for EcefVelocityMeasurementModel {
    fn predict(
        &self,
        epoch: &Epoch,
        state: &DVector<f64>,
        _params: Option<&DVector<f64>>,
    ) -> Result<DVector<f64>, BraheError> {
        if state.len() < 6 {
            return Err(BraheError::Error(format!(
                "EcefVelocityMeasurementModel requires state dimension >= 6, got {}",
                state.len()
            )));
        }

        // Convert full ECI state to ECEF (velocity conversion requires position + velocity)
        let state_eci = SVector6::new(state[0], state[1], state[2], state[3], state[4], state[5]);
        let state_ecef = state_eci_to_ecef(*epoch, state_eci);

        Ok(DVector::from_vec(vec![
            state_ecef[3],
            state_ecef[4],
            state_ecef[5],
        ]))
    }

    // Uses default finite-difference Jacobian

    fn noise_covariance(&self) -> DMatrix<f64> {
        self.noise_cov.clone()
    }

    fn measurement_dim(&self) -> usize {
        3
    }

    fn name(&self) -> &str {
        "EcefVelocity"
    }
}

// =============================================================================
// EcefStateMeasurementModel
// =============================================================================

/// GNSS state measurement model (ECEF frame, position + velocity).
///
/// Observes full 6D state (position and velocity)
/// in the Earth-fixed (ECEF) frame. The estimator state is assumed to be in
/// an inertial (ECI) frame; this model internally converts the full ECI state
/// to ECEF.
///
/// Measurement: `z = state_eci_to_ecef(epoch, [x,y,z,vx,vy,vz])`
///
/// # Examples
///
/// ```no_run
/// use brahe::estimation::{EcefStateMeasurementModel, MeasurementModel};
///
/// // 5m position noise, 0.05 m/s velocity noise
/// let model = EcefStateMeasurementModel::new(5.0, 0.05);
/// assert_eq!(model.measurement_dim(), 6);
/// ```
#[derive(Clone, Debug)]
pub struct EcefStateMeasurementModel {
    noise_cov: DMatrix<f64>,
}

impl EcefStateMeasurementModel {
    /// Create an ECEF state model with isotropic noise per component type.
    ///
    /// # Arguments
    ///
    /// * `pos_sigma` - Position noise standard deviation (meters)
    /// * `vel_sigma` - Velocity noise standard deviation (m/s)
    pub fn new(pos_sigma: f64, vel_sigma: f64) -> Self {
        Self::new_per_axis(
            pos_sigma, pos_sigma, pos_sigma, vel_sigma, vel_sigma, vel_sigma,
        )
    }

    /// Create an ECEF state model with per-axis noise.
    ///
    /// # Arguments
    ///
    /// * `pos_sigma_x` - X-axis position noise (meters)
    /// * `pos_sigma_y` - Y-axis position noise (meters)
    /// * `pos_sigma_z` - Z-axis position noise (meters)
    /// * `vel_sigma_x` - X-axis velocity noise (m/s)
    /// * `vel_sigma_y` - Y-axis velocity noise (m/s)
    /// * `vel_sigma_z` - Z-axis velocity noise (m/s)
    pub fn new_per_axis(
        pos_sigma_x: f64,
        pos_sigma_y: f64,
        pos_sigma_z: f64,
        vel_sigma_x: f64,
        vel_sigma_y: f64,
        vel_sigma_z: f64,
    ) -> Self {
        Self {
            noise_cov: diagonal_covariance(&[
                pos_sigma_x,
                pos_sigma_y,
                pos_sigma_z,
                vel_sigma_x,
                vel_sigma_y,
                vel_sigma_z,
            ]),
        }
    }

    /// Create an ECEF state model from a full 6×6 noise covariance matrix.
    ///
    /// # Arguments
    ///
    /// * `noise_cov` - 6×6 noise covariance matrix
    pub fn from_covariance(noise_cov: DMatrix<f64>) -> Result<Self, BraheError> {
        let cov = validate_covariance(noise_cov)?;
        if cov.nrows() != 6 {
            return Err(BraheError::Error(format!(
                "EcefStateMeasurementModel requires 6x6 covariance, got {}x{}",
                cov.nrows(),
                cov.ncols()
            )));
        }
        Ok(Self { noise_cov: cov })
    }

    /// Create an ECEF state model from upper-triangular covariance elements.
    ///
    /// Elements are in row-major packed order (21 elements for a 6×6 matrix).
    ///
    /// # Arguments
    ///
    /// * `upper` - Upper-triangular elements in row-major packed order
    pub fn from_upper_triangular(upper: &[f64]) -> Result<Self, BraheError> {
        Ok(Self {
            noise_cov: covariance_from_upper_triangular(6, upper)?,
        })
    }
}

impl MeasurementModel for EcefStateMeasurementModel {
    fn predict(
        &self,
        epoch: &Epoch,
        state: &DVector<f64>,
        _params: Option<&DVector<f64>>,
    ) -> Result<DVector<f64>, BraheError> {
        if state.len() < 6 {
            return Err(BraheError::Error(format!(
                "EcefStateMeasurementModel requires state dimension >= 6, got {}",
                state.len()
            )));
        }

        let state_eci = SVector6::new(state[0], state[1], state[2], state[3], state[4], state[5]);
        let state_ecef = state_eci_to_ecef(*epoch, state_eci);

        Ok(DVector::from_iterator(6, state_ecef.iter().copied()))
    }

    // Uses default finite-difference Jacobian

    fn noise_covariance(&self) -> DMatrix<f64> {
        self.noise_cov.clone()
    }

    fn measurement_dim(&self) -> usize {
        6
    }

    fn name(&self) -> &str {
        "EcefState"
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::eop::{EOPExtrapolation, FileEOPProvider, set_global_eop_provider};
    use crate::frames::{position_eci_to_ecef, state_eci_to_ecef};
    use crate::time::TimeSystem;
    use approx::assert_abs_diff_eq;
    use serial_test::serial;

    fn setup_global_test_eop() {
        let eop = FileEOPProvider::from_default_standard(true, EOPExtrapolation::Hold).unwrap();
        set_global_eop_provider(eop);
    }

    fn test_epoch() -> Epoch {
        Epoch::from_datetime(2024, 1, 1, 0, 0, 0.0, 0.0, TimeSystem::UTC)
    }

    /// A 6D ECI state for a LEO orbit (r ≈ 6878 km, circular)
    fn test_eci_state() -> DVector<f64> {
        let r = 6878.0e3;
        let v = (crate::constants::physical::GM_EARTH / r).sqrt();
        DVector::from_vec(vec![r, 0.0, 0.0, 0.0, v, 0.0])
    }

    // =========================================================================
    // Position model tests
    // =========================================================================

    #[test]
    fn test_ecef_position_model_constructors() {
        // Isotropic
        let m = EcefPositionMeasurementModel::new(5.0);
        assert_eq!(m.measurement_dim(), 3);
        assert_eq!(m.name(), "EcefPosition");
        let r = m.noise_covariance();
        assert_eq!(r.nrows(), 3);
        assert_abs_diff_eq!(r[(0, 0)], 25.0, epsilon = 1e-12);
        assert_abs_diff_eq!(r[(1, 1)], 25.0, epsilon = 1e-12);
        assert_abs_diff_eq!(r[(0, 1)], 0.0, epsilon = 1e-12);

        // Per-axis
        let m = EcefPositionMeasurementModel::new_per_axis(1.0, 2.0, 3.0);
        let r = m.noise_covariance();
        assert_abs_diff_eq!(r[(0, 0)], 1.0, epsilon = 1e-12);
        assert_abs_diff_eq!(r[(1, 1)], 4.0, epsilon = 1e-12);
        assert_abs_diff_eq!(r[(2, 2)], 9.0, epsilon = 1e-12);

        // From covariance
        let cov = DMatrix::from_diagonal(&DVector::from_vec(vec![4.0, 9.0, 16.0]));
        let m = EcefPositionMeasurementModel::from_covariance(cov).unwrap();
        let r = m.noise_covariance();
        assert_abs_diff_eq!(r[(0, 0)], 4.0, epsilon = 1e-12);

        // From upper triangular
        let m =
            EcefPositionMeasurementModel::from_upper_triangular(&[4.0, 0.0, 0.0, 9.0, 0.0, 16.0])
                .unwrap();
        let r = m.noise_covariance();
        assert_abs_diff_eq!(r[(2, 2)], 16.0, epsilon = 1e-12);
    }

    #[test]
    #[serial]
    fn test_ecef_position_model_predict() {
        setup_global_test_eop();
        let epoch = test_epoch();
        let state = test_eci_state();

        let model = EcefPositionMeasurementModel::new(5.0);
        let z = model.predict(&epoch, &state, None).unwrap();
        assert_eq!(z.len(), 3);

        // Verify against direct frame conversion
        let pos_eci = nalgebra::Vector3::new(state[0], state[1], state[2]);
        let pos_ecef = position_eci_to_ecef(epoch, pos_eci);
        assert_abs_diff_eq!(z[0], pos_ecef[0], epsilon = 1e-6);
        assert_abs_diff_eq!(z[1], pos_ecef[1], epsilon = 1e-6);
        assert_abs_diff_eq!(z[2], pos_ecef[2], epsilon = 1e-6);

        // ECEF position norm should equal ECI position norm (rotation preserves magnitude)
        let eci_norm = pos_eci.norm();
        let ecef_norm = z.norm();
        assert_abs_diff_eq!(eci_norm, ecef_norm, epsilon = 1e-6);
    }

    #[test]
    fn test_ecef_position_model_from_covariance_wrong_dim() {
        // 2x2 instead of 3x3
        let cov = DMatrix::from_diagonal(&DVector::from_vec(vec![1.0, 1.0]));
        let result = EcefPositionMeasurementModel::from_covariance(cov);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("3x3"));
    }

    #[test]
    #[serial]
    fn test_ecef_position_model_jacobian() {
        setup_global_test_eop();
        let epoch = test_epoch();
        let state = test_eci_state();

        let model = EcefPositionMeasurementModel::new(5.0);
        let h = model.jacobian(&epoch, &state, None).unwrap();

        // H should be 3x6 (3 measurement dims, 6 state dims)
        assert_eq!(h.nrows(), 3);
        assert_eq!(h.ncols(), 6);

        // Position columns should be non-zero (rotation matrix entries)
        let pos_block_norm = h.view((0, 0), (3, 3)).norm();
        assert!(
            pos_block_norm > 0.1,
            "Position Jacobian block should be non-zero"
        );

        // Velocity columns should be ~zero (position doesn't depend on velocity)
        let vel_block_norm = h.view((0, 3), (3, 3)).norm();
        assert!(
            vel_block_norm < 1e-6,
            "Velocity Jacobian block should be ~zero, got {}",
            vel_block_norm
        );
    }

    // =========================================================================
    // Velocity model tests
    // =========================================================================

    #[test]
    fn test_ecef_velocity_model_constructors() {
        let m = EcefVelocityMeasurementModel::new(0.05);
        assert_eq!(m.measurement_dim(), 3);
        assert_eq!(m.name(), "EcefVelocity");
        let r = m.noise_covariance();
        assert_abs_diff_eq!(r[(0, 0)], 0.0025, epsilon = 1e-12);

        let m = EcefVelocityMeasurementModel::new_per_axis(0.01, 0.02, 0.03);
        let r = m.noise_covariance();
        assert_abs_diff_eq!(r[(0, 0)], 0.0001, epsilon = 1e-12);
        assert_abs_diff_eq!(r[(1, 1)], 0.0004, epsilon = 1e-12);
        assert_abs_diff_eq!(r[(2, 2)], 0.0009, epsilon = 1e-12);

        let cov = DMatrix::from_diagonal(&DVector::from_vec(vec![0.01, 0.02, 0.03]));
        let m = EcefVelocityMeasurementModel::from_covariance(cov).unwrap();
        assert_abs_diff_eq!(m.noise_covariance()[(2, 2)], 0.03, epsilon = 1e-12);

        let m =
            EcefVelocityMeasurementModel::from_upper_triangular(&[0.01, 0.0, 0.0, 0.02, 0.0, 0.03])
                .unwrap();
        assert_abs_diff_eq!(m.noise_covariance()[(1, 1)], 0.02, epsilon = 1e-12);
    }

    #[test]
    #[serial]
    fn test_ecef_velocity_model_predict() {
        setup_global_test_eop();
        let epoch = test_epoch();
        let state = test_eci_state();

        let model = EcefVelocityMeasurementModel::new(0.05);
        let z = model.predict(&epoch, &state, None).unwrap();
        assert_eq!(z.len(), 3);

        // Verify against direct frame conversion
        let state_eci = SVector6::new(state[0], state[1], state[2], state[3], state[4], state[5]);
        let state_ecef = state_eci_to_ecef(epoch, state_eci);
        assert_abs_diff_eq!(z[0], state_ecef[3], epsilon = 1e-6);
        assert_abs_diff_eq!(z[1], state_ecef[4], epsilon = 1e-6);
        assert_abs_diff_eq!(z[2], state_ecef[5], epsilon = 1e-6);
    }

    #[test]
    fn test_ecef_velocity_model_from_covariance_wrong_dim() {
        let cov = DMatrix::from_diagonal(&DVector::from_vec(vec![1.0; 6]));
        let result = EcefVelocityMeasurementModel::from_covariance(cov);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("3x3"));
    }

    #[test]
    fn test_ecef_velocity_model_predict_short_state_errors() {
        let model = EcefVelocityMeasurementModel::new(0.05);
        let short_state = DVector::from_vec(vec![1.0, 2.0, 3.0]); // only 3 elements
        let epoch = test_epoch();
        let result = model.predict(&epoch, &short_state, None);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains(">= 6"));
    }

    // =========================================================================
    // State model tests
    // =========================================================================

    #[test]
    fn test_ecef_state_model_constructors() {
        let m = EcefStateMeasurementModel::new(5.0, 0.05);
        assert_eq!(m.measurement_dim(), 6);
        assert_eq!(m.name(), "EcefState");
        let r = m.noise_covariance();
        assert_eq!(r.nrows(), 6);
        assert_abs_diff_eq!(r[(0, 0)], 25.0, epsilon = 1e-12);
        assert_abs_diff_eq!(r[(3, 3)], 0.0025, epsilon = 1e-12);

        let m = EcefStateMeasurementModel::new_per_axis(1.0, 2.0, 3.0, 0.1, 0.2, 0.3);
        let r = m.noise_covariance();
        assert_abs_diff_eq!(r[(0, 0)], 1.0, epsilon = 1e-12);
        assert_abs_diff_eq!(r[(5, 5)], 0.09, epsilon = 1e-12);

        let cov = DMatrix::from_diagonal(&DVector::from_vec(vec![1.0; 6]));
        let m = EcefStateMeasurementModel::from_covariance(cov).unwrap();
        assert_eq!(m.noise_covariance().nrows(), 6);

        let upper: Vec<f64> = vec![
            1.0, 0.0, 0.0, 0.0, 0.0, 0.0, // row 0
            1.0, 0.0, 0.0, 0.0, 0.0, // row 1
            1.0, 0.0, 0.0, 0.0, // row 2
            1.0, 0.0, 0.0, // row 3
            1.0, 0.0, // row 4
            1.0, // row 5
        ];
        let m = EcefStateMeasurementModel::from_upper_triangular(&upper).unwrap();
        assert_eq!(m.noise_covariance().nrows(), 6);
    }

    #[test]
    #[serial]
    fn test_ecef_state_model_predict() {
        setup_global_test_eop();
        let epoch = test_epoch();
        let state = test_eci_state();

        let model = EcefStateMeasurementModel::new(5.0, 0.05);
        let z = model.predict(&epoch, &state, None).unwrap();
        assert_eq!(z.len(), 6);

        // Verify against direct frame conversion
        let state_eci = SVector6::new(state[0], state[1], state[2], state[3], state[4], state[5]);
        let state_ecef = state_eci_to_ecef(epoch, state_eci);
        for i in 0..6 {
            assert_abs_diff_eq!(z[i], state_ecef[i], epsilon = 1e-6);
        }
    }

    #[test]
    fn test_ecef_state_model_from_covariance_wrong_dim() {
        let cov = DMatrix::from_diagonal(&DVector::from_vec(vec![1.0; 3]));
        let result = EcefStateMeasurementModel::from_covariance(cov);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("6x6"));
    }

    #[test]
    fn test_ecef_state_model_predict_short_state_errors() {
        let model = EcefStateMeasurementModel::new(5.0, 0.05);
        let short_state = DVector::from_vec(vec![1.0, 2.0, 3.0]); // only 3 elements
        let epoch = test_epoch();
        let result = model.predict(&epoch, &short_state, None);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains(">= 6"));
    }
}