satkit 0.16.2

Satellite Toolkit
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
//! Orbital Mean-Element Messages (OMM)
//!
//! See: https://ccsds.org/Pubs/502x0b3e1.pdf
//! Also: https://www.space-track.org/documentation#/omm
//!
//!
//! Author notes:
//!
//! - This is a confusing standard that does not appear to be rigidly adhered to.
//!
//!

use serde::{Deserialize, Deserializer};

use anyhow::Result;

#[cfg(feature = "omm-xml")]
mod xml;

use crate::sgp4::{SGP4InitArgs, SGP4Source, SatRec};
use crate::{Instant, TimeScale};

fn de_f64_from_number_or_string<'de, D>(deserializer: D) -> Result<f64, D::Error>
where
    D: Deserializer<'de>,
{
    use serde::de::Error;
    use serde_json::Value;

    let v = Value::deserialize(deserializer)?;
    match v {
        Value::Number(n) => n.as_f64().ok_or_else(|| Error::custom("invalid number")),
        Value::String(s) => s
            .parse::<f64>()
            .map_err(|e| Error::custom(format!("invalid float string: {e}"))),
        _ => Err(Error::custom("expected number or string")),
    }
}

fn de_opt_f64_from_number_or_string<'de, D>(deserializer: D) -> Result<Option<f64>, D::Error>
where
    D: Deserializer<'de>,
{
    use serde::de::Error;
    use serde_json::Value;

    let v = Value::deserialize(deserializer)?;
    match v {
        Value::Null => Ok(None),
        Value::Number(n) => n
            .as_f64()
            .ok_or_else(|| Error::custom("invalid number"))
            .map(Some),
        Value::String(s) => {
            let s = s.trim();
            if s.is_empty() {
                Ok(None) // remove this branch if you want "" to be an error
            } else {
                s.parse::<f64>()
                    .map(Some)
                    .map_err(|e| Error::custom(format!("invalid float string: {e}")))
            }
        }
        _ => Err(Error::custom("expected number, string, or null")),
    }
}

fn de_opt_u32_from_number_or_string<'de, D>(deserializer: D) -> Result<Option<u32>, D::Error>
where
    D: Deserializer<'de>,
{
    use serde::de::Error;
    use serde_json::Value;

    let v = Value::deserialize(deserializer)?;
    match v {
        Value::Null => Ok(None),

        Value::Number(n) => {
            let v = n
                .as_u64()
                .ok_or_else(|| Error::custom("invalid number for u32"))?;
            u32::try_from(v)
                .map(Some)
                .map_err(|_| Error::custom("u32 out of range"))
        }

        Value::String(s) => {
            let s = s.trim();
            if s.is_empty() {
                Ok(None) // remove if "" should be an error
            } else {
                s.parse::<u32>()
                    .map(Some)
                    .map_err(|e| Error::custom(format!("invalid u32 string: {e}")))
            }
        }

        _ => Err(Error::custom("expected number, string, or null")),
    }
}

fn de_opt_u8_from_number_or_string<'de, D>(deserializer: D) -> Result<Option<u8>, D::Error>
where
    D: Deserializer<'de>,
{
    use serde::de::Error;
    use serde_json::Value;

    let v = Value::deserialize(deserializer)?;
    match v {
        Value::Null => Ok(None),

        Value::Number(n) => {
            let v = n
                .as_u64()
                .ok_or_else(|| Error::custom("invalid number for u8"))?;
            u8::try_from(v)
                .map(Some)
                .map_err(|_| Error::custom("u8 out of range"))
        }

        Value::String(s) => {
            let s = s.trim();
            if s.is_empty() {
                Ok(None) // remove if "" should be an error
            } else {
                s.parse::<u8>()
                    .map(Some)
                    .map_err(|e| Error::custom(format!("invalid u8 string: {e}")))
            }
        }

        _ => Err(Error::custom("expected number, string, or null")),
    }
}

