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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
use super::bacon_sci::interp::lagrange;
use super::bacon_sci::polynomial::Polynomial;
use super::crossbeam::thread;
use super::rayon::prelude::*;
use crate::celestia::{Cosm, Frame, Orbit, Spacecraft};
use crate::dimensions::allocator::Allocator;
use crate::dimensions::{DefaultAllocator, DimName, VectorN};
use crate::errors::NyxError;
use crate::io::formatter::StateFormatter;
use crate::md::{events::EventEvaluator, MdHdlr, OrbitStateOutput};
use crate::time::{Duration, Epoch, TimeSeries, TimeUnit};
use crate::utils::normalize;
use crate::{State, TimeTagged};
use std::collections::BTreeMap;
use std::fmt;
use std::iter::Iterator;
use std::sync::mpsc::{channel, Receiver};
use std::sync::Arc;
use std::time::Duration as StdDur;
use std::time::Instant;
const INTERP_TOLERANCE: f64 = 1e-10;
#[derive(Clone)]
pub struct Segment<S: State>
where
DefaultAllocator: Allocator<f64, S::PropVecSize> + Allocator<f64, S::Size>,
{
start_epoch: Epoch,
duration: Duration,
coefficients: Vec<Vec<f64>>,
end_state: S,
}
#[derive(Clone)]
pub struct Traj<S: State>
where
DefaultAllocator: Allocator<f64, S::PropVecSize> + Allocator<f64, S::Size>,
{
pub segments: BTreeMap<i32, Segment<S>>,
pub timeout_ms: u64,
start_state: S,
max_offset: i32,
items_per_segments: usize,
}
pub struct TrajIterator<'a, S: State>
where
DefaultAllocator: Allocator<f64, S::PropVecSize> + Allocator<f64, S::Size>,
{
pub time_series: TimeSeries,
pub traj: &'a Traj<S>,
}
impl<S: State> Segment<S>
where
DefaultAllocator: Allocator<f64, S::PropVecSize> + Allocator<f64, S::Size>,
{
pub fn evaluate(&self, from: S, epoch: Epoch) -> Result<S, NyxError> {
let dur_into_window = epoch - self.start_epoch;
if dur_into_window > self.duration {
return Err(NyxError::OutOfInterpolationWindow(format!(
"Requested trajectory at time {} but that is past the final interpolation window by {}",
epoch, dur_into_window
)));
} else if dur_into_window.in_seconds() < -1.0 {
return Err(NyxError::InvalidInterpolationData(format!(
"Bug: should be in next window: {}",
dur_into_window
)));
}
let t_prime = normalize(
dur_into_window.in_seconds(),
0.0,
self.duration.in_seconds(),
);
let mut state = from;
let mut state_vec = VectorN::<f64, S::PropVecSize>::zeros();
for (cno, coeffs) in self.coefficients.iter().enumerate() {
state_vec[cno] = Polynomial::from_slice(coeffs).evaluate(t_prime)
}
state.set(epoch, &state_vec)?;
Ok(state)
}
}
impl<S: State> Traj<S>
where
DefaultAllocator: Allocator<f64, S::PropVecSize> + Allocator<f64, S::Size>,
{
pub fn new(state: S, rx: Receiver<S>) -> Result<Self, NyxError> {
Self::new_bucket_as(state, if S::PropVecSize::dim() == 43 { 6 } else { 32 }, rx)
}
pub fn new_bucket_as(
state: S,
items_per_segments: usize,
rx: Receiver<S>,
) -> Result<Self, NyxError> {
thread::scope(|s| {
let mut me = Self {
segments: BTreeMap::new(),
start_state: state,
timeout_ms: 100,
max_offset: 0,
items_per_segments,
};
let mut children = vec![];
let mut window_states: Vec<S> = Vec::with_capacity(items_per_segments);
window_states.push(state);
while let Ok(state) = rx.recv_timeout(StdDur::from_millis(me.timeout_ms)) {
if window_states.len() == items_per_segments {
let this_wdn = window_states.clone();
children.push(
s.spawn(move |_| -> Result<Segment<S>, NyxError> { interpolate(this_wdn) }),
);
let last_wdn_state = window_states[items_per_segments - 1];
window_states.clear();
window_states.push(last_wdn_state);
}
window_states.push(state);
}
children.push(
s.spawn(move |_| -> Result<Segment<S>, NyxError> { interpolate(window_states) }),
);
for child in children {
let segment = child.join().unwrap()?;
me.append_segment(segment);
}
Ok(me)
})
.unwrap()
}
fn append_segment(&mut self, segment: Segment<S>) {
let offset_s = ((segment.start_epoch - self.start_state.epoch())
.in_seconds()
.floor()) as i32;
self.segments.insert(offset_s, segment);
if offset_s > self.max_offset {
self.max_offset = offset_s;
}
}
pub fn evaluate(&self, epoch: Epoch) -> Result<S, NyxError> {
let offset_s = ((epoch - self.start_state.epoch()).in_seconds().floor()) as i32;
match self.segments.range(..=offset_s).rev().next() {
None => {
let last_item = self.segments[&self.max_offset].end_state;
if last_item.epoch() == epoch {
Ok(last_item)
} else {
Err(NyxError::NoInterpolationData(format!("{}", epoch)))
}
}
Some((_, segment)) => segment.evaluate(self.start_state, epoch),
}
}
pub fn first(&self) -> S {
self.start_state
}
pub fn last(&self) -> S {
self.segments[&self.max_offset].end_state
}
pub fn every(&self, step: Duration) -> TrajIterator<S> {
self.every_between(step, self.first().epoch(), self.last().epoch())
}
pub fn every_between(&self, step: Duration, start: Epoch, end: Epoch) -> TrajIterator<S> {
TrajIterator {
time_series: TimeSeries::inclusive(start, end, step),
traj: &self,
}
}
#[allow(clippy::identity_op)]
pub fn find_bracketed<E>(&self, start: Epoch, end: Epoch, event: &E) -> Result<S, NyxError>
where
E: EventEvaluator<S>,
{
use std::f64::EPSILON;
let max_iter = 50;
let has_converged =
|x1: f64, x2: f64| (x1 - x2).abs() <= event.epoch_precision().in_seconds();
let arrange = |a: f64, ya: f64, b: f64, yb: f64| {
if ya.abs() > yb.abs() {
(a, ya, b, yb)
} else {
(b, yb, a, ya)
}
};
let xa_e = start;
let xb_e = end;
let mut xa = 0.0;
let mut xb = (xb_e - xa_e).in_seconds();
let mut ya = event.eval(&self.evaluate(xa_e)?);
let mut yb = event.eval(&self.evaluate(xb_e)?);
if ya.abs() <= event.value_precision().abs() {
return self.evaluate(xa_e);
} else if yb.abs() <= event.value_precision().abs() {
return self.evaluate(xb_e);
}
let (mut xc, mut yc, mut xd) = (xa, ya, xa);
let mut flag = true;
for _ in 0..max_iter {
if ya.abs() < event.value_precision().abs() {
return self.evaluate(xa_e + xa * TimeUnit::Second);
}
if yb.abs() < event.value_precision().abs() {
return self.evaluate(xa_e + xb * TimeUnit::Second);
}
if has_converged(xa, xb) {
return Err(NyxError::EventNotInEpochBraket(
start.to_string(),
end.to_string(),
));
}
let mut s = if (ya - yc).abs() > EPSILON && (yb - yc).abs() > EPSILON {
xa * yb * yc / ((ya - yb) * (ya - yc))
+ xb * ya * yc / ((yb - ya) * (yb - yc))
+ xc * ya * yb / ((yc - ya) * (yc - yb))
} else {
xb - yb * (xb - xa) / (yb - ya)
};
let cond1 = (s - xb) * (s - (3.0 * xa + xb) / 4.0) > 0.0;
let cond2 = flag && (s - xb).abs() >= (xb - xc).abs() / 2.0;
let cond3 = !flag && (s - xb).abs() >= (xc - xd).abs() / 2.0;
let cond4 = flag && has_converged(xb, xc);
let cond5 = !flag && has_converged(xc, xd);
if cond1 || cond2 || cond3 || cond4 || cond5 {
s = (xa + xb) / 2.0;
flag = true;
} else {
flag = false;
}
let next_try = self.evaluate(xa_e + s * TimeUnit::Second)?;
let ys = event.eval(&next_try);
xd = xc;
xc = xb;
yc = yb;
if ya * ys < 0.0 {
let next_try = self.evaluate(xa_e + xa * TimeUnit::Second)?;
let ya_p = event.eval(&next_try);
let (_a, _ya, _b, _yb) = arrange(xa, ya_p, s, ys);
{
xa = _a;
ya = _ya;
xb = _b;
yb = _yb;
}
} else {
let next_try = self.evaluate(xa_e + xb * TimeUnit::Second)?;
let yb_p = event.eval(&next_try);
let (_a, _ya, _b, _yb) = arrange(s, ys, xb, yb_p);
{
xa = _a;
ya = _ya;
xb = _b;
yb = _yb;
}
}
}
Err(NyxError::MaxIterReached(format!(
"Brent solver failed after {} iterations",
max_iter
)))
}
#[allow(clippy::identity_op)]
pub fn find_all<E>(&self, event: &E) -> Result<Vec<S>, NyxError>
where
E: EventEvaluator<S>,
{
let start_epoch = self.first().epoch();
let end_epoch = self.last().epoch();
let heuristic = (end_epoch - start_epoch) / 100;
info!(
"Searching for {} with initial heuristic of {}",
event, heuristic
);
let (sender, receiver) = channel();
let epochs: Vec<Epoch> = TimeSeries::inclusive(start_epoch, end_epoch, heuristic).collect();
epochs.into_par_iter().for_each_with(sender, |s, epoch| {
if let Ok(event_state) = self.find_bracketed(epoch, epoch + heuristic, event) {
s.send(event_state).unwrap()
};
});
let mut states: Vec<_> = receiver.iter().collect();
if states.is_empty() {
match self.find_minmax(event, TimeUnit::Second) {
Ok((min_event, max_event)) => {
let lower_min_epoch =
if min_event.epoch() - 1 * TimeUnit::Millisecond < self.first().epoch() {
self.first().epoch()
} else {
min_event.epoch() - 1 * TimeUnit::Millisecond
};
let lower_max_epoch =
if min_event.epoch() + 1 * TimeUnit::Millisecond > self.last().epoch() {
self.last().epoch()
} else {
min_event.epoch() + 1 * TimeUnit::Millisecond
};
let upper_min_epoch =
if max_event.epoch() - 1 * TimeUnit::Millisecond < self.first().epoch() {
self.first().epoch()
} else {
max_event.epoch() - 1 * TimeUnit::Millisecond
};
let upper_max_epoch =
if max_event.epoch() + 1 * TimeUnit::Millisecond > self.last().epoch() {
self.last().epoch()
} else {
max_event.epoch() + 1 * TimeUnit::Millisecond
};
if let Ok(event_state) =
self.find_bracketed(lower_min_epoch, lower_max_epoch, event)
{
states.push(event_state);
};
if let Ok(event_state) =
self.find_bracketed(upper_min_epoch, upper_max_epoch, event)
{
states.push(event_state);
};
if states.is_empty() {
return Err(NyxError::EventNotInEpochBraket(
start_epoch.to_string(),
end_epoch.to_string(),
));
}
}
Err(_) => {
return Err(NyxError::EventNotInEpochBraket(
start_epoch.to_string(),
end_epoch.to_string(),
))
}
};
}
states.sort_by(|s1, s2| s1.epoch().partial_cmp(&s2.epoch()).unwrap());
states.dedup();
for (cnt, event_state) in states.iter().enumerate() {
info!("{} #{}: {}", event, cnt + 1, event_state);
}
Ok(states)
}
#[allow(clippy::identity_op)]
pub fn find_minmax<E>(&self, event: &E, precision: TimeUnit) -> Result<(S, S), NyxError>
where
E: EventEvaluator<S>,
{
let step: Duration = 1 * precision;
let mut min_val = std::f64::INFINITY;
let mut max_val = std::f64::NEG_INFINITY;
let mut min_state = S::zeros();
let mut max_state = S::zeros();
let (sender, receiver) = channel();
let epochs: Vec<Epoch> =
TimeSeries::inclusive(self.first().epoch(), self.last().epoch(), step).collect();
epochs.into_par_iter().for_each_with(sender, |s, epoch| {
let state = self.evaluate(epoch).unwrap();
let this_eval = event.eval(&state);
s.send((this_eval, state)).unwrap();
});
let evald_states: Vec<_> = receiver.iter().collect();
for (this_eval, state) in evald_states {
if this_eval < min_val {
min_val = this_eval;
min_state = state;
}
if this_eval > max_val {
max_val = this_eval;
max_state = state;
}
}
Ok((min_state, max_state))
}
}
impl Traj<Orbit> {
pub fn to_frame(&self, new_frame: Frame, cosm: Arc<Cosm>) -> Result<Self, NyxError> {
thread::scope(|s| {
let start_time = Instant::now();
let (tx, rx) = channel();
let start_state = cosm.frame_chg(&self.first(), new_frame);
let traj_thread = s.spawn(move |_| Self::new(start_state, rx));
let sample_rate =
1.0 / (((self.items_per_segments * 2 + 1) * self.segments.len()) as f64);
let step = sample_rate * (self.last().epoch() - self.first().epoch());
for state in self.every(step) {
let converted_state = cosm.frame_chg(&state, new_frame);
tx.send(converted_state).unwrap();
}
let traj = traj_thread.join().unwrap_or_else(|_| {
Err(NyxError::NoInterpolationData(
"Could not generate trajectory".to_string(),
))
})?;
info!(
"Converted trajectory from {} to {} in {} ms",
self.first().frame,
new_frame,
(Instant::now() - start_time).as_millis()
);
Ok(traj)
})
.unwrap()
}
pub fn to_csv_with_step(
&self,
filename: &str,
step: Duration,
cosm: Arc<Cosm>,
) -> Result<(), NyxError> {
let fmtr = StateFormatter::default(filename.to_string(), cosm);
let mut out = OrbitStateOutput::new(fmtr)?;
for state in self.every(step) {
out.handle(&state);
}
Ok(())
}
pub fn to_csv_between_with_step(
&self,
filename: &str,
start: Option<Epoch>,
end: Option<Epoch>,
step: Duration,
cosm: Arc<Cosm>,
) -> Result<(), NyxError> {
let fmtr = StateFormatter::default(filename.to_string(), cosm);
let mut out = OrbitStateOutput::new(fmtr)?;
let start = match start {
Some(s) => s,
None => self.first().epoch(),
};
let end = match end {
Some(e) => e,
None => self.last().epoch(),
};
for state in self.every_between(step, start, end) {
out.handle(&state);
}
Ok(())
}
#[allow(clippy::identity_op)]
pub fn to_csv(&self, filename: &str, cosm: Arc<Cosm>) -> Result<(), NyxError> {
self.to_csv_with_step(filename, 1 * TimeUnit::Minute, cosm)
}
#[allow(clippy::identity_op)]
pub fn to_csv_between(
&self,
filename: &str,
start: Option<Epoch>,
end: Option<Epoch>,
cosm: Arc<Cosm>,
) -> Result<(), NyxError> {
self.to_csv_between_with_step(filename, start, end, 1 * TimeUnit::Minute, cosm)
}
#[allow(clippy::identity_op)]
pub fn to_groundtrack_csv(
&self,
filename: &str,
body_fixed_frame: Frame,
cosm: Arc<Cosm>,
) -> Result<(), NyxError> {
let fmtr = StateFormatter::from_headers(
vec![
"epoch",
"geodetic_latitude",
"geodetic_longitude",
"geodetic_height",
],
filename.to_string(),
cosm.clone(),
)?;
let mut out = OrbitStateOutput::new(fmtr)?;
for state in self
.to_frame(body_fixed_frame, cosm)?
.every(1 * TimeUnit::Minute)
{
out.handle(&state);
}
Ok(())
}
pub fn to_csv_custom(
&self,
filename: &str,
headers: Vec<&str>,
step: Duration,
cosm: Arc<Cosm>,
) -> Result<(), NyxError> {
let fmtr = StateFormatter::from_headers(headers, filename.to_string(), cosm)?;
let mut out = OrbitStateOutput::new(fmtr)?;
for state in self.every(step) {
out.handle(&state);
}
Ok(())
}
}
impl Traj<Spacecraft> {
pub fn to_frame(&self, new_frame: Frame, cosm: Arc<Cosm>) -> Result<Self, NyxError> {
thread::scope(|s| {
let (tx, rx) = channel();
let mut start_state = self.first();
let start_orbit = cosm.frame_chg(&start_state.orbit, new_frame);
start_state.orbit.x = start_orbit.x;
start_state.orbit.y = start_orbit.y;
start_state.orbit.z = start_orbit.z;
start_state.orbit.vx = start_orbit.vx;
start_state.orbit.vy = start_orbit.vy;
start_state.orbit.vz = start_orbit.vz;
start_state.orbit.frame = start_orbit.frame;
let traj_thread = s.spawn(move |_| Self::new(start_state, rx));
let sample_rate = 1.0 / (((16 * 2 + 1) * self.segments.len()) as f64);
let step = sample_rate * (self.last().epoch() - self.first().epoch());
for state in self.every(step) {
let converted_orbit = cosm.frame_chg(&state.orbit, new_frame);
let mut converted_state = state;
converted_state.orbit.x = converted_orbit.x;
converted_state.orbit.y = converted_orbit.y;
converted_state.orbit.z = converted_orbit.z;
converted_state.orbit.vx = converted_orbit.vx;
converted_state.orbit.vy = converted_orbit.vy;
converted_state.orbit.vz = converted_orbit.vz;
converted_state.orbit.frame = converted_orbit.frame;
tx.send(converted_state).unwrap();
}
let traj = traj_thread.join().unwrap_or_else(|_| {
Err(NyxError::NoInterpolationData(
"Could not generate trajectory".to_string(),
))
})?;
Ok(traj)
})
.unwrap()
}
}
impl<S: State> Iterator for TrajIterator<'_, S>
where
DefaultAllocator: Allocator<f64, S::PropVecSize> + Allocator<f64, S::Size>,
{
type Item = S;
fn next(&mut self) -> Option<Self::Item> {
match self.time_series.next() {
Some(next_epoch) => match self.traj.evaluate(next_epoch) {
Ok(item) => Some(item),
_ => None,
},
None => None,
}
}
}
impl<S: State> fmt::Display for Traj<S>
where
DefaultAllocator: Allocator<f64, S::PropVecSize> + Allocator<f64, S::Size>,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let dur = self.last().epoch() - self.first().epoch();
write!(
f,
"Trajectory from {} to {} ({}, or {:.3} s)",
self.first().epoch(),
self.last().epoch(),
dur,
dur.in_seconds()
)
}
}
fn interpolate<S: State>(this_wdn: Vec<S>) -> Result<Segment<S>, NyxError>
where
DefaultAllocator: Allocator<f64, S::PropVecSize> + Allocator<f64, S::Size>,
{
let start_win_epoch = this_wdn[0].epoch();
let end_win_epoch = this_wdn[this_wdn.len() - 1].epoch();
let window_duration = end_win_epoch - start_win_epoch;
let mut ts = Vec::new();
let mut values = Vec::with_capacity(S::PropVecSize::dim());
let mut coefficients = Vec::new();
for _ in 0..S::PropVecSize::dim() {
values.push(Vec::with_capacity(this_wdn.len()));
coefficients.push(Vec::with_capacity(this_wdn.len()));
}
for state in &this_wdn {
let t_prime = normalize(
(state.epoch() - start_win_epoch).in_seconds(),
0.0,
window_duration.in_seconds(),
);
ts.push(t_prime);
for (pos, val) in state.as_vector().as_ref().unwrap().iter().enumerate() {
values[pos].push(*val);
}
}
for (pos, these_values) in values.iter().enumerate() {
match lagrange(&ts, these_values, INTERP_TOLERANCE) {
Ok(polyn) => coefficients[pos] = polyn.get_coefficients(),
Err(e) => {
return Err(NyxError::InvalidInterpolationData(format!(
"Interpolation failed: {}",
e
)))
}
};
}
Ok(Segment {
start_epoch: start_win_epoch,
duration: window_duration,
coefficients,
end_state: this_wdn[this_wdn.len() - 1],
})
}