brahe 1.3.4

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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
/*
 * Python bindings for the Jacobian computation module.
 *
 * Provides numerical and analytical Jacobian providers for dynamic-sized systems.
 */


// ============================================================================
// Enums
// ============================================================================

/// Finite difference method for numerical Jacobian approximation.
///
/// Different methods trade off accuracy vs computational cost:
/// - **Forward**: O(h) error, dimension+1 function evaluations
/// - **Central**: O(h²) error, 2*dimension function evaluations (more accurate)
/// - **Backward**: O(h) error, dimension+1 function evaluations
///
/// Example:
///     ```python
///     import brahe as bh
///
///     # Use central differences (most accurate)
///     jacobian = bh.NumericalJacobian.central(dynamics_fn)
///
///     # Or explicitly set the method
///     jacobian = bh.NumericalJacobian.new(dynamics_fn).with_method(bh.DifferenceMethod.CENTRAL)
///     ```
#[pyclass(module = "brahe._brahe", from_py_object)]
#[pyo3(name = "DifferenceMethod")]
#[derive(Clone)]
pub struct PyDifferenceMethod {
    pub(crate) value: jacobian::DifferenceMethod,
}

#[pymethods]
impl PyDifferenceMethod {
    /// Forward finite difference: df/dx ≈ (f(x+h) - f(x)) / h
    ///
    /// First-order accurate but cheaper (dimension+1 evaluations).
    #[classattr]
    #[allow(non_snake_case)]
    fn FORWARD() -> Self {
        PyDifferenceMethod {
            value: jacobian::DifferenceMethod::Forward,
        }
    }

    /// Central finite difference: df/dx ≈ (f(x+h) - f(x-h)) / (2h)
    ///
    /// Second-order accurate but more expensive (2*dimension evaluations).
    /// Generally preferred for high-precision applications.
    #[classattr]
    #[allow(non_snake_case)]
    fn CENTRAL() -> Self {
        PyDifferenceMethod {
            value: jacobian::DifferenceMethod::Central,
        }
    }

    /// Backward finite difference: df/dx ≈ (f(x) - f(x-h)) / h
    ///
    /// First-order accurate, same cost as forward differences (dimension+1 evaluations).
    /// Useful when forward perturbations are problematic.
    #[classattr]
    #[allow(non_snake_case)]
    fn BACKWARD() -> Self {
        PyDifferenceMethod {
            value: jacobian::DifferenceMethod::Backward,
        }
    }

    fn __str__(&self) -> String {
        format!("{:?}", self.value)
    }

    fn __repr__(&self) -> String {
        format!("DifferenceMethod.{:?}", self.value)
    }

    fn __richcmp__(&self, other: &Self, op: CompareOp) -> PyResult<bool> {
        match op {
            CompareOp::Eq => Ok(self.value == other.value),
            CompareOp::Ne => Ok(self.value != other.value),
            _ => Err(pyo3::exceptions::PyNotImplementedError::new_err(
                "Only == and != are supported for DifferenceMethod",
            )),
        }
    }
}

/// Strategy for computing perturbation sizes in finite differences.
///
/// The choice of perturbation size balances truncation error (wants large h)
/// vs roundoff error (wants small h). Different strategies suit different problems.
///
/// Example:
///     ```python
///     import brahe as bh
///
///     # Adaptive perturbation (recommended for most cases)
///     jacobian = bh.NumericalJacobian.new(dynamics_fn).with_adaptive(1.0, 1.0)
///
///     # Fixed absolute perturbation for all components
///     jacobian = bh.NumericalJacobian.new(dynamics_fn).with_fixed_offset(1e-6)
///
///     # Percentage-based perturbation
///     jacobian = bh.NumericalJacobian.new(dynamics_fn).with_percentage(1e-6)
///     ```
#[pyclass(module = "brahe._brahe", from_py_object)]
#[pyo3(name = "PerturbationStrategy")]
#[derive(Clone)]
pub struct PyPerturbationStrategy {
    pub(crate) value: jacobian::PerturbationStrategy,
}