/// OMM Structure
///
/// See Table 4-1, Table 4-2, Table 4-3 of CCSDS 502.0-B-3
///
///
/// # Example Usage:
///
/// ```
/// use satkit::prelude::*;
///
/// // JSON structure based on Spacetrack OMM format
/// let json_str = r#"
/// [
///    {
///        "OBJECT_NAME": "ISS (ZARYA)",
///        "OBJECT_ID": "1998-067A",
///        "EPOCH": "2026-02-14T05:08:48.534432",
///        "MEAN_MOTION": 15.4859353,
///        "ECCENTRICITY": 0.00110623,
///        "INCLINATION": 51.6315,
///        "RA_OF_ASC_NODE": 188.3997,
///        "ARG_OF_PERICENTER": 96.9141,
///        "MEAN_ANOMALY": 263.3106,
///        "EPHEMERIS_TYPE": 0,
///        "CLASSIFICATION_TYPE": "U",
///        "NORAD_CAT_ID": 25544,
///        "ELEMENT_SET_NO": 999,
///        "REV_AT_EPOCH": 55269,
///        "BSTAR": 0.00016303535,
///        "MEAN_MOTION_DOT": 8.429e-5,
///        "MEAN_MOTION_DDOT": 0
///    }
/// ]
/// "#;
///
/// let omms = OMM::from_json_string(json_str).unwrap();
/// println!("Parsed OMMs: {:#?}", omms);
///
///  // Test Run initialization from OMM
///  let mut omm = omms[0].clone();
///  let epoch = omm.epoch_instant().unwrap();
///  println!("OMM epoch: {}", epoch);
///  let times = vec![epoch, epoch + Duration::from_minutes(10.0)];
///  let states = sgp4(
///      &mut omm,
///      &times,
///  )
///  .unwrap();
/// ```

#[derive(Debug, Deserialize, Clone, Default)]
pub struct OMM {
    #[serde(rename = "CCSDS_OMM_VERS")] // CCSDS says this is required, but it often is missing
    pub omm_version: Option<String>,
    #[serde(rename = "COMMENT")] // optional
    pub comments: Option<String>,
    #[serde(rename = "ORIGINATOR")] // Optional
    pub originator: Option<String>,
    #[serde(rename = "CLASSIFICATION")]
    pub classification: Option<String>,
    #[serde(rename = "MESSAGE_ID")]
    pub message_id: Option<String>,
    #[serde(rename = "OBJECT_NAME")] // Mandatory
    pub object_name: String,
    #[serde(rename = "OBJECT_ID")] // Mandatory
    pub object_id: String,
    #[serde(rename = "CENTER_NAME")] // Mandatory but often ignored
    pub center_name: Option<String>,
    #[serde(rename = "REF_FRAME")] // Mandatory but often ignored
    pub reference_frame: Option<String>,
    #[serde(rename = "REF_FRAME_EPOCH")] // Optional
    pub reference_frame_epoch: Option<String>,
    #[serde(rename = "TIME_SYSTEM")] // Mandatory but often ignored
    pub time_system: Option<String>,
    #[serde(rename = "MEAN_ELEMENT_THEORY")] // Mandatory but often ignored
    pub mean_element_theory: Option<String>,
    #[serde(rename = "EPOCH")] // Mandatory
    pub epoch: String,
    #[serde(rename = "MEAN_MOTION")] // Mandatory
    #[serde(deserialize_with = "de_f64_from_number_or_string")]
    pub mean_motion: f64,
    #[serde(rename = "ECCENTRICITY")] // Mandatory
    #[serde(deserialize_with = "de_f64_from_number_or_string")]
    pub eccentricity: f64,
    #[serde(rename = "INCLINATION")] // Mandatory
    #[serde(deserialize_with = "de_f64_from_number_or_string")]
    pub inclination: f64,
    #[serde(rename = "RA_OF_ASC_NODE")] // Mandatory
    #[serde(deserialize_with = "de_f64_from_number_or_string")]
    pub raan: f64,
    #[serde(rename = "ARG_OF_PERICENTER")] // Mandatory
    #[serde(deserialize_with = "de_f64_from_number_or_string")]
    pub arg_of_pericenter: f64,
    #[serde(rename = "MEAN_ANOMALY")] // Mandatory
    #[serde(deserialize_with = "de_f64_from_number_or_string")]
    pub mean_anomaly: f64,
    #[serde(rename = "GM")] // Optional
    #[serde(default, deserialize_with = "de_opt_f64_from_number_or_string")]
    pub gm: Option<f64>,
    #[serde(rename = "MASS")] // Optional
    #[serde(default, deserialize_with = "de_opt_f64_from_number_or_string")]
    pub mass: Option<f64>,
    #[serde(rename = "SOLAR_RAD_AREA")] // Optional
    #[serde(default, deserialize_with = "de_opt_f64_from_number_or_string")]
    pub solar_rad_area: Option<f64>,
    #[serde(rename = "DRAG_AREA")] // Optional
    #[serde(default, deserialize_with = "de_opt_f64_from_number_or_string")]
    pub drag_area: Option<f64>,
    #[serde(rename = "SOLAR_RAD_COEFF")] // Optional
    #[serde(default, deserialize_with = "de_opt_f64_from_number_or_string")]
    pub solar_rad_coeff: Option<f64>,
    #[serde(rename = "DRAG_COEFF")] // Optional
    #[serde(default, deserialize_with = "de_opt_f64_from_number_or_string")]
    pub drag_coeff: Option<f64>,
    #[serde(rename = "EPHEMERIS_TYPE")] // Optional
    #[serde(default, deserialize_with = "de_opt_u8_from_number_or_string")]
    pub ephemeris_type: Option<u8>,
    #[serde(rename = "CLASSIFICATION_TYPE")] // Optional
    pub classification_type: Option<String>,
    #[serde(rename = "NORAD_CAT_ID")] // Optional
    #[serde(default, deserialize_with = "de_opt_u32_from_number_or_string")]
    pub norad_cat_id: Option<u32>,
    #[serde(rename = "ELEMENT_SET_NO")] // Optional
    #[serde(default, deserialize_with = "de_opt_u32_from_number_or_string")]
    pub element_set_no: Option<u32>,
    #[serde(rename = "REV_AT_EPOCH")] // Optional
    #[serde(default, deserialize_with = "de_opt_u32_from_number_or_string")]
    pub rev_at_epoch: Option<u32>,
    #[serde(rename = "BSTAR")] // Optional
    #[serde(default, deserialize_with = "de_opt_f64_from_number_or_string")]
    pub bstar: Option<f64>,
    #[serde(rename = "BTERM")] // Optional
    #[serde(default, deserialize_with = "de_opt_f64_from_number_or_string")]
    pub bterm: Option<f64>,
    #[serde(rename = "MEAN_MOTION_DOT")] // Optional
    #[serde(default, deserialize_with = "de_opt_f64_from_number_or_string")]
    pub mean_motion_dot: Option<f64>,
    #[serde(rename = "MEAN_MOTION_DDOT")] // Optional
    #[serde(default, deserialize_with = "de_opt_f64_from_number_or_string")]
    pub mean_motion_ddot: Option<f64>,
    #[serde(rename = "AGOM")] // Optional
    #[serde(default, deserialize_with = "de_opt_f64_from_number_or_string")]
    pub agom: Option<f64>,

