siderust 0.10.1

High-precision astronomy and satellite mechanics in Rust.
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
//! # SINEX station-coordinate reader
//!
//! Parses the Solution INdependent EXchange (SINEX) format to extract
//! station coordinate and velocity estimates from geodetic solutions.
//!
//! Supported blocks: `+SITE/ID`, `+SOLUTION/ESTIMATE`.
//! Estimate types: `STAX`, `STAY`, `STAZ` (position), `VELX`, `VELY`, `VELZ`
//! (velocity).
//!
//! ## References
//!
//! - IERS/IGS SINEX Format Description Version 2.10.

use super::{FileLocation, FormatError, ParseMode};
use affn::cartesian;
use affn::centers::{AffineCenter, ReferenceCenter};
use affn::frames::ITRF;
use qtty::unit::Meter;
use std::collections::HashMap;
use std::io::{BufRead, BufReader, Read};

/// Earth geocenter marker for SINEX ITRF coordinates.
///
/// # Examples
///
/// ```
/// use siderust::formats::igs::sinex::GeoCenterItrf;
/// use affn::centers::ReferenceCenter;
/// assert_eq!(GeoCenterItrf::center_name(), "Geocentric ITRF");
/// ```
#[derive(Debug, Copy, Clone)]
pub struct GeoCenterItrf;

impl ReferenceCenter for GeoCenterItrf {
    type Params = ();
    fn center_name() -> &'static str {
        "Geocentric ITRF"
    }
}

impl AffineCenter for GeoCenterItrf {}

/// SINEX ITRF Cartesian position (meters).
///
/// # Examples
///
/// ```
/// use siderust::formats::igs::sinex::SinexPosition;
/// let _pos = SinexPosition::new(4_641_949.0_f64, 1_393_045.0_f64, 4_133_287.0_f64);
/// ```
pub type SinexPosition = cartesian::Position<GeoCenterItrf, ITRF, Meter>;

/// Velocity unit: meters per year.
///
/// Used for VELX/VELY/VELZ estimates in SINEX files.
pub type MeterPerYear = qtty::Per<qtty::unit::Meter, qtty::unit::Year>;

/// A station solution extracted from a SINEX file.
///
/// # Examples
///
/// ```
/// use siderust::formats::igs::sinex::{StationCoordinate, SinexPosition};
/// let pos = SinexPosition::new(1.0_f64, 2.0_f64, 3.0_f64);
/// let _ = StationCoordinate {
///     code: "MATE".to_string(),
///     point_code: "A".to_string(),
///     solution_id: "1".to_string(),
///     ref_epoch_mjd: 51544.0,
///     position: pos,
///     velocity_m_yr: None,
/// };
/// ```
#[derive(Debug, Clone)]
pub struct StationCoordinate {
    /// 4-character station code (DOMES notation).
    pub code: String,
    /// Point code (e.g. `"A"`).
    pub point_code: String,
    /// Solution ID (e.g. `"1"`).
    pub solution_id: String,
    /// Reference epoch (MJD, f64).
    pub ref_epoch_mjd: f64,
    /// ITRF Cartesian position (meters).
    pub position: SinexPosition,
    /// Velocity vector components in meters/year, if present.
    pub velocity_m_yr: Option<[f64; 3]>,
}

/// Parsed SINEX solution.
///
/// # Examples
///
/// ```
/// use siderust::formats::igs::sinex::SinexSolution;
/// let sol = SinexSolution::default();
/// assert!(sol.stations.is_empty());
/// ```
#[derive(Debug, Default)]
pub struct SinexSolution {
    /// File creation agency.
    pub agency: String,
    /// Solution description.
    pub description: String,
    /// Station coordinate/velocity records.
    pub stations: Vec<StationCoordinate>,
}