#[pymethods]
impl PyPerturbationStrategy {
    /// Create an adaptive perturbation strategy.
    ///
    /// Args:
    ///     scale_factor (float): Multiplier on sqrt(ε), typically 1.0
    ///     min_value (float): Minimum reference value (prevents tiny perturbations near zero)
    ///
    /// Returns:
    ///     PerturbationStrategy: Adaptive perturbation strategy
    #[classmethod]
    #[pyo3(signature = (scale_factor=1.0, min_value=1.0))]
    fn adaptive(
        _cls: &Bound<'_, pyo3::types::PyType>,
        scale_factor: f64,
        min_value: f64,
    ) -> Self {
        PyPerturbationStrategy {
            value: jacobian::PerturbationStrategy::Adaptive {
                scale_factor,
                min_value,
            },
        }
    }

    /// Create a fixed absolute perturbation strategy.
    ///
    /// Args:
    ///     offset (float): Fixed perturbation for all state components
    ///
    /// Returns:
    ///     PerturbationStrategy: Fixed perturbation strategy
    #[classmethod]
    fn fixed(_cls: &Bound<'_, pyo3::types::PyType>, offset: f64) -> Self {
        PyPerturbationStrategy {
            value: jacobian::PerturbationStrategy::Fixed(offset),
        }
    }

    /// Create a percentage-based perturbation strategy.
    ///
    /// Args:
    ///     percentage (float): Percentage of state value to use as perturbation
    ///
    /// Returns:
    ///     PerturbationStrategy: Percentage perturbation strategy
    #[classmethod]
    fn percentage(_cls: &Bound<'_, pyo3::types::PyType>, percentage: f64) -> Self {
        PyPerturbationStrategy {
            value: jacobian::PerturbationStrategy::Percentage(percentage),
        }
    }

    fn __str__(&self) -> String {
        match self.value {
            jacobian::PerturbationStrategy::Adaptive {
                scale_factor,
                min_value,
            } => format!("Adaptive({}, {})", scale_factor, min_value),
            jacobian::PerturbationStrategy::Fixed(offset) => format!("Fixed({})", offset),
            jacobian::PerturbationStrategy::Percentage(pct) => format!("Percentage({})", pct),
        }
    }

    fn __repr__(&self) -> String {
        format!("PerturbationStrategy.{}", self.__str__())
    }
}

// ============================================================================
// Numerical Jacobian Provider
// ============================================================================

/// Numerical Jacobian provider for dynamic-sized systems using finite differences.
///
/// Computes the Jacobian numerically by perturbing the state and evaluating the dynamics.
/// Supports forward, central, and backward finite difference methods with various
/// perturbation strategies.
///
/// Example:
///     ```python
///     import brahe as bh
///     import numpy as np
///
///     # Simple harmonic oscillator dynamics
///     def dynamics(t, state):
///         return np.array([state[1], -state[0]])
///
///     # Default: central differences with adaptive perturbations
///     jacobian = bh.NumericalJacobian.new(dynamics)
///
///     # Or with custom settings:
///     jacobian = bh.NumericalJacobian.forward(dynamics).with_fixed_offset(1e-6)
///
///     state = np.array([1.0, 0.0])
///     jac_matrix = jacobian.compute(0.0, state)
///     print(jac_matrix)  # [[0, 1], [-1, 0]] approximately
///     ```
#[pyclass(module = "brahe._brahe")]
#[pyo3(name = "NumericalJacobian")]
pub struct PyDNumericalJacobian {
    /// Store the Python callable (dynamics function)
    dynamics_fn: Py<PyAny>,
    method: jacobian::DifferenceMethod,
    perturbation: jacobian::PerturbationStrategy,
}