    /// Cached SGP4 record, initialized lazily on first propagation.
    #[serde(skip, default)]
    pub(crate) satrec: Option<SatRec>,

    #[serde(flatten)]
    pub extra_fields: std::collections::HashMap<String, serde_json::Value>,
}

impl OMM {
    /// Parses `self.epoch` (RFC 3339 string) into an [`Instant`].
    ///
    /// # Errors
    ///
    /// Returns an error if `epoch` is not a valid RFC 3339 timestamp.
    pub fn epoch_instant(&self) -> anyhow::Result<Instant> {
        Instant::from_rfc3339(&self.epoch).map_err(|e| anyhow::anyhow!(e))
    }

    /// Deserializes one or more OMM records from a JSON string.
    ///
    /// The expected format is a JSON array of OMM objects as provided by
    /// Space-Track/CelesTrak JSON endpoints.
    ///
    /// # Arguments
    /// - `s`: JSON string containing an array of OMM records.
    ///
    /// # Examples
    ///
    /// ```
    /// use satkit::prelude::OMM;
    ///
    /// let json = r#"[
    ///   {
    ///     "OBJECT_NAME": "ISS (ZARYA)",
    ///     "OBJECT_ID": "1998-067A",
    ///     "EPOCH": "2026-02-14T05:08:48.534432",
    ///     "MEAN_MOTION": 15.4859353,
    ///     "ECCENTRICITY": 0.00110623,
    ///     "INCLINATION": 51.6315,
    ///     "RA_OF_ASC_NODE": 188.3997,
    ///     "ARG_OF_PERICENTER": 96.9141,
    ///     "MEAN_ANOMALY": 263.3106
    ///   }
    /// ]"#;
    ///
    /// let omms = OMM::from_json_string(json)?;
    /// assert_eq!(omms.len(), 1);
    /// assert_eq!(omms[0].object_id, "1998-067A");
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the JSON is malformed or required OMM fields are missing/invalid.
    pub fn from_json_string(s: &str) -> Result<Vec<Self>> {
        serde_json::from_str(s).map_err(|e| anyhow::anyhow!(e))
    }

    /// Deserializes one or more OMM records from a JSON file.
    ///
    /// # Arguments
    /// - `path`: Path to a JSON file containing an array of OMM records.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use satkit::prelude::OMM;
    ///
    /// let omms = OMM::from_json_file("/path/to/omm.json")?;
    /// println!("Loaded {} OMM records", omms.len());
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be read or the JSON payload is invalid.
    pub fn from_json_file<P: AsRef<std::path::Path>>(path: P) -> Result<Vec<Self>> {
        let file = std::fs::File::open(path).map_err(|e| anyhow::anyhow!(e))?;
        let reader = std::io::BufReader::new(file);
        serde_json::from_reader(reader).map_err(|e| anyhow::anyhow!(e))
    }

