Skip to main content

hpr_flightdata/readings/
day_air.rs

1//! The day's air, as the log records it at the pad (#1259): whether the bounds' allowance for the
2//! day's air, [`AIR_TEMPERATURE_SPREAD_K`] from the 1976 US Standard Atmosphere, covers it.
3//!
4//! **Why it matters.** A barometric logger turns pressure into height by the standard
5//! atmosphere. By the hypsometric equation, `dz = −(R T/g) dp/p`, the height between two
6//! pressures goes as the air's temperature between them. So a height read by the standard
7//! atmosphere is `T_std/T` of the true one over the layer it spans, and off by `ΔT/T_std` of
8//! itself when the day's air is `ΔT` off the standard (`docs/research/altimeter-height-formulas.md`;
9//! U.S. Standard Atmosphere, 1976, NOAA-S/T 76-1562). A speed or a rate of descent, a height over a
10//! time, is off by the same share. Each bound holds [`TEMPERATURE_SHARE`] for it: 15 K over the
11//! coldest standard air below 20 km. On a hot day the heights read low, and so do the speeds and
12//! the rates; on a cold day, high. Standard air is 15 °C less 6.5 °C per km of height, so 15 K
13//! over is 30 °C at a sea-level field and about 22 °C at a 1,190 m one; past that, the bound may
14//! not hold.
15//!
16//! **What is read.** The day's offset is the log's temperature at the pad less the standard
17//! atmosphere's at the pad's height above sea level, `ΔT = T_log − T_std(z_pad)`. The log's
18//! temperature at the pad is the median of its temperature samples over the span the readings take
19//! the pad from ([`super::Readings::pad_altitude_m`]). The pad's height above sea level comes, in
20//! this order, from a pressure channel over the same span, turned into a height by the standard
21//! atmosphere (its pressure altitude: the height the standard atmosphere's own temperature is
22//! read at, as the logger's conversion reads it); from a barometric altitude channel above sea
23//! level; or from the ground elevation the logger states. With none of these, or no temperature
24//! channel, there is nothing to compare, and no [`DayAir`]. Nor with a temperature channel that
25//! can't be the air: one whose finite samples are all one value, and that value a unit's zero read
26//! as kelvin ([`UNIT_ZEROS_K`]), as a logger with no sensor writes, or one outside
27//! [`LOGGED_AIR_RANGE_K`]. A channel of one other value is read: a logger quantized to a degree
28//! can read one value over a short log.
29//!
30//! **The size**, stated on the unflattering side: `|ΔT| / T_std(z_top)`, the standard temperature
31//! at the apogee's height above sea level, the coldest standard air the climb spans, so the
32//! largest share the layer's mean temperature allows. With no apogee read, or one that is only a
33//! floor (the log ends on the climb, so the top lay higher), the coldest standard air below 20 km,
34//! 216.65 K, stands for it.
35//!
36//! **A note, not a wider bound.** A logger's temperature channel is often the board's or the
37//! sensor die's, warmed in the electronics bay by the sun and the electronics, not the air's
38//! ([`crate::log::FlightLog::temperature_k`]). Widening every bound to it would move the bounds,
39//! and the 90% intervals calibrated on the synthetic flights (#1055, #1061), by a figure that may
40//! be the bay's. So the readings keep their bounds, and when the logged offset passes
41//! [`AIR_TEMPERATURE_SPREAD_K`], the command line prints a note beside each reading the day's air
42//! moves, with its size, for the flyer to weigh.
43
44use hpr_atmos::Ussa76;
45use serde::{Deserialize, Serialize};
46
47use super::{AIR_TEMPERATURE_SPREAD_K, MAX_INTERVAL_S};
48use crate::filter::median;
49use crate::log::{FlightLog, Quantity};
50
51#[cfg(doc)]
52use super::TEMPERATURE_SHARE;
53
54/// The coldest temperature in the 1976 standard atmosphere below 20 km, K: the tropopause's.
55pub const COLDEST_STANDARD_K: f64 = 216.65;
56
57/// The range a logged temperature must fall in to be taken for the pad's air, K: −100 °C to
58/// +100 °C, well past the coldest and hottest air on record (−89.2 °C at Vostok, 56.7 °C at Death
59/// Valley, WMO's archive of weather extremes), and room for a sun-warmed bay. A channel outside it
60/// isn't the air, and gives no [`DayAir`]. It catches a column of zeros only in kelvin: the readers
61/// turn a column into kelvin first, so zeros in °C read 273.15 K and in °F 255.37 K, both inside
62/// it. Those are refused apart from the range, by [`UNIT_ZEROS_K`].
63pub const LOGGED_AIR_RANGE_K: (f64, f64) = (173.15, 373.15);
64
65/// A unit's zero read as kelvin, K: 0 K, 0 °C (273.15 K) and 0 °F ((0 − 32) × 5/9 + 273.15 =
66/// 255.372 K). A temperature channel whose finite samples are all one value, and that value
67/// within [`UNIT_ZERO_TOLERANCE_K`] of one of these, is taken for a logger with no sensor writing
68/// zeros, and gives no [`DayAir`]. A channel of one other value is read as the air.
69pub const UNIT_ZEROS_K: [f64; 3] = [0.0, 273.15, (0.0 - 32.0) * 5.0 / 9.0 + 273.15];
70
71/// How near a constant channel's value must lie to one of [`UNIT_ZEROS_K`] to be refused, K.
72pub const UNIT_ZERO_TOLERANCE_K: f64 = 0.01;
73
74/// The 1976 standard atmosphere's temperature at a height above sea level, K: 288.15 K at sea
75/// level, less its 6.5 K/km lapse to 11 km, then its isothermal 216.65 K, taken to hold above
76/// it (U.S. Standard Atmosphere, 1976, table 4). Heights here are geopotential, as a pressure
77/// altitude is; below 11 km the two differ by under 0.2%.
78pub(crate) fn standard_temperature_k(height_msl_m: f64) -> f64 {
79    (288.15 - 0.0065 * height_msl_m.min(11_000.0)).max(COLDEST_STANDARD_K)
80}
81
82with_all! {
83/// Where the pad's height above sea level came from.
84#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
85#[serde(rename_all = "snake_case")]
86#[non_exhaustive]
87pub enum PadHeightFrom {
88    /// A pressure channel over the pad's span, turned into a height by the 1976 standard
89    /// atmosphere: the pad's pressure altitude.
90    Pressure,
91    /// A barometric altitude channel above sea level, over the pad's span.
92    AltitudeMsl,
93    /// The ground elevation the logger states.
94    StatedGroundElevation,
95}
96}
97
98/// The day's air at the pad, from the log's own temperature, against the standard atmosphere's.
99#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
100pub struct DayAir {
101    /// The log's temperature at the pad, K: the median of its samples over the pad's span.
102    pub pad_temperature_k: f64,
103    /// The temperature channel it came from, as the file names it.
104    pub temperature_column: String,
105    /// The pad's height above sea level, m.
106    pub pad_height_msl_m: f64,
107    /// Where that height came from.
108    pub pad_height_from: PadHeightFrom,
109    /// The 1976 standard atmosphere's temperature at the pad's height, K.
110    pub pad_standard_temperature_k: f64,
111    /// The day's offset from the standard at the pad, K: the log's temperature less the
112    /// standard's; positive on a hot day, which reads barometric heights, speeds and rates low.
113    pub offset_k: f64,
114    /// Whether the bounds' allowance for the day's air covers the offset: its size no more than
115    /// [`AIR_TEMPERATURE_SPREAD_K`].
116    pub covered: bool,
117    /// The standard temperature the share is taken at, K: at the apogee's height above sea level,
118    /// the coldest standard air the climb spans; [`COLDEST_STANDARD_K`] with no apogee read, or an
119    /// apogee that is only a floor.
120    pub top_standard_temperature_k: f64,
121    /// The share of a barometric height, speed or rate of descent the day's air may move it by,
122    /// `|ΔT| / T_std(z_top)` (the hypsometric equation): up from the reading on a hot day, down on
123    /// a cold one. Against the bounds' own [`TEMPERATURE_SHARE`].
124    pub share: f64,
125}
126
127impl DayAir {
128    /// Whether the day is hotter than the standard: the true heights, speeds and rates then lie
129    /// above the readings.
130    #[must_use]
131    pub fn is_hot(&self) -> bool {
132        self.offset_k > 0.0
133    }
134
135    /// The share taken at the top of a climb `top_height_m` above the pad.
136    pub(crate) fn set_top(&mut self, top_height_m: f64) {
137        let top = standard_temperature_k(self.pad_height_msl_m + top_height_m.max(0.0));
138        self.top_standard_temperature_k = top;
139        self.share = self.offset_k.abs() / top;
140    }
141}
142
143/// The day's air at the pad, from the log's temperature over the pad's span `[from, to]` s, or
144/// `None` where the log has no temperature, no height above sea level for the pad, or a
145/// temperature that can't be the air's: one value throughout the log, that value a unit's zero
146/// ([`UNIT_ZEROS_K`]), or outside [`LOGGED_AIR_RANGE_K`].
147pub(crate) fn day_air(log: &FlightLog, pad_span_s: (f64, f64)) -> Option<DayAir> {
148    let (temperature_column, pad_temperature_k) = pad_temperature(log, pad_span_s)?;
149    let (pad_height_msl_m, pad_height_from) = pad_height(log, pad_span_s)?;
150    let pad_standard_temperature_k = standard_temperature_k(pad_height_msl_m);
151    let offset_k = pad_temperature_k - pad_standard_temperature_k;
152    Some(DayAir {
153        pad_temperature_k,
154        temperature_column,
155        pad_height_msl_m,
156        pad_height_from,
157        pad_standard_temperature_k,
158        offset_k,
159        covered: offset_k.abs() <= AIR_TEMPERATURE_SPREAD_K,
160        top_standard_temperature_k: COLDEST_STANDARD_K,
161        share: offset_k.abs() / COLDEST_STANDARD_K,
162    })
163}
164
165/// The log's temperature at the pad, K, and the column it came from: the first temperature
166/// channel, or the record's own temperature on its clock. `None` where that channel's finite
167/// samples are all one value over the whole log and that value a unit's zero ([`UNIT_ZEROS_K`]):
168/// a column of zeros written by a logger with no sensor, which may read as air in range once
169/// turned into kelvin.
170fn pad_temperature(log: &FlightLog, span: (f64, f64)) -> Option<(String, f64)> {
171    let (column, time_s, values) = match log.channels_of(Quantity::Temperature).next() {
172        Some(channel) => (
173            channel.column.clone(),
174            channel.time_s.as_slice(),
175            channel.values.as_slice(),
176        ),
177        None => (
178            "temperature".to_owned(),
179            log.time_s.as_slice(),
180            log.temperature_k.as_deref()?,
181        ),
182    };
183    if is_unit_zero_column(time_s, values) {
184        return None;
185    }
186    let value = over_span(time_s, values, span)?;
187    (LOGGED_AIR_RANGE_K.0..=LOGGED_AIR_RANGE_K.1)
188        .contains(&value)
189        .then_some((column, value))
190}
191
192/// Whether a channel's samples, those with a finite time and value as [`over_span`] takes them,
193/// are all one value, and that value within [`UNIT_ZERO_TOLERANCE_K`] of a unit's zero.
194fn is_unit_zero_column(time_s: &[f64], values: &[f64]) -> bool {
195    let mut finite = time_s
196        .iter()
197        .zip(values)
198        .filter(|(t, v)| t.is_finite() && v.is_finite())
199        .map(|(_, v)| *v);
200    finite.next().is_some_and(|first| {
201        UNIT_ZEROS_K
202            .iter()
203            .any(|zero| (first - zero).abs() <= UNIT_ZERO_TOLERANCE_K)
204            && finite.all(|value| value == first)
205    })
206}
207
208/// The pad's height above sea level, m, and where it came from.
209fn pad_height(log: &FlightLog, span: (f64, f64)) -> Option<(f64, PadHeightFrom)> {
210    let pressure = log
211        .channels_of(Quantity::Pressure)
212        .next()
213        .and_then(|channel| {
214            let pressure_pa = over_span(&channel.time_s, &channel.values, span)?;
215            Ussa76::standard().pressure_altitude_m(pressure_pa).ok()
216        });
217    let msl = || {
218        log.channels_of(Quantity::AltitudeMsl)
219            .next()
220            .and_then(|channel| over_span(&channel.time_s, &channel.values, span))
221    };
222    pressure
223        .map(|height| (height, PadHeightFrom::Pressure))
224        .or_else(|| msl().map(|height| (height, PadHeightFrom::AltitudeMsl)))
225        .or_else(|| {
226            log.stated
227                .ground_elevation_msl_m
228                .map(|height| (height, PadHeightFrom::StatedGroundElevation))
229        })
230        .filter(|(height, _)| height.is_finite())
231}
232
233/// The median of a channel's finite samples within `[from, to]` s; with none there, its finite
234/// sample nearest the span, if within [`MAX_INTERVAL_S`] of it, as a channel sampled more slowly
235/// than the track may hold none on a short pad.
236fn over_span(time_s: &[f64], values: &[f64], (from, to): (f64, f64)) -> Option<f64> {
237    // A span the wrong way round, or not a number, holds no time.
238    if from.partial_cmp(&to).is_none_or(std::cmp::Ordering::is_gt) {
239        return None;
240    }
241    let finite = || {
242        time_s
243            .iter()
244            .zip(values)
245            .filter(|(t, v)| t.is_finite() && v.is_finite())
246    };
247    let mut within: Vec<f64> = finite()
248        .filter(|(t, _)| (from..=to).contains(*t))
249        .map(|(_, v)| *v)
250        .collect();
251    if let Some(value) = median(&mut within) {
252        return Some(value);
253    }
254    finite()
255        .map(|(t, v)| ((t - t.clamp(from, to)).abs(), *v))
256        .filter(|(gap, _)| *gap <= MAX_INTERVAL_S)
257        .min_by(|a, b| a.0.total_cmp(&b.0))
258        .map(|(_, v)| v)
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264    use crate::log::{Channel, LogFormat, Stated};
265    use crate::readings::{Reading, Readings, TEMPERATURE_SHARE, read};
266    use hpr_core::gravity::STANDARD_GRAVITY_MPS2;
267
268    const DT: f64 = 0.05;
269    /// An invented field's height above sea level, m.
270    const FIELD_M: f64 = 1_190.0;
271    /// The invented flight's drogue and main rates, m/s, and the main's opening height, m.
272    const DROGUE_M_S: f64 = 25.0;
273    const MAIN_M_S: f64 = 6.0;
274    const MAIN_AT_M: f64 = 200.0;
275
276    /// An invented flight's true height above the pad, m, at `t` s: on the pad to 1 s, 60 m/s²
277    /// for 2 s (120 m/s, 120 m), a vacuum coast to its top, 854.2 m at 15.24 s, then down under a
278    /// drogue at 25 m/s to 200 m and a main at 6 m/s to the pad.
279    fn flight(t: f64) -> f64 {
280        let g = STANDARD_GRAVITY_MPS2;
281        let (burn_s, accel) = (2.0, 60.0);
282        let burnout_v = accel * burn_s;
283        let burnout_h = 0.5 * accel * burn_s * burn_s;
284        let top_s = 1.0 + burn_s + burnout_v / g;
285        let top_m = burnout_h + burnout_v * burnout_v / (2.0 * g);
286        let main_s = top_s + (top_m - MAIN_AT_M) / DROGUE_M_S;
287        if t <= 1.0 {
288            0.0
289        } else if t < 1.0 + burn_s {
290            0.5 * accel * (t - 1.0).powi(2)
291        } else if t < top_s {
292            let c = t - 1.0 - burn_s;
293            burnout_h + burnout_v * c - 0.5 * g * c * c
294        } else if t < main_s {
295            top_m - DROGUE_M_S * (t - top_s)
296        } else {
297            (MAIN_AT_M - MAIN_M_S * (t - main_s)).max(0.0)
298        }
299    }
300
301    /// The flight's true top, m above the pad.
302    fn true_top_m() -> f64 {
303        let v = 120.0;
304        120.0 + v * v / (2.0 * STANDARD_GRAVITY_MPS2)
305    }
306
307    /// A log of the flight from a field [`FIELD_M`] up, on a day `offset_k` off the standard
308    /// atmosphere at every height (the hydrostatic air of [`Ussa76::with_offset`], sea-level
309    /// pressure standard): a pressure channel and a temperature channel reading the air.
310    fn day_log(offset_k: f64) -> FlightLog {
311        let day = Ussa76::with_offset(offset_k, 101_325.0).unwrap();
312        let times: Vec<f64> = (0..)
313            .map(|i| f64::from(i) * DT)
314            .take_while(|t| *t <= 90.0)
315            .collect();
316        let air: Vec<_> = times
317            .iter()
318            .map(|t| day.sample(FIELD_M + flight(*t)).unwrap().air)
319            .collect();
320        FlightLog {
321            format: LogFormat::GenericTable,
322            logger: "invented".to_owned(),
323            serial_number: None,
324            firmware: None,
325            flight_number: None,
326            stated: Stated::default(),
327            time_s: Vec::new(),
328            altitude_m: Vec::new(),
329            vertical_speed_m_s: None,
330            temperature_k: None,
331            battery_v: None,
332            channels: vec![
333                Channel::new(
334                    "Pressure (Pa)",
335                    Quantity::Pressure,
336                    times.clone(),
337                    air.iter().map(|a| a.pressure_pa).collect(),
338                ),
339                Channel::new(
340                    "Temp (K)",
341                    Quantity::Temperature,
342                    times,
343                    air.iter().map(|a| a.temperature_k).collect(),
344                ),
345            ],
346            events: Vec::new(),
347            notes: Vec::new(),
348        }
349    }
350
351    /// The offset and share the module's rule gives on [`day_log`], worked here from the day's
352    /// air at the field: the pad's pressure altitude, the standard's temperature there and at
353    /// the read apogee's height above sea level.
354    fn expected(offset_k: f64, apogee_m: f64) -> (f64, f64) {
355        let day = Ussa76::with_offset(offset_k, 101_325.0).unwrap();
356        let pad = day.sample(FIELD_M).unwrap().air;
357        let pad_msl = Ussa76::standard()
358            .pressure_altitude_m(pad.pressure_pa)
359            .unwrap();
360        let offset = pad.temperature_k - (288.15 - 0.0065 * pad_msl);
361        let top = 288.15 - 0.0065 * (pad_msl + apogee_m);
362        (offset, offset.abs() / top)
363    }
364
365    fn uncovered(readings: &Readings) -> &DayAir {
366        let air = readings.day_air.as_ref().expect("the day's air");
367        assert!(!air.covered, "{air:?}");
368        air
369    }
370
371    /// A pad 30 K over standard at a 1,190 m field (#1259): the note fires, says the true values
372    /// lie above the readings, and its share is `|ΔT| / T_std` at the apogee's height above sea
373    /// level, worked here from the day's air. The truth lies past the reading plus its bound, as
374    /// the issue found, and within the reading plus the note's share.
375    #[test]
376    fn a_hot_day_past_the_allowance_is_noted_with_its_size() {
377        let readings = read(&day_log(30.0));
378        let apogee = *readings.apogee.value().expect("an apogee");
379        let air = uncovered(&readings);
380        assert!(air.is_hot());
381        assert_eq!(air.pad_height_from, PadHeightFrom::Pressure);
382        assert_eq!(air.temperature_column, "Temp (K)");
383        let (offset, share) = expected(30.0, apogee.height_m);
384        assert!(
385            (air.offset_k - offset).abs() < 1e-9,
386            "{air:?} against {offset}"
387        );
388        assert!(offset > 25.0, "{offset}");
389        assert!((air.share - share).abs() < 1e-12, "{air:?} against {share}");
390        assert!(air.share > TEMPERATURE_SHARE, "{air:?}");
391        // The issue's finding: the truth lies past the bound.
392        let truth = true_top_m();
393        assert!(
394            truth > apogee.height_m + apogee.bound_m,
395            "{truth} {apogee:?}"
396        );
397        // And within the note's share above the reading.
398        assert!(
399            truth <= apogee.height_m * (1.0 + air.share),
400            "{truth} {} {}",
401            apogee.height_m,
402            air.share
403        );
404        // The main's steady rate likewise, read from its opening to landing.
405        let Reading::Read(main) = &readings.main_descent else {
406            panic!("{:?}", readings.main_descent);
407        };
408        assert!(main.rate_m_s < MAIN_M_S, "{main:?}");
409        assert!(MAIN_M_S <= main.rate_m_s * (1.0 + air.share), "{main:?}");
410    }
411
412    /// A pad 30 K under standard: the note fires the other way, the true values below the
413    /// readings, by the same rule.
414    #[test]
415    fn a_cold_day_past_the_allowance_is_noted_the_other_way() {
416        let readings = read(&day_log(-30.0));
417        let apogee = *readings.apogee.value().expect("an apogee");
418        let air = uncovered(&readings);
419        assert!(!air.is_hot());
420        let (offset, share) = expected(-30.0, apogee.height_m);
421        assert!(offset < -25.0, "{offset}");
422        assert!(
423            (air.offset_k - offset).abs() < 1e-9,
424            "{air:?} against {offset}"
425        );
426        assert!((air.share - share).abs() < 1e-12, "{air:?} against {share}");
427        let truth = true_top_m();
428        assert!(
429            truth < apogee.height_m - apogee.bound_m,
430            "{truth} {apogee:?}"
431        );
432        assert!(
433            truth >= apogee.height_m * (1.0 - air.share),
434            "{truth} {} {}",
435            apogee.height_m,
436            air.share
437        );
438    }
439
440    /// A day 10 K over standard is within the allowance: the day's air is read, and covered.
441    #[test]
442    fn a_day_within_the_allowance_is_covered() {
443        let readings = read(&day_log(10.0));
444        let air = readings.day_air.as_ref().expect("the day's air");
445        assert!(air.covered, "{air:?}");
446        assert!(air.offset_k > 5.0 && air.offset_k < 10.0, "{air:?}");
447    }
448
449    /// A temperature with no pressure, no altitude above sea level and no stated ground
450    /// elevation has nothing to compare it with: no day's air, and the readings as before.
451    #[test]
452    fn a_temperature_with_no_height_above_sea_level_gives_none() {
453        let mut log = day_log(30.0);
454        let pressure = log.channels.remove(0);
455        let air = Ussa76::standard();
456        let pad = air.pressure_altitude_m(pressure.values[0]).unwrap();
457        log.channels.insert(
458            0,
459            Channel::new(
460                "Altitude (m)",
461                Quantity::AltitudeAboveGround,
462                pressure.time_s.clone(),
463                pressure
464                    .values
465                    .iter()
466                    .map(|p| air.pressure_altitude_m(*p).unwrap() - pad)
467                    .collect(),
468            ),
469        );
470        let readings = read(&log);
471        assert!(readings.apogee.value().is_some(), "{:?}", readings.apogee);
472        assert_eq!(readings.day_air, None);
473        // With the logger's stated ground elevation, it is read again.
474        log.stated.ground_elevation_msl_m = Some(FIELD_M);
475        let air = read(&log).day_air.expect("the day's air");
476        assert_eq!(air.pad_height_from, PadHeightFrom::StatedGroundElevation);
477        assert!(!air.covered);
478    }
479
480    /// A temperature channel that can't be the air's, such as zeros from a logger with no sensor,
481    /// or no temperature at all, gives no day's air. Zeros in °C and °F reach the readings as
482    /// 273.15 K and 255.372 K, inside the range a temperature may take: refused for being one
483    /// value throughout, a unit's zero, not for the range. The same log's air, varying, is read.
484    #[test]
485    fn no_temperature_or_one_that_isnt_air_gives_none() {
486        let mut log = day_log(0.0);
487        assert!(read(&log).day_air.is_some());
488        for zeros in [0.0, 273.15, 255.372] {
489            log.channels[1].values.fill(zeros);
490            assert_eq!(read(&log).day_air, None, "{zeros}");
491        }
492        // One value throughout, gaps aside, is still one value.
493        log.channels[1].values[7] = f64::NAN;
494        assert_eq!(read(&log).day_air, None);
495        log.channels.truncate(1);
496        let readings = read(&log);
497        assert!(readings.apogee.value().is_some());
498        assert_eq!(readings.day_air, None);
499    }
500
501    /// A logger quantized to a degree can read one value over a short log: a constant 318.15 K
502    /// (113 °F) at the invented field isn't a unit's zero, so it is read, past the allowance and
503    /// hot, and not refused for being one value.
504    #[test]
505    fn a_constant_hot_reading_that_isnt_a_zero_is_read() {
506        let mut log = day_log(0.0);
507        log.channels[1].values.fill(318.15);
508        let readings = read(&log);
509        let air = uncovered(&readings);
510        assert!(air.is_hot(), "{air:?}");
511        assert_eq!(air.pad_temperature_k, 318.15);
512        assert!(air.share > TEMPERATURE_SHARE, "{air:?}");
513    }
514
515    /// The units' zeros: 0 °F is exactly (0 − 32) × 5/9 + 273.15 K.
516    #[test]
517    fn the_units_zeros_are_kelvin_celsius_and_fahrenheit() {
518        assert_eq!(UNIT_ZEROS_K[0], 0.0);
519        assert_eq!(UNIT_ZEROS_K[1], 273.15);
520        assert!((UNIT_ZEROS_K[2] - 255.372_222).abs() < 1e-6);
521    }
522
523    /// The allowance is strict at its edge: an offset of exactly 15 K is covered, and one a
524    /// hundredth of a kelvin past it, either way, isn't. On the record's own temperature and a
525    /// stated ground elevation.
526    #[test]
527    fn the_allowance_holds_to_its_edge() {
528        let ground = 600.0;
529        let standard = standard_temperature_k(ground);
530        for (offset, covered) in [
531            (AIR_TEMPERATURE_SPREAD_K, true),
532            (-AIR_TEMPERATURE_SPREAD_K, true),
533            (AIR_TEMPERATURE_SPREAD_K + 0.01, false),
534            (-AIR_TEMPERATURE_SPREAD_K - 0.01, false),
535        ] {
536            let channel = &day_log(0.0).channels[0];
537            let mut log = day_log(0.0);
538            log.channels.clear();
539            log.time_s.clone_from(&channel.time_s);
540            log.altitude_m = log.time_s.iter().map(|t| flight(*t)).collect();
541            // The pad's air, then half a kelvin cooler once the rocket is away: a varying
542            // channel, its median over the pad the pad's.
543            log.temperature_k = Some(
544                log.time_s
545                    .iter()
546                    .map(|t| standard + offset - if *t > 2.0 { 0.5 } else { 0.0 })
547                    .collect(),
548            );
549            log.stated.ground_elevation_msl_m = Some(ground);
550            let air = read(&log).day_air.expect("the day's air");
551            assert_eq!(air.temperature_column, "temperature");
552            assert_eq!(air.offset_k.abs() <= AIR_TEMPERATURE_SPREAD_K, covered);
553            assert_eq!(air.covered, covered, "{offset}: {air:?}");
554        }
555    }
556
557    /// A log that ends on the climb reads its apogee as a floor, which may lie below the top: the
558    /// share is then taken at the coldest standard air, 216.65 K, the larger, not at the floor's
559    /// height above sea level.
560    #[test]
561    fn a_floor_takes_the_share_at_the_coldest_standard_air() {
562        let mut log = day_log(30.0);
563        for channel in &mut log.channels {
564            let end = channel.time_s.iter().take_while(|t| **t <= 6.0).count();
565            channel.time_s.truncate(end);
566            channel.values.truncate(end);
567        }
568        let readings = read(&log);
569        let Reading::Read(apogee) = &readings.apogee else {
570            panic!("{:?}", readings.apogee);
571        };
572        assert!(apogee.is_floor, "{apogee:?}");
573        assert!(apogee.height_m > 300.0, "{apogee:?}");
574        let air = uncovered(&readings);
575        assert_eq!(air.top_standard_temperature_k, COLDEST_STANDARD_K);
576        assert_eq!(air.share, air.offset_k.abs() / COLDEST_STANDARD_K);
577    }
578
579    /// The standard atmosphere's temperature: 288.15 K at sea level, 6.5 K/km less up to 11 km,
580    /// then 216.65 K.
581    #[test]
582    fn the_standard_temperature_follows_the_1976_table() {
583        assert_eq!(standard_temperature_k(0.0), 288.15);
584        assert!((standard_temperature_k(1_000.0) - 281.65).abs() < 1e-12);
585        assert!((standard_temperature_k(11_000.0) - 216.65).abs() < 1e-12);
586        assert_eq!(standard_temperature_k(15_000.0), COLDEST_STANDARD_K);
587        let air = Ussa76::standard();
588        for height in [0.0, 1_190.0, 5_000.0, 10_000.0] {
589            let table = air.sample(height).unwrap().air.temperature_k;
590            // `sample` takes a geometric height; the two differ by under 0.2% below 11 km.
591            assert!(
592                (standard_temperature_k(height) - table).abs() < 0.11,
593                "{height}"
594            );
595        }
596    }
597}