#[pymethods]
impl PyDNumericalJacobian {
    /// Create a numerical Jacobian provider with default settings.
    ///
    /// Default: central differences with adaptive perturbations.
    ///
    /// Args:
    ///     dynamics_fn (callable): Function with signature (t: float, state: ndarray) -> ndarray
    ///
    /// Returns:
    ///     NumericalJacobian: New numerical Jacobian provider
    ///
    /// Example:
    ///     ```python
    ///     import brahe as bh
    ///     import numpy as np
    ///
    ///     def dynamics(t, state):
    ///         return np.array([state[1], -state[0]])
    ///
    ///     jacobian = bh.NumericalJacobian.new(dynamics)
    ///     ```
    #[new]
    pub fn new(dynamics_fn: Py<PyAny>) -> Self {
        Self {
            dynamics_fn,
            method: jacobian::DifferenceMethod::Central,
            perturbation: jacobian::PerturbationStrategy::Adaptive {
                scale_factor: 1.0,
                min_value: 1.0,
            },
        }
    }

    /// Create with forward finite differences.
    ///
    /// Args:
    ///     dynamics_fn (callable): Function with signature (t: float, state: ndarray) -> ndarray
    ///
    /// Returns:
    ///     NumericalJacobian: Jacobian provider using forward differences
    #[classmethod]
    pub fn forward(_cls: &Bound<'_, pyo3::types::PyType>, dynamics_fn: Py<PyAny>) -> Self {
        Self {
            dynamics_fn,
            method: jacobian::DifferenceMethod::Forward,
            perturbation: jacobian::PerturbationStrategy::Adaptive {
                scale_factor: 1.0,
                min_value: 1.0,
            },
        }
    }

    /// Create with central finite differences.
    ///
    /// Args:
    ///     dynamics_fn (callable): Function with signature (t: float, state: ndarray) -> ndarray
    ///
    /// Returns:
    ///     NumericalJacobian: Jacobian provider using central differences
    #[classmethod]
    pub fn central(_cls: &Bound<'_, pyo3::types::PyType>, dynamics_fn: Py<PyAny>) -> Self {
        Self::new(dynamics_fn)
    }

    /// Create with backward finite differences.
    ///
    /// Args:
    ///     dynamics_fn (callable): Function with signature (t: float, state: ndarray) -> ndarray
    ///
    /// Returns:
    ///     NumericalJacobian: Jacobian provider using backward differences
    #[classmethod]
    pub fn backward(_cls: &Bound<'_, pyo3::types::PyType>, dynamics_fn: Py<PyAny>) -> Self {
        Self {
            dynamics_fn,
            method: jacobian::DifferenceMethod::Backward,
            perturbation: jacobian::PerturbationStrategy::Adaptive {
                scale_factor: 1.0,
                min_value: 1.0,
            },
        }
    }

    /// Set fixed absolute perturbation for all components.
    ///
    /// Args:
    ///     offset (float): Fixed perturbation size
    ///
    /// Returns:
    ///     NumericalJacobian: Self for method chaining
    pub fn with_fixed_offset(mut slf: PyRefMut<'_, Self>, offset: f64) -> PyRefMut<'_, Self> {
        slf.perturbation = jacobian::PerturbationStrategy::Fixed(offset);
        slf
    }

    /// Set percentage-based perturbation.
    ///
    /// Args:
    ///     percentage (float): Percentage of state value (e.g., 1e-6 for 0.0001%)
    ///
    /// Returns:
    ///     NumericalJacobian: Self for method chaining
    pub fn with_percentage(mut slf: PyRefMut<'_, Self>, percentage: f64) -> PyRefMut<'_, Self> {
        slf.perturbation = jacobian::PerturbationStrategy::Percentage(percentage);
        slf
    }

    /// Set adaptive perturbation with custom parameters.
    ///
    /// Args:
    ///     scale_factor (float): Multiplier on sqrt(ε), typically 1.0
    ///     min_value (float): Minimum reference value
    ///
    /// Returns:
    ///     NumericalJacobian: Self for method chaining
    pub fn with_adaptive(
        mut slf: PyRefMut<'_, Self>,
        scale_factor: f64,
        min_value: f64,
    ) -> PyRefMut<'_, Self> {
        slf.perturbation = jacobian::PerturbationStrategy::Adaptive {
            scale_factor,
            min_value,
        };
        slf
    }

    /// Set the difference method.
    ///
    /// Args:
    ///     method (DifferenceMethod): Finite difference method to use
    ///
    /// Returns:
    ///     NumericalJacobian: Self for method chaining
    pub fn with_method(
        mut slf: PyRefMut<'_, Self>,
        method: PyDifferenceMethod,
    ) -> PyRefMut<'_, Self> {
        slf.method = method.value;
        slf
    }

