empyrean 0.10.0

Uncertainty-first orbit propagation, ephemeris, orbit determination, and event detection for asteroids and comets, powered by automatic differentiation
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
//! Orbit determination — fit an orbit to ADES astrometric observations.
//!
//! Three entry points sit on [`Context`]:
//! [`Context::determine`] (full IOD → DC pipeline),
//! [`Context::evaluate`] (residuals only, no fit), and
//! [`Context::refine`] (Bayesian update against a prior orbit). All
//! three consume an [`Observations`] set and an [`ODConfig`], and
//! return either a [`DetermineResult`] (fit + diagnostics +
//! acceptability verdict) or an [`EvaluateResult`] (residuals only).
//!
//! For interactive workflows where you want to mask observations and
//! compare fits, see [`Session`](crate::Session).
//!
//! # Example: full pipeline with the production hot path
//!
//! ```no_run
//! use empyrean::{Context, ODConfig};
//!
//! let ctx = Context::from_data_dir(None)?;
//! let obs = ctx.read_ades("apophis_2004_2021.psv")?;
//! let cfg = ODConfig::default(); // VFCC2017 weights + EFCC2020 debias + auto-escalate
//!
//! // `determine` fits every object in the arc; `into_single` unwraps
//! // the one-object case and refuses (naming them) if there are more.
//! let fit = ctx.determine(&obs, None, &cfg)?.into_single()?;
//! println!(
//!     "converged={}, χ²_red={:.2}, fit_acceptable={}",
//!     fit.converged, fit.summary.reduced_chi2, fit.acceptability.fit_acceptable,
//! );
//! # Ok::<(), empyrean::Error>(())
//! ```
//!
//! # Reading the acceptability verdict
//!
//! [`AcceptabilityReport::fit_acceptable`] is the AND of the
//! fit-quality gates (convergence, positive-definite covariance,
//! reduced χ², RMS, AT/CT residual isotropy).
//! [`AcceptabilityReport::extrapolation_acceptable`] is
//! `fit_acceptable` AND the four selection / coverage gates: the
//! fraction of observations the fit retained, the span the *selected*
//! observations still cover, whether the most-recent observations were
//! rejected, and fractional σₐ. Use the first to gate publication; the
//! second to gate forward propagation, ephemeris generation, or
//! impact-risk assessment — and read the individual axes to say *why*
//! a fit did not clear it. Tighten thresholds in
//! [`AcceptabilityThresholds`] for impact-monitoring orbits.
//!
//! # Batches
//!
//! [`Context::determine`] fits every object the observations group
//! into and returns a [`DetermineResults`] table; a failed object is an
//! entry carrying its reason, never a missing one. See that type for
//! iteration, by-object lookup, and the single-object convenience.

mod config;
mod debiasing;
mod nuisance;
mod observation;
mod rejection;
mod result;
mod weighting;

pub use config::{
    AcceptabilityThresholds, AutoEscalationPolicy, IODConfig, ODConfig, PhotometryConfig,
};
pub use debiasing::{DebiasingConfig, DebiasingResolution};
pub use nuisance::StationRaDecConfig;
pub use observation::{Observation, Observations, RadarMeasurement, RadarObservation};
pub use rejection::{RejectionConfig, RejectionKind};
pub use result::{
    AcceptabilityReport, BandStat, CovarianceRepresentation, CovarianceTrust, DetermineEntry,
    DetermineFailure, DetermineFailureKind, DetermineResult, DetermineResults, EvaluateResult,
    GateRecord, MAX_THRUST_SEGMENTS, ObservationResidual, OriginPolicy, OutputEpoch,
    PhotometryModel, PhotometryResult, RadarResidual, RadarResidualKind, RejectionReason,
    ResidualSummary, SolveFor, SolveForParams, SolvedCovariance, SolverStop, StallDelivery,
    StationBias, TrustGateEvent,
};
pub use weighting::{SigmaPolicy, WeightingConfig, WeightingLayer, WeightingPreset};

use std::ffi::CString;

use crate::built_system::BuiltSystem;
use crate::context::Context;
use crate::error::{Error, Result};
use crate::orbit::Orbit;
use crate::propagate::ForceModelTier;

