Skip to main content

nyx_space/od/msr/trackingdata/
mod.rs

1/*
2    Nyx, blazing fast astrodynamics
3    Copyright (C) 2018-onwards Christopher Rabotin <christopher.rabotin@gmail.com>
4
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU Affero General Public License as published
7    by the Free Software Foundation, either version 3 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU Affero General Public License for more details.
14
15    You should have received a copy of the GNU Affero General Public License
16    along with this program.  If not, see <https://www.gnu.org/licenses/>.
17*/
18use super::{MeasurementType, measurement::Measurement};
19use core::fmt;
20use hifitime::prelude::{Duration, Epoch};
21use indexmap::{IndexMap, IndexSet};
22use log::{info, warn};
23use std::ops::Bound::{self, Excluded, Included, Unbounded};
24use std::ops::{Add, AddAssign, RangeBounds};
25
26mod io_ccsds_tdm;
27mod io_parquet;
28
29#[cfg(feature = "python")]
30use pyo3::prelude::*;
31#[cfg(feature = "python")]
32mod python;
33
34/// Tracking data storing all of measurements as a B-Tree.
35/// It inherently does NOT support multiple concurrent measurements from several trackers.
36///
37/// # Measurement Moduli, e.g. range modulus
38///
39/// In the case of ranging, and possibly other data types, a code is used to measure the range to the spacecraft. The length of this code
40/// determines the ambiguity resolution, as per equation 9 in section 2.2.2.2 of the JPL DESCANSO, document 214, _Pseudo-Noise and Regenerative Ranging_.
41/// For example, using the JPL Range Code and a frequency range clock of 1 MHz, the range ambiguity is 75,660 km. In other words,
42/// as soon as the spacecraft is at a range of 75,660 + 1 km the JPL Range Code will report the vehicle to be at a range of 1 km.
43/// This is simply because the range code overlaps with itself, effectively loosing track of its own reference:
44/// it's due to the phase shift of the signal "lapping" the original signal length.
45///
46/// ```text
47///             (Spacecraft)
48///             ^
49///             |    Actual Distance = 75,661 km
50///             |
51/// 0 km                                         75,660 km (Wrap-Around)
52/// |-----------------------------------------------|
53///   When the "code length" is exceeded,
54///   measurements wrap back to 0.
55///
56/// So effectively:
57///     Observed code range = Actual range (mod 75,660 km)
58///     75,661 km → 1 km
59///
60/// ```
61///
62/// Nyx can only resolve the range ambiguity if the tracking data specifies a modulus for this specific measurement type.
63/// For example, in the case of the JPL Range Code and a 1 MHz range clock, the ambiguity interval is 75,660 km.
64///
65/// The measurement used in the Orbit Determination Process then becomes the following, where `//` represents the [Euclidian division](https://doc.rust-lang.org/std/primitive.f64.html#method.div_euclid).
66///
67/// ```text
68/// k = computed_obs // ambiguity_interval
69/// real_obs = measured_obs + k * modulus
70/// ```
71///
72/// Reference: JPL DESCANSO, document 214, _Pseudo-Noise and Regenerative Ranging_.
73///
74/// :type measurements: list[Measurement]
75#[derive(Clone, Default)]
76#[cfg_attr(feature = "python", pyclass(from_py_object))]
77pub struct TrackingDataArc {
78    /// All measurements in this data arc
79    pub measurements: Vec<Measurement>,
80    /// Source file if loaded from a file or saved to a file.
81    pub source: Option<String>,
82    /// Optionally provide a map of modulos (e.g. the RANGE_MODULO of CCSDS TDM).
83    pub moduli: Option<IndexMap<MeasurementType, f64>>,
84    /// Reject all of the measurements, useful for debugging passes.
85    pub force_reject: bool,
86}
87
88#[cfg_attr(feature = "python", pymethods)]
89impl TrackingDataArc {
90    /// Sort these measurements by epoch
91    /// :rtype: None
92    pub fn sort(&mut self) {
93        self.measurements.sort_unstable_by(|a, b| {
94            a.epoch
95                .cmp(&b.epoch)
96                .then_with(|| a.tracker.cmp(&b.tracker))
97        });
98
99        // Coalesce adjacent duplicate elements in exactly O(K) time.
100        // dedup_by passes pointers to `(next_element, kept_element)`.
101        // If the closure returns true, `next_element` is physically dropped.
102        self.measurements.dedup_by(|next, kept| {
103            if next.epoch == kept.epoch && next.tracker == kept.tracker {
104                // The tracker and epoch are identical. Drain the sub-observables
105                // from the redundant 'next' measurement and merge them into the 'kept' one.
106                kept.data.extend(next.data.drain(..));
107
108                // If either partial record was manually flagged as rejected,
109                // the combined radiometric record must retain that suspicion.
110                kept.rejected |= next.rejected;
111
112                // Return true to destroy the redundant parent struct.
113                true
114            } else {
115                // Elements differ structurally. Keep both.
116                false
117            }
118        });
119    }
120    /// Returns the start epoch of this tracking arc
121    /// :rtype: Epoch | None
122    pub fn start_epoch(&self) -> Option<Epoch> {
123        self.measurements.first().map(|msr| msr.epoch)
124    }
125
126    /// Returns the end epoch of this tracking arc
127    /// :rtype: Epoch | None
128    pub fn end_epoch(&self) -> Option<Epoch> {
129        self.measurements.last().map(|msr| msr.epoch)
130    }
131
132    /// Returns the duration this tracking arc
133    /// :rtype: Duration | None
134    pub fn duration(&self) -> Option<Duration> {
135        match self.start_epoch() {
136            Some(start) => self.end_epoch().map(|end| end - start),
137            None => None,
138        }
139    }
140
141    /// Returns the number of measurements in this data arc
142    /// :rtype: int
143    pub fn len(&self) -> usize {
144        self.measurements.len()
145    }
146
147    /// Returns whether this arc has no measurements.
148    /// :rtype: bool
149    pub fn is_empty(&self) -> bool {
150        self.measurements.is_empty()
151    }
152
153    /// Returns the minimum duration between two subsequent measurements.
154    /// :rtype: Duration | None
155    pub fn min_duration_sep(&self) -> Option<Duration> {
156        if self.is_empty() {
157            None
158        } else {
159            let mut min_sep = Duration::MAX;
160            let mut prev_epoch = self.start_epoch().unwrap();
161            for msr in self.measurements.iter().skip(1) {
162                let epoch = msr.epoch;
163                let this_sep = epoch - prev_epoch;
164                min_sep = min_sep.min(this_sep);
165                prev_epoch = epoch;
166            }
167            Some(min_sep)
168        }
169    }
170    /// Set (or overwrites) the modulus of the provided measurement type.
171    ///
172    /// :type msr_type: MeasurementType
173    /// :type modulus: float
174    /// :rtype: None
175    pub fn set_moduli(&mut self, msr_type: MeasurementType, modulus: f64) {
176        if modulus.is_nan() || modulus.abs() < f64::EPSILON {
177            warn!("cannot set modulus for {msr_type:?} to {modulus}");
178            return;
179        }
180        if self.moduli.is_none() {
181            self.moduli = Some(IndexMap::new());
182        }
183
184        self.moduli.as_mut().unwrap().insert(msr_type, modulus);
185    }
186
187    /// Applies the moduli to each measurement, if defined.
188    /// :rtype: None
189    pub fn apply_moduli(&mut self) {
190        if let Some(moduli) = &self.moduli {
191            for msr in &mut self.measurements {
192                for (msr_type, modulus) in moduli {
193                    if let Some(msr_value) = msr.data.get_mut(msr_type) {
194                        *msr_value %= *modulus;
195                    }
196                }
197            }
198        }
199    }
200
201    /// Downsamples the tracking data to a lower frequency using a simple moving average low-pass filter followed by decimation,
202    /// returning new `TrackingDataArc` with downsampled measurements.
203    ///
204    /// It provides a computationally efficient approach to reduce the sampling rate while mitigating aliasing effects.
205    ///
206    /// # Algorithm
207    ///
208    /// 1. A simple moving average filter is applied as a low-pass filter.
209    /// 2. Decimation is performed by selecting every Nth sample after filtering.
210    ///
211    /// # Advantages
212    ///
213    /// - Computationally efficient, suitable for large datasets common in spaceflight applications.
214    /// - Provides basic anti-aliasing, crucial for preserving signal integrity in orbit determination and tracking.
215    /// - Maintains phase information, important for accurate timing in spacecraft state estimation.
216    ///
217    /// # Limitations
218    ///
219    /// - The frequency response is not as sharp as more sophisticated filters (e.g., FIR, IIR).
220    /// - May not provide optimal stopband attenuation for high-precision applications.
221    ///
222    /// ## Considerations for Spaceflight Applications
223    ///
224    /// - Suitable for initial data reduction in ground station tracking pipelines.
225    /// - Adequate for many orbit determination and tracking tasks where computational speed is prioritized.
226    /// - For high-precision applications (e.g., interplanetary navigation), consider using more advanced filtering techniques.
227    ///
228    /// :type target_step: Duration
229    /// :rtype: TrackingDataArc
230    pub fn downsample(&self, target_step: Duration) -> Self {
231        if self.is_empty() {
232            return self.clone();
233        }
234        let current_step = self.min_duration_sep().unwrap();
235
236        if current_step >= target_step {
237            warn!(
238                "cannot downsample tracking data from {current_step} to {target_step} (that would be upsampling)"
239            );
240            return self.clone();
241        }
242
243        let current_hz = 1.0 / current_step.to_seconds();
244        let target_hz = 1.0 / target_step.to_seconds();
245
246        // Simple moving average as low-pass filter
247        let window_size = (current_hz / target_hz).round() as usize;
248
249        info!(
250            "downsampling tracking data from {current_step} ({current_hz:.6} Hz) to {target_step} ({target_hz:.6} Hz) (N = {window_size})"
251        );
252
253        let mut result = TrackingDataArc {
254            source: self.source.clone(),
255            ..Default::default()
256        };
257
258        let measurements: Vec<_> = self.measurements.iter().collect();
259
260        for (i, msr) in measurements.iter().enumerate().step_by(window_size) {
261            let epoch = msr.epoch;
262            let start = i.saturating_sub(window_size / 2);
263            let end = (i + window_size / 2 + 1).min(measurements.len());
264            let window = &measurements[start..end];
265
266            let mut filtered_measurement = Measurement {
267                tracker: window[0].tracker.clone(),
268                epoch,
269                data: IndexMap::new(),
270                rejected: false,
271                doppler_config: msr.doppler_config,
272            };
273
274            // Apply moving average filter for each measurement type
275            for mtype in self.unique_types() {
276                let sum: f64 = window.iter().filter_map(|m| m.data.get(&mtype)).sum();
277                let count = window
278                    .iter()
279                    .filter(|m| m.data.contains_key(&mtype))
280                    .count();
281
282                if count > 0 {
283                    filtered_measurement.data.insert(mtype, sum / count as f64);
284                }
285            }
286
287            result.measurements.push(filtered_measurement);
288        }
289        result.sort();
290        result
291    }
292
293    /// Splits a long tracking data arc into smaller chunks, each up to `max_duration` long.
294    ///
295    /// :type max_duration: Duration
296    /// :rtype: list[TrackingDataArc]
297    pub fn chunk(&self, max_duration: Duration) -> Vec<TrackingDataArc> {
298        let mut chunks = Vec::new();
299        if self.is_empty() || max_duration <= Duration::ZERO {
300            return chunks;
301        }
302
303        let mut start_idx = 0;
304        let total_measurements = self.measurements.len();
305
306        while start_idx < total_measurements {
307            let chunk_start_epoch = self.measurements[start_idx].epoch;
308            let chunk_end_time = chunk_start_epoch + max_duration;
309
310            // Isolate the remaining, unprocessed portion of the vector
311            let remaining = &self.measurements[start_idx..];
312
313            // Perform a binary search on the remaining slice to find the first
314            // index that strictly exceeds the chunk_end_time.
315            let offset = remaining.partition_point(|msr| msr.epoch <= chunk_end_time);
316
317            let end_idx = start_idx + offset;
318
319            // Extract and clone ONLY the measurements belonging to this chunk.
320            // This drops the memory complexity from O(K * N) to strictly O(N).
321            let chunk_measurements = self.measurements[start_idx..end_idx].to_vec();
322
323            chunks.push(TrackingDataArc {
324                measurements: chunk_measurements,
325                source: self.source.clone(),
326                moduli: self.moduli.clone(),
327                force_reject: self.force_reject,
328            });
329
330            // Advance the window to the exact start of the next chunk
331            start_idx = end_idx;
332        }
333
334        chunks
335    }
336}
337
338impl TrackingDataArc {
339    /// Helper method to resolve bounds into slice indices via binary search.
340    fn resolve_bounds<R: RangeBounds<Epoch>>(&self, bound: R) -> (usize, usize) {
341        // Find the lower bound index via O(log N) binary search
342        let start_idx = match bound.start_bound() {
343            Bound::Included(&epoch) => self.measurements.partition_point(|m| m.epoch < epoch),
344            Bound::Excluded(&epoch) => self.measurements.partition_point(|m| m.epoch <= epoch),
345            Bound::Unbounded => 0,
346        };
347
348        // Find the upper bound index via O(log N) binary search
349        let end_idx = match bound.end_bound() {
350            Bound::Included(&epoch) => self.measurements.partition_point(|m| m.epoch <= epoch),
351            Bound::Excluded(&epoch) => self.measurements.partition_point(|m| m.epoch < epoch),
352            Bound::Unbounded => self.measurements.len(),
353        };
354
355        (start_idx, end_idx)
356    }
357
358    /// Returns the unique list of aliases in this tracking data arc
359    pub fn unique_aliases(&self) -> IndexSet<String> {
360        self.unique().0
361    }
362
363    /// Returns the unique measurement types in this tracking data arc
364    pub fn unique_types(&self) -> IndexSet<MeasurementType> {
365        self.unique().1
366    }
367
368    /// Returns the unique trackers and unique measurement types in this data arc
369    pub fn unique(&self) -> (IndexSet<String>, IndexSet<MeasurementType>) {
370        let mut aliases = IndexSet::new();
371        let mut types = IndexSet::new();
372        for msr in &self.measurements {
373            aliases.insert(msr.tracker.clone());
374            for k in msr.data.keys() {
375                types.insert(*k);
376            }
377        }
378        (aliases, types)
379    }
380
381    /// Returns a new tracking arc that only contains measurements that fall within the given epoch range.
382    ///
383    /// Executes in O(N) time strictly due to memory shifting, requiring zero new allocations.
384    pub fn filter_by_epoch<R: RangeBounds<Epoch>>(mut self, bound: R) -> Self {
385        let (start_idx, end_idx) = self.resolve_bounds(bound);
386
387        // Handle disjoint bounds or out-of-range queries
388        if start_idx >= end_idx || start_idx >= self.measurements.len() {
389            self.measurements.clear();
390            return self;
391        }
392
393        // In-place memory reduction
394        // Truncate the tail first. This drops trailing measurements without shifting.
395        self.measurements.truncate(end_idx);
396
397        // Drain the head. This removes preceding measurements and shifts the
398        // remaining valid data leftward to index 0 in a single memory move.
399        self.measurements.drain(0..start_idx);
400
401        // Note that the order is preserved, so we don't need to sort again.
402
403        // Clear unused memory
404        self.measurements.shrink_to_fit();
405
406        self
407    }
408
409    /// Returns a new tracking arc that only contains measurements that fall within the given offset from the first epoch.
410    /// For example, a bound of 30.minutes()..90.minutes() will only read measurements from the start of the arc + 30 minutes until start + 90 minutes.
411    pub fn filter_by_offset<R: RangeBounds<Duration>>(self, bound: R) -> Self {
412        if self.is_empty() {
413            return self;
414        }
415        // Rebuild an epoch bound.
416        let start = match bound.start_bound() {
417            Unbounded => self.start_epoch().unwrap(),
418            Included(offset) | Excluded(offset) => self.start_epoch().unwrap() + *offset,
419        };
420
421        let end = match bound.end_bound() {
422            Unbounded => self.end_epoch().unwrap(),
423            Included(offset) | Excluded(offset) => self.start_epoch().unwrap() + *offset,
424        };
425
426        self.filter_by_epoch(start..end)
427    }
428
429    /// Returns a new tracking arc that only contains measurements from the desired tracker.
430    pub fn filter_by_tracker(mut self, tracker: String) -> Self {
431        self.measurements = self
432            .measurements
433            .iter()
434            .filter_map(|msr| {
435                if msr.tracker == tracker {
436                    Some(msr.clone())
437                } else {
438                    None
439                }
440            })
441            .collect::<Vec<Measurement>>();
442        self
443    }
444
445    /// Returns a new tracking arc that only contains measurements of the provided type.
446    pub fn filter_by_measurement_type(mut self, included_type: MeasurementType) -> Self {
447        self.measurements.retain_mut(|msr| {
448            msr.data.retain(|msr_type, _| *msr_type == included_type);
449            !msr.data.is_empty()
450        });
451        self
452    }
453
454    /// Returns a new tracking arc that contains measurements from all trackers except the one provided
455    pub fn exclude_tracker(mut self, excluded_tracker: String) -> Self {
456        self.measurements = self
457            .measurements
458            .iter()
459            .filter_map(|msr| {
460                if msr.tracker != excluded_tracker {
461                    Some(msr.clone())
462                } else {
463                    None
464                }
465            })
466            .collect::<Vec<Measurement>>();
467        self
468    }
469
470    /// Returns a new tracking arc that excludes measurements within the given epoch range.
471    ///
472    /// Executes an in-place O(N) memory shift with zero heap allocations.
473    pub fn exclude_by_epoch<R: RangeBounds<Epoch>>(mut self, bound: R) -> Self {
474        let (start_idx, end_idx) = self.resolve_bounds(bound);
475
476        if start_idx < end_idx && start_idx < self.measurements.len() {
477            // Drain removes the specified range and shifts all subsequent elements
478            // leftward to fill the gap. The extracted elements are immediately dropped.
479            self.measurements.drain(start_idx..end_idx);
480        }
481
482        self
483    }
484
485    /// Returns a new tracking arc that contains measurements from all trackers except the one provided
486    pub fn exclude_measurement_type(mut self, excluded_type: MeasurementType) -> Self {
487        self.measurements = self
488            .measurements
489            .iter_mut()
490            .map(|msr| {
491                msr.data.retain(|msr_type, _| *msr_type != excluded_type);
492                msr.clone()
493            })
494            .collect::<Vec<Measurement>>();
495        self
496    }
497
498    /// Marks measurements within the given epoch range as rejected.
499    ///
500    /// Operates in O(log N) for bound resolution and O(K) for iteration, where K is the slice length.
501    pub fn reject_by_epoch<R: RangeBounds<Epoch>>(mut self, bound: R) -> Self {
502        let (start_idx, end_idx) = self.resolve_bounds(bound);
503
504        if start_idx < end_idx && start_idx < self.measurements.len() {
505            for msr in &mut self.measurements[start_idx..end_idx] {
506                msr.rejected = true;
507            }
508        }
509        self
510    }
511
512    /// Marks measurements from the provided tracker as rejected.
513    /// Requires an O(N) scan. The parameter is downgraded to &str to prevent heap allocations.
514    pub fn reject_by_tracker(mut self, tracker: &str) -> Self {
515        for msr in &mut self.measurements {
516            if msr.tracker == tracker {
517                msr.rejected = true;
518            }
519        }
520        self
521    }
522
523    pub fn resid_vs_ref_check(mut self) -> Self {
524        self.force_reject = true;
525        self
526    }
527}
528
529impl fmt::Display for TrackingDataArc {
530    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
531        if self.is_empty() {
532            write!(f, "Empty tracking arc")
533        } else {
534            let start = self.start_epoch().unwrap();
535            let end = self.end_epoch().unwrap();
536            let src = match &self.source {
537                Some(src) => format!(" (source: {src})"),
538                None => String::new(),
539            };
540            write!(
541                f,
542                "Tracking arc with {} measurements of type {:?} over {} (from {start} to {end}) with trackers {:?}{src}",
543                self.len(),
544                self.unique_types(),
545                end - start,
546                self.unique_aliases()
547            )
548        }
549    }
550}
551
552impl fmt::Debug for TrackingDataArc {
553    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
554        write!(f, "{self} @ {self:p}")
555    }
556}
557
558impl PartialEq for TrackingDataArc {
559    fn eq(&self, other: &Self) -> bool {
560        self.measurements == other.measurements
561    }
562}
563
564impl Add for TrackingDataArc {
565    type Output = Self;
566
567    fn add(mut self, rhs: Self) -> Self::Output {
568        self.force_reject = false;
569        self.measurements.extend(rhs.measurements);
570        self.sort();
571
572        self.force_reject = false;
573        self
574    }
575}
576
577impl AddAssign for TrackingDataArc {
578    fn add_assign(&mut self, rhs: Self) {
579        *self = self.clone() + rhs;
580    }
581}