    /// Compute the Jacobian matrix at the given time and state.
    ///
    /// Args:
    ///     t (float): Current time
    ///     state (ndarray): State vector at time t
    ///
    /// Returns:
    ///     ndarray: Jacobian matrix ∂f/∂x (dimension × dimension)
    ///
    /// Example:
    ///     ```python
    ///     import brahe as bh
    ///     import numpy as np
    ///
    ///     def dynamics(t, state):
    ///         return np.array([state[1], -state[0]])
    ///
    ///     jacobian = bh.NumericalJacobian.new(dynamics)
    ///     state = np.array([1.0, 0.5])
    ///     jac = jacobian.compute(0.0, state)
    ///     # Expected: [[0, 1], [-1, 0]] approximately
    ///     ```
    #[allow(deprecated)]
    pub fn compute<'py>(
        &self,
        py: Python<'py>,
        t: f64,
        state: &Bound<'py, PyAny>,
    ) -> PyResult<Bound<'py, PyArray<f64, numpy::Ix2>>> {
        // Convert Python state to DVector
        let state_vec = pyany_to_f64_array1(state, None)?;
        let dimension = state_vec.len();
        let state_dvec = DVector::from_vec(state_vec);

        // Create a Rust closure that calls the Python function
        let dynamics_closure = {
            let dynamics_fn_clone = self.dynamics_fn.clone_ref(py);
            move |t: f64, state: &DVector<f64>, _params: Option<&DVector<f64>>| -> DVector<f64> {
                Python::attach(|py| {
                    // Convert state to NumPy array
                    let state_py = state.as_slice().to_pyarray(py);

                // Call Python function
                let result = dynamics_fn_clone
                    .call1(py, (t, state_py))
                    .expect("Failed to call dynamics function");

                    // Convert result back to DVector
                    let result_vec = pyany_to_f64_array1(result.bind(py), Some(dimension))
                        .expect("Dynamics function returned invalid array");
                    DVector::from_vec(result_vec)
                })
            }
        };

        // Create Rust numerical Jacobian provider
        let mut provider = match self.method {
            jacobian::DifferenceMethod::Forward => {
                jacobian::DNumericalJacobian::forward(Box::new(dynamics_closure))
            }
            jacobian::DifferenceMethod::Central => {
                jacobian::DNumericalJacobian::central(Box::new(dynamics_closure))
            }
            jacobian::DifferenceMethod::Backward => {
                jacobian::DNumericalJacobian::backward(Box::new(dynamics_closure))
            }
        };

        // Apply perturbation strategy
        provider = match self.perturbation {
            jacobian::PerturbationStrategy::Adaptive {
                scale_factor,
                min_value,
            } => provider.with_adaptive(scale_factor, min_value),
            jacobian::PerturbationStrategy::Fixed(offset) => provider.with_fixed_offset(offset),
            jacobian::PerturbationStrategy::Percentage(pct) => provider.with_percentage(pct),
        };

        // Compute Jacobian
        let jac_matrix = provider.compute(t, &state_dvec, None);

        // Convert DMatrix to NumPy 2D array (row-major order)
        let rows = jac_matrix.nrows();
        let cols = jac_matrix.ncols();
        let mut flat_vec = Vec::with_capacity(rows * cols);
        for i in 0..rows {
            for j in 0..cols {
                flat_vec.push(jac_matrix[(i, j)]);
            }
        }

        flat_vec.into_pyarray(py).reshape([rows, cols])
    }
}