impl Context {
    /// Parse ADES PSV / MPC80 observations from a file path or from the
    /// content itself.
    ///
    /// A string with no newline that names an existing file is read from
    /// disk; anything else is parsed as content. No filename can contain
    /// a newline on POSIX or Windows, so inline multi-line PSV never
    /// reaches the filesystem. This matches the Python `read_ades`
    /// resolution rule exactly.
    pub fn read_ades(&self, path_or_content: &str) -> Result<Observations> {
        let _ = self; // reserved for future context-dependent parsing
        // The C ABI's `empyrean_read_ades` parses content, so a path has
        // to be resolved here. Without this the path string itself is
        // handed to the parser and fails as malformed astrometry.
        let owned;
        let input =
            if !path_or_content.contains('\n') && std::path::Path::new(path_or_content).is_file() {
                owned = std::fs::read_to_string(path_or_content).map_err(|e| {
                    Error::invalid_input(format!("failed to read {path_or_content}: {e}"))
                })?;
                owned.as_str()
            } else {
                path_or_content
            };
        let c_input =
            CString::new(input).map_err(|_| Error::invalid_input("input contains a NUL byte"))?;
        let mut ptr: *mut empyrean_sys::EmpyreanObservation = std::ptr::null_mut();
        let mut num: usize = 0;
        let mut radar_ptr: *mut empyrean_sys::EmpyreanRadarObservation = std::ptr::null_mut();
        let mut radar_num: usize = 0;
        let code = unsafe {
            empyrean_sys::empyrean_read_ades(
                c_input.as_ptr(),
                &mut ptr,
                &mut num,
                &mut radar_ptr,
                &mut radar_num,
            )
        };
        if code != 0 {
            return Err(Error::capture(code));
        }
        Ok(Observations::from_raw_parts(ptr, num, radar_ptr, radar_num))
    }

    /// Run the full orbit-determination pipeline (IOD → differential
    /// correction) over **every object** in `observations`.
    ///
    /// The observations are grouped by ADES object identifier (permID /
    /// provID / trkSub) and each group is fitted independently, so one
    /// call determines a whole batch. The returned
    /// [`DetermineResults`] holds one entry per object, in `object_id`
    /// order, each carrying either the fit or a typed failure — one
    /// object failing never removes the others.
    ///
    /// Fitting a single object is the one-entry case, not a separate
    /// call: use [`DetermineResults::into_single`] to unwrap it, which
    /// refuses (loudly) if the batch turned out to hold more than one.
    ///
    /// Pass `None` for `initial_orbits` to use the internal IOD, or pass
    /// seed orbits to skip IOD and start the differential correction
    /// from the provided states. Seeds that match no observation group
    /// are reported in [`DetermineResults::unmatched_orbit_ids`].
    ///
    /// # Errors
    ///
    /// Returns `Err` only for a batch-level failure — malformed input, or
    /// a configuration the engine rejected before fitting anything. A
    /// batch in which *every* object failed still returns `Ok`: the
    /// per-object failures are the diagnosis, and
    /// [`DetermineResults::all_failed`] reports that state.
    pub fn determine(
        &self,
        observations: &Observations,
        initial_orbits: Option<&[Orbit]>,
        config: &ODConfig,
    ) -> Result<DetermineResults> {
        let mut _orbit_keep: Vec<crate::orbit::OrbitFfiKeep> = Vec::new();
        let ffi_initial: Option<Vec<_>> = match initial_orbits {
            Some(orbs) => {
                _orbit_keep.reserve(orbs.len());
                let v: Vec<_> = orbs
                    .iter()
                    .map(|o| {
                        let (ffi, keep) = o.to_ffi_with_keep()?;
                        _orbit_keep.push(keep);
                        Ok(ffi)
                    })
                    .collect::<Result<Vec<_>>>()?;
                Some(v)
            }
            None => None,
        };
        let (init_ptr, init_len) = match &ffi_initial {
            Some(v) => (v.as_ptr(), v.len()),
            None => (std::ptr::null(), 0),
        };
        let (obs_ptr, obs_len) = observations.as_ffi_slice();
        let (radar_ptr, radar_len) = observations.as_radar_ffi_slice();

        let mut results = empyrean_sys::EmpyreanDetermineResults::default();
        let (ffi_config, _perturbers_keep) = config.to_ffi_with()?;
        let code = unsafe {
            empyrean_sys::empyrean_determine(
                self.as_raw(),
                obs_ptr,
                obs_len,
                radar_ptr,
                radar_len,
                init_ptr,
                init_len,
                &ffi_config,
                &mut results,
            )
        };
        // NONE_DELIVERED still populates (and hands us ownership of) the
        // table; every other nonzero code writes nothing.
        if code != 0 && code != empyrean_sys::EMPYREAN_DETERMINE_NONE_DELIVERED {
            return Err(Error::capture(code));
        }
        let batch = ffi_determine_results_to_rust(&results);
        unsafe { empyrean_sys::empyrean_determine_results_free(&mut results) };
        batch
    }

