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            };
272
273            // Apply moving average filter for each measurement type
274            for mtype in self.unique_types() {
275                let sum: f64 = window.iter().filter_map(|m| m.data.get(&mtype)).sum();
276                let count = window
277                    .iter()
278                    .filter(|m| m.data.contains_key(&mtype))
279                    .count();
280
281                if count > 0 {
282                    filtered_measurement.data.insert(mtype, sum / count as f64);
283                }
284            }
285
286            result.measurements.push(filtered_measurement);
287        }
288        result.sort();
289        result
290    }
291
292    /// Splits a long tracking data arc into smaller chunks, each up to `max_duration` long.
293    ///
294    /// :type max_duration: Duration
295    /// :rtype: list[TrackingDataArc]
296    pub fn chunk(&self, max_duration: Duration) -> Vec<TrackingDataArc> {
297        let mut chunks = Vec::new();
298        if self.is_empty() || max_duration <= Duration::ZERO {
299            return chunks;
300        }
301
302        let mut start_idx = 0;
303        let total_measurements = self.measurements.len();
304
305        while start_idx < total_measurements {
306            let chunk_start_epoch = self.measurements[start_idx].epoch;
307            let chunk_end_time = chunk_start_epoch + max_duration;
308
309            // Isolate the remaining, unprocessed portion of the vector
310            let remaining = &self.measurements[start_idx..];
311
312            // Perform a binary search on the remaining slice to find the first
313            // index that strictly exceeds the chunk_end_time.
314            let offset = remaining.partition_point(|msr| msr.epoch <= chunk_end_time);
315
316            let end_idx = start_idx + offset;
317
318            // Extract and clone ONLY the measurements belonging to this chunk.
319            // This drops the memory complexity from O(K * N) to strictly O(N).
320            let chunk_measurements = self.measurements[start_idx..end_idx].to_vec();
321
322            chunks.push(TrackingDataArc {
323                measurements: chunk_measurements,
324                source: self.source.clone(),
325                moduli: self.moduli.clone(),
326                force_reject: self.force_reject,
327            });
328
329            // Advance the window to the exact start of the next chunk
330            start_idx = end_idx;
331        }
332
333        chunks
334    }
335}
336
337impl TrackingDataArc {
338    /// Helper method to resolve bounds into slice indices via binary search.
339    fn resolve_bounds<R: RangeBounds<Epoch>>(&self, bound: R) -> (usize, usize) {
340        // Find the lower bound index via O(log N) binary search
341        let start_idx = match bound.start_bound() {
342            Bound::Included(&epoch) => self.measurements.partition_point(|m| m.epoch < epoch),
343            Bound::Excluded(&epoch) => self.measurements.partition_point(|m| m.epoch <= epoch),
344            Bound::Unbounded => 0,
345        };
346
347        // Find the upper bound index via O(log N) binary search
348        let end_idx = match bound.end_bound() {
349            Bound::Included(&epoch) => self.measurements.partition_point(|m| m.epoch <= epoch),
350            Bound::Excluded(&epoch) => self.measurements.partition_point(|m| m.epoch < epoch),
351            Bound::Unbounded => self.measurements.len(),
352        };
353
354        (start_idx, end_idx)
355    }
356
357    /// Returns the unique list of aliases in this tracking data arc
358    pub fn unique_aliases(&self) -> IndexSet<String> {
359        self.unique().0
360    }
361
362    /// Returns the unique measurement types in this tracking data arc
363    pub fn unique_types(&self) -> IndexSet<MeasurementType> {
364        self.unique().1
365    }
366
367    /// Returns the unique trackers and unique measurement types in this data arc
368    pub fn unique(&self) -> (IndexSet<String>, IndexSet<MeasurementType>) {
369        let mut aliases = IndexSet::new();
370        let mut types = IndexSet::new();
371        for msr in &self.measurements {
372            aliases.insert(msr.tracker.clone());
373            for k in msr.data.keys() {
374                types.insert(*k);
375            }
376        }
377        (aliases, types)
378    }
379
380    /// Returns a new tracking arc that only contains measurements that fall within the given epoch range.
381    ///
382    /// Executes in O(N) time strictly due to memory shifting, requiring zero new allocations.
383    pub fn filter_by_epoch<R: RangeBounds<Epoch>>(mut self, bound: R) -> Self {
384        let (start_idx, end_idx) = self.resolve_bounds(bound);
385
386        // Handle disjoint bounds or out-of-range queries
387        if start_idx >= end_idx || start_idx >= self.measurements.len() {
388            self.measurements.clear();
389            return self;
390        }
391
392        // In-place memory reduction
393        // Truncate the tail first. This drops trailing measurements without shifting.
394        self.measurements.truncate(end_idx);
395
396        // Drain the head. This removes preceding measurements and shifts the
397        // remaining valid data leftward to index 0 in a single memory move.
398        self.measurements.drain(0..start_idx);
399
400        // Note that the order is preserved, so we don't need to sort again.
401
402        // Clear unused memory
403        self.measurements.shrink_to_fit();
404
405        self
406    }
407
408    /// Returns a new tracking arc that only contains measurements that fall within the given offset from the first epoch.
409    /// 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.
410    pub fn filter_by_offset<R: RangeBounds<Duration>>(self, bound: R) -> Self {
411        if self.is_empty() {
412            return self;
413        }
414        // Rebuild an epoch bound.
415        let start = match bound.start_bound() {
416            Unbounded => self.start_epoch().unwrap(),
417            Included(offset) | Excluded(offset) => self.start_epoch().unwrap() + *offset,
418        };
419
420        let end = match bound.end_bound() {
421            Unbounded => self.end_epoch().unwrap(),
422            Included(offset) | Excluded(offset) => self.start_epoch().unwrap() + *offset,
423        };
424
425        self.filter_by_epoch(start..end)
426    }
427
428    /// Returns a new tracking arc that only contains measurements from the desired tracker.
429    pub fn filter_by_tracker(mut self, tracker: String) -> Self {
430        self.measurements = self
431            .measurements
432            .iter()
433            .filter_map(|msr| {
434                if msr.tracker == tracker {
435                    Some(msr.clone())
436                } else {
437                    None
438                }
439            })
440            .collect::<Vec<Measurement>>();
441        self
442    }
443
444    /// Returns a new tracking arc that only contains measurements of the provided type.
445    pub fn filter_by_measurement_type(mut self, included_type: MeasurementType) -> Self {
446        self.measurements.retain_mut(|msr| {
447            msr.data.retain(|msr_type, _| *msr_type == included_type);
448            !msr.data.is_empty()
449        });
450        self
451    }
452
453    /// Returns a new tracking arc that contains measurements from all trackers except the one provided
454    pub fn exclude_tracker(mut self, excluded_tracker: String) -> Self {
455        self.measurements = self
456            .measurements
457            .iter()
458            .filter_map(|msr| {
459                if msr.tracker != excluded_tracker {
460                    Some(msr.clone())
461                } else {
462                    None
463                }
464            })
465            .collect::<Vec<Measurement>>();
466        self
467    }
468
469    /// Returns a new tracking arc that excludes measurements within the given epoch range.
470    ///
471    /// Executes an in-place O(N) memory shift with zero heap allocations.
472    pub fn exclude_by_epoch<R: RangeBounds<Epoch>>(mut self, bound: R) -> Self {
473        let (start_idx, end_idx) = self.resolve_bounds(bound);
474
475        if start_idx < end_idx && start_idx < self.measurements.len() {
476            // Drain removes the specified range and shifts all subsequent elements
477            // leftward to fill the gap. The extracted elements are immediately dropped.
478            self.measurements.drain(start_idx..end_idx);
479        }
480
481        self
482    }
483
484    /// Returns a new tracking arc that contains measurements from all trackers except the one provided
485    pub fn exclude_measurement_type(mut self, excluded_type: MeasurementType) -> Self {
486        self.measurements = self
487            .measurements
488            .iter_mut()
489            .map(|msr| {
490                msr.data.retain(|msr_type, _| *msr_type != excluded_type);
491                msr.clone()
492            })
493            .collect::<Vec<Measurement>>();
494        self
495    }
496
497    /// Marks measurements within the given epoch range as rejected.
498    ///
499    /// Operates in O(log N) for bound resolution and O(K) for iteration, where K is the slice length.
500    pub fn reject_by_epoch<R: RangeBounds<Epoch>>(mut self, bound: R) -> Self {
501        let (start_idx, end_idx) = self.resolve_bounds(bound);
502
503        if start_idx < end_idx && start_idx < self.measurements.len() {
504            for msr in &mut self.measurements[start_idx..end_idx] {
505                msr.rejected = true;
506            }
507        }
508        self
509    }
510
511    /// Marks measurements from the provided tracker as rejected.
512    /// Requires an O(N) scan. The parameter is downgraded to &str to prevent heap allocations.
513    pub fn reject_by_tracker(mut self, tracker: &str) -> Self {
514        for msr in &mut self.measurements {
515            if msr.tracker == tracker {
516                msr.rejected = true;
517            }
518        }
519        self
520    }
521
522    pub fn resid_vs_ref_check(mut self) -> Self {
523        self.force_reject = true;
524        self
525    }
526}
527
528impl fmt::Display for TrackingDataArc {
529    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
530        if self.is_empty() {
531            write!(f, "Empty tracking arc")
532        } else {
533            let start = self.start_epoch().unwrap();
534            let end = self.end_epoch().unwrap();
535            let src = match &self.source {
536                Some(src) => format!(" (source: {src})"),
537                None => String::new(),
538            };
539            write!(
540                f,
541                "Tracking arc with {} measurements of type {:?} over {} (from {start} to {end}) with trackers {:?}{src}",
542                self.len(),
543                self.unique_types(),
544                end - start,
545                self.unique_aliases()
546            )
547        }
548    }
549}
550
551impl fmt::Debug for TrackingDataArc {
552    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
553        write!(f, "{self} @ {self:p}")
554    }
555}
556
557impl PartialEq for TrackingDataArc {
558    fn eq(&self, other: &Self) -> bool {
559        self.measurements == other.measurements
560    }
561}
562
563impl Add for TrackingDataArc {
564    type Output = Self;
565
566    fn add(mut self, rhs: Self) -> Self::Output {
567        self.force_reject = false;
568        self.measurements.extend(rhs.measurements);
569        self.sort();
570
571        self.force_reject = false;
572        self
573    }
574}
575
576impl AddAssign for TrackingDataArc {
577    fn add_assign(&mut self, rhs: Self) {
578        *self = self.clone() + rhs;
579    }
580}