// ============================================================================
// Analytical Jacobian Provider
// ============================================================================

/// Analytical Jacobian provider for dynamic-sized systems.
///
/// Uses a user-provided function that directly computes the analytical Jacobian.
/// This is the most accurate and efficient method when the analytical Jacobian is known.
///
/// Example:
///     ```python
///     import brahe as bh
///     import numpy as np
///
///     # Simple harmonic oscillator: dx/dt = v, dv/dt = -x
///     # Jacobian is [[0, 1], [-1, 0]]
///     def jacobian_fn(t, state):
///         return np.array([[0.0, 1.0], [-1.0, 0.0]])
///
///     jacobian = bh.AnalyticJacobian.new(jacobian_fn)
///     state = np.array([1.0, 0.0])
///     jac = jacobian.compute(0.0, state)
///     print(jac)  # [[0, 1], [-1, 0]]
///     ```
#[pyclass(module = "brahe._brahe")]
#[pyo3(name = "AnalyticJacobian")]
pub struct PyDAnalyticJacobian {
    /// Store the Python callable (Jacobian function)
    jacobian_fn: Py<PyAny>,
}

#[pymethods]
impl PyDAnalyticJacobian {
    /// Create a new analytical Jacobian provider.
    ///
    /// Args:
    ///     jacobian_fn (callable): Function with signature (t: float, state: ndarray) -> ndarray
    ///         Must return a 2D array (dimension × dimension)
    ///
    /// Returns:
    ///     AnalyticJacobian: New analytical Jacobian provider
    ///
    /// Example:
    ///     ```python
    ///     import brahe as bh
    ///     import numpy as np
    ///
    ///     def jacobian_fn(t, state):
    ///         # For harmonic oscillator
    ///         return np.array([[0.0, 1.0], [-1.0, 0.0]])
    ///
    ///     jacobian = bh.AnalyticJacobian.new(jacobian_fn)
    ///     ```
    #[new]
    pub fn new(jacobian_fn: Py<PyAny>) -> Self {
        Self { jacobian_fn }
    }

    /// Compute the Jacobian matrix at the given time and state.
    ///
    /// Args:
    ///     t (float): Current time
    ///     state (ndarray): State vector at time t
    ///
    /// Returns:
    ///     ndarray: Jacobian matrix ∂f/∂x (dimension × dimension)
    ///
    /// Example:
    ///     ```python
    ///     import brahe as bh
    ///     import numpy as np
    ///
    ///     def jacobian_fn(t, state):
    ///         return np.array([[0.0, 1.0], [-1.0, 0.0]])
    ///
    ///     jacobian = bh.AnalyticJacobian.new(jacobian_fn)
    ///     state = np.array([1.0, 0.5])
    ///     jac = jacobian.compute(0.0, state)
    ///     ```
    pub fn compute<'py>(
        &self,
        py: Python<'py>,
        t: f64,
        state: &Bound<'py, PyAny>,
    ) -> PyResult<Bound<'py, PyArray<f64, numpy::Ix2>>> {
        // Convert Python state to DVector
        let state_vec = pyany_to_f64_array1(state, None)?;
        let dimension = state_vec.len();
        let state_py = state_vec.into_pyarray(py);

        // Call Python function
        let result = self.jacobian_fn.call1(py, (t, state_py))?;

        // Convert result to 2D array
        let jac_matrix_vec = pyany_to_f64_array2(result.bind(py), Some((dimension, dimension)))?;

        // Convert to NumPy 2D array (row-major order)
        let flat_vec: Vec<f64> = jac_matrix_vec.into_iter().flatten().collect();

        flat_vec.into_pyarray(py).reshape([dimension, dimension])
    }
}

// ============================================================================
// Sensitivity Providers
// ============================================================================

use crate::math::sensitivity;