    /// Evaluate a candidate orbit against observations without fitting.
    pub fn evaluate(
        &self,
        orbit: &Orbit,
        observations: &Observations,
        config: &ODConfig,
    ) -> Result<EvaluateResult> {
        let (ffi_orbit, _orbit_keep) = orbit.to_ffi_with_keep()?;
        let (obs_ptr, obs_len) = observations.as_ffi_slice();

        let mut result = empyrean_sys::EmpyreanEvaluateResult::default();
        let (ffi_config, _perturbers_keep) = config.to_ffi_with()?;
        let code = unsafe {
            empyrean_sys::empyrean_evaluate(
                self.as_raw(),
                &ffi_orbit,
                obs_ptr,
                obs_len,
                &ffi_config,
                &mut result,
            )
        };
        if code != 0 {
            return Err(Error::capture(code));
        }
        let residuals = unsafe {
            std::slice::from_raw_parts(result.observations, result.num_observations)
                .iter()
                .map(ObservationResidual::from_ffi)
                .collect()
        };
        let summary = ResidualSummary::from_ffi(&result.summary);
        unsafe { empyrean_sys::empyrean_evaluate_result_free(&mut result) };

        Ok(EvaluateResult { residuals, summary })
    }

    /// Refine an orbit with observations using a Bayesian prior.
    ///
    /// Requires the input orbit to carry a covariance matrix.
    pub fn refine(
        &self,
        orbit: &Orbit,
        observations: &Observations,
        config: &ODConfig,
    ) -> Result<DetermineResult> {
        let (ffi_orbit, _orbit_keep) = orbit.to_ffi_with_keep()?;
        let (obs_ptr, obs_len) = observations.as_ffi_slice();

        let mut result = empyrean_sys::EmpyreanODResult::default();
        let (ffi_config, _perturbers_keep) = config.to_ffi_with()?;
        let code = unsafe {
            empyrean_sys::empyrean_refine(
                self.as_raw(),
                &ffi_orbit,
                obs_ptr,
                obs_len,
                &ffi_config,
                &mut result,
            )
        };
        if code != 0 {
            return Err(Error::capture(code));
        }
        let det = ffi_od_result_to_rust(&result);
        unsafe { empyrean_sys::empyrean_od_result_free(&mut result) };
        det
    }
}