    /// Load OMM(s) from a URL
    ///
    /// Fetches the content at the given URL and auto-detects the format:
    /// - If the response starts with `[` or `{`, it is parsed as JSON.
    /// - Otherwise, it is parsed as XML (requires the `omm-xml` feature).
    ///
    /// Works with CelesTrak and Space-Track API endpoints.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use satkit::omm::OMM;
    ///
    /// let omms = OMM::from_url("https://celestrak.org/NORAD/elements/gp.php?GROUP=stations&FORMAT=json").unwrap();
    /// ```
    pub fn from_url(url: &str) -> Result<Vec<Self>> {
        let agent = ureq::Agent::new_with_defaults();
        let mut resp = agent.get(url).call()?;
        let body = resp.body_mut().read_to_string()?;
        let trimmed = body.trim_start();
        if trimmed.starts_with('[') || trimmed.starts_with('{') {
            // JSON: wrap bare object in array
            if trimmed.starts_with('{') {
                Self::from_json_string(&format!("[{}]", trimmed))
            } else {
                Self::from_json_string(trimmed)
            }
        } else {
            #[cfg(feature = "omm-xml")]
            {
                Self::from_xml_string(trimmed)
            }
            #[cfg(not(feature = "omm-xml"))]
            {
                anyhow::bail!("Response appears to be XML but the `omm-xml` feature is not enabled")
            }
        }
    }
}

impl SGP4Source for OMM {
    fn epoch(&self) -> Instant {
        // `sgp4_full` only calls `epoch()` after `sgp4_init_args()` succeeds.
        self.epoch_instant().unwrap_or(Instant::INVALID)
    }

    fn satrec_mut(&mut self) -> &mut Option<SatRec> {
        &mut self.satrec
    }

    fn sgp4_init_args(&self) -> anyhow::Result<SGP4InitArgs> {
        use std::f64::consts::PI;

        const TWOPI: f64 = PI * 2.0;

        if let Some(theory) = &self.mean_element_theory {
            if !theory.trim().eq_ignore_ascii_case("SGP4") {
                anyhow::bail!("Unsupported MEAN_ELEMENT_THEORY: {theory}");
            }
        }

        if let Some(ts) = &self.time_system {
            if !ts.trim().eq_ignore_ascii_case("UTC") {
                anyhow::bail!("Unsupported TIME_SYSTEM for SGP4: {ts}");
            }
        }

        let epoch = self.epoch_instant()?;

        Ok(SGP4InitArgs {
            jdsatepoch: epoch.as_jd_with_scale(TimeScale::UTC),
            bstar: self.bstar.unwrap_or(0.0),
            // Convert rev/day(+derivatives) to rad/min(+derivatives), matching TLE.
            no: self.mean_motion / (1440.0 / TWOPI),
            ndot: self.mean_motion_dot.unwrap_or(0.0) / (1440.0 * 1440.0 / TWOPI),
            nddot: self.mean_motion_ddot.unwrap_or(0.0) / (1440.0 * 1440.0 * 1440.0 / TWOPI),
            ecco: self.eccentricity,
            inclo: self.inclination.to_radians(),
            nodeo: self.raan.to_radians(),
            argpo: self.arg_of_pericenter.to_radians(),
            mo: self.mean_anomaly.to_radians(),
        })
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use crate::utils::test::*;

    #[test]
    fn test_parse_omm_spacetrack_json() {
        let filename = get_testvec_dir().unwrap().join("omm/spacetrack_omm.json");
        let file = std::fs::File::open(filename).unwrap();
        let reader = std::io::BufReader::new(file);

        let msg: Vec<OMM> = serde_json::from_reader(reader).unwrap();
        println!("number of OMMs: {}", msg.len());
        println!("first OMM: {:#?}", msg[0]);

        // Test SGP4 initialization from first OMM
        let mut omm = msg[0].clone();

        // Actually run SGP4 propagation for 10 minutes past epoch
        let epoch = omm.epoch_instant().unwrap();
        println!("OMM epoch: {}", epoch);
        let times = vec![epoch, epoch + crate::time::Duration::from_minutes(10.0)];
        let states = crate::sgp4::sgp4_full(
            &mut omm,
            &times,
            crate::sgp4::GravConst::WGS72,
            crate::sgp4::OpsMode::IMPROVED,
        )
        .unwrap();
        for (i, _t) in times.iter().enumerate() {
            assert!(states.errcode[i] == crate::sgp4::SGP4Error::SGP4Success);
        }
    }

    #[test]
    fn test_parse_omm_celestrak_json() {
        let filename = get_testvec_dir().unwrap().join("omm/celestrak_omm.json");
        let file = std::fs::File::open(filename).unwrap();
        let reader = std::io::BufReader::new(file);

        let msg: Vec<OMM> = serde_json::from_reader(reader).unwrap();
        println!("number of OMMs: {}", msg.len());
        println!("first OMM: {:#?}", msg[0]);
    }
}