/// Numerical sensitivity provider for dynamic-sized systems using finite differences.
///
/// Computes the sensitivity matrix ∂f/∂p numerically by perturbing the parameters
/// and evaluating the dynamics function.
///
/// Example:
///     ```python
///     import brahe as bh
///     import numpy as np
///
///     # Dynamics with consider parameters
///     def dynamics(t, state, params):
///         cd_area_m = params[0]
///         # ... compute derivatives using cd_area_m
///         return np.array([...])
///
///     sensitivity = bh.NumericalSensitivity(dynamics)
///     state = np.array([7000e3, 0, 0, 0, 7.5e3, 0])
///     params = np.array([0.044])  # cd*A/m
///     sens_matrix = sensitivity.compute(0.0, state, params)
///     ```
#[pyclass(module = "brahe._brahe")]
#[pyo3(name = "NumericalSensitivity")]
pub struct PyDNumericalSensitivity {
    dynamics_fn: Py<PyAny>,
    method: jacobian::DifferenceMethod,
    perturbation: jacobian::PerturbationStrategy,
}

#[pymethods]
impl PyDNumericalSensitivity {
    /// Create a numerical sensitivity provider with default settings.
    ///
    /// Uses central differences with adaptive perturbation strategy.
    ///
    /// Args:
    ///     dynamics_fn (callable): Function with signature (t: float, state: ndarray, params: ndarray) -> ndarray
    ///
    /// Returns:
    ///     NumericalSensitivity: New numerical sensitivity provider
    #[new]
    pub fn new(dynamics_fn: Py<PyAny>) -> Self {
        Self {
            dynamics_fn,
            method: jacobian::DifferenceMethod::Central,
            perturbation: jacobian::PerturbationStrategy::Adaptive {
                scale_factor: 1.0,
                min_value: 1.0,
            },
        }
    }

    /// Create with forward finite differences.
    ///
    /// Args:
    ///     dynamics_fn (callable): Function with signature (t: float, state: ndarray, params: ndarray) -> ndarray
    ///
    /// Returns:
    ///     NumericalSensitivity: Sensitivity provider using forward differences
    #[classmethod]
    pub fn forward(_cls: &Bound<'_, pyo3::types::PyType>, dynamics_fn: Py<PyAny>) -> Self {
        Self {
            dynamics_fn,
            method: jacobian::DifferenceMethod::Forward,
            perturbation: jacobian::PerturbationStrategy::Adaptive {
                scale_factor: 1.0,
                min_value: 1.0,
            },
        }
    }

    /// Create with central finite differences.
    ///
    /// Args:
    ///     dynamics_fn (callable): Function with signature (t: float, state: ndarray, params: ndarray) -> ndarray
    ///
    /// Returns:
    ///     NumericalSensitivity: Sensitivity provider using central differences
    #[classmethod]
    pub fn central(_cls: &Bound<'_, pyo3::types::PyType>, dynamics_fn: Py<PyAny>) -> Self {
        Self::new(dynamics_fn)
    }

    /// Create with backward finite differences.
    ///
    /// Args:
    ///     dynamics_fn (callable): Function with signature (t: float, state: ndarray, params: ndarray) -> ndarray
    ///
    /// Returns:
    ///     NumericalSensitivity: Sensitivity provider using backward differences
    #[classmethod]
    pub fn backward(_cls: &Bound<'_, pyo3::types::PyType>, dynamics_fn: Py<PyAny>) -> Self {
        Self {
            dynamics_fn,
            method: jacobian::DifferenceMethod::Backward,
            perturbation: jacobian::PerturbationStrategy::Adaptive {
                scale_factor: 1.0,
                min_value: 1.0,
            },
        }
    }