/// Orbit determination through a pre-built force model.
///
/// The three verbs mirror [`Context::determine`] / [`Context::evaluate`]
/// / [`Context::refine`] argument for argument, with the context passed
/// explicitly because the handle — not the context — is the receiver. A
/// fit through a matching handle is bit-identical to the one-shot; the
/// handle only changes *when* the force model is assembled.
///
/// # Build the handle with [`BuiltSystem::new_for_od`]
///
/// A fit picks its own integration frame and encounter-timescale divisor,
/// and neither is ICRF-shaped: a handle from
/// [`Context::built_system`] with `Frame::ICRF` — which is what every
/// propagation example in this crate builds — is refused here with
/// [`BuiltSystemGuardError::KeyMismatchFrame`](crate::BuiltSystemGuardError::KeyMismatchFrame).
///
/// # The guard refuses; it does not degrade
///
/// A mismatched handle fails the call rather than quietly assembling a
/// per-solve force model. That is deliberate, and it differs from what
/// the engine does with a handle it injected for itself, where a mismatch
/// costs only speed. Here the caller asked to reuse a *specific* frozen
/// force model, and fitting under a different one while reporting success
/// is exactly the silent substitution this crate refuses to make.
/// Classify the axis with
/// [`Error::builtsystem_guard`](crate::Error::builtsystem_guard).
///
/// # `auto_force_model` is refused, not tolerated
///
/// [`ODConfig::auto_force_model`] lets the fit re-pick its own tier
/// part-way through, which no frozen handle can follow: the engine would
/// drop the handle mid-fit and reassemble per solve while the call still
/// returned `Ok`. All three verbs therefore fail with
/// [`BuiltSystemGuardError::ConfigMutatesKey`](crate::BuiltSystemGuardError::ConfigMutatesKey)
/// — its own axis, because nothing about the handle is wrong — and a
/// message naming the field. Clear it and freeze the handle at the tier
/// you want, or drop the handle and use [`Context::determine`], which is
/// free to choose the tier.
impl BuiltSystem {
    /// Run the full orbit-determination pipeline over **every object** in
    /// `observations`, reusing this handle for every fit in the batch.
    ///
    /// Parallels [`Context::determine`]; see it for the batch semantics,
    /// the seeding rules, and what `Err` does and does not mean.
    pub fn determine(
        &self,
        ctx: &Context,
        observations: &Observations,
        initial_orbits: Option<&[Orbit]>,
        config: &ODConfig,
    ) -> Result<DetermineResults> {
        let mut _orbit_keep: Vec<crate::orbit::OrbitFfiKeep> = Vec::new();
        let ffi_initial: Option<Vec<_>> = match initial_orbits {
            Some(orbs) => {
                _orbit_keep.reserve(orbs.len());
                let v: Vec<_> = orbs
                    .iter()
                    .map(|o| {
                        let (ffi, keep) = o.to_ffi_with_keep()?;
                        _orbit_keep.push(keep);
                        Ok(ffi)
                    })
                    .collect::<Result<Vec<_>>>()?;
                Some(v)
            }
            None => None,
        };
        let (init_ptr, init_len) = match &ffi_initial {
            Some(v) => (v.as_ptr(), v.len()),
            None => (std::ptr::null(), 0),
        };
        let (obs_ptr, obs_len) = observations.as_ffi_slice();
        let (radar_ptr, radar_len) = observations.as_radar_ffi_slice();

        let mut results = empyrean_sys::EmpyreanDetermineResults::default();
        let (ffi_config, _perturbers_keep) = config.to_ffi_with()?;
        let code = unsafe {
            empyrean_sys::empyrean_builtsystem_determine(
                self.as_raw(),
                ctx.as_raw(),
                obs_ptr,
                obs_len,
                radar_ptr,
                radar_len,
                init_ptr,
                init_len,
                &ffi_config,
                &mut results,
            )
        };
        // NONE_DELIVERED still populates (and hands us ownership of) the
        // table; every other nonzero code writes nothing.
        if code != 0 && code != empyrean_sys::EMPYREAN_DETERMINE_NONE_DELIVERED {
            return Err(Error::capture(code));
        }
        let batch = ffi_determine_results_to_rust(&results);
        unsafe { empyrean_sys::empyrean_determine_results_free(&mut results) };
        batch
    }

    /// Evaluate a candidate orbit against observations without fitting,
    /// reusing this handle. Parallels [`Context::evaluate`].
    pub fn evaluate(
        &self,
        ctx: &Context,
        orbit: &Orbit,
        observations: &Observations,
        config: &ODConfig,
    ) -> Result<EvaluateResult> {
        let (ffi_orbit, _orbit_keep) = orbit.to_ffi_with_keep()?;
        let (obs_ptr, obs_len) = observations.as_ffi_slice();

        let mut result = empyrean_sys::EmpyreanEvaluateResult::default();
        let (ffi_config, _perturbers_keep) = config.to_ffi_with()?;
        let code = unsafe {
            empyrean_sys::empyrean_builtsystem_evaluate(
                self.as_raw(),
                ctx.as_raw(),
                &ffi_orbit,
                obs_ptr,
                obs_len,
                &ffi_config,
                &mut result,
            )
        };
        if code != 0 {
            return Err(Error::capture(code));
        }
        let residuals = unsafe {
            std::slice::from_raw_parts(result.observations, result.num_observations)
                .iter()
                .map(ObservationResidual::from_ffi)
                .collect()
        };
        let summary = ResidualSummary::from_ffi(&result.summary);
        unsafe { empyrean_sys::empyrean_evaluate_result_free(&mut result) };

        Ok(EvaluateResult { residuals, summary })
    }

