nyx_space/propagators/event.rs
1/*
2 Nyx, blazing fast astrodynamics
3 Copyright (C) 2018-onwards Christopher Rabotin <[email protected]>
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 super::PropagationError;
20use crate::State;
21use crate::dynamics::Dynamics;
22use crate::linalg::DefaultAllocator;
23use crate::linalg::allocator::Allocator;
24use crate::md::trajectory::{Interpolatable, Traj};
25use crate::propagators::{PropAlmanacSnafu, PropAnalysisSnafu, TrajectoryEventSnafu};
26use crate::time::{Duration, Epoch};
27use anise::analysis::event::Event;
28use anise::analysis::{AnalysisError, brent_solver};
29use anise::frames::Frame;
30use log::info;
31use rayon::iter::ParallelBridge;
32use rayon::prelude::ParallelIterator;
33use snafu::ResultExt;
34use std::f64;
35use std::sync::mpsc::channel;
36#[cfg(not(target_arch = "wasm32"))]
37use std::time::Instant;
38
39use super::PropInstance;
40
41impl<D: Dynamics> PropInstance<'_, D>
42where
43 DefaultAllocator: Allocator<<D::StateType as State>::Size>
44 + Allocator<<D::StateType as State>::Size, <D::StateType as State>::Size>
45 + Allocator<<D::StateType as State>::VecLength>,
46{
47 /// Propagates the dynamics until the specified event has occurred one, or until `max_duration` is reached. Refer to [until_nth_event] for details.
48 pub fn until_event(
49 &mut self,
50 max_duration: Duration,
51 event: &Event,
52 event_frame: Option<Frame>,
53 ) -> Result<(D::StateType, Traj<D::StateType>), PropagationError>
54 where
55 <DefaultAllocator as Allocator<<D::StateType as State>::VecLength>>::Buffer<f64>: Send,
56 D::StateType: Interpolatable,
57 {
58 self.until_nth_event(max_duration, event, event_frame, 1)
59 }
60
61 /// Propagates the dynamics until the specified event has occurred `trigger` times, or until `max_duration` is reached.
62 ///
63 /// This method monitors the provided `event` during propagation. Once the event condition is met
64 /// `trigger` number of times (e.g., set `trigger` to 1 for the first occurrence), the propagation stops
65 /// at the end of that integration step.
66 ///
67 /// A root-finding algorithm (Brent's method) is then used to locate the exact time of the event
68 /// within the final integration step. The returned state corresponds to this precise event time,
69 /// interpolated from the trajectory.
70 ///
71 /// # Arguments
72 ///
73 /// * `max_duration` - The maximum duration to propagate if the event is not triggered the requested number of times.
74 /// * `event` - The event definition (scalar expression and condition) to monitor.
75 /// * `event_frame` - Optional frame used for event evaluation and root refinement.
76 /// The returned state remains in the propagation frame.
77 /// * `trigger` - The 1-based index of the event occurrence to stop at (e.g. 1 for the first crossing, 2 for the second).
78 ///
79 /// # Returns
80 ///
81 /// A tuple containing:
82 /// 1. The interpolated state exactly at the moment the $n$-th event occurred.
83 /// 2. The full trajectory recorded up to the end of the propagation step where the event occurred.
84 ///
85 /// # Errors
86 ///
87 /// * `PropagationError::NthEventError`: Returned if `max_duration` is reached before the event was triggered `trigger` times.
88 /// * `PropagationError::TrajectoryEvent`: Returned if the interpolation of the event state fails.
89 /// * `PropagationError::Analysis`: Returned if the event evaluation fails during the search.
90 pub fn until_nth_event(
91 &mut self,
92 max_duration: Duration,
93 event: &Event,
94 event_frame: Option<Frame>,
95 trigger: usize,
96 ) -> Result<(D::StateType, Traj<D::StateType>), PropagationError>
97 where
98 <DefaultAllocator as Allocator<<D::StateType as State>::VecLength>>::Buffer<f64>: Send,
99 D::StateType: Interpolatable,
100 {
101 info!("Propagating until {event} or {max_duration}");
102
103 let mut crossing_counts = 0;
104 let closure_almanac = self.almanac.clone();
105 let orbit = if let Some(observer_frame) = event_frame {
106 self.almanac
107 .transform_to(self.state.orbit(), observer_frame, None)
108 .context(PropAlmanacSnafu)?
109 } else {
110 self.state.orbit()
111 };
112
113 let mut y_prev = event
114 .eval(orbit, &self.almanac)
115 .context(PropAnalysisSnafu)?;
116
117 let enough_crossings = |next_state: D::StateType| -> Result<bool, PropagationError> {
118 let orbit = if let Some(observer_frame) = event_frame {
119 closure_almanac
120 .transform_to(next_state.orbit(), observer_frame, None)
121 .context(PropAlmanacSnafu)?
122 } else {
123 next_state.orbit()
124 };
125
126 let y_next = event
127 .eval(orbit, &closure_almanac)
128 .context(PropAnalysisSnafu)?;
129
130 let delta = (y_next - y_prev).abs();
131
132 if event.scalar.is_angle() {
133 // Atan2 is a triangular signal so a bracket exists only if y_prev is negative and y_next is positive.
134 // Anything else is a fluke, and we can quickly speed through the whole trajectory.
135 if y_prev.signum() != y_next.signum() && delta < 180.0 {
136 crossing_counts += 1;
137 }
138 } else {
139 // Previous step accepted, check if there was a zero crossing.
140 if y_prev * y_next < 0.0 {
141 crossing_counts += 1;
142 }
143 }
144 y_prev = y_next;
145
146 Ok(crossing_counts >= trigger)
147 };
148
149 // Build the trajectory during the propagation.
150 let end_state;
151 let mut traj = Traj::new();
152 let start_state = self.state;
153
154 // Keep our own tick because it's only available to the propagate function.
155 #[cfg(not(target_arch = "wasm32"))]
156 let tick = Instant::now();
157
158 let rx = {
159 // Channels that have a single state for the propagator
160 let (tx, rx) = channel();
161 // Propagate the dynamics
162 end_state = self.propagate(max_duration, Some(tx), Some(enough_crossings))?;
163 // Note that the end state is also sent on the channel before the return of this function.
164 rx
165 };
166
167 traj.states = rx.into_iter().par_bridge().collect();
168 // Push the start state -- will be reordered in the finalize call.
169 // For some reason, this must happen at the end -- can't figure out why.
170 traj.states.push(start_state);
171
172 traj.finalize();
173
174 // We pushed at least one item to this trajectory, so the following unwrap will always succeed.
175 let last_traj_state = traj.states.last().cloned().unwrap();
176 if end_state == last_traj_state {
177 return Err(PropagationError::NthEventError {
178 nth: trigger,
179 found: crossing_counts,
180 });
181 }
182
183 // Add the final state to the trajectory so we can search it in full.
184 traj.states.push(end_state);
185
186 // We have one bracket to search.
187 let traj_at = |epoch: Epoch| -> Result<f64, AnalysisError> {
188 let state = traj
189 .at(epoch)
190 .map_err(|e| AnalysisError::GenericAnalysisError {
191 err: format!("{e}"),
192 })?;
193
194 // Refine the same observer-frame scalar used to detect the crossing.
195 let orbit = if let Some(frame) = event_frame {
196 self.almanac
197 .transform_to(state.orbit(), frame, None)
198 .map_err(|e| AnalysisError::GenericAnalysisError {
199 err: format!("{e}"),
200 })?
201 } else {
202 state.orbit()
203 };
204 event.eval(orbit, &self.almanac)
205 };
206
207 // Else Brent solver between these states
208 let event_epoch = brent_solver(traj_at, event, last_traj_state.epoch(), end_state.epoch())
209 .context(PropAnalysisSnafu)?;
210
211 #[cfg(not(target_arch = "wasm32"))]
212 {
213 if self.log_progress {
214 let tock: Duration = tick.elapsed().into();
215 if trigger > 1 {
216 info!("\t... event #{trigger} found in {tock}");
217 } else {
218 info!("\t... event found in {tock}");
219 }
220 }
221 }
222 Ok((traj.at(event_epoch).context(TrajectoryEventSnafu)?, traj))
223 }
224}