/// Read a SINEX file from a byte source.
///
/// Parses `+SITE/ID`, `+SOLUTION/EPOCHS`, and `+SOLUTION/ESTIMATE` blocks.
/// Estimates for `STAX`/`STAY`/`STAZ` become position components;
/// `VELX`/`VELY`/`VELZ` become velocity components.
///
/// # Errors
///
/// Returns [`FormatError::Format`] for fatal parse errors in `Strict` mode,
/// or [`FormatError::Io`] for underlying I/O failures.
///
/// # Examples
///
/// ```
/// use siderust::formats::igs::sinex::read_sinex;
/// use siderust::formats::ParseMode;
///
/// let data = b"%=SNX 2.10 IGS 24:001:00000 IGS 00:000:00000 23:365:86370 P 00000 0 S\n\
///              +SITE/ID\n\
///              *Code Pt Domes____ T _Station Description__ _Longitude_ _Latitude__ _Height_\n\
///              ABCD  A 10101M001 P Some Station            010 00 00.0 050 00 00.0  100.000\n\
///              -SITE/ID\n\
///              +SOLUTION/ESTIMATE\n\
///              *Index Type__ Code Pt Soln _Ref_Epoch__ Unit S ___Estimated_Value___ __Std_Dev__\n\
///              1 STAX   ABCD  A    1 00:001:00000 m    2  1.000000000000000E+06  1.000E-04\n\
///              2 STAY   ABCD  A    1 00:001:00000 m    2 -2.000000000000000E+06  1.000E-04\n\
///              3 STAZ   ABCD  A    1 00:001:00000 m    2  3.000000000000000E+06  1.000E-04\n\
///              -SOLUTION/ESTIMATE\n\
///              %ENDSNX\n";
///
/// let sol = read_sinex(&data[..], ParseMode::Permissive).unwrap();
/// assert_eq!(sol.stations.len(), 1);
/// assert_eq!(sol.stations[0].code, "ABCD");
/// ```
pub fn read_sinex<R: Read>(reader: R, mode: ParseMode) -> Result<SinexSolution, FormatError> {
    let mut solution = SinexSolution::default();
    let buf = BufReader::new(reader);

    // Accumulate SOLUTION/ESTIMATE rows keyed by station code.
    #[derive(Default)]
    struct EstRow {
        xyz: [Option<f64>; 3],
        vel: [Option<f64>; 3],
        ref_epoch_mjd: f64,
        pt: String,
        soln: String,
    }
    let mut estimates: HashMap<String, EstRow> = HashMap::new();

    #[derive(PartialEq)]
    enum Block {
        None,
        SiteId,
        Estimate,
    }
    let mut block = Block::None;

    for (lineno, result) in buf.lines().enumerate() {
        let line = result.map_err(FormatError::Io)?;
        let lineno = lineno + 1;

        // SINEX header
        if line.starts_with("%=SNX") {
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() >= 3 {
                solution.agency = parts[2].to_string();
            }
            continue;
        }
        if line.starts_with("%ENDSNX") {
            break;
        }
        // Comment lines inside blocks
        if line.starts_with('*') || line.starts_with('%') {
            continue;
        }
        // Block start/end markers
        if let Some(bname) = line.strip_prefix('+') {
            match bname.trim() {
                "SITE/ID" => block = Block::SiteId,
                "SOLUTION/ESTIMATE" => block = Block::Estimate,
                _ => block = Block::None,
            }
            continue;
        }
        if line.starts_with('-') {
            block = Block::None;
            continue;
        }

        match block {
            Block::SiteId => {
                // We only record that the site exists; ignore detailed site info.
                // The station code is in the first token.
                let parts: Vec<&str> = line.split_whitespace().collect();
                if parts.is_empty() {
                    continue;
                }
                // Just note the code exists; coordinate data comes from ESTIMATE block.
                let _ = parts[0];
            }
            Block::Estimate => {
                // Format: index type code pt soln epoch unit constraint value stddev
                let parts: Vec<&str> = line.split_whitespace().collect();
                if parts.len() < 9 {
                    if mode == ParseMode::Strict {
                        return Err(FormatError::located(
                            "SINEX 2.10 §4.2",
                            FileLocation::at_line(lineno),
                            format!("ESTIMATE line has {} fields, need ≥ 9", parts.len()),
                        ));
                    }
                    continue;
                }
                let est_type = parts[1];
                let code = parts[2].to_string();
                let pt = parts[3].to_string();
                let soln = parts[4].to_string();
                let epoch_raw = parts[5];
                let value: f64 = match parts[8].parse() {
                    Ok(v) => v,
                    Err(_) => {
                        if mode == ParseMode::Strict {
                            return Err(FormatError::located(
                                "SINEX 2.10 §4.2",
                                FileLocation::at_line(lineno),
                                format!("cannot parse value: {}", parts[8]),
                            ));
                        }
                        continue;
                    }
                };

                let ref_epoch_mjd = sinex_epoch_to_mjd(epoch_raw);
                let row = estimates.entry(code.clone()).or_default();
                row.pt = pt;
                row.soln = soln;
                row.ref_epoch_mjd = ref_epoch_mjd;
                match est_type {
                    "STAX" => row.xyz[0] = Some(value),
                    "STAY" => row.xyz[1] = Some(value),
                    "STAZ" => row.xyz[2] = Some(value),
                    "VELX" => row.vel[0] = Some(value),
                    "VELY" => row.vel[1] = Some(value),
                    "VELZ" => row.vel[2] = Some(value),
                    _ => {}
                }
            }
            Block::None => {}
        }
    }

    // Build station records from accumulated estimates.
    for (code, row) in estimates {
        let (x, y, z) = match (row.xyz[0], row.xyz[1], row.xyz[2]) {
            (Some(x), Some(y), Some(z)) => (x, y, z),
            _ => continue,
        };
        let velocity_m_yr = match (row.vel[0], row.vel[1], row.vel[2]) {
            (Some(vx), Some(vy), Some(vz)) => Some([vx, vy, vz]),
            _ => None,
        };
        solution.stations.push(StationCoordinate {
            code,
            point_code: row.pt,
            solution_id: row.soln,
            ref_epoch_mjd: row.ref_epoch_mjd,
            position: SinexPosition::new(x, y, z),
            velocity_m_yr,
        });
    }

    Ok(solution)
}