    /// Refine an orbit with observations using a Bayesian prior, reusing
    /// this handle. Parallels [`Context::refine`], and is the loop this
    /// whole surface exists for: assemble once, refine many.
    pub fn refine(
        &self,
        ctx: &Context,
        orbit: &Orbit,
        observations: &Observations,
        config: &ODConfig,
    ) -> Result<DetermineResult> {
        let (ffi_orbit, _orbit_keep) = orbit.to_ffi_with_keep()?;
        let (obs_ptr, obs_len) = observations.as_ffi_slice();

        let mut result = empyrean_sys::EmpyreanODResult::default();
        let (ffi_config, _perturbers_keep) = config.to_ffi_with()?;
        let code = unsafe {
            empyrean_sys::empyrean_builtsystem_refine(
                self.as_raw(),
                ctx.as_raw(),
                &ffi_orbit,
                obs_ptr,
                obs_len,
                &ffi_config,
                &mut result,
            )
        };
        if code != 0 {
            return Err(Error::capture(code));
        }
        let det = ffi_od_result_to_rust(&result);
        unsafe { empyrean_sys::empyrean_od_result_free(&mut result) };
        det
    }
}

/// Marshal the C-ABI batch table into the owned Rust one.
///
/// Reads every slot — delivered and failed — so no object is dropped on
/// the way across.
fn ffi_determine_results_to_rust(
    results: &empyrean_sys::EmpyreanDetermineResults,
) -> Result<DetermineResults> {
    let slots: &[empyrean_sys::EmpyreanODObjectResult] =
        if results.objects.is_null() || results.num_objects == 0 {
            &[]
        } else {
            unsafe { std::slice::from_raw_parts(results.objects, results.num_objects) }
        };

    let mut entries = Vec::with_capacity(slots.len());
    for slot in slots {
        let object_id = ffi_string(slot.object_id);
        let outcome = if slot.delivered != 0 {
            Ok(ffi_od_result_to_rust(&slot.result)?)
        } else {
            Err(DetermineFailure {
                object_id: object_id.clone(),
                message: ffi_string(slot.error),
                kind: DetermineFailureKind::from_code(slot.error_code),
            })
        };
        entries.push(DetermineEntry { object_id, outcome });
    }

    let unmatched = if results.unmatched_orbit_ids.is_null() || results.num_unmatched_orbit_ids == 0
    {
        Vec::new()
    } else {
        unsafe {
            std::slice::from_raw_parts(results.unmatched_orbit_ids, results.num_unmatched_orbit_ids)
        }
        .iter()
        .map(|p| ffi_string(*p))
        .collect()
    };

    Ok(DetermineResults::new(entries, unmatched))
}

/// An owned `String` from a C-ABI string pointer; empty for null.
fn ffi_string(p: *mut std::ffi::c_char) -> String {
    if p.is_null() {
        String::new()
    } else {
        unsafe { std::ffi::CStr::from_ptr(p) }
            .to_string_lossy()
            .into_owned()
    }
}

/// Internal converter shared with [`crate::session`].
pub(crate) fn ffi_od_result_to_rust_pub(
    result: &empyrean_sys::EmpyreanODResult,
) -> crate::error::Result<DetermineResult> {
    ffi_od_result_to_rust(result)
}

