1use 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
35pub 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 pub state: D::StateType,
46 pub prop: &'a Propagator<D>,
48 pub details: IntegrationDetails,
50 pub log_progress: bool,
52 pub(crate) almanac: Arc<Almanac>,
53 pub(crate) step_size: Duration, pub(crate) fixed_step: bool,
55 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 pub fn quiet(mut self) -> Self {
67 self.log_progress = false;
68 self
69 }
70
71 pub fn verbose(mut self) -> Self {
73 self.log_progress = true;
74 self
75 }
76
77 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 info!("Propagating for {duration} until {stop_time}");
101 }
102 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; }
113
114 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 let Some(mu_km3_s2) = integration_frame.mu_km3_s2 {
129 new_orbit.frame.mu_km3_s2 = Some(mu_km3_s2);
130 }
131 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 if stop_time == epoch {
154 #[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 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 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 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 self.set_step(prev_step_size, prev_step_kind);
194
195 if backprop {
196 self.step_size = -self.step_size; }
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 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 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 return Ok(self.state);
249 }
250
251 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 pub fn for_duration(&mut self, duration: Duration) -> Result<D::StateType, PropagationError> {
263 self.propagate(duration, None, Some(|_| Ok(false)))
264 }
265
266 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 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 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 #[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 let (tx, rx) = channel();
309 end_state = self.for_duration_with_channel(duration, tx)?;
312 rx
313 };
314
315 traj.states = rx.into_iter().collect();
316 traj.states.push(start_state);
318
319 traj.finalize();
320
321 Ok((end_state, traj))
322 }
323
324 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 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 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 self.details.attempts = 1;
362 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 mut ci: f64 = 0.0;
376 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 let mut next_state = state_vec.clone();
399 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 self.details.step = self.step_size;
415 return Ok(((self.details.step), next_state));
416 } else {
417 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 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 self.step_size = step_size_s * Unit::Second;
461 if self.step_size.abs() < self.prop.opts.min_step {
462 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 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 }
487 }
488 }
489 }
490
491 pub fn latest_details(&self) -> IntegrationDetails {
493 self.details
494 }
495}