1use super::traj_it::TrajIterator;
20use super::{ExportCfg, INTERPOLATION_SAMPLES, InterpolationSnafu};
21use super::{Interpolatable, TrajError};
22use crate::errors::{NyxError, StateError};
23use crate::io::InputOutputError;
24use crate::io::watermark::pq_writer;
25use crate::linalg::DefaultAllocator;
26use crate::linalg::allocator::Allocator;
27use crate::md::prelude::{GuidanceMode, StateParameter};
28use crate::md::trajectory::smooth_state_diff_in_place;
29use crate::time::{Duration, Epoch, TimeSeries, TimeUnits};
30use anise::analysis::AnalysisError;
31use anise::analysis::specs::StateSpecTrait;
32use anise::astro::orbit::Orbit;
33use anise::errors::PhysicsError;
34use anise::prelude::{Aberration, Almanac};
35use arrow::array::{Array, Float64Builder, StringBuilder};
36use arrow::datatypes::{DataType, Field, Schema};
37use arrow::record_batch::RecordBatch;
38use hifitime::TimeScale;
39use log::{info, warn};
40use parquet::arrow::ArrowWriter;
41use snafu::ResultExt;
42use std::collections::HashMap;
43use std::error::Error;
44use std::fmt;
45use std::fs::File;
46use std::iter::Iterator;
47use std::ops;
48use std::ops::Bound::{Excluded, Included, Unbounded};
49use std::path::{Path, PathBuf};
50use std::sync::Arc;
51
52#[derive(Clone, PartialEq)]
54pub struct Traj<S: Interpolatable>
55where
56 DefaultAllocator: Allocator<S::VecLength> + Allocator<S::Size> + Allocator<S::Size, S::Size>,
57{
58 pub name: Option<String>,
60 pub states: Vec<S>,
62}
63
64impl<S: Interpolatable> Traj<S>
65where
66 DefaultAllocator: Allocator<S::VecLength> + Allocator<S::Size> + Allocator<S::Size, S::Size>,
67{
68 pub fn new() -> Self {
69 Self {
70 name: None,
71 states: Vec::new(),
72 }
73 }
74 pub fn finalize(&mut self) {
76 self.states.sort_by_key(|a| a.epoch());
78 self.states.dedup_by(|a, b| a.epoch().eq(&b.epoch()));
80 }
81
82 pub fn at(&self, epoch: Epoch) -> Result<S, TrajError> {
84 if self.states.is_empty() {
85 return Err(TrajError::EmptyTrajectory { epoch });
86 } else if self.first().epoch() > epoch || self.last().epoch() < epoch {
87 return Err(TrajError::NoInterpolationData {
88 epoch,
89 start: self.start_epoch(),
90 end: self.end_epoch(),
91 });
92 }
93 match self
94 .states
95 .binary_search_by(|state| state.epoch().cmp(&epoch))
96 {
97 Ok(idx) => {
98 Ok(self.states[idx])
100 }
101 Err(idx) => {
102 if idx == 0 || idx >= self.states.len() {
103 return Err(TrajError::NoInterpolationData {
106 epoch,
107 start: self.start_epoch(),
108 end: self.end_epoch(),
109 });
110 }
111 let num_left = INTERPOLATION_SAMPLES / 2;
116
117 let mut first_idx = idx.saturating_sub(num_left);
119 let last_idx = self.states.len().min(first_idx + INTERPOLATION_SAMPLES);
120
121 if last_idx == self.states.len() {
123 first_idx = last_idx.saturating_sub(2 * num_left);
124 }
125
126 let states = self
127 .states
128 .iter()
129 .take(last_idx)
130 .skip(first_idx)
131 .copied()
132 .collect::<Vec<S>>();
133
134 self.states[idx]
135 .interpolate(epoch, &states)
136 .context(InterpolationSnafu)
137 }
138 }
139 }
140
141 pub fn first(&self) -> &S {
143 self.states.first().unwrap()
145 }
146
147 pub fn last(&self) -> &S {
149 self.states.last().unwrap()
150 }
151
152 pub fn start_epoch(&self) -> Epoch {
153 self.first().epoch()
154 }
155
156 pub fn end_epoch(&self) -> Epoch {
157 self.last().epoch()
158 }
159
160 pub fn every(&self, step: Duration) -> TrajIterator<'_, S> {
162 self.every_between(step, self.first().epoch(), self.last().epoch())
163 }
164
165 pub fn every_between(&self, step: Duration, start: Epoch, end: Epoch) -> TrajIterator<'_, S> {
167 TrajIterator {
168 time_series: TimeSeries::inclusive(
169 start.max(self.first().epoch()),
170 end.min(self.last().epoch()),
171 step,
172 ),
173 traj: self,
174 }
175 }
176
177 pub fn filter_by_epoch<R: ops::RangeBounds<Epoch>>(mut self, bound: R) -> Self {
179 self.states = self
180 .states
181 .iter()
182 .copied()
183 .filter(|s| bound.contains(&s.epoch()))
184 .collect::<Vec<_>>();
185 self
186 }
187
188 pub fn filter_by_offset<R: ops::RangeBounds<Duration>>(self, bound: R) -> Self {
191 if self.states.is_empty() {
192 return self;
193 }
194 let start = match bound.start_bound() {
196 Unbounded => self.states.first().unwrap().epoch(),
197 Included(offset) | Excluded(offset) => self.states.first().unwrap().epoch() + *offset,
198 };
199
200 let end = match bound.end_bound() {
201 Unbounded => self.states.last().unwrap().epoch(),
202 Included(offset) | Excluded(offset) => self.states.first().unwrap().epoch() + *offset,
203 };
204
205 self.filter_by_epoch(start..=end)
206 }
207 pub fn to_parquet_simple<P: AsRef<Path>>(&self, path: P) -> Result<PathBuf, Box<dyn Error>> {
209 self.to_parquet(path, ExportCfg::default())
210 }
211
212 pub fn to_parquet_with_cfg<P: AsRef<Path>>(
214 &self,
215 path: P,
216 cfg: ExportCfg,
217 ) -> Result<PathBuf, Box<dyn Error>> {
218 self.to_parquet(path, cfg)
219 }
220
221 pub fn to_parquet_with_step<P: AsRef<Path>>(
223 &self,
224 path: P,
225 step: Duration,
226 ) -> Result<(), Box<dyn Error>> {
227 self.to_parquet_with_cfg(
228 path,
229 ExportCfg {
230 step: Some(step),
231 ..Default::default()
232 },
233 )?;
234
235 Ok(())
236 }
237
238 pub fn to_parquet<P: AsRef<Path>>(
240 &self,
241 path: P,
242 cfg: ExportCfg,
243 ) -> Result<PathBuf, Box<dyn Error>> {
244 let tick = Epoch::now().unwrap();
245 info!("Exporting trajectory to parquet file...");
246
247 let path_buf = cfg.actual_path(path);
249
250 let states = if cfg.start_epoch.is_some() || cfg.end_epoch.is_some() || cfg.step.is_some() {
252 let start = cfg.start_epoch.unwrap_or_else(|| self.first().epoch());
254 let end = cfg.end_epoch.unwrap_or_else(|| self.last().epoch());
255 let step = cfg.step.unwrap_or_else(|| 1.minutes());
256 self.every_between(step, start, end).collect::<Vec<S>>()
257 } else {
258 self.states.to_vec()
259 };
260
261 let mut hdrs = vec![Field::new("Epoch (UTC)", DataType::Utf8, false)];
263
264 let frame = states
268 .first()
269 .ok_or_else(|| InputOutputError::Inconsistency {
270 msg: "Cannot export an empty trajectory to Parquet".to_string(),
271 })?
272 .frame();
273
274 if let Some(state) = states.iter().find(|state| state.frame() != frame) {
275 return Err(InputOutputError::Inconsistency {
276 msg: format!(
277 "Cannot export mixed-frame trajectory to Parquet: first frame {frame}, frame {} at {}",
278 state.frame(),
279 state.epoch()
280 ),
281 }
282 .into());
283 }
284 let more_meta = Some(vec![(
285 "Frame".to_string(),
286 serde_dhall::serialize(&frame)
287 .static_type_annotation()
288 .to_string()
289 .map_err(|e| {
290 Box::new(InputOutputError::SerializeDhall {
291 what: format!("frame `{frame}`"),
292 err: e.to_string(),
293 })
294 })?,
295 )]);
296
297 let requested_fields = match cfg.fields {
298 Some(fields) => fields,
299 None => S::export_params(),
300 };
301
302 let mut fields = Vec::new();
303 let mut field_nullable = Vec::new();
304 for field in requested_fields {
305 let mut any_ok = false;
306 let mut any_err = false;
307 for state in &states {
308 if state.value(field).is_ok() {
309 any_ok = true;
310 } else {
311 any_err = true;
312 }
313 }
314
315 if any_ok {
316 fields.push(field);
317 field_nullable.push(any_err);
318 }
319 }
320
321 for (field, nullable) in fields.iter().zip(field_nullable.iter().copied()) {
322 hdrs.push(field.to_field(more_meta.clone()).with_nullable(nullable));
323 }
324
325 let schema = Arc::new(Schema::new(hdrs));
327 let mut record: Vec<Arc<dyn Array>> = Vec::new();
328
329 let mut utc_epoch = StringBuilder::new();
333 for s in &states {
334 utc_epoch.append_value(s.epoch().to_time_scale(TimeScale::UTC).to_isoformat());
335 }
336 record.push(Arc::new(utc_epoch.finish()));
337
338 for field in fields {
340 if field == StateParameter::GuidanceMode() {
341 let mut guid_mode = StringBuilder::new();
342 for s in &states {
343 match s.value(field) {
344 Ok(value) => {
345 guid_mode.append_value(format!("{:?}", GuidanceMode::from(value)));
346 }
347 Err(_) => guid_mode.append_null(),
348 }
349 }
350 record.push(Arc::new(guid_mode.finish()));
351 } else {
352 let mut data = Float64Builder::new();
353 for s in &states {
354 match s.value(field) {
355 Ok(value) => data.append_value(value),
356 Err(_) => data.append_null(),
357 };
358 }
359 record.push(Arc::new(data.finish()));
360 }
361 }
362
363 info!(
364 "Serialized {} states from {} to {}",
365 states.len(),
366 states.first().unwrap().epoch(),
367 states.last().unwrap().epoch()
368 );
369
370 let mut metadata = HashMap::new();
372 metadata.insert("Purpose".to_string(), "Trajectory data".to_string());
373 if let Some(add_meta) = cfg.metadata {
374 for (k, v) in add_meta {
375 metadata.insert(k, v);
376 }
377 }
378
379 let props = pq_writer(Some(metadata));
380
381 let file = File::create(&path_buf)?;
382 let mut writer = ArrowWriter::try_new(file, schema.clone(), props).unwrap();
383
384 let batch = RecordBatch::try_new(schema, record)?;
385 writer.write(&batch)?;
386 writer.close()?;
387
388 let tock_time = Epoch::now().unwrap() - tick;
390 info!(
391 "Trajectory written to {} in {tock_time}",
392 path_buf.display()
393 );
394 Ok(path_buf)
395 }
396
397 pub fn resample(&self, step: Duration) -> Result<Self, NyxError> {
400 if self.states.is_empty() {
401 return Err(NyxError::Trajectory {
402 source: TrajError::CreationError {
403 msg: "No trajectory to convert".to_string(),
404 },
405 });
406 }
407
408 let mut traj = Self::new();
409 for state in self.every(step) {
410 traj.states.push(state);
411 }
412
413 traj.finalize();
414
415 Ok(traj)
416 }
417
418 pub fn rebuild(&self, epochs: &[Epoch]) -> Result<Self, NyxError> {
421 if self.states.is_empty() {
422 return Err(NyxError::Trajectory {
423 source: TrajError::CreationError {
424 msg: "No trajectory to convert".to_string(),
425 },
426 });
427 }
428
429 let mut traj = Self::new();
430 for epoch in epochs {
431 traj.states.push(self.at(*epoch)?);
432 }
433
434 traj.finalize();
435
436 Ok(traj)
437 }
438
439 pub fn ric_diff_to_parquet<P: AsRef<Path>>(
444 &self,
445 other: &Self,
446 path: P,
447 cfg: ExportCfg,
448 ) -> Result<PathBuf, TrajError> {
449 let tick = Epoch::now().unwrap();
450 info!("Exporting trajectory to parquet file...");
451
452 let path_buf = cfg.actual_path(path);
454
455 let mut hdrs = vec![Field::new("Epoch (UTC)", DataType::Utf8, false)];
457
458 for coord in ["X", "Y", "Z"] {
460 let mut meta = HashMap::new();
461 meta.insert("unit".to_string(), "km".to_string());
462
463 let field = Field::new(
464 format!("Delta {coord} (RIC) (km)"),
465 DataType::Float64,
466 false,
467 )
468 .with_metadata(meta);
469
470 hdrs.push(field);
471 }
472
473 for coord in ["x", "y", "z"] {
474 let mut meta = HashMap::new();
475 meta.insert("unit".to_string(), "km/s".to_string());
476
477 let field = Field::new(
478 format!("Delta V{coord} (RIC) (km/s)"),
479 DataType::Float64,
480 false,
481 )
482 .with_metadata(meta);
483
484 hdrs.push(field);
485 }
486
487 let frame = self.states[0].frame();
488 let more_meta = Some(vec![(
489 "Frame".to_string(),
490 serde_dhall::serialize(&frame)
491 .static_type_annotation()
492 .to_string()
493 .unwrap_or(frame.to_string()),
494 )]);
495
496 let mut cfg = cfg;
497
498 let mut fields = match cfg.fields {
499 Some(fields) => fields,
500 None => S::export_params(),
501 };
502
503 fields.retain(|param| {
505 param != &StateParameter::GuidanceMode() && self.first().value(*param).is_ok()
506 });
507
508 for field in &fields {
509 hdrs.push(field.to_field(more_meta.clone()));
510 }
511
512 let schema = Arc::new(Schema::new(hdrs));
514 let mut record: Vec<Arc<dyn Array>> = Vec::new();
515
516 cfg.start_epoch = if self.first().epoch() > other.first().epoch() {
518 Some(self.first().epoch())
519 } else {
520 Some(other.first().epoch())
521 };
522
523 cfg.end_epoch = if self.last().epoch() > other.last().epoch() {
524 Some(other.last().epoch())
525 } else {
526 Some(self.last().epoch())
527 };
528
529 let step = cfg.step.unwrap_or_else(|| 1.minutes());
531 let self_states = self
532 .every_between(step, cfg.start_epoch.unwrap(), cfg.end_epoch.unwrap())
533 .collect::<Vec<S>>();
534
535 let other_states = other
536 .every_between(step, cfg.start_epoch.unwrap(), cfg.end_epoch.unwrap())
537 .collect::<Vec<S>>();
538
539 let mut ric_diff = Vec::with_capacity(other_states.len());
541 for (other_state, self_state) in other_states.iter().zip(self_states.iter()) {
542 let self_orbit = self_state.orbit();
543 let other_orbit = other_state.orbit();
544
545 let this_ric_diff = self_orbit
546 .ric_difference(&other_orbit)
547 .map_err(|source: PhysicsError| TrajError::TrajPhysics { source })?;
548
549 ric_diff.push(this_ric_diff);
550 }
551
552 smooth_state_diff_in_place(&mut ric_diff, if other_states.len() > 5 { 5 } else { 1 });
553
554 let mut utc_epoch = StringBuilder::new();
558 for s in &self_states {
559 utc_epoch.append_value(s.epoch().to_time_scale(TimeScale::UTC).to_isoformat());
560 }
561 record.push(Arc::new(utc_epoch.finish()));
562
563 for coord_no in 0..6 {
565 let mut data = Float64Builder::new();
566 for this_ric_dff in &ric_diff {
567 data.append_value(this_ric_dff.to_cartesian_pos_vel()[coord_no]);
568 }
569 record.push(Arc::new(data.finish()));
570 }
571
572 for field in fields {
574 let mut data = Float64Builder::new();
575 for (other_state, self_state) in other_states.iter().zip(self_states.iter()) {
576 let self_val =
577 self_state
578 .value(field)
579 .map_err(|err: StateError| TrajError::TrajGeneric {
580 err: err.to_string(),
581 })?;
582 let other_val =
583 other_state
584 .value(field)
585 .map_err(|err: StateError| TrajError::TrajGeneric {
586 err: err.to_string(),
587 })?;
588 data.append_value(self_val - other_val);
589 }
590
591 record.push(Arc::new(data.finish()));
592 }
593
594 info!("Serialized {} states differences", self_states.len());
595
596 let mut metadata = HashMap::new();
598 metadata.insert(
599 "Purpose".to_string(),
600 "Trajectory difference data".to_string(),
601 );
602 if let Some(add_meta) = cfg.metadata {
603 for (k, v) in add_meta {
604 metadata.insert(k, v);
605 }
606 }
607
608 let props = pq_writer(Some(metadata));
609
610 let file = File::create(&path_buf).map_err(|err| TrajError::TrajGeneric {
611 err: format!("{err:?}"),
612 })?;
613 let mut writer = ArrowWriter::try_new(file, schema.clone(), props).unwrap();
614
615 let batch = RecordBatch::try_new(schema, record).map_err(|err| TrajError::TrajGeneric {
616 err: format!("{err:?}"),
617 })?;
618 writer.write(&batch).map_err(|err| TrajError::TrajGeneric {
619 err: format!("{err:?}"),
620 })?;
621 writer.close().map_err(|err| TrajError::TrajGeneric {
622 err: format!("{err:?}"),
623 })?;
624
625 let tock_time = Epoch::now().unwrap() - tick;
627 info!(
628 "Trajectory written to {} in {tock_time}",
629 path_buf.display()
630 );
631 Ok(path_buf)
632 }
633}
634
635impl<S: Interpolatable> ops::Add for Traj<S>
636where
637 DefaultAllocator: Allocator<S::VecLength> + Allocator<S::Size> + Allocator<S::Size, S::Size>,
638{
639 type Output = Result<Traj<S>, NyxError>;
640
641 fn add(self, other: Traj<S>) -> Self::Output {
643 &self + &other
644 }
645}
646
647impl<S: Interpolatable> ops::Add<&Traj<S>> for &Traj<S>
648where
649 DefaultAllocator: Allocator<S::VecLength> + Allocator<S::Size> + Allocator<S::Size, S::Size>,
650{
651 type Output = Result<Traj<S>, NyxError>;
652
653 fn add(self, other: &Traj<S>) -> Self::Output {
655 if self.first().frame() != other.first().frame() {
656 Err(NyxError::Trajectory {
657 source: TrajError::CreationError {
658 msg: format!(
659 "Frame mismatch in add operation: {} != {}",
660 self.first().frame(),
661 other.first().frame()
662 ),
663 },
664 })
665 } else {
666 if self.last().epoch() < other.first().epoch() {
667 let gap = other.first().epoch() - self.last().epoch();
668 warn!(
669 "Resulting merged trajectory will have a time-gap of {} starting at {}",
670 gap,
671 self.last().epoch()
672 );
673 }
674
675 let mut me = self.clone();
676 for state in &other
678 .states
679 .iter()
680 .copied()
681 .filter(|s| s.epoch() > self.last().epoch())
682 .collect::<Vec<S>>()
683 {
684 me.states.push(*state);
685 }
686 me.finalize();
687
688 Ok(me)
689 }
690 }
691}
692
693impl<S: Interpolatable> ops::AddAssign<&Traj<S>> for Traj<S>
694where
695 DefaultAllocator: Allocator<S::VecLength> + Allocator<S::Size> + Allocator<S::Size, S::Size>,
696{
697 fn add_assign(&mut self, rhs: &Self) {
703 *self = (self.clone() + rhs.clone()).unwrap();
704 }
705}
706
707impl<S: Interpolatable> fmt::Display for Traj<S>
708where
709 DefaultAllocator: Allocator<S::VecLength> + Allocator<S::Size> + Allocator<S::Size, S::Size>,
710{
711 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
712 if self.states.is_empty() {
713 write!(f, "Empty Trajectory!")
714 } else {
715 let dur = self.last().epoch() - self.first().epoch();
716 write!(
717 f,
718 "Trajectory {}in {} from {} to {} ({}, or {:.3} s) [{} states]",
719 match &self.name {
720 Some(name) => format!("of {name} "),
721 None => String::new(),
722 },
723 self.first().frame(),
724 self.first().epoch(),
725 self.last().epoch(),
726 dur,
727 dur.to_seconds(),
728 self.states.len()
729 )
730 }
731 }
732}
733
734impl<S: Interpolatable> fmt::Debug for Traj<S>
735where
736 DefaultAllocator: Allocator<S::VecLength> + Allocator<S::Size> + Allocator<S::Size, S::Size>,
737{
738 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
739 write!(f, "{self}",)
740 }
741}
742
743impl<S: Interpolatable> Default for Traj<S>
744where
745 DefaultAllocator: Allocator<S::VecLength> + Allocator<S::Size> + Allocator<S::Size, S::Size>,
746{
747 fn default() -> Self {
748 Self::new()
749 }
750}
751
752impl<S: Interpolatable> StateSpecTrait for Traj<S>
753where
754 DefaultAllocator: Allocator<S::VecLength> + Allocator<S::Size> + Allocator<S::Size, S::Size>,
755{
756 fn ab_corr(&self) -> Option<Aberration> {
757 None
758 }
759
760 fn evaluate(&self, epoch: Epoch, _almanac: &Almanac) -> Result<Orbit, AnalysisError> {
761 self.at(epoch)
762 .map(|state| state.orbit())
763 .map_err(|e| AnalysisError::GenericAnalysisError {
764 err: format!("{e}"),
765 })
766 }
767}