Skip to main content

nyx_space/od/groundpnt/
solution.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*/
18
19use crate::State;
20use crate::io::watermark::pq_writer;
21use crate::io::{ArrowSnafu, ExportCfg, ParquetSnafu, StdIOSnafu};
22use crate::linalg::DefaultAllocator;
23use crate::linalg::allocator::Allocator;
24use crate::md::StateParameter;
25use crate::md::trajectory::Interpolatable;
26use crate::od::estimate::*;
27use crate::od::groundpnt::GroundAsset;
28use crate::od::interlink::InterlinkTxSpacecraft;
29use crate::od::process::ODSolution;
30use crate::{Spacecraft, od::*};
31use arrow::array::{Array, BooleanBuilder, Float64Builder, StringBuilder};
32use arrow::datatypes::{DataType, Field, Schema};
33use arrow::record_batch::RecordBatch;
34use hifitime::TimeScale;
35use log::{info, warn};
36use nalgebra::{Const, U2};
37use parquet::arrow::ArrowWriter;
38use snafu::prelude::*;
39use std::collections::HashMap;
40use std::fs::File;
41use std::path::{Path, PathBuf};
42
43impl ODSolution<GroundAsset, KfEstimate<GroundAsset>, U2, InterlinkTxSpacecraft>
44where
45    DefaultAllocator: Allocator<U2>
46        + Allocator<U2, <Spacecraft as State>::Size>
47        + Allocator<Const<1>, U2>
48        + Allocator<<Spacecraft as State>::Size>
49        + Allocator<<Spacecraft as State>::Size, <Spacecraft as State>::Size>
50        + Allocator<U2, U2>
51        + Allocator<U2, <Spacecraft as State>::Size>
52        + Allocator<<Spacecraft as State>::Size, U2>
53        + Allocator<<Spacecraft as State>::Size>
54        + Allocator<<Spacecraft as State>::VecLength>
55        + Allocator<<Spacecraft as State>::Size, <Spacecraft as State>::Size>,
56{
57    /// Store the estimates and residuals in a parquet file
58    pub fn to_parquet<P: AsRef<Path>>(&self, path: P, cfg: ExportCfg) -> Result<PathBuf, ODError> {
59        ensure!(
60            !self.estimates.is_empty(),
61            TooFewMeasurementsSnafu {
62                need: 1_usize,
63                action: "exporting PNT results"
64            }
65        );
66
67        if self.estimates.len() != self.residuals.len() {
68            return Err(ODError::ODConfigError {
69                source: ConfigError::InvalidConfig {
70                    msg: format!(
71                        "Estimates ({}) and residuals ({}) are not aligned.",
72                        self.estimates.len(),
73                        self.residuals.len()
74                    ),
75                },
76            });
77        }
78
79        if self.estimates.len() != self.gains.len() {
80            return Err(ODError::ODConfigError {
81                source: ConfigError::InvalidConfig {
82                    msg: format!(
83                        "Estimates ({}) and filter gains ({}) are not aligned.",
84                        self.estimates.len(),
85                        self.gains.len()
86                    ),
87                },
88            });
89        }
90
91        if self.estimates.len() != self.filter_smoother_ratios.len() {
92            return Err(ODError::ODConfigError {
93                source: ConfigError::InvalidConfig {
94                    msg: format!(
95                        "Estimates ({}) and filter-smoother ratios ({}) are not aligned.",
96                        self.estimates.len(),
97                        self.filter_smoother_ratios.len()
98                    ),
99                },
100            });
101        }
102
103        let tick = Epoch::now().unwrap();
104        info!("Exporting orbit determination result to parquet file...");
105
106        if cfg.step.is_some() {
107            warn!(
108                "The `step` parameter in the export is not supported for orbit determination exports."
109            );
110        }
111
112        // Grab the path here before we move stuff.
113        let path_buf = cfg.actual_path(path);
114
115        // Build the schema
116        let mut hdrs = vec![Field::new("Epoch (UTC)", DataType::Utf8, false)];
117
118        let frame = self.estimates[0].state().frame();
119
120        let more_meta = Some(vec![(
121            "Frame".to_string(),
122            serde_dhall::serialize(&frame)
123                .static_type_annotation()
124                .to_string()
125                .map_err(|e| ODError::ODIOError {
126                    source: InputOutputError::SerializeDhall {
127                        what: format!("frame `{frame}`"),
128                        err: e.to_string(),
129                    },
130                })?,
131        )]);
132
133        let mut fields = GroundAsset::export_params();
134
135        // Check that we can retrieve this information
136        fields.retain(|param| match self.estimates[0].state().value(*param) {
137            Ok(_) => param != &StateParameter::GuidanceMode(),
138            Err(_) => false,
139        });
140
141        for field in &fields {
142            hdrs.push(field.to_field(more_meta.clone()));
143        }
144
145        let mut sigma_fields = fields.clone();
146        // Check that we can retrieve this information
147        sigma_fields.retain(|param| matches!(param, StateParameter::Element(_oe)));
148
149        for field in &sigma_fields {
150            hdrs.push(field.to_cov_field(more_meta.clone()));
151        }
152
153        // Don't export the lat/long/alt rate because we don't have the associated state parameters.
154        let state_items = ["Latitude", "Longitude", "Altitude"];
155
156        let state_units = ["deg", "deg", "km"];
157        let mut cov_units = vec![];
158
159        for i in 0..state_items.len() {
160            for j in i..state_items.len() {
161                let cov_unit = format!("{}*{}", state_units[i], state_units[j]);
162
163                cov_units.push(cov_unit);
164            }
165        }
166
167        let mut idx = 0;
168        for i in 0..state_items.len() {
169            for j in i..state_items.len() {
170                hdrs.push(Field::new(
171                    format!(
172                        "Covariance {}*{} ({frame:x}) ({})",
173                        state_items[i], state_items[j], cov_units[idx]
174                    ),
175                    DataType::Float64,
176                    false,
177                ));
178                idx += 1;
179            }
180        }
181
182        // Add the fields of the residuals
183        let mut msr_fields = Vec::new();
184        for f in &self.measurement_types {
185            msr_fields.push(
186                f.to_field()
187                    .with_nullable(true)
188                    .with_name(format!("Prefit residual: {f:?} ({})", f.unit())),
189            );
190        }
191        for f in &self.measurement_types {
192            msr_fields.push(
193                f.to_field()
194                    .with_nullable(true)
195                    .with_name(format!("Postfit residual: {f:?} ({})", f.unit())),
196            );
197        }
198        for f in &self.measurement_types {
199            msr_fields.push(
200                f.to_field()
201                    .with_nullable(true)
202                    .with_name(format!("Measurement noise: {f:?} ({})", f.unit())),
203            );
204        }
205        for f in &self.measurement_types {
206            msr_fields.push(
207                f.to_field()
208                    .with_nullable(true)
209                    .with_name(format!("Real observation: {f:?} ({})", f.unit())),
210            );
211        }
212        for f in &self.measurement_types {
213            msr_fields.push(
214                f.to_field()
215                    .with_nullable(true)
216                    .with_name(format!("Computed observation: {f:?} ({})", f.unit())),
217            );
218        }
219
220        msr_fields.push(Field::new("Residual ratio", DataType::Float64, true));
221        msr_fields.push(Field::new("Residual Rejected", DataType::Boolean, true));
222        msr_fields.push(Field::new("Tracker", DataType::Utf8, true));
223
224        hdrs.append(&mut msr_fields);
225
226        // Add the filter gain columns
227        for i in 0..state_items.len() {
228            for f in &self.measurement_types {
229                hdrs.push(Field::new(
230                    format!(
231                        "Gain {}*{f:?} ({}*{}*{})",
232                        state_items[i],
233                        state_units[i],
234                        state_units[i],
235                        f.unit()
236                    ),
237                    DataType::Float64,
238                    true,
239                ));
240            }
241        }
242
243        // Add the filter-smoother ratio columns
244        for i in 0..state_items.len() {
245            hdrs.push(Field::new(
246                format!(
247                    "Filter-smoother ratio {} ({}*{})",
248                    state_items[i], state_units[i], state_units[i],
249                ),
250                DataType::Float64,
251                true,
252            ));
253        }
254
255        // Build the schema
256        let schema = Arc::new(Schema::new(hdrs));
257        let mut record: Vec<Arc<dyn Array>> = Vec::new();
258
259        // Build the states iterator -- this does require copying the current states but I can't either get a reference or a copy of all the states.
260        let (estimates, residuals) =
261            if cfg.start_epoch.is_some() || cfg.end_epoch.is_some() || cfg.step.is_some() {
262                // Must interpolate the data!
263                let start = cfg
264                    .start_epoch
265                    .unwrap_or_else(|| self.estimates.first().unwrap().state().epoch());
266                let end = cfg
267                    .end_epoch
268                    .unwrap_or_else(|| self.estimates.last().unwrap().state().epoch());
269
270                let mut residuals: Vec<Option<Residual<U2>>> =
271                    Vec::with_capacity(self.residuals.len());
272                let mut estimates = Vec::with_capacity(self.estimates.len());
273
274                for (estimate, residual) in self.estimates.iter().zip(self.residuals.iter()) {
275                    if estimate.epoch() >= start && estimate.epoch() <= end {
276                        estimates.push(*estimate);
277                        residuals.push(residual.clone());
278                    }
279                }
280
281                (estimates, residuals)
282            } else {
283                (self.estimates.to_vec(), self.residuals.to_vec())
284            };
285
286        // Build all of the records
287
288        // Epochs
289        let mut utc_epoch = StringBuilder::new();
290        for s in &estimates {
291            utc_epoch.append_value(s.epoch().to_time_scale(TimeScale::UTC).to_isoformat());
292        }
293        record.push(Arc::new(utc_epoch.finish()));
294
295        // Add all of the fields
296        for field in fields {
297            let mut data = Float64Builder::new();
298            for s in &estimates {
299                data.append_value(
300                    s.state()
301                        .value(field)
302                        .context(ODStateSnafu { action: "export" })?,
303                );
304            }
305            record.push(Arc::new(data.finish()));
306        }
307
308        // Add the sigma/uncertainty in the integration frame
309        for i in 0..state_items.len() {
310            let mut data = Float64Builder::new();
311            for s in &estimates {
312                data.append_value(s.covar()[(i, i)].sqrt());
313            }
314            record.push(Arc::new(data.finish()));
315        }
316
317        // Add the 1-sigma covariance in the integration frame
318        for i in 0..state_items.len() {
319            for j in i..state_items.len() {
320                let mut data = Float64Builder::new();
321                for s in &estimates {
322                    data.append_value(s.covar()[(i, j)]);
323                }
324                record.push(Arc::new(data.finish()));
325            }
326        }
327
328        // Finally, add the residuals.
329        // Prefits
330        for msr_type in &self.measurement_types {
331            let mut data = Float64Builder::new();
332            for resid_opt in &residuals {
333                if let Some(resid) = resid_opt {
334                    match resid.prefit(*msr_type) {
335                        Some(prefit) => data.append_value(prefit),
336                        None => data.append_null(),
337                    };
338                } else {
339                    data.append_null();
340                }
341            }
342            record.push(Arc::new(data.finish()));
343        }
344        // Postfit
345        for msr_type in &self.measurement_types {
346            let mut data = Float64Builder::new();
347            for resid_opt in &residuals {
348                if let Some(resid) = resid_opt {
349                    match resid.postfit(*msr_type) {
350                        Some(postfit) => data.append_value(postfit),
351                        None => data.append_null(),
352                    };
353                } else {
354                    data.append_null();
355                }
356            }
357            record.push(Arc::new(data.finish()));
358        }
359
360        // Measurement noise
361        for msr_type in &self.measurement_types {
362            let mut data = Float64Builder::new();
363            for resid_opt in &residuals {
364                if let Some(resid) = resid_opt {
365                    match resid.trk_noise(*msr_type) {
366                        Some(noise) => data.append_value(noise),
367                        None => data.append_null(),
368                    };
369                } else {
370                    data.append_null();
371                }
372            }
373            record.push(Arc::new(data.finish()));
374        }
375
376        // Real observation
377        for msr_type in &self.measurement_types {
378            let mut data = Float64Builder::new();
379            for resid_opt in &residuals {
380                if let Some(resid) = resid_opt {
381                    match resid.real_obs(*msr_type) {
382                        Some(postfit) => data.append_value(postfit),
383                        None => data.append_null(),
384                    };
385                } else {
386                    data.append_null();
387                }
388            }
389            record.push(Arc::new(data.finish()));
390        }
391
392        // Computed observation
393        for msr_type in &self.measurement_types {
394            let mut data = Float64Builder::new();
395            for resid_opt in &residuals {
396                if let Some(resid) = resid_opt {
397                    match resid.computed_obs(*msr_type) {
398                        Some(postfit) => data.append_value(postfit),
399                        None => data.append_null(),
400                    };
401                } else {
402                    data.append_null();
403                }
404            }
405            record.push(Arc::new(data.finish()));
406        }
407
408        // Residual ratio (unique entry regardless of the size)
409        let mut data = Float64Builder::new();
410        for resid_opt in &residuals {
411            if let Some(resid) = resid_opt {
412                data.append_value(resid.ratio);
413            } else {
414                data.append_null();
415            }
416        }
417        record.push(Arc::new(data.finish()));
418
419        // Residual acceptance (unique entry regardless of the size)
420        let mut data = BooleanBuilder::new();
421        for resid_opt in &residuals {
422            if let Some(resid) = resid_opt {
423                data.append_value(resid.rejected);
424            } else {
425                data.append_null();
426            }
427        }
428        record.push(Arc::new(data.finish()));
429
430        // Residual tracker (unique entry regardless of the size)
431        let mut data = StringBuilder::new();
432        for resid_opt in &residuals {
433            if let Some(resid) = resid_opt {
434                data.append_value(
435                    resid
436                        .tracker
437                        .clone()
438                        .unwrap_or("Undefined tracker".to_string()),
439                );
440            } else {
441                data.append_null();
442            }
443        }
444        record.push(Arc::new(data.finish()));
445
446        // Add the filter gains
447        for i in 0..state_items.len() {
448            for j in 0..2 {
449                let mut data = Float64Builder::new();
450                for opt_k in &self.gains {
451                    if let Some(k) = opt_k {
452                        data.append_value(k[(i, j)]);
453                    } else {
454                        data.append_null();
455                    }
456                }
457                record.push(Arc::new(data.finish()));
458            }
459        }
460
461        // Add the filter-smoother consistency ratios
462        for i in 0..state_items.len() {
463            let mut data = Float64Builder::new();
464            for opt_fsr in &self.filter_smoother_ratios {
465                if let Some(fsr) = opt_fsr {
466                    data.append_value(fsr[i]);
467                } else {
468                    data.append_null();
469                }
470            }
471            record.push(Arc::new(data.finish()));
472        }
473
474        info!("Serialized {} estimates and residuals", estimates.len());
475
476        // Serialize all of the devices and add that to the parquet file too.
477        let mut metadata = HashMap::new();
478        metadata.insert("Purpose".to_string(), "PNT results".to_string());
479        if let Some(add_meta) = cfg.metadata {
480            for (k, v) in add_meta {
481                metadata.insert(k, v);
482            }
483        }
484
485        let props = pq_writer(Some(metadata));
486
487        let file = File::create(&path_buf)
488            .context(StdIOSnafu {
489                action: "creating PNT results file",
490            })
491            .context(ODIOSnafu)?;
492
493        let mut writer = ArrowWriter::try_new(file, schema.clone(), props)
494            .context(ParquetSnafu {
495                action: "exporting PNT results",
496            })
497            .context(ODIOSnafu)?;
498
499        let batch = RecordBatch::try_new(schema, record)
500            .context(ArrowSnafu {
501                action: "writing PNT results (building batch record)",
502            })
503            .context(ODIOSnafu)?;
504
505        writer
506            .write(&batch)
507            .context(ParquetSnafu {
508                action: "writing PNT results",
509            })
510            .context(ODIOSnafu)?;
511
512        writer
513            .close()
514            .context(ParquetSnafu {
515                action: "closing PNT results file",
516            })
517            .context(ODIOSnafu)?;
518
519        // Return the path this was written to
520        let tock_time = Epoch::now().unwrap() - tick;
521        info!(
522            "PNT results written to {} in {tock_time}",
523            path_buf.display()
524        );
525        Ok(path_buf)
526    }
527}