1use serde::{Deserialize, Serialize};
41
42use crate::log::FlightLog;
43use crate::readings::interval::{Interval, Shares};
44use crate::readings::{self, Provenance, Reading, Readings, Source, Withheld};
45use crate::smoother::{self, INTERVAL_Z, Options};
46
47pub const METHOD: &str = "shared liftoff";
49
50pub const OFFSET_SHARES: Shares = Shares {
54 low: -0.0526,
55 high: 0.0515,
56};
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
60#[serde(rename_all = "snake_case")]
61pub enum Flew {
62 OneAirframe,
64 Stages,
67}
68
69#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
71pub struct Placed {
72 pub zero_s: f64,
74 pub bound_s: f64,
76 pub interval_s: Option<Interval>,
78}
79
80#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
82pub struct Offset {
83 pub offset_s: f64,
85 pub bound_s: f64,
87 pub interval_s: Option<Interval>,
89}
90
91pub fn offset(first: &Placed, other: &Placed) -> Offset {
93 let offset_s = other.zero_s - first.zero_s;
94 let bound_s = first.bound_s + other.bound_s;
95 Offset {
96 offset_s,
97 bound_s,
98 interval_s: OFFSET_SHARES.interval(offset_s, bound_s),
99 }
100}
101
102#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
104#[serde(rename_all = "snake_case")]
105pub enum What {
106 ApogeeHeight,
108 ApogeeTime,
110 SmoothedApogee,
112 TopSpeed,
114 TopAcceleration,
116 Burnout,
118 FlightTime,
120 DrogueRate,
122 MainOpening,
124 MainRate,
126}
127
128#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
130#[serde(tag = "status", rename_all = "snake_case")]
131pub enum Cell {
132 Read(Given),
134 Withheld {
136 detail: String,
138 },
139}
140
141#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
143pub struct Given {
144 pub value: f64,
146 pub bound: Option<f64>,
149 pub interval: Option<Interval>,
152 pub is_floor: bool,
154 pub source: Option<Source>,
156 pub provenance: Option<Provenance>,
158}
159
160#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
162pub struct Row {
163 pub what: What,
165 pub cells: Vec<Cell>,
167 pub spread: Option<f64>,
170}
171
172#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
174pub struct SideBySide {
175 pub method: String,
177 pub flew: Flew,
179 pub placed: Vec<Reading<Placed>>,
181 pub offsets: Vec<Reading<Offset>>,
183 pub rows: Vec<Row>,
185}
186
187pub fn place(read: &Readings) -> Reading<Placed> {
189 match &read.liftoff {
190 Reading::Read(liftoff) => Reading::Read(Placed {
191 zero_s: liftoff.time_s,
192 bound_s: liftoff.bound_s,
193 interval_s: liftoff.interval_s,
194 }),
195 Reading::Withheld(withheld) => Reading::Withheld(withheld.clone()),
196 }
197}
198
199pub fn side_by_side(logs: &[&FlightLog], flew: Flew) -> SideBySide {
201 let reads: Vec<Readings> = logs.iter().map(|log| readings::read(log)).collect();
202 let pairs: Vec<(&FlightLog, &Readings)> = logs.iter().copied().zip(&reads).collect();
203 side_by_side_read(&pairs, flew)
204}
205
206pub fn side_by_side_read(logs: &[(&FlightLog, &Readings)], flew: Flew) -> SideBySide {
208 let reads: Vec<&Readings> = logs.iter().map(|(_, read)| *read).collect();
209 let placed: Vec<Reading<Placed>> = reads.iter().map(|read| place(read)).collect();
210 let offsets = placed
211 .iter()
212 .skip(1)
213 .map(|other| match (&placed[0], other) {
214 (Reading::Read(first), Reading::Read(other)) => Reading::Read(offset(first, other)),
215 (Reading::Withheld(withheld), _) | (_, Reading::Withheld(withheld)) => {
216 Reading::Withheld(withheld.clone())
217 }
218 })
219 .collect();
220 let smoothed: Vec<Cell> = logs
221 .iter()
222 .map(|(log, read)| smoothed_apogee(log, read))
223 .collect();
224 let mut rows = vec![
225 row(What::ApogeeHeight, &reads, |read| {
226 cell(&read.apogee, |a| Given {
227 value: a.height_m,
228 bound: Some(a.bound_m),
229 interval: a.height_interval_m,
230 is_floor: a.is_floor,
231 source: Some(a.source),
232 provenance: Some(a.provenance),
233 })
234 }),
235 row(What::ApogeeTime, &reads, |read| {
236 after_liftoff(read, &read.apogee, |a, liftoff_bound_s| {
237 a.time_after_liftoff_s.map(|value| Given {
238 value,
239 bound: Some(a.time_bound_s + liftoff_bound_s),
240 interval: None,
241 is_floor: a.is_floor,
242 source: Some(a.source),
243 provenance: Some(a.provenance),
244 })
245 })
246 }),
247 ];
248 rows.push(with_spread(What::SmoothedApogee, smoothed));
249 rows.extend([
250 row(What::TopSpeed, &reads, |read| {
251 cell(&read.max_speed, |s| Given {
252 value: s.speed_m_s,
253 bound: Some(s.bound_m_s),
254 interval: s.interval_m_s,
255 is_floor: s.is_floor,
256 source: Some(s.source),
257 provenance: Some(s.provenance),
258 })
259 }),
260 row(What::TopAcceleration, &reads, |read| {
261 cell(&read.max_acceleration, |a| Given {
262 value: a.acceleration_m_s2,
263 bound: Some(a.bound_m_s2),
264 interval: a.interval_m_s2,
265 is_floor: a.is_floor,
266 source: Some(a.source),
267 provenance: Some(a.provenance),
268 })
269 }),
270 row(What::Burnout, &reads, |read| {
271 after_liftoff(read, &read.burnout, |b, liftoff_bound_s| {
272 b.time_after_liftoff_s.map(|value| Given {
273 value,
274 bound: Some(b.bound_s + liftoff_bound_s),
275 interval: None,
276 is_floor: b.is_floor,
277 source: Some(b.source),
278 provenance: Some(b.provenance),
279 })
280 })
281 }),
282 row(What::FlightTime, &reads, |read| {
283 cell(&read.flight_time, |f| Given {
284 value: f.time_s,
285 bound: Some(f.bound_s),
286 interval: f.interval_s,
287 is_floor: false,
288 source: Some(f.source),
289 provenance: Some(f.provenance),
290 })
291 }),
292 row(What::DrogueRate, &reads, |read| {
293 cell(&read.drogue_descent, |d| Given {
294 value: d.rate_m_s,
295 bound: Some(d.bound_m_s),
296 interval: d.interval_m_s,
297 is_floor: false,
298 source: Some(d.source),
299 provenance: Some(d.provenance),
300 })
301 }),
302 row(What::MainOpening, &reads, |read| match &read.main_descent {
303 Reading::Withheld(withheld) => Cell::Withheld {
304 detail: withheld.detail.clone(),
305 },
306 Reading::Read(main) => match main.opening {
307 Some(opening) => Cell::Read(Given {
308 value: opening.height_m,
309 bound: None,
310 interval: None,
311 is_floor: false,
312 source: Some(main.source),
313 provenance: Some(main.provenance),
314 }),
315 None => Cell::Withheld {
316 detail: "the descent shows one canopy".to_owned(),
317 },
318 },
319 }),
320 row(What::MainRate, &reads, |read| {
321 cell(&read.main_descent, |m| Given {
322 value: m.rate_m_s,
323 bound: Some(m.bound_m_s),
324 interval: m.interval_m_s,
325 is_floor: false,
326 source: Some(m.source),
327 provenance: Some(m.provenance),
328 })
329 }),
330 ]);
331 if flew == Flew::Stages {
332 for row in &mut rows {
333 row.spread = None;
334 }
335 }
336 SideBySide {
337 method: METHOD.to_owned(),
338 flew,
339 placed,
340 offsets,
341 rows,
342 }
343}
344
345fn cell<T>(reading: &Reading<T>, given: impl FnOnce(&T) -> Given) -> Cell {
347 match reading {
348 Reading::Read(value) => Cell::Read(given(value)),
349 Reading::Withheld(Withheld { detail, .. }) => Cell::Withheld {
350 detail: detail.clone(),
351 },
352 }
353}
354
355fn after_liftoff<T>(
358 read: &Readings,
359 reading: &Reading<T>,
360 given: impl FnOnce(&T, f64) -> Option<Given>,
361) -> Cell {
362 let liftoff = match &read.liftoff {
363 Reading::Read(liftoff) => liftoff,
364 Reading::Withheld(Withheld { detail, .. }) => {
365 return Cell::Withheld {
366 detail: detail.clone(),
367 };
368 }
369 };
370 match reading {
371 Reading::Withheld(Withheld { detail, .. }) => Cell::Withheld {
372 detail: detail.clone(),
373 },
374 Reading::Read(value) => match given(value, liftoff.bound_s) {
375 Some(given) => Cell::Read(given),
376 None => Cell::Withheld {
377 detail: "liftoff is withheld".to_owned(),
378 },
379 },
380 }
381}
382
383fn smoothed_apogee(log: &FlightLog, read: &Readings) -> Cell {
385 let smoothed = match smoother::smooth_with(log, read, Options::default()) {
386 Ok(smoothed) => smoothed,
387 Err(withheld) => {
388 return Cell::Withheld {
389 detail: withheld.detail,
390 };
391 }
392 };
393 match smoothed.at(smoothed.apogee_time_s) {
394 Some(state) => {
395 let half = INTERVAL_Z * state.height_sd_m;
396 let is_floor = smoothed.apogee_is_floor;
399 Cell::Read(Given {
400 value: state.height_m,
401 bound: None,
402 interval: (!is_floor).then_some(Interval {
403 low: state.height_m - half,
404 high: state.height_m + half,
405 }),
406 is_floor,
407 source: None,
408 provenance: None,
409 })
410 }
411 None => Cell::Withheld {
412 detail: "the smoothed track holds no apogee".to_owned(),
413 },
414 }
415}
416
417fn row(what: What, reads: &[&Readings], cell: impl Fn(&Readings) -> Cell) -> Row {
419 with_spread(what, reads.iter().map(|read| cell(read)).collect())
420}
421
422fn with_spread(what: What, cells: Vec<Cell>) -> Row {
424 let spread = spread(&cells);
425 Row {
426 what,
427 cells,
428 spread,
429 }
430}
431
432fn spread(cells: &[Cell]) -> Option<f64> {
435 let values: Vec<f64> = cells
436 .iter()
437 .filter_map(|cell| match cell {
438 Cell::Read(given) if !given.is_floor => Some(given.value),
439 _ => None,
440 })
441 .collect();
442 if values.len() < 2 {
443 return None;
444 }
445 let least = values.iter().copied().fold(f64::INFINITY, f64::min);
446 let largest = values.iter().copied().fold(f64::NEG_INFINITY, f64::max);
447 Some(largest - least)
448}
449
450#[cfg(test)]
451mod tests {
452 use super::*;
453 use crate::log::{LogFormat, Stated};
454
455 fn flown(liftoff_s: f64, peak_m: f64) -> FlightLog {
458 let mut time_s = Vec::new();
459 let mut altitude_m = Vec::new();
460 for k in 0..6_000 {
461 let since = f64::from(k) * 0.05 - 10.0;
462 let t = since + liftoff_s;
463 let climb = 10.0;
464 let height = if since < 0.0 {
465 0.0
466 } else if since < climb {
467 peak_m * (1.0 - (1.0 - since / climb).powi(2))
468 } else {
469 (peak_m - 12.0 * (since - climb)).max(0.0)
470 };
471 time_s.push(t);
472 altitude_m.push(height);
473 }
474 FlightLog {
475 format: LogFormat::GenericTable,
476 logger: "invented".to_owned(),
477 serial_number: None,
478 firmware: None,
479 flight_number: None,
480 stated: Stated::default(),
481 time_s,
482 altitude_m,
483 vertical_speed_m_s: None,
484 temperature_k: None,
485 battery_v: None,
486 channels: Vec::new(),
487 events: Vec::new(),
488 notes: Vec::new(),
489 }
490 }
491
492 fn zero_of(side: &SideBySide, log: usize) -> f64 {
493 side.placed[log].value().unwrap().zero_s
494 }
495
496 #[test]
497 fn the_offset_is_the_clocks_difference_with_the_bounds_added() {
498 let (a, b) = (flown(3.0, 500.0), flown(103.0, 510.0));
499 let side = side_by_side(&[&a, &b], Flew::OneAirframe);
500 assert_eq!(side.method, "shared liftoff");
501 let offset = side.offsets[0].value().unwrap();
502 assert_eq!(offset.offset_s, zero_of(&side, 1) - zero_of(&side, 0));
503 assert!((offset.offset_s - 100.0).abs() <= offset.bound_s);
504 let (first, second) = (
505 side.placed[0].value().unwrap(),
506 side.placed[1].value().unwrap(),
507 );
508 assert_eq!(offset.bound_s, first.bound_s + second.bound_s);
509 let interval = offset.interval_s.unwrap();
510 assert_eq!(
511 interval.low,
512 offset.offset_s - OFFSET_SHARES.high * offset.bound_s
513 );
514 assert_eq!(
515 interval.high,
516 offset.offset_s - OFFSET_SHARES.low * offset.bound_s
517 );
518 }
519
520 #[test]
521 fn swapping_the_logs_turns_the_offset_round_and_keeps_every_spread() {
522 let (a, b) = (flown(3.0, 500.0), flown(103.0, 510.0));
523 let ab = side_by_side(&[&a, &b], Flew::OneAirframe);
524 let ba = side_by_side(&[&b, &a], Flew::OneAirframe);
525 let (ab_offset, ba_offset) = (
526 ab.offsets[0].value().unwrap(),
527 ba.offsets[0].value().unwrap(),
528 );
529 assert_eq!(ab_offset.offset_s, -ba_offset.offset_s);
530 assert_eq!(ab_offset.bound_s, ba_offset.bound_s);
531 for (x, y) in ab.rows.iter().zip(&ba.rows) {
532 assert_eq!(x.spread, y.spread, "{:?}", x.what);
533 }
534 }
535
536 #[test]
537 fn each_log_keeps_its_own_reading_and_the_spread_is_the_largest_less_the_least() {
538 let (a, b) = (flown(3.0, 500.0), flown(103.0, 520.0));
539 let side = side_by_side(&[&a, &b], Flew::OneAirframe);
540 let read_a = readings::read(&a);
541 let read_b = readings::read(&b);
542 let apogee = side
543 .rows
544 .iter()
545 .find(|row| row.what == What::ApogeeHeight)
546 .unwrap();
547 let height = |read: &Readings| read.apogee.value().unwrap().height_m;
548 assert_eq!(
549 apogee.cells,
550 [
551 cell(&read_a.apogee, |a| Given {
552 value: a.height_m,
553 bound: Some(a.bound_m),
554 interval: a.height_interval_m,
555 is_floor: a.is_floor,
556 source: Some(a.source),
557 provenance: Some(a.provenance),
558 }),
559 cell(&read_b.apogee, |a| Given {
560 value: a.height_m,
561 bound: Some(a.bound_m),
562 interval: a.height_interval_m,
563 is_floor: a.is_floor,
564 source: Some(a.source),
565 provenance: Some(a.provenance),
566 }),
567 ]
568 );
569 assert_eq!(apogee.spread, Some(height(&read_b) - height(&read_a)));
570 }
571
572 #[test]
573 fn nothing_in_the_result_is_a_mean() {
574 let (a, b) = (flown(3.0, 500.0), flown(103.0, 520.0));
575 let side = side_by_side(&[&a, &b], Flew::OneAirframe);
576 let json = serde_json::to_string(&side).unwrap();
577 for word in ["mean", "average", "fused", "weighted", "combined"] {
578 assert!(!json.contains(word), "{word} in {json}");
579 }
580 let apogee = side
582 .rows
583 .iter()
584 .find(|row| row.what == What::ApogeeHeight)
585 .unwrap();
586 let (Cell::Read(first), Cell::Read(second)) = (&apogee.cells[0], &apogee.cells[1]) else {
587 panic!("both logs read an apogee: {apogee:?}");
588 };
589 assert_ne!(first.value, second.value);
590 }
591
592 #[test]
593 fn stages_report_no_spread_because_their_readings_are_of_different_bodies() {
594 let (a, b) = (flown(3.0, 500.0), flown(103.0, 900.0));
595 let side = side_by_side(&[&a, &b], Flew::Stages);
596 assert!(side.rows.iter().all(|row| row.spread.is_none()));
597 assert!(side.offsets[0].value().is_some());
599 }
600
601 #[test]
602 fn a_log_with_no_liftoff_sits_on_no_timeline_and_says_why() {
603 let a = flown(3.0, 500.0);
604 let mut none = flown(103.0, 500.0);
605 none.time_s.truncate(2);
606 none.altitude_m.truncate(2);
607 let side = side_by_side(&[&a, &none], Flew::OneAirframe);
608 assert!(side.placed[0].value().is_some());
609 let reason = side.placed[1].reason().unwrap();
610 assert_eq!(side.offsets[0].reason(), Some(reason));
611 let turned = side_by_side(&[&none, &a], Flew::OneAirframe);
613 assert_eq!(turned.offsets[0].reason(), Some(reason));
614 let apogee_time = side
615 .rows
616 .iter()
617 .find(|row| row.what == What::ApogeeTime)
618 .unwrap();
619 assert!(matches!(apogee_time.cells[1], Cell::Withheld { .. }));
620 assert_eq!(apogee_time.spread, None);
621 }
622
623 #[test]
624 fn a_log_cut_on_the_climb_gives_floors_in_every_row_its_top_stands_for() {
625 let whole = flown(3.0, 500.0);
626 let mut cut = whole.clone();
627 let keep = cut.time_s.iter().position(|t| *t > 3.0 + 4.0).unwrap();
629 cut.time_s.truncate(keep);
630 cut.altitude_m.truncate(keep);
631 let read = readings::read(&cut);
632 assert!(
633 read.apogee.value().is_some_and(|a| a.is_floor),
634 "{:?}",
635 read.apogee
636 );
637 let side = side_by_side(&[&whole, &cut], Flew::OneAirframe);
638 for what in [What::ApogeeHeight, What::SmoothedApogee, What::TopSpeed] {
639 let row = side.rows.iter().find(|row| row.what == what).unwrap();
640 assert_eq!(row.spread, None, "{what:?}: {row:?}");
641 let Cell::Read(given) = &row.cells[1] else {
642 panic!("{what:?}: {row:?}");
643 };
644 assert!(given.is_floor, "{what:?}: {given:?}");
645 assert_eq!(given.interval, None, "{what:?}: {given:?}");
646 let Cell::Read(whole) = &row.cells[0] else {
648 panic!("{what:?}: {row:?}");
649 };
650 assert!(!whole.is_floor, "{what:?}: {whole:?}");
651 }
652 }
653
654 #[test]
655 fn a_floor_joins_no_spread() {
656 let given = |value, is_floor| {
657 Cell::Read(Given {
658 value,
659 bound: None,
660 interval: None,
661 is_floor,
662 source: None,
663 provenance: None,
664 })
665 };
666 assert_eq!(spread(&[given(1.0, false), given(4.0, false)]), Some(3.0));
667 assert_eq!(spread(&[given(1.0, true), given(4.0, false)]), None);
668 assert_eq!(
669 spread(&[given(1.0, false), given(9.0, true), given(4.0, false)]),
670 Some(3.0)
671 );
672 }
673}