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
extern crate hyperdual;

use self::hyperdual::linalg::norm;
use self::hyperdual::{hyperspace_from_vector, Float, Hyperdual};
use super::{AccelModel, Dynamics};
use crate::dimensions::{DimName, Matrix6, Vector3, Vector6, VectorN, U3, U36, U42, U6, U7};
use crate::time::Epoch;
use celestia::{Cosm, Frame, LTCorr, State};
use od::{AutoDiffDynamics, Estimable};
use std::f64;

/// `CelestialDynamics` provides the equations of motion for any celestial dynamic, without state transition matrix computation.
pub struct CelestialDynamics<'a> {
    /// Current state of these dynamics
    pub state: State,
    /// Loss in precision is avoided by using a relative time parameter initialized to zero
    relative_time: f64,
    /// Allows us to rebuilt the true epoch
    init_tai_secs: f64,
    pub accel_models: Vec<Box<dyn AccelModel + 'a>>,
}

impl<'a> CelestialDynamics<'a> {
    /// Initialize third body dynamics given the EXB IDs and a Cosm
    pub fn new(state: State, bodies: Vec<i32>, cosm: &'a Cosm) -> Self {
        // Create the point masses
        let pts = PointMasses::new(state.frame, bodies, cosm);
        Self {
            state,
            relative_time: 0.0,
            init_tai_secs: state.dt.as_tai_seconds(),
            accel_models: vec![Box::new(pts)],
        }
    }

    /// Initializes a CelestialDynamics which does not simulate the gravity pull of other celestial objects but the primary one.
    pub fn two_body(state: State) -> Self {
        Self {
            state,
            relative_time: 0.0,
            init_tai_secs: state.dt.as_tai_seconds(),
            accel_models: Vec::new(),
        }
    }

    pub fn add_model(&mut self, accel_model: Box<dyn AccelModel + 'a>) {
        self.accel_models.push(accel_model);
    }

    pub fn state_ctor(&self, rel_time: f64, state_vec: &Vector6<f64>) -> State {
        State::cartesian(
            state_vec[0],
            state_vec[1],
            state_vec[2],
            state_vec[3],
            state_vec[4],
            state_vec[5],
            Epoch::from_tai_seconds(self.init_tai_secs + rel_time),
            self.state.frame,
        )
    }
}

impl<'a> Dynamics for CelestialDynamics<'a> {
    type StateSize = U6;
    type StateType = State;
    /// Returns the relative time to the propagator. Use prop.dynamics.state.dt for absolute time
    fn time(&self) -> f64 {
        self.relative_time
    }

    fn state_vector(&self) -> VectorN<f64, Self::StateSize> {
        self.state.to_cartesian_vec()
    }

    fn set_state(&mut self, new_t: f64, new_state: &VectorN<f64, Self::StateSize>) {
        self.relative_time = new_t;
        self.state = self.state_ctor(new_t, new_state);
    }

    fn state(&self) -> State {
        self.state
    }

    fn eom(&self, t: f64, state: &VectorN<f64, Self::StateSize>) -> VectorN<f64, Self::StateSize> {
        let osc = self.state_ctor(t, state);
        let body_acceleration = (-self.state.frame.gm() / osc.rmag().powi(3)) * osc.radius();
        let mut d_x = Vector6::from_iterator(
            osc.velocity()
                .iter()
                .chain(body_acceleration.iter())
                .cloned(),
        );

        // Apply the acceleration models
        for model in &self.accel_models {
            let model_acc = model.eom(&osc);
            for i in 0..3 {
                d_x[i + 3] += model_acc[i];
            }
        }

        d_x
    }
}

pub struct PointMasses<'a> {
    /// The propagation frame
    pub frame: Frame,
    pub bodies: Vec<i32>,
    /// Optional point to a Cosm, needed if extra point masses are needed
    pub cosm: &'a Cosm,
    /// Light-time correction computation if extra point masses are needed
    pub correction: LTCorr,
}

impl<'a> PointMasses<'a> {
    pub fn new(propagation_frame: Frame, bodies: Vec<i32>, cosm: &'a Cosm) -> Self {
        Self::with_correction(propagation_frame, bodies, cosm, LTCorr::None)
    }

    pub fn with_correction(
        propagation_frame: Frame,
        bodies: Vec<i32>,
        cosm: &'a Cosm,
        correction: LTCorr,
    ) -> Self {
        // Check that these celestial bodies exist
        for exb_id in &bodies {
            cosm.try_frame_by_exb_id(*exb_id)
                .expect("unknown EXB ID in list of third bodies");
        }

        Self {
            frame: propagation_frame,
            bodies,
            cosm,
            correction,
        }
    }
}