fn ffi_od_result_to_rust(
    result: &empyrean_sys::EmpyreanODResult,
) -> crate::error::Result<DetermineResult> {
    let orbit = ffi_od_result_orbit(result)?;
    let residuals = unsafe {
        std::slice::from_raw_parts(result.observations, result.num_observations)
            .iter()
            .map(ObservationResidual::from_ffi)
            .collect()
    };
    let summary = ResidualSummary::from_ffi(&result.summary);
    let acceptability = AcceptabilityReport::from_ffi(&result.acceptability);
    let force_model_used = match result.force_model_used {
        0 => ForceModelTier::Approximate,
        1 => ForceModelTier::Basic,
        _ => ForceModelTier::Standard,
    };
    let station_biases: Vec<StationBias> =
        if result.station_biases.is_null() || result.num_station_biases == 0 {
            Vec::new()
        } else {
            unsafe {
                std::slice::from_raw_parts(result.station_biases, result.num_station_biases)
                    .iter()
                    .map(StationBias::from_ffi)
                    .collect()
            }
        };
    let solved_covariance = (result.has_solved_covariance != 0)
        .then(|| SolvedCovariance::from_ffi(&result.solved_covariance));
    // Both per-segment arrays are DECLARED-indexed and NaN-filled at a
    // segment the fit did not solve, so `None` is read off the NaN
    // rather than inferred from a count. Pairing a solved-order Δv with
    // a declared-order covariance would attribute a burn's correction to
    // another burn's uncertainty.
    let n_declared = result.n_thrust_segments as usize;
    let thrust_delta_m_per_s: Vec<Option<[f64; 3]>> = result.thrust_delta_m_per_s[..n_declared]
        .iter()
        .map(|dv| dv.iter().all(|v| v.is_finite()).then_some(*dv))
        .collect();
    let thrust_correction_covariances: Vec<Option<[[f64; 3]; 3]>> = result
        .thrust_correction_covariances[..n_declared]
        .iter()
        .map(|m| m.iter().flatten().all(|v| v.is_finite()).then_some(*m))
        .collect();
    // dv_frame is only meaningful when a thrust segment was solved.
    let dv_frame = (n_declared > 0)
        .then(|| crate::coordinate::int_to_frame(result.dv_frame).ok())
        .flatten();
    let dispositions = SolveFor::from_ffi(&result.dispositions)?;
    let warnings: Vec<String> = if result.warnings.is_null() || result.num_warnings == 0 {
        Vec::new()
    } else {
        unsafe { std::slice::from_raw_parts(result.warnings, result.num_warnings) }
            .iter()
            .filter(|p| !p.is_null())
            .map(|p| {
                unsafe { std::ffi::CStr::from_ptr(*p) }
                    .to_string_lossy()
                    .into_owned()
            })
            .collect()
    };
    let photometry =
        (result.has_photometry != 0).then(|| PhotometryResult::from_ffi(&result.photometry));
    let covariance_trust = CovarianceTrust::from_ffi(result);
    Ok(DetermineResult {
        orbit,
        residuals,
        summary,
        iterations: result.iterations,
        update_norm: result.update_norm,
        converged: result.converged != 0,
        covariance: result.covariance,
        covariance_representation: CovarianceRepresentation::from_int(
            result.covariance_representation,
        ),
        covariance_9x9: (result.has_covariance_9x9 != 0).then_some(result.covariance_9x9),
        non_grav_delta: (result.has_non_grav_delta != 0).then_some(result.non_grav_delta),
        rejection_passes: result.rejection_passes,
        num_oppositions_fit: result.num_oppositions_fit,
        force_model_used,
        // Reconstruct the solved axes: an Explicit fit's exact set is
        // recovered from the covariance slot tags, not the coarse code.
        solve_for_used: SolveForParams::from_result(
            result.solve_for_used,
            solved_covariance.as_ref(),
        ),
        acceptability,
        station_biases,
        solved_covariance,
        dt_delta: (result.has_dt_delta != 0).then_some(result.dt_delta),
        amrat_delta: (result.has_amrat_delta != 0).then_some(result.amrat_delta),
        thrust_delta_m_per_s,
        dv_frame,
        photometry,
        covariance_trust,
        thrust_correction_covariances,
        dispositions,
        warnings,
        // NaN is the C ABI's absent marker for these two — exactly NaN,
        // so the reconstruction is `!is_nan()`, the marshal's inverse.
        // (`is_finite()` would silently fold a ±∞ reading into "not
        // reported", which is a real value disappearing.)
        termination: SolverStop::from_int(result.termination),
        gn_step_qnorm: (!result.gn_step_qnorm.is_nan()).then_some(result.gn_step_qnorm),
        mu_final: (!result.mu_final.is_nan()).then_some(result.mu_final),
        accepted_steps: result.accepted_steps,
        final_solve_iterations: (result.final_solve_iterations >= 0)
            .then_some(result.final_solve_iterations as usize),
        stall_delivery: StallDelivery::from_ffi(result),
    })
}

