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
//! [![github]](https://github.com/FusRoman/Outfit) [![crates-io]](https://crates.io/crates/outfit) [![docs-rs]](crate)
//!
//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs
//!
//! <br>
//!
//! # Outfit
//!
//! **Outfit** is a modern **Rust library for orbit determination and propagation**
//! of small Solar System bodies.
//!
//! It provides a **memory-safe, modular, and extensible** implementation of
//! algorithms that transform raw astrometric observations into orbital solutions,
//! and propagate them through time.
//!
//! ## Why Outfit?
//!
//! - **Safe Rust**: strong typing, memory safety, and explicit error handling.
//! - **Modular**: interchangeable ephemerides, error models, and IOD algorithms.
//! - **Scientific grounding**: consistent with established astronomical standards.
//! - **Scalable workflows**: designed for survey-scale batch processing.
//!
//! ## Features
//!
//! - **Initial Orbit Determination (IOD)**:
//! - Classical **Gauss method** for three observations.
//! - **Differential Orbit Correction**:
//! - Iterative **Newton–Raphson least-squares** refinement of equinoctial elements,
//! - Projection-based **outlier rejection** loop (chi-squared per observation),
//! - Covariance matrix estimation with posterior uncertainty rescaling,
//! - Configurable free/fixed element mask for under-determined arcs,
//! - [`FitLSQ`] trait: full pipeline (IOD seed → differential correction) on any [`ObsDataset`](photom::observation_dataset::ObsDataset).
//! - **Ephemeris generation**:
//! - Predict apparent sky positions `(RA, Dec)` and distances from any [`OrbitalElements`],
//! - Compute geometric quantities: **phase angle**, **solar elongation**, **radial velocity**, apparent angular rates,
//! - Combined mode computes position and geometry in a single propagation,
//! - Three generation modes per observer: `Single`, `Range` (uniform grid), `At` (arbitrary epoch list),
//! - Multiple observers in one typed [`EphemerisRequest`]; per-epoch errors collected without aborting the batch,
//! - Choice of **two-body (Keplerian)** or **N-body (DOP853)** propagator; first- or second-order aberration correction.
//! - **Orbital elements**:
//! - Classical **Keplerian elements**,
//! - **Equinoctial elements** with conversions and two-body solver,
//! - **Cometary elements** for parabolic and hyperbolic trajectories.
//! - **Uncertainty propagation**:
//! - Full **covariance matrix propagation** between orbital element representations,
//! - Standard deviations and correlations tracked via **Jacobian transformations**,
//! - Rigorous linear uncertainty propagation for orbit conversions.
//! - **Reference frames & preprocessing**:
//! - Precession, nutation (IAU 1980), aberration, and light-time correction,
//! - Ecliptic ↔ equatorial conversions, RA/DEC parsing, time systems.
//! - **JPL ephemerides**:
//! - Built-in support for **JPL DE440** (NAIF/SPICE kernels and Horizons format).
//! - **Observer management**:
//! - Build from **MPC observatory code** or custom geodetic coordinates.
//! - **Residuals & quality metrics**:
//! - RMS computation of normalized astrometric residuals, filtering utilities.
//! - **Examples**:
//! - End-to-end examples in `examples/`.
//! - **Parallel batch processing (feature `parallel`)**
//!
//! ### Planned extensions
//!
//! - **Vaisalä method** for short arcs,
//! - Full support for **hyperbolic trajectories**.
//!
//! ## Uncertainty Propagation
//!
//! Outfit tracks orbital uncertainties throughout the full pipeline — from the least-squares fit
//! through to element representation conversions.
//!
//! ### Generation from differential correction
//!
//! The [`FitLSQ`] pipeline produces a **6×6 covariance matrix** Γ = (G⊤WG)⁻¹ in equinoctial
//! element space directly from the normal equations of the weighted least-squares fit.
//! This raw covariance is then rescaled by a posterior inflation factor μ that accounts for
//! the degrees of freedom and the quality of the fit (normalised RMS):
//!
//! - normalised RMS ≤ 1: μ = √(n_meas / (n_meas − n_free))
//! - normalised RMS > 1: μ = rms × √(n_meas / (n_meas − n_free))
//!
//! The rescaled covariance is stored in [`DifferentialCorrectionOutput`] and embedded in the
//! returned [`OrbitalElements::Equinoctial`](OrbitalElements) variant alongside 1-σ standard deviations
//! (extracted from the diagonal).
//!
//! ### Propagation between element representations
//!
//! Each [`OrbitalElements`] variant carries an optional `covariance: Option<OrbitalCovariance>`
//! (full 6×6 matrix) and an optional `uncertainty` (per-element 1-σ standard deviations).
//! When converting between representations, the covariance is propagated via
//! **first-order linear (Jacobian) propagation**:
//!
//! Σ_y = J · Σ_x · Jᵀ
//!
//! where J = ∂y/∂x is the 6×6 Jacobian of the transformation evaluated at the nominal elements.
//! Jacobians are computed **analytically** for all supported conversions:
//!
//! - Keplerian ↔ Equinoctial
//! - Cometary → Keplerian (and via chain rule → Equinoctial)
//!
//! Equinoctial elements are preferred as the primary representation: they are non-singular
//! for e < 1 and 0 ≤ i < π, avoiding the degenerate Jacobians that arise for nearly circular
//! or equatorial orbits in Keplerian form.
//!
//! For mathematical details, singularity handling, and usage examples, see the
//! [`orbit_type::uncertainty`] module documentation.
//!
//! ## Workflow at a Glance
//!
//! 1. **Load observations** into an [`ObsDataset`](photom::observation_dataset::ObsDataset)
//! (MPC 80-column, ADES XML, or Parquet).
//! 2. **Load JPL ephemerides** via [`JPLEphem`] and prepare a UT1 provider.
//! 3. **Run IOD** by calling [`FitIOD::fit_iod`](crate::FitIOD::fit_iod) on the dataset,
//! or run a full **least-squares fit** via [`FitLSQ::fit_lsq`](crate::FitLSQ::fit_lsq)
//! (which seeds itself from IOD automatically).
//! 4. **Evaluate residuals** (normalised RMS) using the returned result.
//! 5. **Generate ephemerides** by calling [`OrbitalElements::compute`] with an
//! [`EphemerisRequest`] to predict apparent positions and geometric quantities.
//! 6. **Propagate** using Keplerian dynamics or convert to equinoctial elements as needed.
//!
//! ## Example (single-trajectory IOD from MPC 80-column)
//!
//! ```rust,no_run
//! use photom::observation_dataset::ObsDataset;
//! use photom::observer::error_model::ObsErrorModel;
//! use hifitime::ut1::Ut1Provider;
//! use rand::{rngs::StdRng, SeedableRng};
//! use outfit::FitIOD;
//! use outfit::jpl_ephem::{download_jpl_file::EphemFileSource, JPLEphem};
//! use outfit::IODParams;
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Load observations from an MPC 80-column file.
//! let dataset = ObsDataset::from_mpc_80_col("tests/data/2015AB.obs")?;
//!
//! // Load JPL DE440 ephemeris (Horizons format).
//! let jpl_source: EphemFileSource = "horizon:DE440".try_into()?;
//! let jpl = JPLEphem::new(&jpl_source)?;
//!
//! // Obtain a UT1 provider for Earth orientation corrections.
//! let ut1 = Ut1Provider::download_from_jpl("latest_eop2.long")?;
//!
//! // Configure IOD.
//! let params = IODParams::builder()
//! .n_noise_realizations(10)
//! .max_obs_for_triplets(50)
//! .max_triplets(30)
//! .build()?;
//!
//! let mut rng = StdRng::seed_from_u64(42);
//!
//! // Run Gauss IOD for a single trajectory.
//! let fit_result = dataset.fit_iod(
//! "K09R05F",
//! &jpl,
//! &ut1,
//! ¶ms,
//! ObsErrorModel::FCCT14,
//! &mut rng,
//! )?;
//!
//! println!("Best orbit: {}", fit_result.orbital_elements());
//! println!("Quality: {:.6}", fit_result.orbit_quality());
//! Ok(())
//! }
//! ```
//!
//! For more end-to-end flows, see the [`examples/`](https://github.com/FusRoman/Outfit/tree/main/examples) folder.
//!
//! ## Example (differential correction — IOD seed + least-squares refinement)
//!
//! ```rust,no_run
//! use photom::observation_dataset::ObsDataset;
//! use photom::observer::error_model::ObsErrorModel;
//! use hifitime::ut1::Ut1Provider;
//! use rand::{rngs::StdRng, SeedableRng};
//! use outfit::{FitLSQ, DifferentialCorrectionConfig, IODParams};
//! use outfit::jpl_ephem::{download_jpl_file::EphemFileSource, JPLEphem};
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let dataset = ObsDataset::from_mpc_80_col("tests/data/2015AB.obs")?;
//!
//! let jpl_source: EphemFileSource = "horizon:DE440".try_into()?;
//! let jpl = JPLEphem::new(&jpl_source)?;
//! let ut1 = Ut1Provider::download_from_jpl("latest_eop2.long")?;
//!
//! let iod_params = IODParams::builder().build()?;
//! let dc_config = DifferentialCorrectionConfig::default();
//! let mut rng = StdRng::seed_from_u64(42);
//!
//! // Run IOD + differential correction for every trajectory.
//! let results = dataset.fit_lsq(
//! &jpl, &ut1,
//! ObsErrorModel::FCCT14,
//! &iod_params,
//! &dc_config,
//! None,
//! &mut rng,
//! )?;
//!
//! for (traj_id, res) in &results {
//! match res {
//! Ok(fit) => println!("{traj_id} → normalised RMS = {:.4}", fit.normalised_rms()),
//! Err(e) => eprintln!("{traj_id} → error: {e}"),
//! }
//! }
//! Ok(())
//! }
//! ```
//!
//! ## Example (ephemeris generation)
//!
//! ```rust,no_run
//! use outfit::{OrbitalElements, EphemerisConfig, EphemerisRequest, EphemerisMode, Combined};
//! use hifitime::{Epoch, Duration};
//!
//! // `elements` obtained from IOD or differential correction.
//! let result = elements.compute(
//! &EphemerisRequest::<Combined>::new(EphemerisConfig::default())
//! .add(observer, EphemerisMode::Range {
//! start: Epoch::from_mjd_tt(60310.0),
//! end: Epoch::from_mjd_tt(60340.0),
//! step: Duration::from_days(1.0),
//! }),
//! &jpl,
//! &ut1,
//! );
//!
//! for entry in result.successes() {
//! let (pos, geo) = entry.result.as_ref().unwrap();
//! println!(
//! "{}: RA={:.4} Dec={:.4} phase={:.2}°",
//! entry.epoch, pos.coord.ra, pos.coord.dec,
//! geo.phase_angle.to_degrees(),
//! );
//! }
//! ```
//!
//! ## Example (batch IOD — all trajectories at once)
//!
//! ```rust,no_run
//! use photom::observation_dataset::ObsDataset;
//! use photom::observer::error_model::ObsErrorModel;
//! use hifitime::ut1::Ut1Provider;
//! use rand::{rngs::StdRng, SeedableRng};
//! use outfit::{FitIOD, FullOrbitResult};
//! use outfit::jpl_ephem::{download_jpl_file::EphemFileSource, JPLEphem};
//! use outfit::IODParams;
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let dataset = ObsDataset::from_mpc_80_col("tests/data/2015AB.obs")?;
//!
//! let jpl_source: EphemFileSource = "horizon:DE440".try_into()?;
//! let jpl = JPLEphem::new(&jpl_source)?;
//! let ut1 = Ut1Provider::download_from_jpl("latest_eop2.long")?;
//!
//! let params = IODParams::builder()
//! .n_noise_realizations(10)
//! .max_obs_for_triplets(50)
//! .build()?;
//!
//! let mut rng = StdRng::seed_from_u64(42);
//!
//! // Run Gauss IOD for every trajectory in the dataset.
//! let results: FullOrbitResult = dataset.fit_full_iod(
//! &jpl,
//! &ut1,
//! ¶ms,
//! ObsErrorModel::FCCT14,
//! &mut rng,
//! )?;
//!
//! for (traj_id, res) in &results {
//! match res {
//! Ok(fit) => println!("{traj_id} → quality = {:.4}\n{}", fit.orbit_quality(), fit.orbital_elements()),
//! Err(e) => eprintln!("{traj_id} → error: {e}"),
//! }
//! }
//! Ok(())
//! }
//! ```
//!
//! ## Error Handling
//!
//! Outfit uses [`thiserror`] for descriptive error types and idiomatic `Result<T, E>` returns,
//! with transparent conversions via `#[from]` where appropriate.
//!
//! ## MSRV & Platforms
//!
//! - Tested on **stable Rust** (see `Cargo.toml` and CI for the current MSRV policy).
//! - Linux/macOS are primary targets; Windows is expected to work but may have different I/O performance.
//!
//! ## Scientific Background
//!
//! - Milani, A. & Gronchi, G. F. (2010), *Theory of Orbit Determination*, Cambridge University Press.
//! - The open-source [OrbFit](http://adams.dm.unipi.it/orbfit/) software suite.
//!
//! ## License
//!
//! Distributed under the **CeCILL-C** license. See
//! [`LICENSE`](https://github.com/FusRoman/Outfit/blob/main/LICENSE).
//!
//! ## Authors
//!
//! Developed by **FusRoman** and contributors.
//!
//! ## See also
//!
//! - [`initial_orbit_determination`] — Gauss IOD algorithm, triplet generation, IOD parameters, public API to perform IOD on an [`ObsDataset`](photom::observation_dataset::ObsDataset).
//! - [`differential_orbit_correction`] — Weighted least-squares orbit refinement: Newton–Raphson loop, outlier rejection, covariance estimation, [`FitLSQ`] trait.
//! - [`ephemeris`] — Ephemeris generation: apparent position, geometric quantities, [`EphemerisRequest`]/[`EphemerisResult`] API.
//! - [`jpl_ephem`] — Ephemerides backends (Horizons/NAIF DE440).
//! - [`orbit_type`] — Orbital element representations (Keplerian, Equinoctial, Cometary) with full covariance propagation and uncertainty tracking for conversions between representations.
//! - [`ref_system`] — Reference frame transformations.
//! - [`constants`] — Physical constants and unit conversions.
//! - [`conversion`] — RA/DEC parsing and coordinate utilities.
//! - [`earth_orientation`] — Precession, nutation, and obliquity models.
//! - [`kepler`] — Universal Kepler propagator and Lagrange f–g solver.
//! - [`orb_elem`] — State-vector to orbital-elements conversion.
//! - [`outfit_errors`] — Unified error enum for the whole crate.
//! - [`time`] — Time scale conversions and sidereal time.
//! - [`cache`] — Precomputed observer position cache.
//! - [`observer_extension`] — Geocentric and heliocentric observer position routines.
// === Modules (internals). Keep public modules as they are; the facade is built via `pub use` below.
/// Constants and astronomical unit conversions.
/// Coordinate conversions (RA/DEC, spherical ↔ cartesian, etc.).
/// Earth orientation parameters and related corrections (nutation, precession).
/// Initial Orbit Determination algorithms (Gauss method).
/// Differential orbit correction utilities.
/// JPL ephemerides management (Horizon/NAIF kernels).
/// Ephemeris interpolation and access.
/// Keplerian solver for propagation.
/// Orbital types and conversions between them.
/// Orbital elements utilities (conversion, normalization).
/// Errors returned by Outfit operations.
/// Reference frame transformations.
/// Time management and conversions (UTC, TDB, TT).
/// Precomputed observer position cache used throughout the fitting pipeline.
/// Ground-observer geometry: body-fixed and heliocentric position routines.
/// Orbit propagation strategies (TwoBody, N-body DOP853).
/// Core IOD pipeline trait over sorted observation slices.
pub
// === Public API FACADE =====================================================
// Re-export carefully curated symbols for a simple, stable top-level API.
// Users can import from `outfit::...` without diving into deep module paths.
// Orbital element representations
pub use crate;
pub use crateOutfitError;
// IOD (Gauss) key types
pub use crateGaussResult;
pub use crateIODParams;
// Selected constants that are widely useful
pub use crate;
// JPL ephemeris enum for runtime inspection (optional but convenient)
pub use crateJPLEphem;
// Ephemeris façade
pub use crate;
// IOD entry points and result types
pub use crateFitIOD;
// Differential correction entry points
pub use crateFitLSQ;
pub use crate;
// A convenient crate-wide Result alias.
pub type Result<T> = Result;
/// Prelude with common imports for quick-start users.
///
/// Bring the most frequently used types and traits into scope in one line:
/// ```rust
/// use outfit::prelude::*;
/// ```
// === Tests support ==========================================================
pub