hpr_forensics/boost.rs
1//! Apogee predicted from the boost: a log cut after burnout, fitted, and flown on to apogee
2//! ([ADR-257][adr-257] §3; [ADR-321][adr-321], amended 2026-11-06).
3//!
4//! The cut must not read the flight after it. A test replaces every later value and time with
5//! noise and the prediction stays bit-identical. Two rules hold that by construction:
6//!
7//! - [`find_cut`] walks the height track forward and decides at each sample from that sample and
8//! the ones before it. A vertical speed is fitted by least squares over the last
9//! [`SPEED_WINDOW_S`] of samples, leaving out a sample the analyzer's Hampel rule calls bad: one
10//! bad reading of 12 to 100 m put in set A's flights moved a cut by 0.70 s at most (measured).
11//! Liftoff is where that line stands [`LIFTOFF_RISE_M`] above the pad, the line where it last
12//! stood still ([`STILL_M_S`]), or before that the first window's. The cut is at
13//! the first sample where the speed has stood below its top by [`DROP_SHARE`] of it, and by at
14//! least [`DROP_FLOOR_M_S`], for [`HOLD_S`], and is the lowest it has been over the last
15//! [`HOLD_S`]. After burnout gravity takes about 9.8 m/s off the vertical speed every second,
16//! drag more, so the speed keeps falling and the log keeps the coast's start. A barometer's
17//! reading can dip in the boost and catch up: on the public logs the falls that dips gave
18//! recovered within the hold (measured once), and on the synthetic dips a fall that can outlast
19//! it (likely the fall back from a catch-up's overshoot, not traced) had begun to rise again
20//! while the motor burned.
21//! - Everything after that reads the log cut there: its readings, the fit's observations and so
22//! the fit. The log's own clock is cut at the cut's sample, by position, so a time it logs later
23//! can't enter. A channel on a clock of its own is cut at its first time past the cut or out of
24//! order: a sample it stamps in order at or before the cut is read wherever the file puts it,
25//! as nothing else says when it was logged.
26//!
27//! The finder refuses the tracks the analyzer distrusts in the boost: a GNSS receiver's, and a
28//! barometer's once its speed reaches [`readings::TRANSONIC_SPEED_M_S`] (Mach 0.8 in the coldest
29//! air), where the port may read the transonic flow. Without that rule, and with an earlier rule's 1 s
30//! hold in the cut, the fitted top speed was over 1.1 times the true one on 57 of set A's first 200
31//! synthetic flights, the barometer's jump near Mach 1 read as the top, so the cut's place followed
32//! the jump rather than burnout (a sweep run once). So a flight whose fitted climb speed reaches
33//! 227.7 m/s gets no prediction from its barometer: on that set the slowest refused had a true top
34//! of 221 m/s and the fastest cut a true 233 m/s, its fitted speed under the limit (measured
35//! once). An accelerometer's cut isn't built.
36//!
37//! A motor whose thrust falls below the rocket's weight and drag well before it burns out, as a
38//! long tail-off does, slows the climb by the fall the cut needs while still burning, and is cut
39//! before its burnout; the cut is checked only on the synthetic flights' motors.
40//!
41//! The analyzer's own burnout reading isn't used: its spike filter, its burnout mean and its
42//! noise span are centered windows, and [`readings::read`] takes the whole log at once.
43//!
44//! How far to trust it: the cut and the fit are tested for not reading past the cut; how close
45//! the predicted apogee comes to a logged one is [not measured yet][plan], on real flights or
46//! synthetic ones.
47//!
48//! [plan]: https://hpr.fusionspace.co/decisions-and-roadmap.html#m7-3d
49//!
50//! [adr-257]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0257-the-2026-10-13-review-calibrated-intervals-and-the-post-flight-comparison.md
51//! [adr-321]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0321-m7-3c4-in-three-the-track-as-a-receiver-reads-it.md
52
53use std::borrow::Cow;
54use std::collections::VecDeque;
55
56use hpr_flightdata::log::FlightLog;
57use hpr_flightdata::readings;
58use serde::{Deserialize, Serialize};
59
60use crate::fit::{self, Fit, Forward, Noise, Observations, Stated};
61use crate::residuals::HeightKind;
62
63/// How far the window's fitted line must stand above the pad's for liftoff, m: past the
64/// largest excursion of a raw height from the track's first on the pad, 6.8 m over sets A and B's
65/// first 200 synthetic flights each (their barometers' logs, measured once), while a hobby rocket
66/// climbs it in about a second or less. HPR Sim's choice.
67pub const LIFTOFF_RISE_M: f64 = 10.0;
68
69/// The fitted speed under which the line stands still, m/s, either way: where it does, the pad is
70/// re-read there, and a liftoff, a top speed and a fall read before it are forgotten. A run of bad
71/// samples on the pad or a step there that stays can lift the line past [`LIFTOFF_RISE_M`] and
72/// read a speed faster than the flight's own top; the line stands still again once they leave the
73/// window, or at the step's new level ([#1362][i1362]). Bad samples close enough to ignition
74/// leave no still window between them and the climb, and can then still be the top and cut early:
75/// a known gap ([#1441][i1441]), from 0.2 s before ignition on the test's flights, not bounded on
76/// others. A dip in the boost can stand the line still
77/// too, and the pad is then read again in the burn: the dip test still finds every cut after
78/// burnout. On sets A and B's first 200 synthetic
79/// flights' barometer logs with a cut (measured once, not committed), 98.8% and 98.4% of the pad's
80/// windows read under it, no stretch of the pad between windows that did lasted over 0.25 s, and
81/// no speed from liftoff to the cut read under 17.6 m/s. A climb whose fitted top speed is under about 22 m/s
82/// (this speed, the [`DROP_FLOOR_M_S`] fall and [`HOLD_S`] of gravity's 7.4 m/s), or a little more
83/// where drag slows it too, reaches this speed before its cut and is refused as never lifting off
84/// ([`NoCut::NeverLifted`]); the walk before this rule cut such slow climbs. HPR Sim's choice.
85///
86/// [i1362]: https://github.com/nrdptel/fusionspace-eridanus/issues/1362
87/// [i1441]: https://github.com/nrdptel/fusionspace-eridanus/issues/1441
88pub const STILL_M_S: f64 = 5.0;
89
90/// The span of the trailing window the vertical speed is fitted over, s: a straight line by
91/// least squares through the samples in it. HPR Sim's choice: long enough to average a
92/// barometer's noise over about 10 samples at 20 Hz, short against a boost of a few seconds.
93pub const SPEED_WINDOW_S: f64 = 0.5;
94
95/// The share of its top the fitted speed must fall below that top for the cut. HPR Sim's choice:
96/// 10%, a margin over the window's noise on a fast flight's speed, as a barometer's noise in height
97/// grows with altitude. Unmeasured: on set A's first 200 synthetic flights the cut's test passes on
98/// [`DROP_FLOOR_M_S`] alone.
99pub const DROP_SHARE: f64 = 0.1;
100
101/// The least fall below the top speed for the cut, m/s: about a second of gravity alone, so a
102/// slow flight's noise doesn't cut it during the boost. HPR Sim's choice.
103pub const DROP_FLOOR_M_S: f64 = 10.0;
104
105/// How long the fall must hold before the cut, s, and the span its speed must be the lowest of:
106/// a barometer's fitted speed can fall by [`DROP_FLOOR_M_S`] and more during the boost and
107/// recover. On the public flights' logs, the longest such fall inside a burn lasted 0.48 s from
108/// its first sample to the one it recovered at, and the deepest went 63.2 m/s below its top (Lince
109/// and Juno III, measured once in a run not committed); after burnout gravity and drag keep the speed falling. HPR Sim's
110/// choice: about half again the longest, 0.75 s. On set A's first 200 synthetic flights the cuts
111/// came 1.08 s to 2.30 s after burnout, 0.33 s to 1.48 s before this rule.
112pub const HOLD_S: f64 = 0.75;
113
114/// How long the fitted flight is flown to find its apogee, s: past any hobby rocket's climb.
115pub const APOGEE_HORIZON_S: f64 = 300.0;
116
117/// Where the boost's log is cut.
118#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
119pub struct Cut {
120 /// The index of the last sample the finder read, the cut's: in the log's own clock's samples,
121 /// or, on a log of channels alone, in its track's channel up to its first time out of order.
122 pub index: usize,
123 /// That sample's time on the log's clock, s. The log is kept up to it, inclusive.
124 pub time_s: f64,
125 /// The end of the window whose fitted speed was the top, s.
126 pub top_speed_s: f64,
127 /// That top speed, m/s.
128 pub top_speed_m_s: f64,
129}
130
131/// The slope and intercept of a straight line fitted by least squares through `points`, on times
132/// taken from the first point's; `None` where its times don't spread.
133fn line(points: &[(f64, f64)]) -> Option<(f64, f64)> {
134 let t0 = points.first()?.0;
135 #[expect(
136 clippy::cast_precision_loss,
137 reason = "a window of a second's samples, far below 2^53"
138 )]
139 let n = points.len() as f64;
140 let (st, sh) = points
141 .iter()
142 .fold((0.0, 0.0), |(st, sh), &(t, h)| (st + (t - t0), sh + h));
143 let (mt, mh) = (st / n, sh / n);
144 let (num, den) = points.iter().fold((0.0, 0.0), |(num, den), &(t, h)| {
145 let dt = t - t0 - mt;
146 (num + dt * (h - mh), den + dt * dt)
147 });
148 let slope = (den > 0.0).then(|| num / den)?;
149 let intercept = mh - slope * mt;
150 (slope.is_finite() && intercept.is_finite()).then_some((slope, intercept))
151}
152
153/// The vertical speed over `window`, m/s, and the height the line gives at its last time, m: a
154/// straight line fitted by least squares without each sample whose residual from a first, robust
155/// line (the median of the slopes between samples half the window's samples apart) lies further
156/// than [`readings::SPIKE_THRESHOLD`] robust standard deviations (1.4826 times the residuals'
157/// median absolute deviation) from their median, the analyzer's Hampel rule (Pearson et al.,
158/// EUSIPCO 2015, §2). One bad sample that far out, a pulse at the port or a corrupt reading, is so
159/// left out of every window that holds it; at 20 Hz three side by side can carry the first line
160/// with them (the cut's test measures what that does), and at 8 to 10 Hz, with 5 or 6 samples to
161/// a window, two may (untested). Where most residuals are 0, as on a quantized pad, only the samples on the line
162/// are kept.
163/// `None` where fewer than [`readings::SPEED_MIN_SAMPLES`] are kept or the times don't spread.
164fn robust_line(window: &VecDeque<(f64, f64)>, scratch: &mut Scratch) -> Option<(f64, f64)> {
165 let Scratch {
166 points,
167 values,
168 residuals,
169 kept,
170 } = scratch;
171 points.clear();
172 points.extend(window.iter().copied());
173 let t0 = points.first()?.0;
174 // The first line, robust to one bad sample: the median of the slopes between samples half the
175 // window apart, each sample in at most two of them, and the median of the heights' offsets.
176 let apart = (points.len() / 2).max(1);
177 values.clear();
178 values.extend(
179 points
180 .iter()
181 .zip(points.iter().skip(apart))
182 .filter(|(a, b)| b.0 > a.0)
183 .map(|(a, b)| (b.1 - a.1) / (b.0 - a.0)),
184 );
185 let slope = median_of(values);
186 values.clear();
187 values.extend(points.iter().map(|&(t, h)| h - slope * (t - t0)));
188 let intercept = median_of(values);
189 if !slope.is_finite() || !intercept.is_finite() {
190 return None;
191 }
192 residuals.clear();
193 residuals.extend(
194 points
195 .iter()
196 .map(|&(t, h)| h - (intercept + slope * (t - t0))),
197 );
198 values.clear();
199 values.extend(residuals.iter().copied());
200 let center = median_of(values);
201 values.clear();
202 values.extend(residuals.iter().map(|r| (r - center).abs()));
203 let spread = 1.4826 * median_of(values);
204 let limit = readings::SPIKE_THRESHOLD * spread;
205 kept.clear();
206 kept.extend(
207 points
208 .iter()
209 .zip(residuals.iter())
210 .filter(|&(_, r)| (r - center).abs() <= limit)
211 .map(|(&point, _)| point),
212 );
213 if kept.len() < readings::SPEED_MIN_SAMPLES {
214 return None;
215 }
216 let (slope, intercept) = line(kept)?;
217 let last_s = kept.last()?.0 - kept.first()?.0;
218 Some((slope, intercept + slope * last_s))
219}
220
221/// The buffers [`robust_line`] fills at each sample, kept from one sample to the next so a walk
222/// allocates them once rather than seven times a sample.
223#[derive(Default)]
224struct Scratch {
225 points: Vec<(f64, f64)>,
226 values: Vec<f64>,
227 residuals: Vec<f64>,
228 kept: Vec<(f64, f64)>,
229}
230
231/// `log` with each channel kept up to its first time that doesn't follow the one before it: a
232/// channel-only log's track is refused whole when any of its times runs back, so a time logged
233/// after the cut would decide whether there is one. The log's own clock is left whole; the finder
234/// passes over its times out of order one by one.
235fn in_order(log: &FlightLog) -> FlightLog {
236 let mut ordered = log.clone();
237 for channel in &mut ordered.channels {
238 let kept = in_order_count(&channel.time_s, f64::INFINITY);
239 channel.time_s.truncate(kept);
240 channel.values.truncate(kept);
241 }
242 ordered
243}
244
245/// How many of `times` to keep: up to the last time that follows the one before it and isn't
246/// past `cut_s`, before the first that is past it or doesn't follow. A time not a number between
247/// two kept ones is kept where it stands, as a gap in the clock; one after the last kept isn't.
248fn in_order_count(times: &[f64], cut_s: f64) -> usize {
249 let mut last_s = f64::NEG_INFINITY;
250 let mut kept = 0;
251 for (index, &t) in times.iter().enumerate() {
252 if t.is_nan() {
253 continue;
254 }
255 if t <= last_s || t > cut_s {
256 break;
257 }
258 last_s = t;
259 kept = index + 1;
260 }
261 kept
262}
263
264/// Where the boost's log is cut, decided at each sample of the height track from it and the ones
265/// before it (the module's rules); `None` where the log holds no height track, its track is a GNSS
266/// receiver's, any [`SPEED_WINDOW_S`] of it holds more samples than the analyzer's fastest rate
267/// allows ([`readings::MIN_INTERVAL_S`]), it never lifts off or climbs too slowly ([`STILL_M_S`]), it never holds
268/// [`readings::SPEED_MIN_SAMPLES`] in a [`SPEED_WINDOW_S`] window (a log slower than 8 Hz, or one
269/// whose samples can't be read), its
270/// fitted speed reaches
271/// [`readings::TRANSONIC_SPEED_M_S`] before the cut, or it never slows by [`DROP_SHARE`] of its
272/// top speed and [`DROP_FLOOR_M_S`] for [`HOLD_S`], at a speed the lowest of the last [`HOLD_S`].
273/// The cut stands where the window's line is more than [`LIFTOFF_RISE_M`] above the pad's:
274/// three bad samples side by side on the pad can lift the line past that for a sample, and the
275/// speed then falls back as it does at burnout. The pad is read again wherever the line stands
276/// still ([`STILL_M_S`]), dropping the top speed and fall read before, so a pad spike faster than
277/// the flight's own top, or a step up on the pad that stays, doesn't stay the top
278/// ([#1362][i1362]), unless it comes too close to ignition for the line to stand still between
279/// it and the climb ([#1441][i1441]).
280///
281/// A GNSS receiver's altitude in the boost can drop out at ignition and burnout and lag the
282/// climb, by up to 440 m in one flight a flyer reports, while its fix reads valid
283/// ([GNSS in boost][gnss]): on set A's first 60 synthetic flights such tracks were cut up to 11 s
284/// after burnout or not at all (a sweep run once, with an earlier rule's 1 s hold in the cut). A staged
285/// flight is cut at the first burnout whose coast lasts long enough for that fall; untested on
286/// one.
287///
288/// [gnss]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/research/gnss-in-boost.md
289/// [i1362]: https://github.com/nrdptel/fusionspace-eridanus/issues/1362
290/// [i1441]: https://github.com/nrdptel/fusionspace-eridanus/issues/1441
291#[must_use]
292pub fn find_cut(log: &FlightLog) -> Option<Cut> {
293 try_cut(log).ok()
294}
295
296/// Why [`find_cut`] finds no cut in a log, in the order it decides.
297#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
298pub enum NoCut {
299 /// The log holds no height track.
300 NoTrack,
301 /// Its track is a GNSS receiver's.
302 Gnss,
303 /// A [`SPEED_WINDOW_S`] of it holds more samples than the analyzer's fastest rate allows.
304 TooFast,
305 /// No [`SPEED_WINDOW_S`] of it holds [`readings::SPEED_MIN_SAMPLES`] whose time and height are
306 /// numbers, in order: a log slower than 8 Hz, or a track whose samples can't be read.
307 TooSparse,
308 /// Its fitted line never stands [`LIFTOFF_RISE_M`] above the pad's, where it last stood still
309 /// ([`STILL_M_S`]), or stands still again before any cut, which drops the liftoff: a climb
310 /// whose top speed is under about 22 m/s does, and is refused here.
311 NeverLifted,
312 /// Its fitted speed reached [`readings::TRANSONIC_SPEED_M_S`] before any cut.
313 Transonic {
314 /// The end of the window that reached it, s on the log's clock.
315 time_s: f64,
316 /// That window's fitted speed, m/s.
317 speed_m_s: f64,
318 },
319 /// Its speed never fell by [`DROP_SHARE`] of its top and [`DROP_FLOOR_M_S`] for [`HOLD_S`], at
320 /// a speed the lowest of the last [`HOLD_S`].
321 NeverSlowed,
322}
323
324/// [`find_cut`]'s cut, or why there is none.
325///
326/// # Errors
327///
328/// [`NoCut`]: the first of the finder's refusals the log meets.
329pub fn try_cut(log: &FlightLog) -> Result<Cut, NoCut> {
330 walk(log, HOLD_S, &mut |_, _, _| {})
331}
332
333/// [`try_cut`]'s walk, with the fall held for `hold_s` before the cut, telling `fell` of each fall
334/// that doesn't reach the cut: the time the fall first held, the first time it no longer did
335/// (infinite for one still holding where the walk ends without a cut), and how far it went below
336/// the top, m/s.
337fn walk(log: &FlightLog, hold_s: f64, fell: &mut dyn FnMut(f64, f64, f64)) -> Result<Cut, NoCut> {
338 // On a log with its own clock the track is that clock's: its channels are never read here.
339 let ordered = if log.time_s.is_empty() {
340 Cow::Owned(in_order(log))
341 } else {
342 Cow::Borrowed(log)
343 };
344 if readings::height_track_source(&ordered).ok_or(NoCut::NoTrack)? == readings::Source::Gnss {
345 return Err(NoCut::Gnss);
346 }
347 let (times, heights) = readings::height_track(&ordered).ok_or(NoCut::NoTrack)?;
348 let most = most_in(SPEED_WINDOW_S);
349 let mut last_s = f64::NEG_INFINITY;
350 let mut window: VecDeque<(f64, f64)> = VecDeque::new();
351 let mut pad_m: Option<f64> = None;
352 let mut lifted = false;
353 let mut top: Option<(f64, f64)> = None;
354 // Since when, and how deep, the speed has stood below its top by the fall the cut needs.
355 let mut falling: Option<(f64, f64)> = None;
356 // The speeds of the last `hold_s` since liftoff, to tell a fall still going from one settled.
357 let mut recent: VecDeque<(f64, f64)> = VecDeque::new();
358 let mut full = false;
359 let mut scratch = Scratch::default();
360 for (index, (&t, &h)) in times.iter().zip(&heights).enumerate() {
361 // A sample out of order or not a number is passed over, as it is read.
362 if !t.is_finite() || !h.is_finite() || t <= last_s {
363 continue;
364 }
365 last_s = t;
366 window.push_back((t, h));
367 while window.front().is_some_and(|&(s, _)| s < t - SPEED_WINDOW_S) {
368 window.pop_front();
369 }
370 // Faster than the analyzer reads a log: refused, which also bounds each sample's work.
371 if window.len() > most {
372 return Err(NoCut::TooFast);
373 }
374 if window.len() < readings::SPEED_MIN_SAMPLES {
375 continue;
376 }
377 full = true;
378 let Some((speed, level)) = robust_line(&window, &mut scratch) else {
379 continue;
380 };
381 // The pad is where the line last stood still: bad samples on it or a step that stays lift
382 // the line and read a speed, but it stands still again after them, unless they come too
383 // close to ignition for that (#1441).
384 if speed.abs() < STILL_M_S {
385 pad_m = Some(level);
386 if lifted {
387 if let Some((since, deepest)) = falling.take() {
388 fell(since, t, deepest);
389 }
390 lifted = false;
391 top = None;
392 recent.clear();
393 }
394 }
395 // Liftoff where the window's line, refitted without its outliers, stands high enough
396 // above the pad: one bad sample on the pad doesn't lift it.
397 let pad = *pad_m.get_or_insert(level);
398 let aloft = level - pad > LIFTOFF_RISE_M;
399 lifted = lifted || aloft;
400 if !lifted {
401 continue;
402 }
403 // The analyzer's transonic speed: a barometer's speed this fast may be the flow's.
404 if speed >= readings::TRANSONIC_SPEED_M_S {
405 if let Some((since, deepest)) = falling {
406 fell(since, f64::INFINITY, deepest);
407 }
408 return Err(NoCut::Transonic {
409 time_s: t,
410 speed_m_s: speed,
411 });
412 }
413 while recent.front().is_some_and(|&(s, _)| s < t - hold_s) {
414 recent.pop_front();
415 }
416 recent.push_back((t, speed));
417 // Whether this speed is the lowest of the last `hold_s`, the samples before this one; read
418 // only once the fall has held, so a walk with no hold to end it (the tests' `fell` walks,
419 // with an infinite hold and so every sample since liftoff kept) doesn't rescan the climb at
420 // every sample.
421 let lowest = |recent: &VecDeque<(f64, f64)>| {
422 recent
423 .iter()
424 .take(recent.len() - 1)
425 .all(|&(_, v)| speed <= v)
426 };
427 match top {
428 Some((best, at)) if best - speed >= (DROP_SHARE * best).max(DROP_FLOOR_M_S) => {
429 let (since, deepest) = falling.get_or_insert((t, 0.0));
430 *deepest = deepest.max(best - speed);
431 // Never on the pad: three bad samples side by side there can lift the line past
432 // the rise for a sample, and the speed's fall back after it holds as burnout's does.
433 if t - *since >= hold_s && lowest(&recent) && aloft {
434 return Ok(Cut {
435 index,
436 time_s: t,
437 top_speed_s: at,
438 top_speed_m_s: best,
439 });
440 }
441 }
442 // A fall that doesn't hold: a dip in the reading, not burnout.
443 Some((best, _)) if speed <= best => {
444 if let Some((since, deepest)) = falling.take() {
445 fell(since, t, deepest);
446 }
447 }
448 _ => {
449 if let Some((since, deepest)) = falling.take() {
450 fell(since, t, deepest);
451 }
452 top = Some((speed, t));
453 }
454 }
455 }
456 if let Some((since, deepest)) = falling {
457 fell(since, f64::INFINITY, deepest);
458 }
459 Err(match (full, lifted) {
460 (false, _) => NoCut::TooSparse,
461 (true, false) => NoCut::NeverLifted,
462 (true, true) => NoCut::NeverSlowed,
463 })
464}
465
466/// The most samples a trailing window of `span_s` holds on a log sampled no faster than the
467/// analyzer reads ([`readings::MIN_INTERVAL_S`], its clock a part in a thousand fast).
468fn most_in(span_s: f64) -> usize {
469 #[expect(
470 clippy::cast_possible_truncation,
471 clippy::cast_sign_loss,
472 reason = "a small positive count: 0.5 s over 2 ms is 250"
473 )]
474 let most = (span_s / (readings::MIN_INTERVAL_S * 0.999)).floor() as usize;
475 most + 1
476}
477
478/// The median of `values`, reordering them: the middle one, or the mean of the middle two, in
479/// `f64::total_cmp`'s order. Selection finds the same middle values a full sort would put there.
480fn median_of(values: &mut [f64]) -> f64 {
481 let count = values.len();
482 if count == 0 {
483 return f64::NAN;
484 }
485 let (lower, &mut upper, _) = values.select_nth_unstable_by(count / 2, f64::total_cmp);
486 if count % 2 == 1 {
487 return upper;
488 }
489 // The largest of those below the middle is the sorted order's one before it.
490 lower
491 .iter()
492 .copied()
493 .max_by(f64::total_cmp)
494 .map_or(upper, |below| (below + upper) / 2.0)
495}
496
497/// Whether a sample at `t` stays in a log cut at `cut_s`: at or before it, or with no time to
498/// place it, as a gap in the clock is kept where it stands.
499fn kept_at(t: f64, cut_s: f64) -> bool {
500 t <= cut_s || t.is_nan()
501}
502
503/// `log` with only its samples up to `cut_s`: its own clock's columns and each channel's samples
504/// up to their first time past `cut_s` or out of order, and its events at or before `cut_s` (the
505/// readings and the fit read none). What it says of itself is kept.
506#[must_use]
507pub fn truncated(log: &FlightLog, cut_s: f64) -> FlightLog {
508 truncated_at(log, in_order_count(&log.time_s, cut_s), cut_s)
509}
510
511/// `log` with the first `kept` samples of its own clock's columns, each channel's samples up to
512/// its first past `cut_s` or out of order, and its events at or before `cut_s`. Both clocks are
513/// cut by position, so a time logged later can't enter.
514fn truncated_at(log: &FlightLog, kept: usize, cut_s: f64) -> FlightLog {
515 let cut = |values: &Vec<f64>| values.iter().copied().take(kept).collect::<Vec<f64>>();
516 let mut boost = log.clone();
517 boost.time_s = cut(&log.time_s);
518 boost.altitude_m = cut(&log.altitude_m);
519 boost.vertical_speed_m_s = log.vertical_speed_m_s.as_ref().map(cut);
520 boost.temperature_k = log.temperature_k.as_ref().map(cut);
521 boost.battery_v = log.battery_v.as_ref().map(cut);
522 for channel in &mut boost.channels {
523 let kept = in_order_count(&channel.time_s, cut_s);
524 channel.time_s.truncate(kept);
525 channel.values.truncate(kept);
526 }
527 boost.events.retain(|event| kept_at(event.time_s, cut_s));
528 boost
529}
530
531/// Apogee predicted from the boost.
532#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
533pub struct Prediction {
534 /// Where the log was cut.
535 pub cut: Cut,
536 /// The fit of the log up to the cut.
537 pub fit: Fit,
538 /// The fitted flight's apogee, s after its start, on the simulation's clock: the fit's
539 /// `clock_offset_s` places it on the log's.
540 pub apogee_s: f64,
541 /// The fitted flight's apogee, m above the pad: the height climbed, not what a barometer reads
542 /// for it.
543 pub apogee_above_pad_m: f64,
544 /// The fitted flight's height at its apogee as the log's sensor reads it, m above the pad: a
545 /// barometer's reading of the day's pressure there, or the height climbed for a sensor of
546 /// height. What a log's own apogee is compared with.
547 pub apogee_reading_m: f64,
548}
549
550/// Why a log gives no prediction.
551#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
552pub enum Unpredicted {
553 /// The finder found no cut, and why.
554 NoCut(NoCut),
555 /// The log up to the cut holds too little to fit: no pad or height track read, a window from
556 /// liftoff to the cut that is empty or longer than 1,000 s, or no more bins of
557 /// [`fit::BIN_S`] with a sample, from a second before liftoff, than the fit has unknowns (11).
558 /// A log with no liftoff read stands its first sample for liftoff, so that alone doesn't
559 /// refuse it.
560 /// A log cut within 2 s of its liftoff can't hold 12, nor a later one logged from liftoff only.
561 NothingToFit(Cut),
562 /// The fit came back with what was stated: its residual more than [`fit::MISFIT_SHARE`] of the
563 /// spread of the heights it read (`misfit_share`), or a flight it couldn't fly.
564 NotFitted {
565 /// The cut.
566 cut: Cut,
567 /// The fit's residual as a share of the heights' spread, where it came to one.
568 misfit_share: Option<f64>,
569 },
570 /// The fitted flight reaches no apogee within [`APOGEE_HORIZON_S`], or can't be flown.
571 NoApogee(Cut),
572}
573
574/// What the prediction reads of `log`, and the log it read: the log [`truncated`] at the cut
575/// and `extra` samples of its track past it (none but in the test's probe).
576fn read_to_cut(log: &FlightLog, extra: usize) -> Result<(Cut, Observations), Unpredicted> {
577 let cut = try_cut(log).map_err(Unpredicted::NoCut)?;
578 let nothing = Unpredicted::NothingToFit(cut);
579 let to_s = match extra {
580 0 => cut.time_s,
581 _ => {
582 let (times, _) = readings::height_track(&in_order(log)).ok_or(nothing)?;
583 *times.get(cut.index + extra).ok_or(nothing)?
584 }
585 };
586 // On the log's own clock, the track the finder read, the cut is by position.
587 let boost = if log.time_s.is_empty() {
588 truncated(log, to_s)
589 } else {
590 truncated_at(log, cut.index + extra + 1, to_s)
591 };
592 let read = readings::read(&boost);
593 let kind = HeightKind::of(read.source.ok_or(nothing)?);
594 // The probe reads its extra sample into the fit, past the whole bins the prediction keeps to.
595 let observed =
596 fit::observations_until(&boost, &read, to_s.next_up(), kind, extra == 0).ok_or(nothing)?;
597 Ok((cut, observed))
598}
599
600/// Apogee predicted from `log` cut after burnout: the boost fitted by [`fit::fit`], each
601/// parameter held to what `stated` gives for the boost's observations, then flown on by `forward`
602/// to its apogee. The fit's own `converged` says whether it settled.
603///
604/// # Errors
605///
606/// [`Unpredicted`]: why there is no prediction, where the log has no cut, the boost says nothing
607/// to fit, the fit keeps to what was stated, or the fitted flight doesn't reach an apogee within
608/// [`APOGEE_HORIZON_S`].
609pub fn predict(
610 log: &FlightLog,
611 stated: impl FnOnce(&Observations) -> Stated,
612 noise: Noise,
613 forward: &mut dyn Forward,
614) -> Result<Prediction, Unpredicted> {
615 predict_reading(log, 0, stated, noise, forward)
616}
617
618fn predict_reading(
619 log: &FlightLog,
620 extra: usize,
621 stated: impl FnOnce(&Observations) -> Stated,
622 noise: Noise,
623 forward: &mut dyn Forward,
624) -> Result<Prediction, Unpredicted> {
625 let (cut, observed) = read_to_cut(log, extra)?;
626 let fit = fit::fit(Some(&observed), &stated(&observed), noise, forward);
627 if !fit.fitted {
628 return Err(Unpredicted::NotFitted {
629 cut,
630 misfit_share: fit.misfit_share,
631 });
632 }
633 let no_apogee = Unpredicted::NoApogee(cut);
634 let flown = forward
635 .fly(&fit.parameters, APOGEE_HORIZON_S)
636 .map_err(|_| no_apogee)?;
637 let (apogee_s, apogee_above_pad_m) = flown.top().ok_or(no_apogee)?;
638 let apogee_reading_m = flown.top_reading_m(observed.kind).ok_or(no_apogee)?;
639 Ok(Prediction {
640 cut,
641 fit,
642 apogee_s,
643 apogee_above_pad_m,
644 apogee_reading_m,
645 })
646}
647
648/// The exact sign-flip interval on the center of `differences`, at a coverage of at least
649/// `level`: the paired difference of two methods' errors on the same flights, where a bootstrap
650/// undercovers on a few ([ADR-257][adr-257] §3).
651///
652/// The sign-flip test of a center `μ` takes the `2ⁿ` ways of flipping the signs of `dᵢ − μ` as
653/// equally likely, as they are when each difference is drawn from a distribution symmetric about
654/// `μ` and independent. Inverted, it gives Hartigan's interval (J. A. Hartigan, "Using subsample values as typical
655/// values", *J. Am. Stat. Assoc.* 64, 1969, pp. 1303–1317, Theorem 1): the means of the `2ⁿ − 1`
656/// non-empty subsets of the differences cut the line into `2ⁿ` intervals, each holding the
657/// center with probability `2⁻ⁿ`. From the `k`-th smallest subset mean to the `k`-th largest
658/// holds it with probability `1 − 2k/2ⁿ`, for independent differences each symmetric about it, so
659/// `k` is the largest whole number with
660/// `2k/2ⁿ ≤ 1 − level`. Where `k` is 0, no pattern of signs is rare enough to reject anything:
661/// the interval is the whole line, `(−∞, ∞)`, as it is at 95% for 5 flights or fewer.
662///
663/// Returns `None` for no differences, more than 20 (a million subsets), a level not inside 0 to
664/// 1, or a difference that isn't a number.
665///
666/// [adr-257]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0257-the-2026-10-13-review-calibrated-intervals-and-the-post-flight-comparison.md
667#[must_use]
668pub fn sign_flip_interval(differences: &[f64], level: f64) -> Option<(f64, f64)> {
669 let n = differences.len();
670 if n == 0
671 || n > 20
672 || !(level > 0.0 && level < 1.0)
673 || differences.iter().any(|d| !d.is_finite())
674 {
675 return None;
676 }
677 let patterns = 1_u32 << n;
678 // The largest k with 2k ≤ (1 − level)·2ⁿ.
679 #[expect(
680 clippy::cast_possible_truncation,
681 clippy::cast_sign_loss,
682 reason = "a count below 2^20, rounded down from a positive product"
683 )]
684 let k = ((1.0 - level) * f64::from(patterns) / 2.0).floor() as usize;
685 if k == 0 {
686 return Some((f64::NEG_INFINITY, f64::INFINITY));
687 }
688 let mut means: Vec<f64> = (1..patterns)
689 .map(|subset| {
690 let (sum, count) = differences
691 .iter()
692 .enumerate()
693 .filter(|(i, _)| subset & (1 << i) != 0)
694 .fold((0.0, 0_u32), |(sum, count), (_, d)| (sum + d, count + 1));
695 sum / f64::from(count)
696 })
697 .collect();
698 means.sort_by(f64::total_cmp);
699 Some((means[k - 1], means[means.len() - k]))
700}
701
702/// The paired bootstrap's percentile interval on the mean of `differences`, at `level`: the
703/// paired difference of two methods' errors on the same flights, resampled by flight, as
704/// [ADR-257][adr-257] §3 asks for the private collection's flights.
705///
706/// Each of `resamples` resamples draws `n` of the `n` differences with replacement, each index
707/// equally likely, from a xoshiro256++ stream seeded with `seed` (`hpr_core::random`), and takes
708/// their mean. The interval runs from the resample means' `(1 − level)/2` quantile to their
709/// `(1 + level)/2` quantile, each the smallest mean at or below which that share of the means
710/// lies (B. Efron and R. J. Tibshirani, *An Introduction to the Bootstrap*, Chapman & Hall,
711/// 1993, §13.3, the percentile interval). Pairing keeps each flight's two errors together, so what
712/// the flights share cancels in the difference.
713///
714/// It is approximate: on a few flights it can cover less than `level` (Efron and Tibshirani,
715/// §13.5), which is why the public flights' report, on 7 flights at most, gives
716/// [`sign_flip_interval`] instead. Same differences, level, count and seed, same interval, bit for
717/// bit.
718///
719/// It keeps every resample's mean, 8 bytes each: 10,000 resamples take 80 kB. On `n` flights a
720/// resample of one flight `n` times comes `(1/n)ⁿ` of the time; where that is at least
721/// `(1 − level)/2` (3 flights or fewer at 95%) both ends are the smallest and largest difference,
722/// and the interval is only their range.
723///
724/// Returns `None` for no differences, no resamples, a level not inside 0 to 1, a difference that
725/// isn't finite, or an interval end that isn't finite (a mean overflowing in more than the
726/// tail's share of the resamples).
727///
728/// [adr-257]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0257-the-2026-10-13-review-calibrated-intervals-and-the-post-flight-comparison.md
729#[must_use]
730pub fn paired_bootstrap_interval(
731 differences: &[f64],
732 level: f64,
733 resamples: u32,
734 seed: u64,
735) -> Option<(f64, f64)> {
736 let n = differences.len();
737 if n == 0
738 || resamples == 0
739 || !(level > 0.0 && level < 1.0)
740 || differences.iter().any(|d| !d.is_finite())
741 {
742 return None;
743 }
744 let count = u64::try_from(n).ok()?;
745 // A draw below the largest multiple of n that fits is kept, so each index is exactly as
746 // likely as every other; the rest are drawn again.
747 let zone = u64::MAX - u64::MAX % count;
748 let mut rng = hpr_core::random::SeededRng::seed_from_u64(seed);
749 #[expect(
750 clippy::cast_precision_loss,
751 reason = "a count of flights, far below 2^53"
752 )]
753 let size = n as f64;
754 let mut means: Vec<f64> = (0..resamples)
755 .map(|_| {
756 let mut sum = 0.0;
757 for _ in 0..n {
758 let index = loop {
759 let draw = rng.next_u64();
760 if draw < zone {
761 break draw % count;
762 }
763 };
764 // The index is below n, a usize.
765 sum += differences[usize::try_from(index).unwrap_or(0)];
766 }
767 sum / size
768 })
769 .collect();
770 means.sort_by(f64::total_cmp);
771 let tail = (1.0 - level) / 2.0;
772 let at = |share: f64| means[percentile_rank(share, resamples) - 1];
773 let (low, high) = (at(tail), at(1.0 - tail));
774 (low.is_finite() && high.is_finite()).then_some((low, high))
775}
776
777/// The 1-based rank in `resamples` sorted values of the `share` quantile: the smallest `r` with
778/// `r ≥ share · resamples`, at least 1 and at most `resamples`. A product within `1e-9 ·
779/// resamples` of a whole number counts as that number, so `(1 − 0.95)/2` of 10,000 is rank 250,
780/// not 251.
781fn percentile_rank(share: f64, resamples: u32) -> usize {
782 let total = f64::from(resamples);
783 let product = share * total;
784 let rounded = product.round();
785 let rank = if (product - rounded).abs() <= 1e-9 * total {
786 rounded
787 } else {
788 product.ceil()
789 };
790 #[expect(
791 clippy::cast_possible_truncation,
792 clippy::cast_sign_loss,
793 reason = "a rank clamped to 1..=resamples, below 2^32"
794 )]
795 let rank = rank.clamp(1.0, total) as usize;
796 rank
797}
798
799#[cfg(test)]
800mod tests {
801 use std::collections::BTreeMap;
802
803 use super::*;
804 use crate::synthetic::designs::DesignFiles;
805 use crate::synthetic::fits::{Flown, stated_for, weighed_factor};
806 use crate::synthetic::logger::Profile;
807 use crate::synthetic::{Flight, Flyer, Set};
808
809 /// A draw far from anything a flight logs, in any column's unit: ±2,500.
810 fn draws() -> impl FnMut() -> f64 {
811 let mut state: u64 = 0x9E37_79B9_7F4A_7C15;
812 move || {
813 state = state
814 .wrapping_mul(6_364_136_223_846_793_005)
815 .wrapping_add(1_442_695_040_888_963_407);
816 #[expect(clippy::cast_precision_loss, reason = "a draw's top bits, to a float")]
817 let unit = (state >> 11) as f64 / (1_u64 << 53) as f64;
818 5_000.0 * (unit - 0.5)
819 }
820 }
821
822 /// `log` with every value after `cut_s` replaced by a draw, or with `nudge` moved by a
823 /// thousandth of one (±2.5 in its unit); with `clocks`, each clock's later times noise too.
824 /// On the log's own clock, cut by position, they fall around the cut, the first a millisecond
825 /// before it. A channel on a clock of its own is cut by its times, so its first
826 /// later time repeats the one before it, out of order, and the rest fall after the cut.
827 fn noisy_after(log: &FlightLog, cut_s: f64, clocks: bool, nudge: bool) -> FlightLog {
828 let mut draw = draws();
829 let value = |v: f64, draw: f64| if nudge { v + draw / 1_000.0 } else { draw };
830 let mut noisy = log.clone();
831 let later = |times: &[f64]| times.iter().position(|&t| t > cut_s);
832 let own = log.time_s.clone();
833 for column in [
834 Some(&mut noisy.altitude_m),
835 noisy.vertical_speed_m_s.as_mut(),
836 noisy.temperature_k.as_mut(),
837 noisy.battery_v.as_mut(),
838 ]
839 .into_iter()
840 .flatten()
841 {
842 for (t, v) in own.iter().zip(column.iter_mut()) {
843 if *t > cut_s {
844 *v = value(*v, draw());
845 }
846 }
847 }
848 if clocks && let Some(first) = later(&own) {
849 for t in &mut noisy.time_s[first..] {
850 *t = cut_s + draw() / 1_000.0;
851 }
852 noisy.time_s[first] = cut_s - 1e-3;
853 }
854 for channel in &mut noisy.channels {
855 let Some(first) = later(&channel.time_s) else {
856 continue;
857 };
858 for v in &mut channel.values[first..] {
859 *v = value(*v, draw());
860 }
861 if clocks {
862 for t in &mut channel.time_s[first..] {
863 *t = cut_s + 1e-3 + draw().abs() / 1_000.0;
864 }
865 if first > 0 {
866 channel.time_s[first] = channel.time_s[first - 1];
867 }
868 }
869 }
870 noisy
871 }
872
873 /// `log` without its own clock's columns, as a log of channels alone; `None` if it has no
874 /// pressure channel to keep its track.
875 fn channels_only(log: &FlightLog) -> Option<FlightLog> {
876 log.channels_of(hpr_flightdata::log::Quantity::Pressure)
877 .next()?;
878 let mut only = log.clone();
879 only.time_s.clear();
880 only.altitude_m.clear();
881 only.vertical_speed_m_s = None;
882 only.temperature_k = None;
883 only.battery_v = None;
884 Some(only)
885 }
886
887 /// The first of set A's first 60 flights with a cut that `pick` takes, as it takes it.
888 fn first_cut(flyer: &mut Flyer, pick: impl Fn(Flight) -> Option<Flight>) -> (u64, Flight) {
889 (0..60)
890 .find_map(|k| {
891 let flight = pick(flyer.flight(Set::A, k).ok()?)?;
892 find_cut(&flight.log).map(|_| (k, flight))
893 })
894 .expect("one of set A's first 60 flights of each kind has a cut")
895 }
896
897 /// Apogee predicted from a synthetic flight's log cut after burnout stays bit-identical
898 /// when every later value and time is noise; a probe that lets the prediction read a whole bin
899 /// past the cut, the values noise but the times kept, doesn't. Run on three of set A's flights:
900 /// the first with a cut; the first with a cut whose logger, like a TeleMetrum, writes channels
901 /// besides the track (pressure, an accelerometer and a GNSS receiver's fixes); and the first
902 /// with a pressure channel and a cut, its own clock's columns taken out so that the channel's
903 /// clock is the track's. The finder decides from the samples up to the cut: on the log cut
904 /// there it finds the same cut, and on the log cut one sample sooner none.
905 #[test]
906 fn the_prediction_from_the_boost_reads_nothing_past_its_cut() {
907 let files = DesignFiles::committed();
908 let mut flyer = Flyer::new(DesignFiles::committed());
909 let mut tables = BTreeMap::new();
910 let logs = [
911 first_cut(&mut flyer, Some),
912 first_cut(&mut flyer, |flight| {
913 (flight.draw.logger.profile == Profile::Altos).then_some(flight)
914 }),
915 first_cut(&mut flyer, |mut flight| {
916 flight.log = channels_only(&flight.log)?;
917 Some(flight)
918 }),
919 ];
920 assert!(logs[1].1.log.channels.len() >= 3, "the TeleMetrum-like log");
921 for (index, flight) in logs {
922 let weighed = weighed_factor(Set::A, index);
923 let mut predicted = |log: &FlightLog, extra: usize| {
924 let mut forward = Flown::new(&flight.draw, &files, weighed, &mut tables);
925 predict_reading(
926 log,
927 extra,
928 |observed| stated_for(Some(observed)),
929 Noise::FromResiduals,
930 &mut forward,
931 )
932 };
933 let clean = predicted(&flight.log, 0).expect("the flight's boost predicts an apogee");
934 let cut = clean.cut;
935 let read = readings::read(&flight.log);
936 let apogee_s = match &read.apogee {
937 readings::Reading::Read(apogee) => apogee.time_s,
938 readings::Reading::Withheld(_) => panic!("the synthetic log reads its apogee"),
939 };
940 assert!(cut.time_s < apogee_s, "flight {index}: {cut:?}");
941 assert_eq!(find_cut(&truncated(&flight.log, cut.time_s)), Some(cut));
942 let (times, _) = readings::height_track(&in_order(&flight.log)).expect("a track");
943 let sooner = times[..cut.index]
944 .iter()
945 .rev()
946 .copied()
947 .find(|t| t.is_finite())
948 .expect("samples before the cut");
949 assert_eq!(find_cut(&truncated(&flight.log, sooner)), None);
950 let noisy_log = noisy_after(&flight.log, cut.time_s, true, false);
951 assert_ne!(noisy_log, flight.log);
952 let noisy = predicted(&noisy_log, 0).expect("the noisy log predicts as well");
953 assert_eq!(noisy.cut, cut, "flight {index}");
954 assert_eq!(
955 noisy.apogee_above_pad_m.to_bits(),
956 clean.apogee_above_pad_m.to_bits(),
957 "flight {index}"
958 );
959 assert_eq!(noisy.apogee_s.to_bits(), clean.apogee_s.to_bits());
960 assert_eq!(
961 noisy.apogee_reading_m.to_bits(),
962 clean.apogee_reading_m.to_bits()
963 );
964 assert_eq!(
965 noisy.fit.parameters.to_array().map(f64::to_bits),
966 clean.fit.parameters.to_array().map(f64::to_bits)
967 );
968 // The probe: the track's samples up to two bins past the cut, so that a whole bin is
969 // read; with the values moved by noise of ±2.5 in each unit, the prediction sees it.
970 let bin = times[cut.index + 1..]
971 .iter()
972 .take_while(|&&t| t <= cut.time_s + 2.0 * fit::BIN_S)
973 .count();
974 let values_noisy = noisy_after(&flight.log, cut.time_s, false, true);
975 let probed = (
976 predicted(&flight.log, bin).expect("the probe predicts"),
977 predicted(&values_noisy, bin).expect("the probe predicts on noise"),
978 );
979 assert_ne!(
980 probed.0.apogee_above_pad_m.to_bits(),
981 probed.1.apogee_above_pad_m.to_bits(),
982 "flight {index}: the probe must see the noise"
983 );
984 }
985 }
986
987 /// Over set A's first 200 synthetic flights: no GNSS tracker's log is cut, nor any whose fitted
988 /// speed reaches the transonic speed; every other flight whose true top vertical speed stays
989 /// 10% below that speed is cut (the fitted speed can read above the true one by its noise and
990 /// the port's error). Every cut falls after the true peak of the vertical speed and after
991 /// burnout, before apogee, and within 2.83 s of burnout: the time the largest fall the cut
992 /// needs takes under gravity alone, plus a window. Each cut found on a log with one bad sample
993 /// put in, or two or three side by side, passes the same checks: 100 m or 15 m up halfway
994 /// through the burn, 30 m down at four fifths of it, 12 m up on the pad, or 15 m down at the
995 /// first. A cut the bad samples lose is refused for its speed. A GNSS log is refused as one, and
996 /// any other uncut log for its speed. Measured, not asserted: 51 cut,
997 /// 1.08 s to 2.30 s after burnout; 43 GNSS logs and 106 fast ones refused, the slowest of those
998 /// at 221.3 m/s. Of the 785 spiked logs of each run's length, 255 of flights that are cut: one
999 /// bad sample made or lost no cut and moved 8 by 0.70 s at most; two side by side, 9 by 0.70 s
1000 /// at most, none made or lost; three side by side moved 23 by 1.35 s at most and lost 40, their
1001 /// speed read past the transonic one (100 m up halfway through the burn, or 30 m down at four
1002 /// fifths). Measured once on the earlier rule, before a cut had to stand above the pad by
1003 /// [`LIFTOFF_RISE_M`]: three 12 m up on the pad gave 33 cuts before the speed's peak, 32 of them
1004 /// before ignition, 2.37 s to 7.85 s before burnout. A step halfway through the pad that stays,
1005 /// of 8, 12, 30, 60 or 100 m, is cut as the flight is or refused for its speed. Measured, not
1006 /// asserted: 51 cut and 106 refused for each step to 60 m, all 157 refused at 100 m; steps of 12
1007 /// to 60 m cut 142 before the peak before [`STILL_M_S`] ([#1362][i1362], measured once).
1008 ///
1009 /// Set B's first 200, run once before the [`HOLD_S`] rule, not in the test: 57 cut, 0.35 s to
1010 /// 1.55 s after burnout, 34 GNSS and 109 fast refused.
1011 ///
1012 /// [i1362]: https://github.com/nrdptel/fusionspace-eridanus/issues/1362
1013 #[test]
1014 fn the_cut_falls_just_after_the_true_burnout() {
1015 let latest_s = (DROP_SHARE * readings::TRANSONIC_SPEED_M_S).max(DROP_FLOOR_M_S)
1016 / hpr_core::gravity::STANDARD_GRAVITY_MPS2
1017 + SPEED_WINDOW_S;
1018 let mut flyer = Flyer::new(DesignFiles::committed());
1019 let mut cut_count = 0_usize;
1020 let (mut early, mut late) = (f64::INFINITY, 0.0_f64);
1021 #[derive(Default)]
1022 struct Spiked {
1023 logs: usize,
1024 moved: usize,
1025 made: usize,
1026 lost: usize,
1027 moved_most_s: f64,
1028 }
1029 let mut runs: [Spiked; 3] = Default::default();
1030 const STEPS_M: [f64; 5] = [8.0, 12.0, 30.0, 60.0, 100.0];
1031 // Of each step's logs, those cut and those refused as transonic.
1032 let mut steps = [(0_usize, 0_usize); STEPS_M.len()];
1033 for k in 0..200 {
1034 let flight = flyer.flight(Set::A, k).expect("set A's flights fly");
1035 let cut = find_cut(&flight.log);
1036 if flight.draw.logger.profile == Profile::GnssTracker {
1037 assert_eq!(try_cut(&flight.log), Err(NoCut::Gnss), "flight {k}");
1038 continue;
1039 }
1040 let peak = flight
1041 .truth
1042 .samples
1043 .iter()
1044 .max_by(|a, b| a.vertical_speed_m_s.total_cmp(&b.vertical_speed_m_s))
1045 .expect("the truth has samples");
1046 let pad_s = flight.draw.logger.pad_s;
1047 let events = &flight.truth.events;
1048 let check = |cut: &Cut, what: &str| {
1049 let after_burnout_s = cut.time_s - (pad_s + events.burnout_s);
1050 assert!(
1051 cut.time_s > pad_s + peak.time_s,
1052 "flight {k}{what}: cut before the speed's peak"
1053 );
1054 assert!(
1055 after_burnout_s > 0.0 && after_burnout_s <= latest_s,
1056 "flight {k}{what}: cut {after_burnout_s} s after burnout"
1057 );
1058 assert!(
1059 cut.time_s < pad_s + events.apogee_s,
1060 "flight {k}{what}: cut at or past apogee"
1061 );
1062 assert!(cut.top_speed_m_s < readings::TRANSONIC_SPEED_M_S);
1063 assert!(
1064 cut.top_speed_s > pad_s,
1065 "flight {k}{what}: top speed read before ignition"
1066 );
1067 };
1068 match &cut {
1069 Some(cut) => {
1070 cut_count += 1;
1071 let after = cut.time_s - (pad_s + events.burnout_s);
1072 early = early.min(after);
1073 late = late.max(after);
1074 check(cut, "");
1075 }
1076 None => {
1077 assert!(
1078 peak.vertical_speed_m_s >= 0.9 * readings::TRANSONIC_SPEED_M_S,
1079 "flight {k}, its top {} m/s, has no cut",
1080 peak.vertical_speed_m_s
1081 );
1082 assert!(
1083 matches!(try_cut(&flight.log), Err(NoCut::Transonic { speed_m_s, .. })
1084 if speed_m_s >= readings::TRANSONIC_SPEED_M_S),
1085 "flight {k}: refused, but not for its speed"
1086 );
1087 }
1088 }
1089 let burn_s = pad_s + events.burnout_s;
1090 for (at_s, by_m) in [
1091 (pad_s + 0.5 * events.burnout_s, 100.0),
1092 (pad_s + 0.5 * events.burnout_s, 15.0),
1093 (pad_s + 0.8 * events.burnout_s, -30.0),
1094 (0.5 * pad_s, 12.0),
1095 (f64::NEG_INFINITY, -15.0),
1096 ] {
1097 let Some(i) = flight.log.time_s.iter().position(|&t| t >= at_s) else {
1098 continue;
1099 };
1100 for run in 1..=3 {
1101 let mut spiked = flight.log.clone();
1102 let Some(bad) = spiked.altitude_m.get_mut(i..i + run) else {
1103 continue;
1104 };
1105 for h in bad {
1106 *h += by_m;
1107 }
1108 let what = format!(" with {by_m} m on {run} at {at_s} s (burnout {burn_s} s)");
1109 let spiked_found = find_cut(&spiked);
1110 if let Some(spiked_cut) = &spiked_found {
1111 check(spiked_cut, &what);
1112 }
1113 let tally = &mut runs[run - 1];
1114 tally.logs += 1;
1115 match (&cut, &spiked_found) {
1116 (Some(a), Some(b)) if a.time_s != b.time_s => {
1117 tally.moved += 1;
1118 tally.moved_most_s =
1119 tally.moved_most_s.max((a.time_s - b.time_s).abs());
1120 }
1121 (Some(_), None) => {
1122 assert!(
1123 matches!(try_cut(&spiked), Err(NoCut::Transonic { .. })),
1124 "flight {k}{what}: cut lost, but not for its speed"
1125 );
1126 tally.lost += 1;
1127 }
1128 (None, Some(_)) => tally.made += 1,
1129 _ => {}
1130 }
1131 }
1132 }
1133 // A step halfway through the pad that stays, every later sample raised.
1134 for (j, by_m) in STEPS_M.into_iter().enumerate() {
1135 let mut stepped = flight.log.clone();
1136 for (t, h) in stepped.time_s.iter().zip(&mut stepped.altitude_m) {
1137 if *t >= 0.5 * pad_s {
1138 *h += by_m;
1139 }
1140 }
1141 let what = format!(" with a {by_m} m step from {} s", 0.5 * pad_s);
1142 match try_cut(&stepped) {
1143 Ok(stepped_cut) => {
1144 check(&stepped_cut, &what);
1145 assert_eq!(
1146 cut.map(|c| c.index),
1147 Some(stepped_cut.index),
1148 "flight {k}{what}: not cut where its log is without the step"
1149 );
1150 steps[j].0 += 1;
1151 }
1152 Err(NoCut::Transonic { .. }) => steps[j].1 += 1,
1153 Err(why) => panic!("flight {k}{what}: refused, {why:?}"),
1154 }
1155 }
1156 }
1157 println!("set A: {cut_count} cut, {early:.2} s to {late:.2} s after burnout");
1158 for (run, tally) in runs.iter().enumerate() {
1159 println!(
1160 "{} bad side by side: of {} spiked logs {} moved, by {:.3} s at most, {} made, {} lost",
1161 run + 1,
1162 tally.logs,
1163 tally.moved,
1164 tally.moved_most_s,
1165 tally.made,
1166 tally.lost
1167 );
1168 }
1169 for (by_m, (cut, refused)) in STEPS_M.iter().zip(steps) {
1170 println!(
1171 "a {by_m} m step on the pad that stays: {cut} cut, {refused} refused as transonic"
1172 );
1173 }
1174 assert!(cut_count >= 51, "{cut_count} cut");
1175 }
1176
1177 /// A barometer's log every 0.05 s, on the pad until 3.0 s with 0.3 m of noise on every
1178 /// sample (uniform, its standard deviation 0.3 m), then a climb at net acceleration `climb`
1179 /// of the time since ignition until `burn_s` after it, then a coast in gravity alone; with
1180 /// `bad_m` added to the three samples from 1.5 s on, or to every sample from 1.5 s on when
1181 /// `stays`. Built to [#1362][i1362]'s account of its hand-built logs.
1182 ///
1183 /// [i1362]: https://github.com/nrdptel/fusionspace-eridanus/issues/1362
1184 fn pad_spiked_log(
1185 climb: &dyn Fn(f64) -> f64,
1186 burn_s: f64,
1187 bad_m: f64,
1188 stays: bool,
1189 ) -> FlightLog {
1190 pad_spiked_log_at(climb, burn_s, bad_m, stays, 1.5)
1191 }
1192
1193 /// [`pad_spiked_log`] with its bad samples from `at_s` on.
1194 fn pad_spiked_log_at(
1195 climb: &dyn Fn(f64) -> f64,
1196 burn_s: f64,
1197 bad_m: f64,
1198 stays: bool,
1199 at_s: f64,
1200 ) -> FlightLog {
1201 const STEP_S: f64 = 0.05;
1202 const SUBSTEPS: u32 = 50;
1203 let g = hpr_core::gravity::STANDARD_GRAVITY_MPS2;
1204 let mut draw = draws();
1205 let (mut v, mut h) = (0.0_f64, 0.0_f64);
1206 let mut time_s = Vec::new();
1207 let mut altitude_m = Vec::new();
1208 for i in 0..500_u32 {
1209 let t = f64::from(i) * STEP_S;
1210 if i > 0 {
1211 // The climb by the midpoint rule in small steps: a millimeter's error at most.
1212 let dt = STEP_S / f64::from(SUBSTEPS);
1213 for j in 0..SUBSTEPS {
1214 let tau = t - STEP_S + (f64::from(j) + 0.5) * dt - 3.0;
1215 let a = if tau <= 0.0 {
1216 0.0
1217 } else if tau < burn_s {
1218 climb(tau)
1219 } else {
1220 -g
1221 };
1222 h += v * dt + 0.5 * a * dt * dt;
1223 v += a * dt;
1224 }
1225 h = h.max(0.0);
1226 }
1227 // A draw is uniform over ±2,500: scaled to ±0.3·√3 m, its deviation is 0.3 m.
1228 let noise = draw() / 2_500.0 * 0.3 * 3.0_f64.sqrt();
1229 let bad = if (at_s - 1e-9..at_s + 3.0 * STEP_S - 1e-9).contains(&t)
1230 || (stays && t >= at_s - 1e-9)
1231 {
1232 bad_m
1233 } else {
1234 0.0
1235 };
1236 time_s.push(t);
1237 altitude_m.push(h + noise + bad);
1238 }
1239 FlightLog {
1240 format: hpr_flightdata::log::LogFormat::GenericTable,
1241 logger: "a test's".to_owned(),
1242 serial_number: None,
1243 firmware: None,
1244 flight_number: None,
1245 stated: hpr_flightdata::log::Stated::default(),
1246 time_s,
1247 altitude_m,
1248 vertical_speed_m_s: None,
1249 temperature_k: None,
1250 battery_v: None,
1251 channels: Vec::new(),
1252 events: Vec::new(),
1253 notes: Vec::new(),
1254 }
1255 }
1256
1257 /// [#1362][i1362]'s logs: three bad samples side by side on the pad, faster than the flight's
1258 /// own top speed, don't stay its top, and a 15 m step on the pad that stays doesn't cut the
1259 /// flight early. Ignition is at 3.0 s. A 2.0 s burn at 40 m/s² to 80 m/s with 45 m on the
1260 /// pad, a 1.25 s burn to 50 m/s with 30 m, and a long tail-off, its thrust falling through the
1261 /// weight 4.95 s into a 6.0 s burn and to nothing at its end, with 100 m; then the first flight with 15 m from 1.5 s on.
1262 /// Each is cut where its clean log is: the cut after its true peak and its burnout, its top speed
1263 /// read after ignition. Before [`STILL_M_S`] the spiked three were cut at 5.90, 5.05 and 8.75 s
1264 /// (their clean logs at 7.25, 6.50 and 10.60 s), each top read at 1.6 s on the pad, the
1265 /// tail-off's cut before its burnout; the step was cut at 3.05 s, 0.05 s after ignition.
1266 ///
1267 /// [i1362]: https://github.com/nrdptel/fusionspace-eridanus/issues/1362
1268 #[test]
1269 fn a_bad_sample_on_the_pad_is_not_the_top_speed() {
1270 let g = hpr_core::gravity::STANDARD_GRAVITY_MPS2;
1271 // The tail-off's net push falls in a line, through nothing at 4.95 s to the weight's pull
1272 // alone at its burnout, 6.0 s in.
1273 let tail_off = move |tau: f64| g / 1.05 * (4.95 - tau);
1274 let constant = |_tau: f64| 40.0;
1275 /// The net push, as a function of the time since ignition.
1276 type Climb<'a> = &'a dyn Fn(f64) -> f64;
1277 // (what, net push, burn, true peak's time, bad meters, a step that stays)
1278 let cases: [(&str, Climb, f64, f64, f64, bool); 4] = [
1279 ("80 m/s", &constant, 2.0, 5.0, 45.0, false),
1280 ("50 m/s", &constant, 1.25, 4.25, 30.0, false),
1281 ("the tail-off", &tail_off, 6.0, 7.95, 100.0, false),
1282 ("80 m/s, a step", &constant, 2.0, 5.0, 15.0, true),
1283 ];
1284 let found: Vec<_> = cases
1285 .iter()
1286 .map(|&(what, climb, burn_s, _, bad_m, stays)| {
1287 let clean = try_cut(&pad_spiked_log(climb, burn_s, 0.0, false));
1288 let spiked = try_cut(&pad_spiked_log(climb, burn_s, bad_m, stays));
1289 println!("{what}: clean {clean:?}, {bad_m} m on the pad: {spiked:?}");
1290 (clean, spiked)
1291 })
1292 .collect();
1293 for ((what, _, burn_s, peak_s, _, _), (clean, spiked)) in cases.into_iter().zip(found) {
1294 let clean = clean.unwrap_or_else(|why| panic!("{what}, clean: refused, {why:?}"));
1295 for (cut, which) in [(Ok(clean), "clean"), (spiked, "with the bad samples")] {
1296 let cut = cut.unwrap_or_else(|why| panic!("{what}, {which}: refused, {why:?}"));
1297 assert!(
1298 cut.top_speed_s > 3.0,
1299 "{what}, {which}: top read at {} s",
1300 cut.top_speed_s
1301 );
1302 assert!(
1303 cut.time_s > peak_s,
1304 "{what}, {which}: cut at {} s",
1305 cut.time_s
1306 );
1307 assert!(
1308 cut.time_s > 3.0 + burn_s,
1309 "{what}, {which}: cut at {} s",
1310 cut.time_s
1311 );
1312 assert_eq!(
1313 cut.index, clean.index,
1314 "{what}, {which}: moved from the clean cut"
1315 );
1316 }
1317 }
1318 // The bad samples anywhere on the pad from 1.50 s to 2.75 s, ignition at 3.0 s: each log is
1319 // cut where its clean log is, after its true peak and burnout, its top read after ignition,
1320 // or refused as transonic. From 2.80 s they can still be the top (#1441; the test below).
1321 let mut refused = 0_usize;
1322 let mut flown = 0_usize;
1323 const STARTS: u32 = 26;
1324 for (what, climb, burn_s, peak_s, _, _) in cases {
1325 let clean = try_cut(&pad_spiked_log(climb, burn_s, 0.0, false))
1326 .unwrap_or_else(|why| panic!("{what}, clean: refused, {why:?}"));
1327 // Six spikes, then two steps that stay.
1328 for (j, bad_m) in [-100.0, -60.0, -30.0, 30.0, 60.0, 100.0, 15.0, 60.0]
1329 .into_iter()
1330 .enumerate()
1331 {
1332 for start in 0..STARTS {
1333 let at_s = 1.5 + 0.05 * f64::from(start);
1334 let stays = j >= 6;
1335 let log = pad_spiked_log_at(climb, burn_s, bad_m, stays, at_s);
1336 flown += 1;
1337 let which = format!("{what}, {bad_m} m from {at_s:.2} s (stays: {stays})");
1338 match try_cut(&log) {
1339 Ok(cut) => {
1340 assert!(cut.top_speed_s > 3.0, "{which}: top at {}", cut.top_speed_s);
1341 assert!(cut.time_s > peak_s, "{which}: cut at {} s", cut.time_s);
1342 assert!(
1343 cut.time_s > 3.0 + burn_s,
1344 "{which}: cut at {} s",
1345 cut.time_s
1346 );
1347 assert_eq!(cut.index, clean.index, "{which}: moved from the clean cut");
1348 }
1349 Err(NoCut::Transonic { .. }) => refused += 1,
1350 Err(why) => panic!("{which}: refused, {why:?}"),
1351 }
1352 }
1353 }
1354 }
1355 println!("{flown} logs with bad samples on the pad, {refused} refused as transonic");
1356 // A slow climb stands still again before its cut: at 12 m/s² for 1.5 s, its top 18 m/s,
1357 // it is refused as never lifting off; at 15 m/s² for 2.0 s, its top 30 m/s, it is cut
1358 // after its burnout.
1359 assert_eq!(
1360 try_cut(&pad_spiked_log(&|_| 12.0, 1.5, 0.0, false)),
1361 Err(NoCut::NeverLifted)
1362 );
1363 let cut = try_cut(&pad_spiked_log(&|_| 15.0, 2.0, 0.0, false));
1364 assert!(
1365 cut.is_ok_and(|cut| cut.time_s > 5.0),
1366 "a 30 m/s climb: {cut:?}"
1367 );
1368 }
1369
1370 /// A known gap ([#1441][i1441]): bad samples close to ignition leave no still window between
1371 /// them and the climb, so their leaving the window reads a climb faster than the flight's,
1372 /// which stays its top. On the flights of [`a_bad_sample_on_the_pad_is_not_the_top_speed`]
1373 /// that starts 0.2 s before ignition. Pinned as it is, so that a fix shows here: three
1374 /// readings 60 m low from 2.80 s cut its tail-off at 8.75 s, before its 9.0 s burnout, its top
1375 /// 133.9 m/s read at 3.30 s; a 60 m step from 2.95 s that stays cuts it at 8.75 s too, its top
1376 /// 164.0 m/s read at 3.20 s. Its clean log is cut at 10.60 s.
1377 ///
1378 /// [i1441]: https://github.com/nrdptel/fusionspace-eridanus/issues/1441
1379 #[test]
1380 fn a_low_reading_just_before_ignition_is_still_the_top() {
1381 let g = hpr_core::gravity::STANDARD_GRAVITY_MPS2;
1382 let tail_off = move |tau: f64| g / 1.05 * (4.95 - tau);
1383 // (bad meters, a step that stays, from, the top's time and speed)
1384 let cases = [
1385 (-60.0, false, 2.80, 3.30, 133.94),
1386 (60.0, true, 2.95, 3.20, 163.95),
1387 ];
1388 for (bad_m, stays, at_s, top_s, top_m_s) in cases {
1389 let cut = try_cut(&pad_spiked_log_at(&tail_off, 6.0, bad_m, stays, at_s));
1390 assert!(
1391 cut.is_ok_and(|cut| (cut.time_s - 8.75).abs() < 1e-9
1392 && (cut.top_speed_s - top_s).abs() < 1e-9
1393 && (cut.top_speed_m_s - top_m_s).abs() < 0.01),
1394 "{bad_m} m from {at_s} s: {cut:?}; if it's now cut where the clean log is (10.60 s), \
1395 #1441 is fixed"
1396 );
1397 }
1398 }
1399
1400 /// [`median_of`] gives exactly what sorting by `f64::total_cmp` and taking the middle gives,
1401 /// on odd and even counts, repeats, signed zeros, infinities and NaN.
1402 #[test]
1403 fn the_median_by_selection_is_the_sorted_one() {
1404 let sorted_median = |values: &[f64]| {
1405 let mut sorted = values.to_vec();
1406 sorted.sort_by(f64::total_cmp);
1407 let mid = sorted.len() / 2;
1408 match (sorted.len() % 2, sorted.get(mid)) {
1409 (1, Some(&middle)) => middle,
1410 (_, Some(&upper)) => sorted
1411 .get(mid.wrapping_sub(1))
1412 .map_or(upper, |&lower| (lower + upper) / 2.0),
1413 (_, None) => f64::NAN,
1414 }
1415 };
1416 let mut state = 0x9e37_79b9_7f4a_7c15_u64;
1417 let specials = [
1418 0.0,
1419 -0.0,
1420 1.0,
1421 f64::INFINITY,
1422 f64::NEG_INFINITY,
1423 f64::NAN,
1424 1e-300,
1425 ];
1426 for count in 0..40 {
1427 for round in 0..50 {
1428 let values: Vec<f64> = (0..count)
1429 .map(|_| {
1430 state ^= state << 13;
1431 state ^= state >> 7;
1432 state ^= state << 17;
1433 let pick = usize::try_from(state % 64).unwrap_or(0);
1434 if round % 5 == 0 && pick < specials.len() {
1435 specials[pick]
1436 } else {
1437 // Coarse values repeat often.
1438 f64::from(u32::try_from(state % 7).unwrap_or(0)) - 3.0
1439 }
1440 })
1441 .collect();
1442 let want = sorted_median(&values);
1443 let got = median_of(&mut values.clone());
1444 assert_eq!(want.to_bits(), got.to_bits(), "{values:?}");
1445 }
1446 }
1447 }
1448
1449 /// A barometer's dip in the boost isn't burnout. Over set A's first 200 synthetic flights, on
1450 /// each one cut, a dip is put in the height, `depth · sin²(π (t − start) / span)` below it, its
1451 /// start at ignition or 0.3 or 0.6 of the way through the burn, its span 0.2 to 0.6 s and its
1452 /// depth 10, 20 or 40 m. Every dipped log whose fitted speed falls before burnout by what the
1453 /// cut needs is cut after burnout, within the 2.83 s of
1454 /// [`the_cut_falls_just_after_the_true_burnout`], before apogee, or refused for the transonic
1455 /// speed its catch-up can read. Among the logs whose falls each last 0.5 s at most and recover
1456 /// before burnout, as the public logs' did, the falls reach the public logs' deepest, 63.2 m/s, and
1457 /// last at least the public logs' longest, 0.48 s. Measured, not asserted: of 51 flights, 1,793 dipped logs give
1458 /// such a fall; 1,642 are cut, 0.14 s to 2.30 s after burnout, and 151 refused as transonic.
1459 /// 797 hold every fall to 0.5 s and recover in the burn, up to 98.9 m/s deep; 218 have a fall
1460 /// still running at burnout, whose depth takes in the coast's, so it isn't counted; the other
1461 /// 778 have a fall that lasts longer (likely the fall back from a catch-up's overshoot, not traced). The other 502 dipped
1462 /// logs give no such fall. A dip can bring the fitted speed under [`STILL_M_S`] in the burn, so
1463 /// that the pad is read again there; before that rule the counts were 1,787, 1,635, 152, 791 and
1464 /// 508. With the hold alone, not the lowest
1465 /// speed, 416 of those 778 were cut in the burn (run once, before the [`STILL_M_S`] rule).
1466 #[test]
1467 fn a_dip_in_the_boost_is_not_burnout() {
1468 let latest_s = (DROP_SHARE * readings::TRANSONIC_SPEED_M_S).max(DROP_FLOOR_M_S)
1469 / hpr_core::gravity::STANDARD_GRAVITY_MPS2
1470 + SPEED_WINDOW_S;
1471 /// One worker's counts; each is a sum, a least or a most, so the order the workers' flights
1472 /// are taken in can't change the totals.
1473 #[derive(Clone, Copy)]
1474 struct Tally {
1475 dipped: usize,
1476 cut: usize,
1477 refused: usize,
1478 longer: usize,
1479 running: usize,
1480 longest_s: f64,
1481 deepest_m_s: f64,
1482 earliest_s: f64,
1483 latest_s: f64,
1484 }
1485 let empty = Tally {
1486 dipped: 0,
1487 cut: 0,
1488 refused: 0,
1489 longer: 0,
1490 running: 0,
1491 longest_s: 0.0,
1492 deepest_m_s: 0.0,
1493 earliest_s: f64::INFINITY,
1494 latest_s: 0.0,
1495 };
1496 // The 200 flights are independent: each worker flies every `workers`-th one with a flyer
1497 // of its own, so the test's wall time is a share of its 2,295 dipped logs, every one still
1498 // flown and held to the same assertions.
1499 let fly = |worker: u64, workers: u64| -> Tally {
1500 let mut flyer = Flyer::new(DesignFiles::committed());
1501 let mut tally = empty;
1502 for k in (0..200_u64).filter(|k| k % workers == worker) {
1503 let flight = flyer.flight(Set::A, k).expect("set A's flights fly");
1504 if find_cut(&flight.log).is_none() {
1505 continue;
1506 }
1507 let pad_s = flight.draw.logger.pad_s;
1508 let events = &flight.truth.events;
1509 let burnout_s = pad_s + events.burnout_s;
1510 for start in [0.0, 0.3, 0.6] {
1511 for span_s in [0.2, 0.3, 0.4, 0.5, 0.6] {
1512 for depth_m in [10.0, 20.0, 40.0] {
1513 let start_s = pad_s + start * events.burnout_s;
1514 let mut dipped = flight.log.clone();
1515 for (t, h) in dipped.time_s.iter().zip(&mut dipped.altitude_m) {
1516 if (start_s..=start_s + span_s).contains(t) {
1517 *h -= depth_m
1518 * (std::f64::consts::PI * (t - start_s) / span_s)
1519 .sin()
1520 .powi(2);
1521 }
1522 }
1523 // Each fall's time before burnout, a fall still holding at the walk's
1524 // end included, and whether it still runs at burnout: its depth then
1525 // takes in the coast's, so it isn't a dip's.
1526 let mut falls = Vec::new();
1527 let _ = walk(&dipped, f64::INFINITY, &mut |since, until, deepest| {
1528 if since < burnout_s {
1529 falls.push((
1530 until.min(burnout_s) - since,
1531 deepest,
1532 until > burnout_s,
1533 ));
1534 }
1535 });
1536 if falls.is_empty() {
1537 continue;
1538 }
1539 tally.dipped += 1;
1540 if falls.iter().any(|&(held_s, _, _)| held_s > 0.5) {
1541 tally.longer += 1;
1542 } else if falls.iter().any(|&(_, _, running)| running) {
1543 tally.running += 1;
1544 } else {
1545 for &(held_s, deepest, _) in &falls {
1546 tally.longest_s = tally.longest_s.max(held_s);
1547 tally.deepest_m_s = tally.deepest_m_s.max(deepest);
1548 }
1549 }
1550 let what = format!(
1551 "flight {k}, a {depth_m} m dip over {span_s} s from {start_s} s \
1552 (burnout {burnout_s} s)"
1553 );
1554 match try_cut(&dipped) {
1555 Ok(cut) => {
1556 tally.cut += 1;
1557 let after_s = cut.time_s - burnout_s;
1558 assert!(
1559 after_s > 0.0 && after_s <= latest_s,
1560 "{what}: cut {after_s} s after burnout"
1561 );
1562 assert!(cut.time_s < pad_s + events.apogee_s, "{what}");
1563 tally.earliest_s = tally.earliest_s.min(after_s);
1564 tally.latest_s = tally.latest_s.max(after_s);
1565 }
1566 Err(NoCut::Transonic { .. }) => tally.refused += 1,
1567 Err(why) => panic!("{what}: refused, {why:?}"),
1568 }
1569 }
1570 }
1571 }
1572 }
1573 tally
1574 };
1575 let workers =
1576 std::thread::available_parallelism().map_or(1, |n| u64::try_from(n.get()).unwrap_or(1));
1577 let fly = &fly;
1578 let tallies: Vec<Tally> = std::thread::scope(|scope| {
1579 let handles: Vec<_> = (0..workers)
1580 .map(|worker| scope.spawn(move || fly(worker, workers)))
1581 .collect();
1582 handles
1583 .into_iter()
1584 .map(|handle| {
1585 handle
1586 .join()
1587 .expect("a worker's assertion failed; see its message")
1588 })
1589 .collect()
1590 });
1591 let mut all = empty;
1592 for tally in tallies {
1593 all.dipped += tally.dipped;
1594 all.cut += tally.cut;
1595 all.refused += tally.refused;
1596 all.longer += tally.longer;
1597 all.running += tally.running;
1598 all.longest_s = all.longest_s.max(tally.longest_s);
1599 all.deepest_m_s = all.deepest_m_s.max(tally.deepest_m_s);
1600 all.earliest_s = all.earliest_s.min(tally.earliest_s);
1601 all.latest_s = all.latest_s.max(tally.latest_s);
1602 }
1603 let Tally {
1604 dipped,
1605 cut,
1606 refused,
1607 longer,
1608 running,
1609 longest_s,
1610 deepest_m_s,
1611 earliest_s,
1612 latest_s: latest_found_s,
1613 } = all;
1614 println!(
1615 "{dipped} dipped logs, {cut} cut {earliest_s:.2} s to {latest_found_s:.2} s \
1616 after burnout, {refused} refused as transonic; falls up to {longest_s:.2} s and \
1617 {deepest_m_s:.1} m/s in those whose falls each held 0.5 s at most and recovered in \
1618 the burn; {longer} with a longer one; {running} with one still running at burnout"
1619 );
1620 assert!(
1621 longest_s >= 0.48,
1622 "the longest fall kept held {longest_s} s"
1623 );
1624 assert!(
1625 deepest_m_s >= 63.2,
1626 "the deepest fall kept went {deepest_m_s} m/s"
1627 );
1628 assert!(cut >= 1600, "{cut} dipped logs cut");
1629 }
1630
1631 /// A hostile log is refused without a panic, and each refusal names its reason: no samples, one,
1632 /// times all equal, not numbers or infinite, heights at the float's edge, and a log sampled
1633 /// every microsecond, faster than the analyzer reads, 200,000 samples refused at its first
1634 /// window; a log of channels alone is refused too, naming its reason: too sparse with its track
1635 /// emptied, its times or values not numbers, or its values infinite; too fast with its samples a
1636 /// microsecond apart. A log at the
1637 /// analyzer's fastest rate fills a
1638 /// window to the most it allows, 251 samples, and is read.
1639 #[test]
1640 fn a_hostile_log_is_refused_without_a_panic() {
1641 let mut flyer = Flyer::new(DesignFiles::committed());
1642 let base = flyer.flight(Set::A, 1).expect("a flight").log;
1643 let with = |time_s: Vec<f64>, altitude_m: Vec<f64>| {
1644 let mut log = base.clone();
1645 log.channels.clear();
1646 log.vertical_speed_m_s = None;
1647 log.temperature_k = None;
1648 log.battery_v = None;
1649 log.time_s = time_s;
1650 log.altitude_m = altitude_m;
1651 log
1652 };
1653 #[expect(clippy::cast_precision_loss, reason = "small counts")]
1654 let climb = |n: usize, dt: f64| {
1655 let times: Vec<f64> = (0..n).map(|i| i as f64 * dt).collect();
1656 let heights = times.iter().map(|t| 100.0 * t).collect();
1657 (times, heights)
1658 };
1659 let (dense_t, dense_h) = climb(200_000, 1e-6);
1660 let cases = [
1661 with(Vec::new(), Vec::new()),
1662 with(vec![0.0], vec![0.0]),
1663 with(vec![1.0; 50], (0..50).map(f64::from).collect()),
1664 with(
1665 (0..50)
1666 .map(|i| if i % 2 == 0 { f64::NAN } else { f64::INFINITY })
1667 .collect(),
1668 vec![0.0; 50],
1669 ),
1670 with(
1671 (0..50).map(|i| 1e300 * f64::from(i)).collect(),
1672 (0..50).map(|i| 1e308 * f64::from(i % 2)).collect(),
1673 ),
1674 with(dense_t, dense_h),
1675 ];
1676 for log in &cases {
1677 assert_eq!(find_cut(log), None);
1678 }
1679 // And says why: an empty log holds no track; one sample, times all equal, not numbers, or
1680 // a lifetime apart are too few to a window; the dense log reads too fast.
1681 let why: Vec<_> = cases.iter().map(try_cut).collect();
1682 assert_eq!(
1683 why,
1684 [
1685 Err(NoCut::NoTrack),
1686 Err(NoCut::TooSparse),
1687 Err(NoCut::TooSparse),
1688 Err(NoCut::TooSparse),
1689 Err(NoCut::TooSparse),
1690 Err(NoCut::TooFast),
1691 ]
1692 );
1693 // A steady climb logged at 5 Hz is too sparse, at 20 Hz never slowing, and a log at rest
1694 // at 20 Hz never lifts off.
1695 let (t, h) = climb(100, 0.2);
1696 assert_eq!(try_cut(&with(t, h)), Err(NoCut::TooSparse));
1697 let (t, h) = climb(400, 0.05);
1698 assert_eq!(try_cut(&with(t.clone(), h)), Err(NoCut::NeverSlowed));
1699 assert_eq!(try_cut(&with(t, vec![0.0; 400])), Err(NoCut::NeverLifted));
1700 // At the analyzer's fastest rate, 500 Hz, and with intervals a part in a thousand shorter,
1701 // a window holds 251 samples, the most allowed, and is read; with intervals 0.6% or 2%
1702 // shorter it holds 252 or 256 and is refused.
1703 assert_eq!(most_in(SPEED_WINDOW_S), 251);
1704 for (dt, held, why) in [
1705 (readings::MIN_INTERVAL_S, 251, NoCut::NeverSlowed),
1706 (readings::MIN_INTERVAL_S * 0.999, 251, NoCut::NeverSlowed),
1707 (readings::MIN_INTERVAL_S * 0.994, 252, NoCut::TooFast),
1708 (readings::MIN_INTERVAL_S * 0.98, 256, NoCut::TooFast),
1709 ] {
1710 let (t, h) = climb(1_000, dt);
1711 let last = t[t.len() - 1];
1712 let most = t.iter().filter(|&&s| s >= last - SPEED_WINDOW_S).count();
1713 assert_eq!(most, held, "{dt} s");
1714 assert_eq!(try_cut(&with(t, h)), Err(why), "{dt} s");
1715 }
1716 // A log of channels alone, with no clock of its own, its pressure channel the track: emptied,
1717 // its times or values not numbers, or its values infinite, the track holds no window of
1718 // samples it can read; its samples 1 µs apart, it reads too fast. An emptied channel is
1719 // still the log's track, so it is too sparse, where a log with no columns has none.
1720 let only = (0..60)
1721 .find_map(|k| channels_only(&flyer.flight(Set::A, k).ok()?.log))
1722 .expect("one of set A's first 60 flights logs pressure");
1723 let channeled = |change: &dyn Fn(&mut hpr_flightdata::log::Channel)| {
1724 let mut log = only.clone();
1725 for channel in &mut log.channels {
1726 if channel.quantity == hpr_flightdata::log::Quantity::Pressure {
1727 change(channel);
1728 }
1729 }
1730 log
1731 };
1732 let refused = [
1733 channeled(&|c| {
1734 c.time_s.clear();
1735 c.values.clear();
1736 }),
1737 channeled(&|c| c.time_s.fill(f64::NAN)),
1738 channeled(&|c| c.values.fill(f64::NAN)),
1739 channeled(&|c| c.values.fill(f64::INFINITY)),
1740 channeled(&|c| {
1741 #[expect(clippy::cast_precision_loss, reason = "small counts")]
1742 for (i, t) in c.time_s.iter_mut().enumerate() {
1743 *t = i as f64 * 1e-6;
1744 }
1745 }),
1746 ];
1747 let why: Vec<_> = refused.iter().map(try_cut).collect();
1748 assert_eq!(
1749 why,
1750 [
1751 Err(NoCut::TooSparse),
1752 Err(NoCut::TooSparse),
1753 Err(NoCut::TooSparse),
1754 Err(NoCut::TooSparse),
1755 Err(NoCut::TooFast),
1756 ]
1757 );
1758 }
1759
1760 /// A forward model that flies as the flight's own does but refuses each flight `refuses`
1761 /// takes, by the time it is flown to.
1762 struct Refusing<'a, 'b> {
1763 inner: &'a mut Flown<'b>,
1764 refuses: fn(f64) -> bool,
1765 }
1766
1767 impl Forward for Refusing<'_, '_> {
1768 fn fly(
1769 &mut self,
1770 p: &fit::Parameters,
1771 until_s: f64,
1772 ) -> Result<crate::residuals::Simulated, String> {
1773 if (self.refuses)(until_s) {
1774 return Err("refused".to_owned());
1775 }
1776 self.inner.fly(p, until_s)
1777 }
1778
1779 fn fly_sheared(
1780 &mut self,
1781 p: &fit::Parameters,
1782 until_s: f64,
1783 exponent: f64,
1784 ) -> Result<crate::residuals::Simulated, String> {
1785 if (self.refuses)(until_s) {
1786 return Err("refused".to_owned());
1787 }
1788 self.inner.fly_sheared(p, until_s, exponent)
1789 }
1790 }
1791
1792 /// Each variant of [`Unpredicted`] is matched by one case: a log with no cut says why the finder
1793 /// found none; a boost cut within 2 s of liftoff holds too little to fit; a flight that can't be
1794 /// flown keeps the fit to what was stated; and a fitted flight that can't be flown to its apogee
1795 /// reaches none. The flight that predicts is set A's first with a cut. Not pinned: the other
1796 /// ways a boost holds too little, and a fit refused for its misfit share.
1797 #[test]
1798 fn each_refusal_of_a_prediction_names_its_reason() {
1799 let files = DesignFiles::committed();
1800 let mut flyer = Flyer::new(DesignFiles::committed());
1801 let mut tables = BTreeMap::new();
1802 let (index, flight) = first_cut(&mut flyer, Some);
1803 let weighed = weighed_factor(Set::A, index);
1804 let mut flown = Flown::new(&flight.draw, &files, weighed, &mut tables);
1805 let mut predicted = |log: &FlightLog, refuses: fn(f64) -> bool| {
1806 let mut forward = Refusing {
1807 inner: &mut flown,
1808 refuses,
1809 };
1810 predict(
1811 log,
1812 |observed| stated_for(Some(observed)),
1813 Noise::FromResiduals,
1814 &mut forward,
1815 )
1816 };
1817 let cut = find_cut(&flight.log).expect("the flight is cut");
1818 assert!(predicted(&flight.log, |_| false).is_ok());
1819 assert_eq!(
1820 predicted(&flight.log, |_| true),
1821 Err(Unpredicted::NotFitted {
1822 cut,
1823 misfit_share: None
1824 })
1825 );
1826 assert_eq!(
1827 predicted(&flight.log, |until_s| until_s >= APOGEE_HORIZON_S),
1828 Err(Unpredicted::NoApogee(cut))
1829 );
1830 // A log at rest, and a short boost: 2 s on the pad at 20 Hz, 0.5 s at 200 m/s², then a
1831 // coast slowing at 60 m/s².
1832 let mut log = flight.log.clone();
1833 log.channels.clear();
1834 log.vertical_speed_m_s = None;
1835 log.temperature_k = None;
1836 log.battery_v = None;
1837 log.time_s = (0..100).map(|i| f64::from(i) * 0.05).collect();
1838 log.altitude_m = vec![0.0; 100];
1839 assert_eq!(
1840 predicted(&log, |_| false),
1841 Err(Unpredicted::NoCut(NoCut::NeverLifted))
1842 );
1843 log.altitude_m = log
1844 .time_s
1845 .iter()
1846 .map(|&t| match t {
1847 t if t <= 2.0 => 0.0,
1848 t if t <= 2.5 => 100.0 * (t - 2.0).powi(2),
1849 t => 25.0 + 100.0 * (t - 2.5) - 30.0 * (t - 2.5).powi(2),
1850 })
1851 .collect();
1852 let short = find_cut(&log).expect("the short boost is cut");
1853 assert!(short.time_s < 4.0, "{short:?}");
1854 assert_eq!(
1855 predicted(&log, |_| false),
1856 Err(Unpredicted::NothingToFit(short))
1857 );
1858 }
1859
1860 /// The two one-sided p-values of the sign-flip test of the center `mu`, every pattern of signs
1861 /// counted: the share of patterns whose sum of `dᵢ − μ` is at most the observed one's, and at
1862 /// least.
1863 fn sign_flip_p(differences: &[f64], mu: f64) -> (f64, f64) {
1864 let n = differences.len();
1865 let observed: f64 = differences.iter().map(|d| d - mu).sum();
1866 let (mut low, mut high) = (0_u32, 0_u32);
1867 for pattern in 0..(1_u32 << n) {
1868 let sum: f64 = differences
1869 .iter()
1870 .enumerate()
1871 .map(|(i, d)| {
1872 if pattern & (1 << i) == 0 {
1873 d - mu
1874 } else {
1875 mu - d
1876 }
1877 })
1878 .sum();
1879 low += u32::from(sum <= observed);
1880 high += u32::from(sum >= observed);
1881 }
1882 let all = f64::from(1_u32 << n);
1883 (f64::from(low) / all, f64::from(high) / all)
1884 }
1885
1886 /// Up to 5 differences no pattern of signs is rare enough at 95%: the whole line. At 6 the
1887 /// interval runs from the least to the greatest, holding the center with probability
1888 /// `1 − 2/64`. At 7 and 9 each end is where the test, every pattern counted, first rejects at
1889 /// 2.5% a side: a center just inside holds both p-values above 2.5%, one just outside doesn't.
1890 #[test]
1891 fn the_sign_flip_interval_is_the_tests_inversion() {
1892 let five = [1.0, -2.0, 3.5, 0.25, 7.0];
1893 assert_eq!(
1894 sign_flip_interval(&five, 0.95),
1895 Some((f64::NEG_INFINITY, f64::INFINITY))
1896 );
1897 let six = [1.0, -2.0, 3.5, 0.25, 7.0, -0.5];
1898 assert_eq!(sign_flip_interval(&six, 0.95), Some((-2.0, 7.0)));
1899 for differences in [
1900 vec![-3.1, 0.4, 2.2, -0.7, 5.3, 1.9, -1.2],
1901 vec![0.3, -4.2, 1.1, 2.7, -0.2, 3.3, 6.1, -2.4, 0.9],
1902 ] {
1903 let (low, high) = sign_flip_interval(&differences, 0.95).expect("an interval");
1904 assert!(low.is_finite() && high.is_finite() && low < high);
1905 let step = 1e-9;
1906 for (mu, inside) in [
1907 (low + step, true),
1908 (high - step, true),
1909 (low - step, false),
1910 (high + step, false),
1911 ] {
1912 let (p_low, p_high) = sign_flip_p(&differences, mu);
1913 assert_eq!(
1914 p_low > 0.025 && p_high > 0.025,
1915 inside,
1916 "{differences:?} at {mu}: p {p_low}, {p_high}"
1917 );
1918 }
1919 }
1920 assert_eq!(sign_flip_interval(&[], 0.95), None);
1921 assert_eq!(sign_flip_interval(&[1.0, f64::NAN], 0.95), None);
1922 assert_eq!(sign_flip_interval(&six, 1.0), None);
1923 }
1924
1925 /// On 20,000 draws of 7 differences from a symmetric distribution about 0.3 (a uniform one, on
1926 /// a fixed stream), the interval holds the center about `1 − 6/128 = 95.3%` of the time:
1927 /// within 0.8 points, five standard errors. Narrowed by one subset mean a side it would hold
1928 /// it `1 − 8/128 = 93.75%` of the time, which the band excludes.
1929 #[test]
1930 fn the_sign_flip_interval_covers_as_it_states() {
1931 let mut draw = draws();
1932 let trials = 20_000;
1933 let mut held = 0_u32;
1934 for _ in 0..trials {
1935 let differences: Vec<f64> = (0..7).map(|_| 0.3 + draw() / 2_500.0).collect();
1936 let (low, high) = sign_flip_interval(&differences, 0.95).expect("an interval");
1937 held += u32::from(low <= 0.3 && 0.3 <= high);
1938 }
1939 let share = f64::from(held) / f64::from(trials);
1940 assert!((share - (1.0 - 6.0 / 128.0)).abs() < 0.008, "held {share}");
1941 assert!(share > 1.0 - 8.0 / 128.0 + 0.008, "held {share}");
1942 }
1943
1944 /// The quantile's rank: 2.5% and 97.5% of 10,000 are ranks 250 and 9,750 (as `(1 − 0.95)/2`
1945 /// computes them too, a hair above 0.025), a share between two ranks takes the higher, a share
1946 /// of 0 takes the first rank (clamped up from 0) and a share of 1 the last.
1947 #[test]
1948 fn the_percentile_rank_is_the_smallest_reaching_the_share() {
1949 assert_eq!(percentile_rank(0.025, 10_000), 250);
1950 assert_eq!(percentile_rank((1.0 - 0.95) / 2.0, 10_000), 250);
1951 assert_eq!(percentile_rank(1.0 - (1.0 - 0.95) / 2.0, 10_000), 9_750);
1952 assert_eq!(percentile_rank(0.5, 3), 2);
1953 assert_eq!(percentile_rank(0.0001, 100), 1);
1954 assert_eq!(percentile_rank(0.0, 100), 1);
1955 assert_eq!(percentile_rank(1.0, 100), 100);
1956 }
1957
1958 /// Exact cases, whatever the stream draws. One difference: every resample is it. Equal ones:
1959 /// the same. Two, `a` and `b`: a resample's mean is `a` a quarter of the time, so both 2.5%
1960 /// tails sit on the ends. Four zeros and a 10: a resample's mean is 2k for k ~ Binomial(5, 1/5),
1961 /// P(k ≤ 2) = 0.942 and P(k ≤ 3) = 0.9933, so the 97.5% quantile is 6 and the 2.5% one is 0
1962 /// (P(k = 0) = 0.328); on 10,000 resamples each share sits more than 11 standard errors from 97.5%.
1963 #[test]
1964 fn the_paired_bootstrap_takes_the_percentiles() {
1965 for seed in [1, 7, 2_026] {
1966 assert_eq!(
1967 paired_bootstrap_interval(&[3.5], 0.95, 10_000, seed),
1968 Some((3.5, 3.5))
1969 );
1970 assert_eq!(
1971 paired_bootstrap_interval(&[-1.25; 6], 0.95, 10_000, seed),
1972 Some((-1.25, -1.25))
1973 );
1974 assert_eq!(
1975 paired_bootstrap_interval(&[-2.0, 5.0], 0.95, 10_000, seed),
1976 Some((-2.0, 5.0))
1977 );
1978 assert_eq!(
1979 paired_bootstrap_interval(&[0.0, 0.0, 10.0, 0.0, 0.0], 0.95, 10_000, seed),
1980 Some((0.0, 6.0))
1981 );
1982 }
1983 assert_eq!(paired_bootstrap_interval(&[], 0.95, 10_000, 1), None);
1984 assert_eq!(paired_bootstrap_interval(&[1.0], 0.95, 0, 1), None);
1985 assert_eq!(paired_bootstrap_interval(&[1.0], 1.0, 10_000, 1), None);
1986 assert_eq!(
1987 paired_bootstrap_interval(&[1.0, f64::NAN], 0.95, 10, 1),
1988 None
1989 );
1990 // Finite differences whose sum overflows.
1991 assert_eq!(paired_bootstrap_interval(&[f64::MAX; 3], 0.95, 10, 1), None);
1992 }
1993
1994 /// On 2 resamples the 2.5% point is rank 1, the lower mean, and the 97.5% point rank 2, the
1995 /// higher: an off-by-one in the rank would put both ends on one mean. Seed 3 draws two
1996 /// different resample means of these two differences (a resample's mean is −2, 1.5 or 5).
1997 #[test]
1998 fn the_paired_bootstrap_takes_each_rank_from_the_sorted_means() {
1999 let (low, high) = paired_bootstrap_interval(&[-2.0, 5.0], 0.95, 2, 3).expect("an interval");
2000 assert!(low < high, "{low}, {high}");
2001 for end in [low, high] {
2002 assert!([-2.0, 1.5, 5.0].contains(&end), "{end}");
2003 }
2004 }
2005
2006 /// Same differences and seed, same interval bit for bit; another seed moves it a little.
2007 #[test]
2008 fn the_paired_bootstrap_is_its_seeds() {
2009 let differences = [-3.1, 0.4, 2.2, -0.7, 5.3, 1.9, -1.2, 0.8, -2.6, 4.4];
2010 let one = paired_bootstrap_interval(&differences, 0.95, 2_000, 11).expect("an interval");
2011 let again = paired_bootstrap_interval(&differences, 0.95, 2_000, 11).expect("an interval");
2012 let other = paired_bootstrap_interval(&differences, 0.95, 2_000, 12).expect("an interval");
2013 assert_eq!(
2014 (one.0.to_bits(), one.1.to_bits()),
2015 (again.0.to_bits(), again.1.to_bits())
2016 );
2017 assert_ne!(one, other);
2018 assert!(one.0 < 0.74 && 0.74 < one.1, "{one:?} holds the mean");
2019 }
2020
2021 /// On 2,000 draws of 40 differences from a symmetric distribution about 0.3 (a uniform one, on
2022 /// a fixed stream), the 95% interval holds the center 92% to 96.5% of the time: the percentile
2023 /// interval's coverage on 40 is near its level. Against 95% the band runs about 6 standard
2024 /// errors of the share below and 3 above. Taking a 90% interval instead held it 89.25% of the
2025 /// time, outside the band (a probe, run once).
2026 #[test]
2027 fn the_paired_bootstrap_covers_near_its_level() {
2028 let mut draw = draws();
2029 let trials = 2_000;
2030 let mut held = 0_u32;
2031 for trial in 0..trials {
2032 let differences: Vec<f64> = (0..40).map(|_| 0.3 + draw() / 2_500.0).collect();
2033 let (low, high) =
2034 paired_bootstrap_interval(&differences, 0.95, 1_000, trial).expect("an interval");
2035 held += u32::from(low <= 0.3 && 0.3 <= high);
2036 }
2037 let share = f64::from(held) / 2_000.0;
2038 assert!((0.92..=0.965).contains(&share), "held {share}");
2039 }
2040}