    /// Set fixed absolute perturbation for all parameters.
    ///
    /// Args:
    ///     offset (float): Fixed perturbation size
    ///
    /// Returns:
    ///     NumericalSensitivity: Self for method chaining
    pub fn with_fixed_offset(mut slf: PyRefMut<'_, Self>, offset: f64) -> PyRefMut<'_, Self> {
        slf.perturbation = jacobian::PerturbationStrategy::Fixed(offset);
        slf
    }

    /// Set percentage-based perturbation.
    ///
    /// Args:
    ///     percentage (float): Percentage of parameter value (e.g., 1e-6 for 0.0001%)
    ///
    /// Returns:
    ///     NumericalSensitivity: Self for method chaining
    pub fn with_percentage(mut slf: PyRefMut<'_, Self>, percentage: f64) -> PyRefMut<'_, Self> {
        slf.perturbation = jacobian::PerturbationStrategy::Percentage(percentage);
        slf
    }

    /// Set adaptive perturbation with custom parameters.
    ///
    /// Args:
    ///     scale_factor (float): Multiplier on sqrt(ε), typically 1.0
    ///     min_value (float): Minimum reference value
    ///
    /// Returns:
    ///     NumericalSensitivity: Self for method chaining
    pub fn with_adaptive(
        mut slf: PyRefMut<'_, Self>,
        scale_factor: f64,
        min_value: f64,
    ) -> PyRefMut<'_, Self> {
        slf.perturbation = jacobian::PerturbationStrategy::Adaptive {
            scale_factor,
            min_value,
        };
        slf
    }

    /// Set the difference method.
    ///
    /// Args:
    ///     method (DifferenceMethod): Finite difference method to use
    ///
    /// Returns:
    ///     NumericalSensitivity: Self for method chaining
    pub fn with_method(
        mut slf: PyRefMut<'_, Self>,
        method: PyDifferenceMethod,
    ) -> PyRefMut<'_, Self> {
        slf.method = method.value;
        slf
    }

    /// Compute the sensitivity matrix at the given time, state, and parameters.
    ///
    /// Args:
    ///     t (float): Current time
    ///     state (ndarray): State vector at time t
    ///     params (ndarray): Consider parameters
    ///
    /// Returns:
    ///     ndarray: Sensitivity matrix ∂f/∂p (state_dim × param_dim)
    #[allow(deprecated)]
    pub fn compute<'py>(
        &self,
        py: Python<'py>,
        t: f64,
        state: &Bound<'py, PyAny>,
        params: &Bound<'py, PyAny>,
    ) -> PyResult<Bound<'py, PyArray<f64, numpy::Ix2>>> {
        // Convert Python arrays to vectors
        let state_vec = pyany_to_f64_array1(state, None)?;
        let params_vec = pyany_to_f64_array1(params, None)?;
        let state_dim = state_vec.len();
        let param_dim = params_vec.len();
        let state_dvec = DVector::from_vec(state_vec);
        let params_dvec = DVector::from_vec(params_vec);

        // Create a Rust closure that calls the Python function
        let dynamics_closure = {
            let dynamics_fn_clone = self.dynamics_fn.clone_ref(py);
            move |t: f64, state: &DVector<f64>, params: &DVector<f64>| -> DVector<f64> {
                Python::attach(|py| {
                    let state_py = state.as_slice().to_pyarray(py);
                    let params_py = params.as_slice().to_pyarray(py);

                    let result = dynamics_fn_clone
                        .call1(py, (t, state_py, params_py))
                        .expect("Failed to call dynamics function");

                    let result_vec = pyany_to_f64_array1(result.bind(py), Some(state.len()))
                        .expect("Dynamics function returned invalid array");
                    DVector::from_vec(result_vec)
                })
            }
        };

        // Create Rust numerical sensitivity provider
        let mut provider = match self.method {
            jacobian::DifferenceMethod::Forward => {
                sensitivity::DNumericalSensitivity::forward(Box::new(dynamics_closure))
            }
            jacobian::DifferenceMethod::Central => {
                sensitivity::DNumericalSensitivity::central(Box::new(dynamics_closure))
            }
            jacobian::DifferenceMethod::Backward => {
                sensitivity::DNumericalSensitivity::backward(Box::new(dynamics_closure))
            }
        };

        // Apply perturbation strategy
        provider = match self.perturbation {
            jacobian::PerturbationStrategy::Adaptive {
                scale_factor,
                min_value,
            } => provider.with_strategy(jacobian::PerturbationStrategy::Adaptive {
                scale_factor,
                min_value,
            }),
            jacobian::PerturbationStrategy::Fixed(offset) => {
                provider.with_strategy(jacobian::PerturbationStrategy::Fixed(offset))
            }
            jacobian::PerturbationStrategy::Percentage(pct) => {
                provider.with_strategy(jacobian::PerturbationStrategy::Percentage(pct))
            }
        };

        // Compute sensitivity
        let sens_matrix = provider.compute(t, &state_dvec, &params_dvec);

        // Convert DMatrix to NumPy 2D array
        let rows = sens_matrix.nrows();
        let cols = sens_matrix.ncols();
        let mut flat_vec = Vec::with_capacity(rows * cols);
        for i in 0..rows {
            for j in 0..cols {
                flat_vec.push(sens_matrix[(i, j)]);
            }
        }

        flat_vec.into_pyarray(py).reshape([state_dim, param_dim])
    }
}