/// Build the re-feedable fitted [`Orbit`] from a C-ABI OD result: the
/// Cartesian state + covariance from `result.orbit`, plus the **absolute**
/// non-gravitational model from `result.non_grav` (when present). This orbit
/// is what `evaluate` / `refine` / `propagate` /
/// `compute_impact_probabilities` accept directly — no reconstruction, no
/// silently-dropped force model.
fn ffi_od_result_orbit(result: &empyrean_sys::EmpyreanODResult) -> crate::error::Result<Orbit> {
    use crate::coordinate::Origin;
    let s = &result.orbit;
    let origin = Origin::from_naif_id(s.origin).ok_or_else(|| {
        Error::invalid_input(format!(
            "C ABI returned unknown NAIF id for origin: {}",
            s.origin
        ))
    })?;
    let frame = crate::coordinate::int_to_frame(s.frame)?;
    let mut state = crate::CoordinateState::cartesian(
        crate::Epoch::from_mjd_tdb(s.epoch_mjd_tdb),
        [s.x, s.y, s.z, s.vx, s.vy, s.vz],
        frame,
        origin,
    );
    // ── The two-convention seam, refused rather than passed through ──
    //
    // The fitted STATE is always Cartesian here — the C layer refuses to
    // flatten anything else. The fitted COVARIANCE is in the fit's
    // `covariance_representation`, and the session path can deliver
    // Keplerian / Cometary / Spherical. Attaching one to the other would
    // produce a `CoordinateState` labelled Cartesian carrying a
    // covariance that is not: not a unit mismatch but a mislabeled
    // matrix, which a re-feed would then propagate as if it were
    // Cartesian.
    //
    // The engine's angular convention differs too — a non-Cartesian
    // fitted covariance comes back in RADIANS, while every covariance
    // this crate accepts on input is in the coordinate's own units
    // (degrees for angular rows). Converting here would need the
    // representation Jacobian, which this layer does not have and must
    // not approximate.
    //
    // So the re-feedable orbit is refused with the remedy named, rather
    // than handed back wrong.
    if s.has_covariance != 0 {
        let rep = result.covariance_representation;
        if rep != empyrean_sys::EMPYREAN_REPRESENTATION_CARTESIAN as i32 {
            return Err(Error::invalid_input(format!(
                "this fit reports its covariance in representation {rep}, not \
                 Cartesian, while its state is Cartesian — the two cannot be \
                 assembled into one re-feedable orbit without the \
                 representation Jacobian, and the non-Cartesian covariance is \
                 additionally in radians rather than the degrees this crate's \
                 inputs use. Re-run the fit with a Cartesian output \
                 representation, or read `covariance` and \
                 `covariance_representation` off the result directly and \
                 transform them yourself."
            )));
        }
        state = state.with_covariance(s.covariance);
    }
    let mut orbit = Orbit::new(state);
    if result.has_non_grav != 0 {
        let ng = &result.non_grav;
        orbit = orbit.with_nongrav(ng.a1, ng.a2, ng.a3);
        // Any non-zero exponent selects the explicit Marsden–Sekanina g(r);
        // all-zero is the inverse-square default `with_nongrav` already set.
        if ng.ng_alpha != 0.0
            || ng.ng_r0 != 0.0
            || ng.ng_m != 0.0
            || ng.ng_n != 0.0
            || ng.ng_k != 0.0
        {
            orbit = orbit.with_g_function(ng.ng_alpha, ng.ng_r0, ng.ng_m, ng.ng_n, ng.ng_k);
        }
        if ng.has_dt != 0 {
            orbit = orbit.with_non_grav_dt(Some(ng.non_grav_dt));
        }
        // Carry the fitted non-grav covariance so the orbit re-feeds into a
        // StateAndNonGrav refine without losing its non-grav prior.
        if ng.has_covariance != 0 {
            orbit = orbit.with_nongrav_covariance(Some(ng.covariance));
        }
    }
    // The DT posterior. It had no wire before the 0.10.0 ABI, so a solved-DT
    // fit used to round-trip with its DT column closed.
    if result.has_non_grav != 0 && result.non_grav.has_dt_variance != 0 {
        orbit = orbit.with_non_grav_dt_variance(Some(result.non_grav.dt_variance));
    }
    // Carry the fitted/absolute SRP slot so a solved AMRAT orbit re-feeds into
    // propagate / refine without silently dropping its SRP force. When the
    // AMRAT was solved, `amrat_variance` is the fitted posterior — chaining the
    // correct prior into a follow-on StateAndAMRAT refine.
    if result.has_srp != 0 {
        let srp = &result.srp;
        orbit = orbit.with_srp(srp.amrat, srp.cr);
        if srp.has_amrat_variance != 0 {
            orbit = orbit.with_srp_amrat_variance(Some(srp.amrat_variance));
        }
    }
    // The cross terms — the half of the posterior that is not a diagonal
    // block. Both halves land where a re-feed reads them: the border on
    // the coordinate beside its 6×6, the carrier on the orbit. Without
    // this the returned orbit carries a block-diagonal covariance, which
    // is a tighter claim than the fit made.
    let joint = unsafe { crate::JointCovariance::from_ffi(&result.orbit.orbit_cov) }?;
    orbit.state.non_grav_cross = joint.non_grav_cross;
    orbit.wide_cross = joint.wide_cross;
    Ok(orbit)
}