1use serde::{Deserialize, Serialize};
62
63use crate::error::SimError;
64
65#[derive(Debug, Clone, PartialEq)]
67struct Samples {
68 times_s: Vec<f64>,
69 values: Vec<f64>,
70}
71
72impl Samples {
73 fn new(history: &'static str, times_s: Vec<f64>, values: Vec<f64>) -> Result<Self, SimError> {
76 let refuse = |why: &'static str| SimError::History { history, why };
77 if times_s.len() != values.len() {
78 return Err(refuse("it holds another number of values than of times"));
79 }
80 let (Some(&first), Some(_)) = (times_s.first(), values.first()) else {
81 return Err(refuse("it holds no sample"));
82 };
83 if !times_s.iter().chain(&values).all(|x| x.is_finite()) {
84 return Err(refuse("a time or a value is not a finite number"));
85 }
86 if times_s.windows(2).any(|pair| pair[1] <= pair[0]) {
87 return Err(refuse("its times don't rise from each sample to the next"));
88 }
89 if first > 0.0 {
90 return Err(refuse(
91 "its first sample comes after launch, so it doesn't cover the flight's start",
92 ));
93 }
94 Ok(Self { times_s, values })
95 }
96
97 fn at(&self, t_s: f64) -> f64 {
100 if t_s.is_nan() {
101 return f64::NAN;
102 }
103 let times = &self.times_s;
104 let after = times.partition_point(|&t| t <= t_s);
105 if after == 0 {
106 return self.values[0];
107 }
108 if after == times.len() {
109 return self.values[times.len() - 1];
110 }
111 let (t0, t1) = (times[after - 1], times[after]);
112 let (y0, y1) = (self.values[after - 1], self.values[after]);
113 y0 + (y1 - y0) * ((t_s - t0) / (t1 - t0))
115 }
116
117 fn corner(&self, index: usize) -> bool {
119 if index == 0 || index + 1 >= self.times_s.len() {
120 return true;
121 }
122 let slope = |i: usize| {
123 (self.values[i + 1] - self.values[i]) / (self.times_s[i + 1] - self.times_s[i])
124 };
125 slope(index - 1) != slope(index)
126 }
127
128 fn corners_s(&self) -> impl Iterator<Item = f64> + '_ {
130 (0..self.times_s.len())
131 .filter(|&index| self.corner(index))
132 .map(|index| self.times_s[index])
133 }
134
135 fn varies_within(&self, (a, b): (f64, f64)) -> bool {
137 let times = &self.times_s;
138 let first = times.partition_point(|&t| t <= a).saturating_sub(1);
140 let last = times.partition_point(|&t| t < b).min(times.len() - 1);
141 (first..last).any(|i| self.values[i + 1] != self.values[i])
142 }
143}
144
145#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
149#[serde(try_from = "ThrustHistoryData", into = "ThrustHistoryData")]
150pub struct ThrustHistory {
151 thrust: Samples,
152}
153
154impl ThrustHistory {
155 pub fn new(times_s: Vec<f64>, thrust_n: Vec<f64>) -> Result<Self, SimError> {
163 let thrust = Samples::new("thrust", times_s, thrust_n)?;
164 let refuse = |why: &'static str| SimError::History {
165 history: "thrust",
166 why,
167 };
168 if thrust.values.iter().any(|&f| f < 0.0) {
169 return Err(refuse("a thrust is negative"));
170 }
171 if thrust.values.last().is_some_and(|&f| f != 0.0) {
172 return Err(refuse(
173 "its last thrust isn't zero, so it would stop while the motor still pushed",
174 ));
175 }
176 Ok(Self { thrust })
177 }
178
179 #[must_use]
181 pub fn thrust_n(&self, t_s: f64) -> f64 {
182 self.thrust.at(t_s)
183 }
184
185 #[must_use]
187 pub fn times_s(&self) -> &[f64] {
188 &self.thrust.times_s
189 }
190}
191
192#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
196#[serde(try_from = "MassHistoryData", into = "MassHistoryData")]
197pub struct MassHistory {
198 mass: Samples,
199 cg: Samples,
200}
201
202impl MassHistory {
203 pub fn new(
211 times_s: Vec<f64>,
212 mass_kg: Vec<f64>,
213 cg_aft_of_nose_m: Vec<f64>,
214 ) -> Result<Self, SimError> {
215 let mass = Samples::new("mass", times_s.clone(), mass_kg)?;
216 let cg = Samples::new("mass", times_s, cg_aft_of_nose_m)?;
217 if mass.values.iter().any(|&m| m <= 0.0) {
218 return Err(SimError::History {
219 history: "mass",
220 why: "a mass isn't positive",
221 });
222 }
223 Ok(Self { mass, cg })
224 }
225
226 #[must_use]
228 pub fn mass_kg(&self, t_s: f64) -> f64 {
229 self.mass.at(t_s)
230 }
231
232 #[must_use]
234 pub fn cg_aft_of_nose_m(&self, t_s: f64) -> f64 {
235 self.cg.at(t_s)
236 }
237
238 #[must_use]
240 pub fn times_s(&self) -> &[f64] {
241 &self.mass.times_s
242 }
243
244 pub(crate) fn varies_within(&self, window: (f64, f64)) -> bool {
246 self.mass.varies_within(window) || self.cg.varies_within(window)
247 }
248}
249
250#[derive(Serialize, Deserialize)]
252#[serde(deny_unknown_fields)]
253struct ThrustHistoryData {
254 times_s: Vec<f64>,
255 thrust_n: Vec<f64>,
256}
257
258impl TryFrom<ThrustHistoryData> for ThrustHistory {
259 type Error = SimError;
260
261 fn try_from(data: ThrustHistoryData) -> Result<Self, SimError> {
262 Self::new(data.times_s, data.thrust_n)
263 }
264}
265
266impl From<ThrustHistory> for ThrustHistoryData {
267 fn from(history: ThrustHistory) -> Self {
268 Self {
269 times_s: history.thrust.times_s,
270 thrust_n: history.thrust.values,
271 }
272 }
273}
274
275#[derive(Serialize, Deserialize)]
277#[serde(deny_unknown_fields)]
278struct MassHistoryData {
279 times_s: Vec<f64>,
280 mass_kg: Vec<f64>,
281 cg_aft_of_nose_m: Vec<f64>,
282}
283
284impl TryFrom<MassHistoryData> for MassHistory {
285 type Error = SimError;
286
287 fn try_from(data: MassHistoryData) -> Result<Self, SimError> {
288 Self::new(data.times_s, data.mass_kg, data.cg_aft_of_nose_m)
289 }
290}
291
292impl From<MassHistory> for MassHistoryData {
293 fn from(history: MassHistory) -> Self {
294 Self {
295 times_s: history.mass.times_s,
296 mass_kg: history.mass.values,
297 cg_aft_of_nose_m: history.cg.values,
298 }
299 }
300}
301
302#[derive(Debug, Clone, Default, PartialEq)]
304pub(crate) struct Histories {
305 pub(crate) thrust: Option<ThrustHistory>,
306 pub(crate) nozzle_m: hpr_core::DVec3,
308 pub(crate) mass: Option<MassHistory>,
309}
310
311impl Histories {
312 pub(crate) fn corners_s(&self) -> Vec<f64> {
314 let mut times: Vec<f64> = self
315 .thrust
316 .iter()
317 .flat_map(|h| h.thrust.corners_s())
318 .chain(
319 self.mass
320 .iter()
321 .flat_map(|h| h.mass.corners_s().chain(h.cg.corners_s())),
322 )
323 .filter(|t| *t > 0.0)
324 .collect();
325 times.sort_by(f64::total_cmp);
326 times.dedup();
327 times
328 }
329}
330
331#[cfg(test)]
332mod tests {
333 use super::*;
334
335 fn refusal(error: SimError) -> (&'static str, &'static str) {
336 match error {
337 SimError::History { history, why } => (history, why),
338 other => panic!("not a history's refusal: {other}"),
339 }
340 }
341
342 #[test]
343 fn a_history_reads_the_line_between_samples_and_holds_its_ends() {
344 let h = ThrustHistory::new(vec![0.0, 0.5, 2.0], vec![10.0, 40.0, 0.0]).unwrap();
345 assert_eq!(h.thrust_n(-1.0), 10.0);
346 assert_eq!(h.thrust_n(0.0), 10.0);
347 assert_eq!(h.thrust_n(0.5), 40.0);
348 assert_eq!(h.thrust_n(2.0), 0.0);
349 assert_eq!(h.thrust_n(9.0), 0.0);
350 assert!((h.thrust_n(0.25) - 25.0).abs() < 1e-12);
352 assert!((h.thrust_n(1.25) - 20.0).abs() < 1e-12);
353 assert!(h.thrust_n(f64::NAN).is_nan());
354 }
355
356 #[test]
357 fn a_history_read_from_json_round_trips_and_is_checked_as_built() {
358 let thrust = ThrustHistory::new(vec![0.0, 0.5, 2.0], vec![10.0, 40.0, 0.0]).unwrap();
359 let text = serde_json::to_string(&thrust).unwrap();
360 assert_eq!(
361 text,
362 r#"{"times_s":[0.0,0.5,2.0],"thrust_n":[10.0,40.0,0.0]}"#
363 );
364 assert_eq!(
365 serde_json::from_str::<ThrustHistory>(&text).unwrap(),
366 thrust
367 );
368 let mass = MassHistory::new(vec![0.0, 1.0], vec![2.0, 1.5], vec![0.5, 0.45]).unwrap();
369 let text = serde_json::to_string(&mass).unwrap();
370 assert_eq!(
371 text,
372 r#"{"times_s":[0.0,1.0],"mass_kg":[2.0,1.5],"cg_aft_of_nose_m":[0.5,0.45]}"#
373 );
374 assert_eq!(serde_json::from_str::<MassHistory>(&text).unwrap(), mass);
375
376 let refused = |text: &str| {
378 serde_json::from_str::<ThrustHistory>(text)
379 .unwrap_err()
380 .to_string()
381 };
382 for (text, why) in [
383 (r#"{"times_s":[],"thrust_n":[]}"#, "it holds no sample"),
384 (
385 r#"{"times_s":[1.0,0.5],"thrust_n":[3.0,0.0]}"#,
386 "its times don't rise from each sample to the next",
387 ),
388 (
389 r#"{"times_s":[0.0,1.0],"thrust_n":[-5.0,0.0]}"#,
390 "a thrust is negative",
391 ),
392 (
393 r#"{"times_s":[0.0,1.0],"thrust_n":[5.0,3.0]}"#,
394 "its last thrust isn't zero",
395 ),
396 ] {
397 let message = refused(text);
398 assert!(message.contains(why), "{text}: {message}");
399 }
400 let mass_refused = serde_json::from_str::<MassHistory>(
401 r#"{"times_s":[0.0],"mass_kg":[1.0,1.0,1.0],"cg_aft_of_nose_m":[0.5]}"#,
402 )
403 .unwrap_err()
404 .to_string();
405 assert!(
406 mass_refused.contains("it holds another number of values than of times"),
407 "{mass_refused}"
408 );
409 assert!(
411 serde_json::from_str::<ThrustHistory>(r#"{"times_s":[0.0],"thrust_n":[0.0],"cg":[]}"#)
412 .is_err()
413 );
414 }
415
416 #[test]
417 fn corners_leave_out_samples_on_a_straight_line() {
418 let h = ThrustHistory::new(
419 vec![-0.1, 0.0, 1.0, 2.0, 3.0, 4.0],
420 vec![0.0, 0.0, 5.0, 10.0, 0.0, 0.0],
421 )
422 .unwrap();
423 let histories = Histories {
425 thrust: Some(h),
426 ..Histories::default()
427 };
428 assert_eq!(histories.corners_s(), vec![2.0, 3.0, 4.0]);
429 }
430
431 #[test]
432 fn a_mass_history_varies_only_where_its_samples_change() {
433 let h = MassHistory::new(
434 vec![0.0, 1.0, 2.0, 3.0],
435 vec![2.0, 1.5, 1.5, 1.5],
436 vec![0.5, 0.45, 0.45, 0.45],
437 )
438 .unwrap();
439 assert!(h.varies_within((0.2, 0.3)));
440 assert!(h.varies_within((0.9, 1.1)));
441 assert!(!h.varies_within((1.0, 2.5)));
442 assert!(!h.varies_within((2.5, 9.0)));
443 assert!((h.mass_kg(0.5) - 1.75).abs() < 1e-15);
444 assert!((h.cg_aft_of_nose_m(0.5) - 0.475).abs() < 1e-15);
445 }
446
447 #[test]
448 fn bad_samples_are_refused_with_why() {
449 let thrust = |t: Vec<f64>, f: Vec<f64>| refusal(ThrustHistory::new(t, f).unwrap_err());
450 assert_eq!(
451 thrust(vec![0.0, 1.0], vec![1.0]).1,
452 "it holds another number of values than of times"
453 );
454 assert_eq!(thrust(vec![], vec![]).1, "it holds no sample");
455 assert_eq!(
456 thrust(vec![0.0, f64::NAN], vec![1.0, 0.0]).1,
457 "a time or a value is not a finite number"
458 );
459 assert_eq!(
460 thrust(vec![0.0, 1.0, 1.0], vec![1.0, 1.0, 0.0]).1,
461 "its times don't rise from each sample to the next"
462 );
463 assert_eq!(
464 thrust(vec![0.1, 1.0], vec![1.0, 0.0]).1,
465 "its first sample comes after launch, so it doesn't cover the flight's start"
466 );
467 assert_eq!(
468 thrust(vec![0.0, 1.0], vec![-1.0, 0.0]).1,
469 "a thrust is negative"
470 );
471 assert_eq!(
472 thrust(vec![0.0, 1.0], vec![1.0, 0.5]),
473 (
474 "thrust",
475 "its last thrust isn't zero, so it would stop while the motor still pushed"
476 )
477 );
478 let mass =
479 refusal(MassHistory::new(vec![0.0, 1.0], vec![1.0, 0.0], vec![0.5, 0.5]).unwrap_err());
480 assert_eq!(mass, ("mass", "a mass isn't positive"));
481 }
482}