impl<'a> AccelModel for PointMasses<'a> {
    fn eom(&self, osc: &State) -> Vector3<f64> {
        let mut d_x = Vector3::zeros();
        // Get all of the position vectors between the center body and the third bodies
        for exb_id in &self.bodies {
            let third_body = self.cosm.frame_by_exb_id(*exb_id);
            // State of j-th body as seen from primary body
            let st_ij = self
                .cosm
                .celestial_state(*exb_id, osc.dt, self.frame, self.correction);

            let r_ij = st_ij.radius();
            let r_ij3 = st_ij.rmag().powi(3);
            let r_j = osc.radius() - r_ij; // sc as seen from 3rd body
            let r_j3 = r_j.norm().powi(3);
            d_x += -third_body.gm() * (r_j / r_j3 + r_ij / r_ij3);
        }
        d_x
    }
}

/// `CelestialDynamicsStm` provides the equations of motion for any celestial dynamic, **with** state transition matrix computation.
#[derive(Clone)]
pub struct CelestialDynamicsStm<'a> {
    pub state: State,
    pub bodies: Vec<i32>,
    pub stm: Matrix6<f64>,
    // Loss in precision is avoided by using a relative time parameter initialized to zero
    relative_time: f64,
    // Allows us to rebuilt the true epoch
    init_tai_secs: f64,
    pub cosm: Option<&'a Cosm>,
    pub correction: LTCorr,
}

impl<'a> CelestialDynamicsStm<'a> {
    /// Initialize third body dynamics given the EXB IDs and a Cosm
    pub fn new(state: State, bodies: Vec<i32>, cosm: &'a Cosm) -> Self {
        // Check that these bodies are present in the EXB.
        for exb_id in &bodies {
            cosm.try_frame_by_exb_id(*exb_id)
                .expect("unknown EXB ID in list of third bodies");
        }
        Self {
            state,
            bodies,
            stm: Matrix6::identity(),
            relative_time: 0.0,
            init_tai_secs: state.dt.as_tai_seconds(),
            cosm: Some(cosm),
            correction: LTCorr::None,
        }
    }

    /// Initializes a CelestialDynamicsStm which does not simulate the gravity pull of other celestial objects but the primary one.
    pub fn two_body(state: State) -> Self {
        Self {
            state,
            bodies: Vec::new(),
            stm: Matrix6::identity(),
            relative_time: 0.0,
            init_tai_secs: state.dt.as_tai_seconds(),
            cosm: None,
            correction: LTCorr::None,
        }
    }

    /// Provides a copy to the state.
    pub fn as_state(&self) -> State {
        self.state
    }

    /// Used only to set the orbital state, useful for Extended Kalman Filters.
    pub fn set_orbital_state(&mut self, new_t: f64, new_state: &Vector6<f64>) {
        self.relative_time = new_t;
        self.state.dt = Epoch::from_tai_seconds(self.init_tai_secs + new_t);
        self.state.x = new_state[0];
        self.state.y = new_state[1];
        self.state.z = new_state[2];
        self.state.vx = new_state[3];
        self.state.vy = new_state[4];
        self.state.vz = new_state[5];
    }

    /// Rebuild the state and STM from the provided vector
    pub fn state_ctor(&self, t: f64, in_state: &VectorN<f64, U42>) -> (State, Matrix6<f64>) {
        // Copy the current state, and then modify it
        let (mut state, mut stm) = self.state();
        state.dt = Epoch::from_tai_seconds(self.init_tai_secs + t);
        state.x = in_state[0];
        state.y = in_state[1];
        state.z = in_state[2];
        state.vx = in_state[3];
        state.vy = in_state[4];
        state.vz = in_state[5];

        for i in 0..6 {
            for j in 0..6 {
                stm[(i, j)] = in_state[i * 6 + j + 6];
            }
        }

        (state, stm)
    }
}

impl<'a> AutoDiffDynamics for CelestialDynamicsStm<'a> {
    type HyperStateSize = U7;
    type STMSize = U6;

    fn dual_eom(
        &self,
        t: f64,
        state: &VectorN<Hyperdual<f64, U7>, U6>,
    ) -> (Vector6<f64>, Matrix6<f64>) {
        // Extract data from hyperspace
        let radius = state.fixed_rows::<U3>(0).into_owned();
        let velocity = state.fixed_rows::<U3>(3).into_owned();

        // Code up math as usual
        let rmag = norm(&radius);
        let body_acceleration =
            radius * (Hyperdual::<f64, U7>::from_real(-self.state.frame.gm()) / rmag.powi(3));

        // Extract result into Vector6 and Matrix6
        let mut fx = Vector6::zeros();
        let mut grad = Matrix6::zeros();
        for i in 0..U6::dim() {
            fx[i] = if i < 3 {
                velocity[i].real()
            } else {
                body_acceleration[i - 3].real()
            };
            for j in 1..U7::dim() {
                grad[(i, j - 1)] = if i < 3 {
                    velocity[i][j]
                } else {
                    body_acceleration[i - 3][j]
                };
            }
        }

        // Get all of the position vectors between the center body and the third bodies
        let jde = Epoch::from_tai_seconds(self.init_tai_secs + t);
        for exb_id in &self.bodies {
            let third_body = self.cosm.unwrap().frame_by_exb_id(*exb_id);
            let gm_d = Hyperdual::<f64, U7>::from_real(-third_body.gm());

            // State of j-th body as seen from primary body
            let st_ij =
                self.cosm
                    .unwrap()
                    .celestial_state(*exb_id, jde, self.state.frame, self.correction);

            let r_ij: Vector3<Hyperdual<f64, U7>> = hyperspace_from_vector(&st_ij.radius());
            let r_ij3 = norm(&r_ij).powi(3) / gm_d;
            // The difference leads to the dual parts nulling themselves out, so let's fix that.
            let mut r_j = radius - r_ij; // sc as seen from 3rd body
            r_j[0][1] = 1.0;
            r_j[1][2] = 1.0;
            r_j[2][3] = 1.0;

            let r_j3 = norm(&r_j).powi(3) / gm_d;
            let third_body_acc_d = r_j / r_j3 + r_ij / r_ij3;

            for i in 0..U3::dim() {
                fx[i + 3] += third_body_acc_d[i][0];
                for j in 1..U7::dim() {
                    grad[(i + 3, j - 1)] += third_body_acc_d[i][j];
                }
            }
        }

        (fx, grad)
    }
}

