Skip to main content

hpr_sim/
recorder.rs

1//! Watching a flight: the [`Observer`] trait, the [`Sample`] of derived quantities at an instant,
2//! and the [`Recorder`], which keeps a chosen set of [`Channel`]s at a fixed interval.
3
4use hpr_core::DVec3;
5use serde::{Deserialize, Serialize};
6
7use crate::dynamics::Phase;
8use crate::error::SimError;
9use crate::flight::FlightEvent;
10use crate::metrics::Stability;
11use crate::recovery::BodySample;
12use crate::state::State;
13
14/// The flight's state and the quantities derived from it at one instant.
15#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
16pub struct Sample {
17    /// Time since launch, s: the flight's clock, from which each motor's ignition is counted.
18    pub time_s: f64,
19    /// The phase the flight was in.
20    pub phase: Phase,
21    /// The integrated state.
22    pub state: State,
23    /// The center of mass in the launch frame, m.
24    pub cg_enu_m: DVec3,
25    /// The center of mass's velocity relative to the launch frame, m/s.
26    pub cg_velocity_enu_m_s: DVec3,
27    /// The center of mass's ellipsoidal height above the launch site, m.
28    pub height_above_ground_m: f64,
29    /// The rate of that height, m/s.
30    pub vertical_speed_m_s: f64,
31    /// The nose tip's acceleration relative to the launch frame, m/s².
32    pub acceleration_enu_m_s2: DVec3,
33    /// The specific force at the nose tip, m/s²: its acceleration less gravity and the Coriolis
34    /// term (both taken at the center of mass), which is the thrust, aerodynamic and rail forces
35    /// over the mass, what an accelerometer there reads. Under the recovery devices, a point mass,
36    /// it is `(drag + thrust)/m`: the opening load over the mass (Knacke, *Parachute Recovery
37    /// Systems Design Manual*, NWC TP 6575, 1991, p. 5-50, gives the opening force as
38    /// `F = (C_D S) q C_x X₁`). On the pad, held still, it is gravity's opposite.
39    pub specific_force_enu_m_s2: DVec3,
40    /// The airspeed of the center of mass, m/s.
41    pub airspeed_m_s: f64,
42    /// Its Mach number.
43    pub mach: f64,
44    /// The total angle of attack at the center of mass, rad.
45    pub angle_of_attack_rad: f64,
46    /// The dynamic pressure, Pa.
47    pub dynamic_pressure_pa: f64,
48    /// The axial force coefficient `C_A` on the reference area.
49    pub axial_coefficient: f64,
50    /// The thrust, N.
51    pub thrust_n: f64,
52    /// The mass, kg.
53    pub mass_kg: f64,
54    /// The drag area `C_D S` of the open recovery devices, m² (zero before any deploys).
55    pub recovery_drag_area_m2: f64,
56}
57
58/// What a recorder can keep. Vector channels take three columns (east, north, up or x, y, z).
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
60#[serde(rename_all = "snake_case")]
61#[non_exhaustive]
62pub enum Channel {
63    /// Time since launch, s.
64    Time,
65    /// The nose tip's position in the launch frame, m.
66    Position,
67    /// The nose tip's velocity, m/s.
68    Velocity,
69    /// The attitude quaternion `(w, x, y, z)`, body to launch frame.
70    Attitude,
71    /// The body rates, rad/s.
72    BodyRates,
73    /// The center of mass's position, m.
74    CgPosition,
75    /// The center of mass's height above the site, m.
76    HeightAboveGround,
77    /// The vertical speed, m/s.
78    VerticalSpeed,
79    /// The nose tip's acceleration, m/s².
80    Acceleration,
81    /// The airspeed, m/s.
82    Airspeed,
83    /// The Mach number.
84    Mach,
85    /// The total angle of attack, rad.
86    AngleOfAttack,
87    /// The dynamic pressure, Pa.
88    DynamicPressure,
89    /// The axial force coefficient.
90    AxialCoefficient,
91    /// The thrust, N.
92    Thrust,
93    /// The mass, kg.
94    Mass,
95    /// The open recovery devices' drag area `C_D S`, m².
96    RecoveryDragArea,
97}
98
99impl Channel {
100    /// Every channel, in column order.
101    pub const ALL: &'static [Channel] = &[
102        Channel::Time,
103        Channel::Position,
104        Channel::Velocity,
105        Channel::Attitude,
106        Channel::BodyRates,
107        Channel::CgPosition,
108        Channel::HeightAboveGround,
109        Channel::VerticalSpeed,
110        Channel::Acceleration,
111        Channel::Airspeed,
112        Channel::Mach,
113        Channel::AngleOfAttack,
114        Channel::DynamicPressure,
115        Channel::AxialCoefficient,
116        Channel::Thrust,
117        Channel::Mass,
118        Channel::RecoveryDragArea,
119    ];
120
121    /// The column names, with units.
122    #[must_use]
123    pub fn columns(self) -> Vec<String> {
124        let three = |base: &str, unit: &str, axes: [&str; 3]| {
125            axes.iter()
126                .map(|axis| format!("{base}_{axis}_{unit}"))
127                .collect()
128        };
129        let one = |name: &str| vec![name.to_owned()];
130        let enu = ["east", "north", "up"];
131        let xyz = ["x", "y", "z"];
132        match self {
133            Self::Time => one("time_s"),
134            Self::Position => three("position", "m", enu),
135            Self::Velocity => three("velocity", "m_s", enu),
136            Self::Attitude => ["attitude_w", "attitude_x", "attitude_y", "attitude_z"]
137                .iter()
138                .map(|s| (*s).to_owned())
139                .collect(),
140            Self::BodyRates => three("body_rate", "rad_s", xyz),
141            Self::CgPosition => three("cg", "m", enu),
142            Self::HeightAboveGround => one("height_above_ground_m"),
143            Self::VerticalSpeed => one("vertical_speed_m_s"),
144            Self::Acceleration => three("acceleration", "m_s2", enu),
145            Self::Airspeed => one("airspeed_m_s"),
146            Self::Mach => one("mach"),
147            Self::AngleOfAttack => one("angle_of_attack_rad"),
148            Self::DynamicPressure => one("dynamic_pressure_pa"),
149            Self::AxialCoefficient => one("axial_coefficient"),
150            Self::Thrust => one("thrust_n"),
151            Self::Mass => one("mass_kg"),
152            Self::RecoveryDragArea => one("recovery_drag_area_m2"),
153        }
154    }
155
156    /// Appends this channel's values from `sample` to `row`.
157    pub fn push(self, sample: &Sample, row: &mut Vec<f64>) {
158        let s = &sample.state;
159        match self {
160            Self::Time => row.push(sample.time_s),
161            Self::Position => row.extend(s.position_enu_m.to_array()),
162            Self::Velocity => row.extend(s.velocity_enu_m_s.to_array()),
163            Self::Attitude => {
164                let q = s.unit_attitude();
165                row.extend([q.w, q.x, q.y, q.z]);
166            }
167            Self::BodyRates => row.extend(s.body_rate_rad_s.to_array()),
168            Self::CgPosition => row.extend(sample.cg_enu_m.to_array()),
169            Self::HeightAboveGround => row.push(sample.height_above_ground_m),
170            Self::VerticalSpeed => row.push(sample.vertical_speed_m_s),
171            Self::Acceleration => row.extend(sample.acceleration_enu_m_s2.to_array()),
172            Self::Airspeed => row.push(sample.airspeed_m_s),
173            Self::Mach => row.push(sample.mach),
174            Self::AngleOfAttack => row.push(sample.angle_of_attack_rad),
175            Self::DynamicPressure => row.push(sample.dynamic_pressure_pa),
176            Self::AxialCoefficient => row.push(sample.axial_coefficient),
177            Self::Thrust => row.push(sample.thrust_n),
178            Self::Mass => row.push(sample.mass_kg),
179            Self::RecoveryDragArea => row.push(sample.recovery_drag_area_m2),
180        }
181    }
182}
183
184/// One accepted integration step of a flight, with its dense output.
185pub trait FlightStep {
186    /// The phase.
187    fn phase(&self) -> Phase;
188    /// When the step starts, s.
189    fn start_s(&self) -> f64;
190    /// When it ends, s.
191    fn end_s(&self) -> f64;
192    /// The state at `t` in `[start_s, end_s]`, from the dense output.
193    fn state_at(&self, t_s: f64) -> State;
194    /// The sample at `t` in `[start_s, end_s]`: the dense output's state and one evaluation of
195    /// the equations of motion there.
196    ///
197    /// # Errors
198    ///
199    /// Whatever the evaluation returns (it succeeded at the step's own stages).
200    fn sample(&self, t_s: f64) -> Result<Sample, SimError>;
201
202    /// The rocket's stability at `t` in `[start_s, end_s]`: its static margin and its margin at
203    /// the flight's Mach number there, both with the air along the axis, from the aerodynamic
204    /// model flying (the sustainer's after a powered separation) and the center of mass at `t`
205    /// ([`crate::metrics::stability`]).
206    ///
207    /// # Errors
208    ///
209    /// Whatever the evaluation or the aerodynamic model returns.
210    fn stability(&self, t_s: f64) -> Result<Stability, SimError>;
211}
212
213/// Keeps [`BodyStep`] the library's to implement.
214pub(crate) mod sealed {
215    /// Implemented only inside this crate, so a trait bounded by it can't be implemented outside.
216    pub trait Sealed {}
217}
218
219/// One accepted integration step of a separated body, flown as a point mass.
220///
221/// Sealed: only the library implements it, so a method added here breaks no outside code. An
222/// [`Observer`] receives it; nothing outside builds one.
223pub trait BodyStep: sealed::Sealed {
224    /// When the step starts, s since launch.
225    fn start_s(&self) -> f64;
226
227    /// When the step ends, s since launch.
228    fn end_s(&self) -> f64;
229
230    /// The body at `t_s`, inside the step, from the integrator's dense output.
231    ///
232    /// # Errors
233    ///
234    /// Whatever the atmosphere or the frame returns.
235    fn sample(&self, t_s: f64) -> Result<BodySample, SimError>;
236
237    /// Its acceleration in the launch frame at `t_s`, m/s²: the point mass's equation of motion
238    /// (`docs/physics/recovery.md`).
239    ///
240    /// # Errors
241    ///
242    /// As [`Self::sample`].
243    fn acceleration_enu_m_s2(&self, t_s: f64) -> Result<DVec3, SimError>;
244
245    /// Its specific force at `t_s`, m/s²: the force on it other than gravity over its mass, here
246    /// the drag of its open devices alone, `−½ ρ (C_D S) |v − w| (v − w) / m`, a point mass having
247    /// no thrust and no airframe drag (`docs/physics/recovery.md`). With nothing open it is zero.
248    /// Under its devices the mass times this is the opening force, as the stack's
249    /// [`crate::Sample::specific_force_enu_m_s2`] is.
250    ///
251    /// # Errors
252    ///
253    /// As [`Self::sample`].
254    fn specific_force_enu_m_s2(&self, t_s: f64) -> Result<DVec3, SimError>;
255}
256
257/// Watches a flight as it runs. Every method does nothing by default; `()` watches nothing.
258pub trait Observer {
259    /// Sees every accepted integration step, in order.
260    ///
261    /// # Errors
262    ///
263    /// An error stops the flight and is returned from it.
264    fn step(&mut self, step: &dyn FlightStep) -> Result<(), SimError> {
265        let _ = step;
266        Ok(())
267    }
268
269    /// Sees every flight event as it is recorded.
270    fn event(&mut self, event: &FlightEvent) {
271        let _ = event;
272    }
273
274    /// Sees every accepted integration step of a separated body's flight to the ground, in order,
275    /// the body numbered as [`crate::BodyFlight::body`] is.
276    ///
277    /// # Errors
278    ///
279    /// An error stops the flight and is returned from it.
280    fn body_step(&mut self, body: usize, step: &dyn BodyStep) -> Result<(), SimError> {
281        let _ = (body, step);
282        Ok(())
283    }
284}
285
286impl Observer for () {}
287
288/// An observer lent to a flight, so the caller keeps it.
289impl<T: Observer + ?Sized> Observer for &mut T {
290    fn step(&mut self, step: &dyn FlightStep) -> Result<(), SimError> {
291        (**self).step(step)
292    }
293
294    fn event(&mut self, event: &FlightEvent) {
295        (**self).event(event);
296    }
297
298    fn body_step(&mut self, body: usize, step: &dyn BodyStep) -> Result<(), SimError> {
299        (**self).body_step(body, step)
300    }
301}
302
303/// Two observers watch one flight: each sees every step and event, the first before the second.
304impl<A: Observer, B: Observer> Observer for (A, B) {
305    fn step(&mut self, step: &dyn FlightStep) -> Result<(), SimError> {
306        self.0.step(step)?;
307        self.1.step(step)
308    }
309
310    fn event(&mut self, event: &FlightEvent) {
311        self.0.event(event);
312        self.1.event(event);
313    }
314
315    fn body_step(&mut self, body: usize, step: &dyn BodyStep) -> Result<(), SimError> {
316        self.0.body_step(body, step)?;
317        self.1.body_step(body, step)
318    }
319}
320
321/// Records chosen channels, one row per sample.
322///
323/// - With an interval, a row at every multiple of `interval_s` after launch that falls within the
324///   flight, and a row at every event (unless the last row already has that time).
325/// - Without one, a row at the flight's first step's start and at every step's end; events end
326///   steps, so they are among the rows.
327///
328/// A recorder keeps one flight: [`Recorder::clear`] it before recording another. It serializes its
329/// settings and rows for inspection; it is built with [`Recorder::new`], not deserialized.
330#[derive(Debug, Clone, PartialEq, Serialize)]
331pub struct Recorder {
332    channels: Vec<Channel>,
333    interval_s: Option<f64>,
334    /// The next interval sample is at `next_index · interval_s`.
335    next_index: u64,
336    rows: Vec<Vec<f64>>,
337    samples: usize,
338    last_time_s: Option<f64>,
339}
340
341impl Recorder {
342    /// A recorder of `channels`, sampling every `interval_s` seconds (`None`: every step's end).
343    ///
344    /// # Errors
345    ///
346    /// [`SimError::Domain`] for an interval that isn't finite and positive;
347    /// [`SimError::Unsupported`] for a channel listed twice, which would give two columns one name.
348    pub fn new(channels: Vec<Channel>, interval_s: Option<f64>) -> Result<Self, SimError> {
349        if let Some(dt) = interval_s
350            && !(dt.is_finite() && dt > 0.0)
351        {
352            return Err(SimError::Domain {
353                what: "recorder interval",
354                value: dt,
355            });
356        }
357        if channels
358            .iter()
359            .enumerate()
360            .any(|(i, channel)| channels[..i].contains(channel))
361        {
362            return Err(SimError::Unsupported {
363                what: "a recorder channel listed twice",
364            });
365        }
366        Ok(Self {
367            channels,
368            interval_s,
369            next_index: 0,
370            rows: Vec::new(),
371            samples: 0,
372            last_time_s: None,
373        })
374    }
375
376    /// A recorder holding `rows` as if it had recorded them, for tests of what reads its rows.
377    #[cfg(test)]
378    pub(crate) fn with_rows(channels: Vec<Channel>, rows: Vec<Vec<f64>>) -> Self {
379        Self {
380            channels,
381            interval_s: None,
382            next_index: 0,
383            samples: rows.len(),
384            last_time_s: None,
385            rows,
386        }
387    }
388
389    /// Forgets the recorded rows, ready for another flight.
390    pub fn clear(&mut self) {
391        self.next_index = 0;
392        self.rows.clear();
393        self.samples = 0;
394        self.last_time_s = None;
395    }
396
397    /// The column names.
398    #[must_use]
399    pub fn columns(&self) -> Vec<String> {
400        self.channels.iter().flat_map(|c| c.columns()).collect()
401    }
402
403    /// The recorded rows.
404    #[must_use]
405    pub fn rows(&self) -> &[Vec<f64>] {
406        &self.rows
407    }
408
409    fn record(&mut self, sample: &Sample) {
410        let mut row = Vec::new();
411        for channel in &self.channels {
412            channel.push(sample, &mut row);
413        }
414        self.rows.push(row);
415        self.samples += 1;
416        self.last_time_s = Some(sample.time_s);
417    }
418}
419
420impl Observer for Recorder {
421    fn step(&mut self, step: &dyn FlightStep) -> Result<(), SimError> {
422        match self.interval_s {
423            None => {
424                if self.samples == 0 {
425                    self.record(&step.sample(step.start_s())?);
426                }
427                self.record(&step.sample(step.end_s())?);
428            }
429            Some(dt) => {
430                // A flight that starts after launch samples from its start.
431                let first = (step.start_s() / dt).ceil();
432                if (self.next_index as f64) < first {
433                    self.next_index = first as u64;
434                }
435                if !(dt.is_finite() && dt > 0.0) {
436                    return Err(SimError::Domain {
437                        what: "recorder interval",
438                        value: dt,
439                    });
440                }
441                loop {
442                    let t = self.next_index as f64 * dt;
443                    if t > step.end_s() {
444                        break;
445                    }
446                    let sample = step.sample(t)?;
447                    self.record(&sample);
448                    self.next_index += 1;
449                }
450            }
451        }
452        Ok(())
453    }
454
455    fn event(&mut self, event: &FlightEvent) {
456        if self.interval_s.is_some() && self.last_time_s != Some(event.sample.time_s) {
457            self.record(&event.sample);
458        }
459    }
460}