/// Convert a SINEX epoch string `"YY:DDD:SSSSS"` to MJD.
fn sinex_epoch_to_mjd(s: &str) -> f64 {
    let parts: Vec<&str> = s.split(':').collect();
    if parts.len() != 3 {
        return 0.0;
    }
    let yy: i32 = parts[0].parse().unwrap_or(0);
    let doy: u32 = parts[1].parse().unwrap_or(1);
    let sod: f64 = parts[2].parse().unwrap_or(0.0);
    let yyyy = if yy == 0 {
        2000
    } else if yy >= 80 {
        1900 + yy
    } else {
        2000 + yy
    };
    let epoch = match chrono::NaiveDate::from_yo_opt(yyyy, doy.max(1)) {
        Some(d) => d,
        None => return 0.0,
    };
    let mjd_ref = chrono::NaiveDate::from_ymd_opt(1858, 11, 17).expect("valid MJD epoch");
    let days = (epoch - mjd_ref).num_days() as f64;
    days + sod / 86400.0
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::formats::ParseMode;

    fn sample_sinex(with_velocity: bool, epoch: &str) -> Vec<u8> {
        let mut data = format!(
            "%=SNX 2.10 IGS 24:001:00000 IGS 00:000:00000 23:365:86370 P 00000 0 S\n\
             +SITE/ID\n\
             *Code Pt Domes____ T _Station Description__ _Longitude_ _Latitude__ _Height_\n\
             ABCD  A 10101M001 P Some Station            010 00 00.0 050 00 00.0  100.000\n\
             -SITE/ID\n\
             +SOLUTION/ESTIMATE\n\
             *Index Type__ Code Pt Soln _Ref_Epoch__ Unit S ___Estimated_Value___ __Std_Dev__\n\
             1 STAX   ABCD  A    1 {epoch} m    2  1.000000000000000E+06  1.000E-04\n\
             2 STAY   ABCD  A    1 {epoch} m    2 -2.000000000000000E+06  1.000E-04\n\
             3 STAZ   ABCD  A    1 {epoch} m    2  3.000000000000000E+06  1.000E-04\n"
        );
        if with_velocity {
            data.push_str(&format!(
                "4 VELX   ABCD  A    1 {epoch} m/y  2  0.010000000000000E+00  1.000E-04\n\
                 5 VELY   ABCD  A    1 {epoch} m/y  2  0.020000000000000E+00  1.000E-04\n\
                 6 VELZ   ABCD  A    1 {epoch} m/y  2  0.030000000000000E+00  1.000E-04\n"
            ));
        }
        data.push_str("-SOLUTION/ESTIMATE\n%ENDSNX\n");
        data.into_bytes()
    }

    #[test]
    fn parse_station_position() {
        let sol = read_sinex(
            sample_sinex(false, "00:001:00000").as_slice(),
            ParseMode::Permissive,
        )
        .expect("parse");
        assert_eq!(sol.agency, "IGS");
        assert_eq!(sol.stations.len(), 1);
        let st = &sol.stations[0];
        assert_eq!(st.code, "ABCD");
        assert_eq!(st.point_code, "A");
        assert_eq!(st.solution_id, "1");
        assert!((st.position.x().value() - 1.0e6).abs() < 1e-3);
        assert!((st.position.y().value() + 2.0e6).abs() < 1e-3);
        assert!((st.position.z().value() - 3.0e6).abs() < 1e-3);
        assert!(st.velocity_m_yr.is_none());
        assert!(st.ref_epoch_mjd > 0.0);
    }

    #[test]
    fn parse_station_with_velocity() {
        let sol = read_sinex(
            sample_sinex(true, "00:001:00000").as_slice(),
            ParseMode::Permissive,
        )
        .expect("parse");
        let vel = sol.stations[0].velocity_m_yr.expect("velocity");
        assert!((vel[0] - 0.01).abs() < 1e-12);
        assert!((vel[1] - 0.02).abs() < 1e-12);
        assert!((vel[2] - 0.03).abs() < 1e-12);
    }

    #[test]
    fn strict_rejects_short_estimate_line() {
        let data = b"%=SNX 2.10 IGS 24:001:00000 IGS 00:000:00000 23:365:86370 P 00000 0 S\n\
                      +SOLUTION/ESTIMATE\n\
                      1 STAX ABCD\n\
                      -SOLUTION/ESTIMATE\n\
                      %ENDSNX\n";
        let err = read_sinex(&data[..], ParseMode::Strict).unwrap_err();
        assert!(matches!(err, FormatError::Located { .. }));
    }

    #[test]
    fn strict_rejects_unparseable_value() {
        let data = b"%=SNX 2.10 IGS 24:001:00000 IGS 00:000:00000 23:365:86370 P 00000 0 S\n\
                      +SOLUTION/ESTIMATE\n\
                      *Index Type__ Code Pt Soln _Ref_Epoch__ Unit S ___Estimated_Value___ __Std_Dev__\n\
                      1 STAX   ABCD  A    1 00:001:00000 m    2  not-a-number  1.000E-04\n\
                      -SOLUTION/ESTIMATE\n\
                      %ENDSNX\n";
        let err = read_sinex(&data[..], ParseMode::Strict).unwrap_err();
        assert!(matches!(err, FormatError::Located { .. }));
    }

    #[test]
    fn permissive_skips_bad_estimate_lines() {
        let data = b"%=SNX 2.10 IGS 24:001:00000 IGS 00:000:00000 23:365:86370 P 00000 0 S\n\
                      +SOLUTION/ESTIMATE\n\
                      short line\n\
                      1 STAX   ABCD  A    1 00:001:00000 m    2  1.000000000000000E+06  1.000E-04\n\
                      bad-value-line\n\
                      2 STAY   ABCD  A    1 00:001:00000 m    2 -2.000000000000000E+06  1.000E-04\n\
                      3 STAZ   ABCD  A    1 00:001:00000 m    2  3.000000000000000E+06  1.000E-04\n\
                      -SOLUTION/ESTIMATE\n\
                      %ENDSNX\n";
        let sol = read_sinex(&data[..], ParseMode::Permissive).expect("parse");
        assert_eq!(sol.stations.len(), 1);
    }

    #[test]
    fn incomplete_xyz_skips_station() {
        let data = b"%=SNX 2.10 IGS 24:001:00000 IGS 00:000:00000 23:365:86370 P 00000 0 S\n\
                      +SOLUTION/ESTIMATE\n\
                      1 STAX   ABCD  A    1 00:001:00000 m    2  1.000000000000000E+06  1.000E-04\n\
                      2 STAY   ABCD  A    1 00:001:00000 m    2 -2.000000000000000E+06  1.000E-04\n\
                      -SOLUTION/ESTIMATE\n\
                      %ENDSNX\n";
        let sol = read_sinex(&data[..], ParseMode::Permissive).expect("parse");
        assert!(sol.stations.is_empty());
    }

    #[test]
    fn epoch_yy80_maps_to_19xx() {
        let sol = read_sinex(
            sample_sinex(false, "85:001:00000").as_slice(),
            ParseMode::Permissive,
        )
        .expect("parse");
        assert!(sol.stations[0].ref_epoch_mjd > 46_000.0);
    }

    #[test]
    fn invalid_epoch_returns_zero_mjd() {
        let sol = read_sinex(
            sample_sinex(false, "not-valid").as_slice(),
            ParseMode::Permissive,
        )
        .expect("parse");
        assert_eq!(sol.stations[0].ref_epoch_mjd, 0.0);
    }

    #[test]
    fn geo_center_name() {
        assert_eq!(GeoCenterItrf::center_name(), "Geocentric ITRF");
    }
}