impl<'a> Dynamics for CelestialDynamicsStm<'a> {
    type StateSize = U42;
    type StateType = (State, Matrix6<f64>);
    /// Returns the relative time to the propagator. Use prop.dynamics.state.dt for absolute time
    fn time(&self) -> f64 {
        self.relative_time
    }

    fn state_vector(&self) -> VectorN<f64, Self::StateSize> {
        let mut stm_as_vec = VectorN::<f64, U36>::zeros();
        let mut stm_idx = 0;
        for i in 0..6 {
            for j in 0..6 {
                stm_as_vec[(stm_idx, 0)] = self.stm[(i, j)];
                stm_idx += 1;
            }
        }
        VectorN::<f64, Self::StateSize>::from_iterator(
            self.state
                .to_cartesian_vec()
                .iter()
                .chain(stm_as_vec.iter())
                .cloned(),
        )
    }

    /// Returns the celestial state and the state transition matrix
    fn state(&self) -> Self::StateType {
        (self.state, self.stm)
    }

    fn set_state(&mut self, new_t: f64, new_state: &VectorN<f64, Self::StateSize>) {
        self.relative_time = new_t;
        self.state.dt = Epoch::from_tai_seconds(self.init_tai_secs + new_t);
        self.state.x = new_state[0];
        self.state.y = new_state[1];
        self.state.z = new_state[2];
        self.state.vx = new_state[3];
        self.state.vy = new_state[4];
        self.state.vz = new_state[5];
        // And update the STM
        let mut stm_k_to_0 = Matrix6::zeros();
        let mut stm_idx = 6;
        for i in 0..6 {
            for j in 0..6 {
                stm_k_to_0[(i, j)] = new_state[(stm_idx, 0)];
                stm_idx += 1;
            }
        }

        let mut stm_prev = self.stm;
        if !stm_prev.try_inverse_mut() {
            println!("{}", self.stm);
            panic!("STM not invertible");
        }
        self.stm = stm_k_to_0 * stm_prev;
    }

    fn eom(&self, t: f64, state: &VectorN<f64, Self::StateSize>) -> VectorN<f64, Self::StateSize> {
        let pos_vel = state.fixed_rows::<U6>(0).into_owned();
        let (state, grad) = self.compute(t, &pos_vel);
        let stm_dt = self.stm * grad;
        // Rebuild the STM as a vector.
        let mut stm_as_vec = VectorN::<f64, U36>::zeros();
        let mut stm_idx = 0;
        for i in 0..6 {
            for j in 0..6 {
                stm_as_vec[(stm_idx, 0)] = stm_dt[(i, j)];
                stm_idx += 1;
            }
        }
        VectorN::<f64, Self::StateSize>::from_iterator(
            state.iter().chain(stm_as_vec.iter()).cloned(),
        )
    }
}

impl<'a> Estimable<State> for CelestialDynamicsStm<'a> {
    type LinStateSize = U6;

    fn to_measurement(&self, prop_state: &Self::StateType) -> (Epoch, State) {
        (prop_state.0.dt, prop_state.0)
    }

    fn extract_stm(&self, prop_state: &Self::StateType) -> Matrix6<f64> {
        prop_state.1
    }

    fn extract_estimated_state(
        &self,
        prop_state: &Self::StateType,
    ) -> VectorN<f64, Self::LinStateSize> {
        prop_state.0.to_cartesian_vec()
    }

    /// Returns the estimated state
    fn set_estimated_state(&mut self, new_state: VectorN<f64, Self::LinStateSize>) {
        self.state.x = new_state[0];
        self.state.y = new_state[1];
        self.state.z = new_state[2];
        self.state.vx = new_state[3];
        self.state.vy = new_state[4];
        self.state.vz = new_state[5];
    }
}