Skip to main content

nyx_space/propagators/
instance.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::{DynamicsSnafu, IntegrationDetails, PropagationError, Propagator};
20use crate::State;
21use crate::dynamics::{Dynamics, DynamicsAlmanacSnafu};
22use crate::linalg::allocator::Allocator;
23use crate::linalg::{DefaultAllocator, OVector};
24use crate::md::trajectory::{Interpolatable, Traj};
25use crate::time::{Duration, Epoch, Unit};
26use anise::almanac::Almanac;
27use anise::errors::MathError;
28use log::{info, warn};
29use snafu::ResultExt;
30use std::sync::Arc;
31use std::sync::mpsc::{Sender, channel};
32#[cfg(not(target_arch = "wasm32"))]
33use std::time::Instant;
34
35/// A Propagator allows propagating a set of dynamics forward or backward in time.
36/// It is an EventTracker, without any event tracking. It includes the options, the integrator
37/// details of the previous step, and the set of coefficients used for the monomorphic instance.
38pub struct PropInstance<'a, D: Dynamics>
39where
40    DefaultAllocator: Allocator<<D::StateType as State>::Size>
41        + Allocator<<D::StateType as State>::Size, <D::StateType as State>::Size>
42        + Allocator<<D::StateType as State>::VecLength>,
43{
44    /// The state of this propagator instance
45    pub state: D::StateType,
46    /// The propagator setup (kind, stages, etc.)
47    pub prop: &'a Propagator<D>,
48    /// Stores the details of the previous integration step
49    pub details: IntegrationDetails,
50    /// Should progress reports be logged
51    pub log_progress: bool,
52    pub(crate) almanac: Arc<Almanac>,
53    pub(crate) step_size: Duration, // Stores the adapted step for the _next_ call
54    pub(crate) fixed_step: bool,
55    // Allows us to do pre-allocation of the ki vectors
56    pub(crate) k: Vec<OVector<f64, <D::StateType as State>::VecLength>>,
57}
58
59impl<D: Dynamics> PropInstance<'_, D>
60where
61    DefaultAllocator: Allocator<<D::StateType as State>::Size>
62        + Allocator<<D::StateType as State>::Size, <D::StateType as State>::Size>
63        + Allocator<<D::StateType as State>::VecLength>,
64{
65    /// Sets this instance to not log progress
66    pub fn quiet(mut self) -> Self {
67        self.log_progress = false;
68        self
69    }
70
71    /// Sets this instance to log progress
72    pub fn verbose(mut self) -> Self {
73        self.log_progress = true;
74        self
75    }
76
77    /// Allows setting the step size of the propagator
78    pub fn set_step(&mut self, step_size: Duration, fixed: bool) {
79        self.step_size = step_size;
80        self.fixed_step = fixed;
81    }
82
83    #[allow(clippy::erasing_op)]
84    pub(crate) fn propagate<F>(
85        &mut self,
86        duration: Duration,
87        maybe_tx_chan: Option<Sender<D::StateType>>,
88        mut stop_condition: Option<F>,
89    ) -> Result<D::StateType, PropagationError>
90    where
91        F: FnMut(D::StateType) -> Result<bool, PropagationError>,
92    {
93        if duration == 0 * Unit::Second {
94            return Ok(self.state);
95        }
96        let stop_time = self.state.epoch() + duration;
97
98        if self.log_progress {
99            // Prevent the print spam for orbit determination cases
100            info!("Propagating for {duration} until {stop_time}");
101        }
102        // Call `finally` on the current state to set anything up
103        self.state = self
104            .prop
105            .dynamics
106            .finally(self.state, &self.almanac)
107            .context(DynamicsSnafu)?;
108
109        let backprop = duration.is_negative();
110        if backprop {
111            self.step_size = -self.step_size; // Invert the step size
112        }
113
114        // Transform the state if needed
115        let mut original_frame = None;
116        if let Some(integration_frame) = self.prop.opts.integration_frame
117            && integration_frame != self.state.orbit().frame
118        {
119            original_frame = Some(self.state.orbit().frame);
120            let mut new_orbit = self
121                .almanac
122                .transform_to(self.state.orbit(), integration_frame, None)
123                .context(DynamicsAlmanacSnafu {
124                    action: "transforming state into desired integration frame",
125                })
126                .context(DynamicsSnafu)?;
127            // If the integration frame has parameters, we set them here.
128            if let Some(mu_km3_s2) = integration_frame.mu_km3_s2 {
129                new_orbit.frame.mu_km3_s2 = Some(mu_km3_s2);
130            }
131            // If the integration frame has parameters, we set them here.
132            if let Some(shape) = integration_frame.shape {
133                new_orbit.frame.shape = Some(shape);
134            }
135            if self.log_progress {
136                info!("State transformed to the integration frame {integration_frame}");
137            }
138            self.state.set_orbit(new_orbit);
139        }
140
141        #[cfg(not(target_arch = "wasm32"))]
142        let tick = Instant::now();
143        #[cfg(not(target_arch = "wasm32"))]
144        let mut prev_tick = Instant::now();
145
146        loop {
147            let epoch = self.state.epoch();
148            if (!backprop && epoch + self.step_size > stop_time)
149                || (backprop && epoch + self.step_size <= stop_time)
150            {
151                // We don't check for the interrupt condition on the last step.
152                // If we're reached this far without hitting it, we most certainly won't trigger it.
153                if stop_time == epoch {
154                    // No propagation necessary
155                    #[cfg(not(target_arch = "wasm32"))]
156                    {
157                        if self.log_progress {
158                            let tock: Duration = tick.elapsed().into();
159                            info!("\t... done in {tock}");
160                        }
161                    }
162
163                    // Rotate back if needed
164                    if let Some(original_frame) = original_frame {
165                        let new_orbit = self
166                            .almanac
167                            .transform_to(self.state.orbit(), original_frame, None)
168                            .context(DynamicsAlmanacSnafu {
169                                action: "transforming state from desired integration frame",
170                            })
171                            .context(DynamicsSnafu)?;
172                        self.state.set_orbit(new_orbit);
173                    }
174
175                    return Ok(self.state);
176                }
177
178                // Take one final step of exactly the needed duration until the stop time
179                let prev_step_size = self.step_size;
180                let prev_step_kind = self.fixed_step;
181                self.set_step(stop_time - epoch, true);
182
183                self.single_step()?;
184
185                // Publish to channel if provided
186                if let Some(ref chan) = maybe_tx_chan
187                    && let Err(e) = chan.send(self.state)
188                {
189                    warn!("{e} when sending on channel")
190                }
191
192                // Restore the step size for subsequent calls
193                self.set_step(prev_step_size, prev_step_kind);
194
195                if backprop {
196                    self.step_size = -self.step_size; // Restore to a positive step size
197                }
198
199                #[cfg(not(target_arch = "wasm32"))]
200                {
201                    if self.log_progress {
202                        let tock: Duration = tick.elapsed().into();
203                        info!("\t... done in {tock}");
204                    }
205                }
206
207                // Rotate back if needed
208                if let Some(original_frame) = original_frame {
209                    let new_orbit = self
210                        .almanac
211                        .transform_to(self.state.orbit(), original_frame, None)
212                        .context(DynamicsAlmanacSnafu {
213                            action: "transforming state from desired integration frame",
214                        })
215                        .context(DynamicsSnafu)?;
216                    self.state.set_orbit(new_orbit);
217                }
218
219                return Ok(self.state);
220            } else {
221                #[cfg(not(target_arch = "wasm32"))]
222                {
223                    if self.log_progress {
224                        let tock: Duration = prev_tick.elapsed().into();
225                        if tock.to_unit(Unit::Minute) > 1.0 {
226                            // Report status every minute
227                            let cur_epoch = self.state.epoch();
228                            let dur_to_go = (stop_time - cur_epoch).floor(Unit::Second * 1);
229                            info!(
230                                "\t... current epoch {}, remaining {} (step size = {})",
231                                cur_epoch, dur_to_go, self.details.step
232                            );
233                            prev_tick = Instant::now();
234                        }
235                    }
236                }
237
238                self.single_step()?;
239
240                if let Some(ref mut condition) = stop_condition
241                    && condition(self.state)?
242                {
243                    // Stopping condition triggered. We don't send
244                    // the new state on the channel for the caller to know that the exact
245                    // condition they are seeking is between the last state on the channel
246                    // and the state we're returning
247
248                    return Ok(self.state);
249                }
250
251                // Publish to channel if provided
252                if let Some(ref chan) = maybe_tx_chan
253                    && let Err(e) = chan.send(self.state)
254                {
255                    warn!("{e} when sending on channel")
256                }
257            }
258        }
259    }
260
261    /// This method propagates the provided Dynamics for the provided duration.
262    pub fn for_duration(&mut self, duration: Duration) -> Result<D::StateType, PropagationError> {
263        self.propagate(duration, None, Some(|_| Ok(false)))
264    }
265
266    /// This method propagates the provided Dynamics for the provided duration and publishes each state on the channel.
267    pub fn for_duration_with_channel(
268        &mut self,
269        duration: Duration,
270        tx_chan: Sender<D::StateType>,
271    ) -> Result<D::StateType, PropagationError> {
272        self.propagate(duration, Some(tx_chan), Some(|_| Ok(false)))
273    }
274
275    /// Propagates the provided Dynamics until the provided epoch. Returns the end state.
276    pub fn until_epoch(&mut self, end_time: Epoch) -> Result<D::StateType, PropagationError> {
277        let duration: Duration = end_time - self.state.epoch();
278        self.for_duration(duration)
279    }
280
281    /// Propagates the provided Dynamics until the provided epoch and publishes states on the provided channel. Returns the end state.
282    pub fn until_epoch_with_channel(
283        &mut self,
284        end_time: Epoch,
285        tx_chan: Sender<D::StateType>,
286    ) -> Result<D::StateType, PropagationError> {
287        let duration: Duration = end_time - self.state.epoch();
288        self.for_duration_with_channel(duration, tx_chan)
289    }
290
291    /// Propagates the provided Dynamics for the provided duration and generate the trajectory of these dynamics on its own thread.
292    /// Returns the end state and the trajectory.
293    #[allow(clippy::map_clone)]
294    pub fn for_duration_with_traj(
295        &mut self,
296        duration: Duration,
297    ) -> Result<(D::StateType, Traj<D::StateType>), PropagationError>
298    where
299        <DefaultAllocator as Allocator<<D::StateType as State>::VecLength>>::Buffer<f64>: Send,
300        D::StateType: Interpolatable,
301    {
302        let end_state;
303        let mut traj = Traj::new();
304        let start_state = self.state;
305
306        let rx = {
307            // Channels that have a single state for the propagator
308            let (tx, rx) = channel();
309            // Propagate the dynamics
310            // Note that the end state is also sent on the channel before the return of this function.
311            end_state = self.for_duration_with_channel(duration, tx)?;
312            rx
313        };
314
315        traj.states = rx.into_iter().collect();
316        // Push the start state -- will be reordered and deduplicated in the finalize call.
317        traj.states.push(start_state);
318
319        traj.finalize();
320
321        Ok((end_state, traj))
322    }
323
324    /// Propagates the provided Dynamics until the provided epoch and generate the trajectory of these dynamics on its own thread.
325    /// Returns the end state and the trajectory.
326    pub fn until_epoch_with_traj(
327        &mut self,
328        end_time: Epoch,
329    ) -> Result<(D::StateType, Traj<D::StateType>), PropagationError>
330    where
331        <DefaultAllocator as Allocator<<D::StateType as State>::VecLength>>::Buffer<f64>: Send,
332        D::StateType: Interpolatable,
333    {
334        let duration: Duration = end_time - self.state.epoch();
335        self.for_duration_with_traj(duration)
336    }
337
338    /// Take a single propagator step and emit the result on the TX channel (if enabled)
339    pub fn single_step(&mut self) -> Result<(), PropagationError> {
340        let (t, state_vec) = self.derive()?;
341        self.state.set(self.state.epoch() + t, &state_vec);
342        self.state = self
343            .prop
344            .dynamics
345            .finally(self.state, &self.almanac)
346            .context(DynamicsSnafu)?;
347        Ok(())
348    }
349
350    /// This method integrates whichever function is provided as `d_xdt`. Everything passed to this function is in **seconds**.
351    ///
352    /// This function returns the step sized used (as a Duration) and the new state as y_{n+1} = y_n + \frac{dy_n}{dt}.
353    /// To get the integration details, check `self.latest_details`.
354    fn derive(
355        &mut self,
356    ) -> Result<(Duration, OVector<f64, <D::StateType as State>::VecLength>), PropagationError>
357    {
358        let state_vec = &self.state.to_vector();
359        let state_ctx = &self.state;
360        // Reset the number of attempts used (we don't reset the error because it's set before it's read)
361        self.details.attempts = 1;
362        // Convert the step size to seconds -- it's mutable because we may change it below
363        let mut step_size_s = self.step_size.to_seconds();
364        loop {
365            let ki = self
366                .prop
367                .dynamics
368                .eom(0.0, state_vec, state_ctx, &self.almanac)
369                .context(DynamicsSnafu)?;
370            self.k[0] = ki;
371            let mut a_idx: usize = 0;
372            for i in 0..(self.prop.method.stages() - 1) {
373                // Let's compute the c_i by summing the relevant items from the list of coefficients.
374                // \sum_{j=1}^{i-1} a_ij  ∀ i ∈ [2, s]
375                let mut ci: f64 = 0.0;
376                // The wi stores the a_{s1} * k_1 + a_{s2} * k_2 + ... + a_{s, s-1} * k_{s-1} +
377                let mut wi = OVector::<f64, <D::StateType as State>::VecLength>::from_element(0.0);
378                for kj in &self.k[0..i + 1] {
379                    let a_ij = self.prop.method.a_coeffs()[a_idx];
380                    ci += a_ij;
381                    wi += a_ij * kj;
382                    a_idx += 1;
383                }
384
385                let ki = self
386                    .prop
387                    .dynamics
388                    .eom(
389                        ci * step_size_s,
390                        &(state_vec + step_size_s * wi),
391                        state_ctx,
392                        &self.almanac,
393                    )
394                    .context(DynamicsSnafu)?;
395                self.k[i + 1] = ki;
396            }
397            // Compute the next state and the error
398            let mut next_state = state_vec.clone();
399            // State error estimation from https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods#Adaptive_Runge%E2%80%93Kutta_methods
400            // This is consistent with GMAT https://github.com/ChristopherRabotin/GMAT/blob/37201a6290e7f7b941bc98ee973a527a5857104b/src/base/propagator/RungeKutta.cpp#L537
401            let mut error_est =
402                OVector::<f64, <D::StateType as State>::VecLength>::from_element(0.0);
403            for (i, ki) in self.k.iter().enumerate() {
404                let b_i = self.prop.method.b_coeffs()[i];
405                if !self.fixed_step {
406                    let b_i_star = self.prop.method.b_coeffs()[i + self.prop.method.stages()];
407                    error_est += step_size_s * (b_i - b_i_star) * ki;
408                }
409                next_state += step_size_s * b_i * ki;
410            }
411
412            if self.fixed_step {
413                // Using a fixed step, no adaptive step necessary
414                self.details.step = self.step_size;
415                return Ok(((self.details.step), next_state));
416            } else {
417                // Compute the error estimate.
418                self.details.error =
419                    self.prop
420                        .opts
421                        .error_ctrl
422                        .estimate(&error_est, &next_state, state_vec);
423
424                if self.details.error <= self.prop.opts.tolerance
425                    || step_size_s <= self.prop.opts.min_step.to_seconds()
426                    || self.details.attempts >= self.prop.opts.attempts
427                {
428                    if next_state.iter().any(|x| x.is_nan()) {
429                        return Err(PropagationError::PropMathError {
430                            source: MathError::DomainError {
431                                value: f64::NAN,
432                                msg: "try another integration method, or decrease step size; part of state vector is",
433                            },
434                        });
435                    }
436                    if self.details.attempts >= self.prop.opts.attempts {
437                        warn!(
438                            "Could not further decrease step size: maximum number of attempts reached ({})",
439                            self.details.attempts
440                        );
441                    }
442
443                    self.details.step = step_size_s * Unit::Second;
444                    if self.details.error < self.prop.opts.tolerance {
445                        // Let's increase the step size for the next iteration.
446                        // Error is less than tolerance, let's attempt to increase the step for the next iteration.
447                        let proposed_step_s = 0.9
448                            * step_size_s
449                            * (self.prop.opts.tolerance / self.details.error)
450                                .powf(1.0 / f64::from(self.prop.method.order()));
451
452                        step_size_s =
453                            if proposed_step_s.abs() > self.prop.opts.max_step.to_seconds().abs() {
454                                self.prop.opts.max_step.to_seconds() * proposed_step_s.signum()
455                            } else {
456                                proposed_step_s
457                            };
458                    }
459                    // In all cases, let's update the step size to whatever was the adapted step size
460                    self.step_size = step_size_s * Unit::Second;
461                    if self.step_size.abs() < self.prop.opts.min_step {
462                        // Custom signum in case the step size becomes zero.
463                        let signum = if self.step_size.is_negative() {
464                            -1.0
465                        } else {
466                            1.0
467                        };
468                        self.step_size = self.prop.opts.min_step * signum;
469                    }
470                    return Ok((self.details.step, next_state));
471                } else {
472                    // Error is too high and we aren't using the smallest step, and we haven't hit the max number of attempts.
473                    // So let's adapt the step size.
474                    self.details.attempts += 1;
475                    let proposed_step_s = 0.9
476                        * step_size_s
477                        * (self.prop.opts.tolerance / self.details.error)
478                            .powf(1.0 / f64::from(self.prop.method.order() - 1));
479
480                    step_size_s = if proposed_step_s < self.prop.opts.min_step.to_seconds() {
481                        self.prop.opts.min_step.to_seconds()
482                    } else {
483                        proposed_step_s
484                    };
485                    // Note that we don't set self.step_size, that will be updated right before we return
486                }
487            }
488        }
489    }
490
491    /// Copy the details of the latest integration step.
492    pub fn latest_details(&self) -> IntegrationDetails {
493        self.details
494    }
495}