/// Analytical sensitivity provider for dynamic-sized systems.
///
/// Uses a user-provided function that directly computes the analytical sensitivity matrix.
///
/// Example:
///     ```python
///     import brahe as bh
///     import numpy as np
///
///     def sensitivity_fn(t, state, params):
///         # Return ∂f/∂p matrix
///         sens = np.zeros((6, 1))
///         # ... compute analytical sensitivity
///         return sens
///
///     sensitivity = bh.AnalyticSensitivity(sensitivity_fn)
///     state = np.array([7000e3, 0, 0, 0, 7.5e3, 0])
///     params = np.array([0.044])
///     sens_matrix = sensitivity.compute(0.0, state, params)
///     ```
#[pyclass(module = "brahe._brahe")]
#[pyo3(name = "AnalyticSensitivity")]
pub struct PyDAnalyticSensitivity {
    sensitivity_fn: Py<PyAny>,
}

#[pymethods]
impl PyDAnalyticSensitivity {
    /// Create a new analytical sensitivity provider.
    ///
    /// Args:
    ///     sensitivity_fn (callable): Function with signature (t: float, state: ndarray, params: ndarray) -> ndarray
    ///         Must return a 2D array (state_dim × param_dim)
    ///
    /// Returns:
    ///     AnalyticSensitivity: New analytical sensitivity provider
    #[new]
    pub fn new(sensitivity_fn: Py<PyAny>) -> Self {
        Self { sensitivity_fn }
    }

    /// Compute the sensitivity matrix at the given time, state, and parameters.
    ///
    /// Args:
    ///     t (float): Current time
    ///     state (ndarray): State vector at time t
    ///     params (ndarray): Consider parameters
    ///
    /// Returns:
    ///     ndarray: Sensitivity matrix ∂f/∂p (state_dim × param_dim)
    pub fn compute<'py>(
        &self,
        py: Python<'py>,
        t: f64,
        state: &Bound<'py, PyAny>,
        params: &Bound<'py, PyAny>,
    ) -> PyResult<Bound<'py, PyArray<f64, numpy::Ix2>>> {
        // Convert Python arrays
        let state_vec = pyany_to_f64_array1(state, None)?;
        let params_vec = pyany_to_f64_array1(params, None)?;
        let state_dim = state_vec.len();
        let param_dim = params_vec.len();
        let state_py = state_vec.into_pyarray(py);
        let params_py = params_vec.into_pyarray(py);

        // Call Python function
        let result = self.sensitivity_fn.call1(py, (t, state_py, params_py))?;

        // Convert result to 2D array
        let sens_matrix_vec = pyany_to_f64_array2(result.bind(py), Some((state_dim, param_dim)))?;

        // Convert to NumPy 2D array
        let flat_vec: Vec<f64> = sens_matrix_vec.into_iter().flatten().collect();

        flat_vec.into_pyarray(py).reshape([state_dim, param_dim])
    }
}