Skip to main content

hpr_atmos/
profile.rs

1//! Custom atmospheres from soundings or forecasts: temperature, pressure, humidity and wind at
2//! levels, interpolated in height, with the offset standard atmosphere beyond them.
3//!
4//! **Geopotential height.** A profile knows its latitude `φ`, and works in WMO geopotential height
5//! `Z(z, φ)` ([`wmo_geopotential_from_geometric_m`]), whose gravity is the normal gravity at that
6//! latitude. Pressure then falls hydrostatically with the local gravity, which is up to 0.27%
7//! from the standard's `g₀` at the equator and poles.
8//!
9//! **Between two levels** `i` and `i + 1`, interpolation runs in `Z`, at fraction
10//! `t = (Z − Z_i)/(Z_{i+1} − Z_i)`:
11//!
12//! ```text
13//! T = T_i + t (T_{i+1} − T_i)
14//! U = U_i + t (U_{i+1} − U_i)                                      relative humidity
15//! ln P = ln P_i + ln(P_{i+1}/P_i) · ln(T/T_i) / ln(T_{i+1}/T_i)
16//! ```
17//!
18//! The pressure form is exact for a dry hydrostatic layer whose temperature is linear in
19//! geopotential height, as every layer of the standard atmosphere is, and it passes through both
20//! levels' pressures whatever the data. When the temperatures are equal it is log-linear.
21//!
22//! **Missing pressures** above the lowest level are filled in hydrostatically from the level
23//! below, with virtual temperature linear in geopotential height (the hypsometric equation, as in
24//! WMO-No. 8 (2023), Vol. I, eqs. 12.17 and 12.18):
25//!
26//! ```text
27//! ln(P_{i+1}/P_i) = −(g₀/R_d) (Z_{i+1} − Z_i) · ln(T_v,i+1/T_v,i) / (T_v,i+1 − T_v,i)
28//! ```
29//!
30//! **Beyond the levels** the profile continues as the 1976 standard atmosphere, offset to pass
31//! through the end level's temperature and pressure ([`Ussa76::anchored`]) and evaluated at the
32//! same geopotential height (the standard's geopotential `H` set equal to `Z`), and flags the
33//! sample.
34//! Below the lowest level the lowest level's relative humidity is held. Above the highest, its
35//! vapor mole fraction is held, capped at saturation, so a humid top does not put water into the
36//! cold stratosphere. The continued pressure is the dry standard's, so in humid air it falls up to
37//! `x_v (1 − M_v/M₀)` (about 1.6% at 30 °C and saturation) faster than hydrostatic balance; the
38//! samples are flagged.
39//!
40//! Heights are geometric above mean sea level. Soundings and forecasts usually report WMO
41//! geopotential height; convert it with [`geometric_from_wmo_geopotential_m`].
42
43use hpr_core::interp::Side;
44use serde::{Deserialize, Serialize};
45
46use crate::air::{AirSample, Atmosphere};
47use crate::error::{AtmosError, finite, positive};
48use crate::moist::{check_relative_humidity, moist_air_unchecked, saturation_vapor_pressure_pa};
49use crate::ussa76::{DRY_AIR_GAS_CONSTANT_J_PER_KG_K, Ussa76, geometric_from_geopotential_m};
50use crate::wind::{LayeredWind, WindInterpolation, WindLevel};
51use hpr_core::gravity::STANDARD_GRAVITY_MPS2;
52
53/// Iterations of the hydrostatic fill with humidity: the virtual temperature depends on the
54/// pressure being solved for only through `e/p`, a few percent at most, so each iteration gains
55/// about two digits.
56const FILL_ITERATIONS: usize = 8;
57
58/// One level of a sounding or forecast profile.
59#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
60#[serde(deny_unknown_fields)]
61pub struct SoundingLevel {
62    /// Geometric height above mean sea level, m.
63    pub height_msl_m: f64,
64    /// Temperature, K.
65    pub temperature_k: f64,
66    /// Pressure, Pa. Required on the lowest level; filled in hydrostatically where omitted above.
67    #[serde(default)]
68    pub pressure_pa: Option<f64>,
69    /// Relative humidity with respect to liquid water, as a fraction in `[0, 1]`. Give it on every
70    /// level or on none; without it the air is dry.
71    #[serde(default)]
72    pub relative_humidity: Option<f64>,
73    /// Wind speed, m/s. Give it with a direction, on every level or on none.
74    #[serde(default)]
75    pub wind_speed_m_s: Option<f64>,
76    /// Direction the wind blows from, clockwise from true north, rad.
77    #[serde(default)]
78    pub wind_direction_from_rad: Option<f64>,
79}
80
81/// An atmosphere built from a sounding or a forecast profile.
82///
83/// It serializes as its levels as given, its latitude and its wind interpolation, and rebuilds
84/// (and re-checks) everything else when deserialized.
85#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
86#[serde(try_from = "SoundingProfileData", into = "SoundingProfileData")]
87pub struct SoundingProfile {
88    levels: Vec<SoundingLevel>,
89    latitude_rad: f64,
90    wind_interpolation: WindInterpolation,
91    /// `γ_s(φ)/γ₄₅` and `R(φ)` of WMO-No. 8 eq. 12.16 at the profile's latitude.
92    gravity_ratio: f64,
93    radius_m: f64,
94    heights_m: Vec<f64>,
95    /// WMO geopotential height of each level, gpm.
96    geopotentials_m: Vec<f64>,
97    temperatures_k: Vec<f64>,
98    pressures_pa: Vec<f64>,
99    /// Relative humidity per level; empty for dry air.
100    humidities: Vec<f64>,
101    below: Ussa76,
102    above: Ussa76,
103    /// Vapor mole fraction at the highest level.
104    top_vapor_fraction: f64,
105    wind: Option<LayeredWind>,
106}
107
108#[derive(Serialize, Deserialize)]
109#[serde(deny_unknown_fields)]
110struct SoundingProfileData {
111    levels: Vec<SoundingLevel>,
112    latitude_rad: f64,
113    #[serde(default)]
114    wind_interpolation: WindInterpolation,
115    /// The program that wrote the file, which `hpr weather --output` names beside the profile
116    /// (ADR-174): read past, as it says nothing about the air.
117    #[serde(default, skip_serializing)]
118    #[expect(
119        dead_code,
120        reason = "read only so that the key is not refused as unknown"
121    )]
122    tool: Option<serde::de::IgnoredAny>,
123    /// The kind of figures the profile holds (`measured`, `forecast` or `reanalysis`), which
124    /// `hpr weather --output` writes after `tool` (#409): read past, as `tool` is.
125    #[serde(default, skip_serializing)]
126    #[expect(
127        dead_code,
128        reason = "read only so that the key is not refused as unknown"
129    )]
130    kind: Option<serde::de::IgnoredAny>,
131    /// How far to trust the profile, the note `hpr weather` ends with, written after `kind`
132    /// (#409): read past, as `tool` is.
133    #[serde(default, skip_serializing)]
134    #[expect(
135        dead_code,
136        reason = "read only so that the key is not refused as unknown"
137    )]
138    trust: Option<serde::de::IgnoredAny>,
139}
140
141impl TryFrom<SoundingProfileData> for SoundingProfile {
142    type Error = AtmosError;
143
144    fn try_from(data: SoundingProfileData) -> Result<Self, AtmosError> {
145        SoundingProfile::new(data.levels, data.latitude_rad, data.wind_interpolation)
146    }
147}
148
149impl From<SoundingProfile> for SoundingProfileData {
150    fn from(profile: SoundingProfile) -> Self {
151        SoundingProfileData {
152            levels: profile.levels,
153            latitude_rad: profile.latitude_rad,
154            wind_interpolation: profile.wind_interpolation,
155            tool: None,
156            kind: None,
157            trust: None,
158        }
159    }
160}
161
162/// Vapor pressure (Pa) for relative humidity `u` (none for dry air) at temperature `t`.
163fn vapor(humidity: Option<f64>, t: f64) -> f64 {
164    humidity.map_or(0.0, |u| u * saturation_vapor_pressure_pa(t))
165}
166
167/// Virtual temperature `T / (1 − x_v (1 − M_v/M₀))` from the moist-air state's density.
168fn virtual_temperature(t: f64, p: f64, e: f64) -> f64 {
169    let air = moist_air_unchecked(t, p, e);
170    p / (DRY_AIR_GAS_CONSTANT_J_PER_KG_K * air.density_kg_m3)
171}
172
173/// `ln(b/a)/(b − a)`, the reciprocal log-mean of two positive numbers, without cancellation when
174/// they are close.
175fn inverse_log_mean(a: f64, b: f64) -> f64 {
176    let r = (b - a) / a;
177    if r == 0.0 {
178        1.0 / a
179    } else {
180        r.ln_1p() / (r * a)
181    }
182}
183
184impl SoundingProfile {
185    /// A profile from `levels`, lowest first, measured at geodetic latitude `latitude_rad`, whose
186    /// wind (if the levels give one) interpolates as `wind_interpolation`.
187    ///
188    /// # Errors
189    ///
190    /// - [`AtmosError::NoLevels`] with no levels.
191    /// - [`AtmosError::HeightsNotIncreasing`] unless heights strictly increase.
192    /// - [`AtmosError::MissingBasePressure`] if the lowest level has no pressure.
193    /// - [`AtmosError::PressureNotDecreasing`] if a given pressure is not below the pressure of
194    ///   the level beneath it.
195    /// - [`AtmosError::IncompleteColumn`] if humidity or wind is given on some levels but not all,
196    ///   or a wind speed comes without its direction.
197    /// - [`AtmosError::Domain`] for a non-positive temperature or pressure, a relative humidity
198    ///   outside `[0, 1]`, a negative wind speed, a latitude beyond ±90°, a non-finite value, or
199    ///   end levels whose offset standard atmosphere is out of range.
200    pub fn new(
201        levels: Vec<SoundingLevel>,
202        latitude_rad: f64,
203        wind_interpolation: WindInterpolation,
204    ) -> Result<Self, AtmosError> {
205        let (gamma_s, radius_m) = wmo_gravity_and_radius(latitude_rad)?;
206        let gravity_ratio = gamma_s / GAMMA_45_MPS2;
207        let Some(first) = levels.first() else {
208            return Err(AtmosError::NoLevels);
209        };
210        let has_humidity = first.relative_humidity.is_some();
211        let has_wind = first.wind_speed_m_s.is_some() || first.wind_direction_from_rad.is_some();
212        if first.pressure_pa.is_none() {
213            return Err(AtmosError::MissingBasePressure);
214        }
215
216        let n = levels.len();
217        let mut heights_m = Vec::with_capacity(n);
218        let mut geopotentials_m = Vec::with_capacity(n);
219        let mut temperatures_k = Vec::with_capacity(n);
220        let mut humidities = Vec::with_capacity(if has_humidity { n } else { 0 });
221        let mut wind_levels = Vec::with_capacity(if has_wind { n } else { 0 });
222        for (index, level) in levels.iter().enumerate() {
223            let z = finite("sounding level height (m)", level.height_msl_m)?;
224            if heights_m.last().is_some_and(|&previous| z <= previous) {
225                return Err(AtmosError::HeightsNotIncreasing { index });
226            }
227            heights_m.push(z);
228            geopotentials_m.push(wmo_geopotential(gravity_ratio, radius_m, z)?);
229            temperatures_k.push(positive("sounding temperature (K)", level.temperature_k)?);
230            if let Some(p) = level.pressure_pa {
231                positive("sounding pressure (Pa)", p)?;
232            }
233            match (has_humidity, level.relative_humidity) {
234                (true, Some(u)) => humidities.push(check_relative_humidity(u)?),
235                (false, None) => {}
236                _ => {
237                    return Err(AtmosError::IncompleteColumn {
238                        index,
239                        column: "relative humidity",
240                    });
241                }
242            }
243            match (
244                has_wind,
245                level.wind_speed_m_s,
246                level.wind_direction_from_rad,
247            ) {
248                (true, Some(speed), Some(direction)) => wind_levels.push(WindLevel {
249                    height_msl_m: z,
250                    speed_m_s: speed,
251                    direction_from_rad: direction,
252                }),
253                (false, None, None) => {}
254                _ => {
255                    return Err(AtmosError::IncompleteColumn {
256                        index,
257                        column: "wind speed and direction",
258                    });
259                }
260            }
261        }
262
263        let humidity_at = |i: usize| humidities.get(i).copied();
264        let mut pressures_pa: Vec<f64> = Vec::with_capacity(n);
265        for (i, level) in levels.iter().enumerate() {
266            let pressure = match (level.pressure_pa, pressures_pa.last()) {
267                (Some(p), Some(&below)) if p >= below => {
268                    return Err(AtmosError::PressureNotDecreasing {
269                        index: i,
270                        pressure_pa: p,
271                        below_pa: below,
272                    });
273                }
274                (Some(p), _) => p,
275                (None, Some(&below)) => {
276                    let (t0, t1) = (temperatures_k[i - 1], temperatures_k[i]);
277                    let dh = geopotentials_m[i] - geopotentials_m[i - 1];
278                    let tv0 = virtual_temperature(t0, below, vapor(humidity_at(i - 1), t0));
279                    let k = STANDARD_GRAVITY_MPS2 / DRY_AIR_GAS_CONSTANT_J_PER_KG_K * dh;
280                    let mut p = below * (-k * inverse_log_mean(t0, t1)).exp();
281                    if has_humidity {
282                        for _ in 0..FILL_ITERATIONS {
283                            let tv1 = virtual_temperature(t1, p, vapor(humidity_at(i), t1));
284                            p = below * (-k * inverse_log_mean(tv0, tv1)).exp();
285                        }
286                    }
287                    positive("filled sounding pressure (Pa)", p)?
288                }
289                // The first level's pressure was checked above.
290                (None, None) => return Err(AtmosError::MissingBasePressure),
291            };
292            pressures_pa.push(pressure);
293        }
294
295        let last = n - 1;
296        let below = Ussa76::anchored(
297            geometric_from_geopotential_m(geopotentials_m[0])?,
298            temperatures_k[0],
299            pressures_pa[0],
300        )?;
301        let above = Ussa76::anchored(
302            geometric_from_geopotential_m(geopotentials_m[last])?,
303            temperatures_k[last],
304            pressures_pa[last],
305        )?;
306        let top_vapor_fraction =
307            (vapor(humidity_at(last), temperatures_k[last]) / pressures_pa[last]).min(1.0);
308        let wind = if has_wind {
309            Some(LayeredWind::new(wind_levels, wind_interpolation)?)
310        } else {
311            None
312        };
313        Ok(SoundingProfile {
314            levels,
315            latitude_rad,
316            wind_interpolation,
317            gravity_ratio,
318            radius_m,
319            heights_m,
320            geopotentials_m,
321            temperatures_k,
322            pressures_pa,
323            humidities,
324            below,
325            above,
326            top_vapor_fraction,
327            wind,
328        })
329    }
330
331    /// The levels as given.
332    pub fn levels(&self) -> &[SoundingLevel] {
333        &self.levels
334    }
335
336    /// The geodetic latitude the profile was measured at, rad.
337    pub fn latitude_rad(&self) -> f64 {
338        self.latitude_rad
339    }
340
341    /// The pressure at each level, Pa, with omitted ones filled in.
342    pub fn pressures_pa(&self) -> &[f64] {
343        &self.pressures_pa
344    }
345
346    /// The profile's wind, if its levels give one.
347    pub fn wind(&self) -> Option<&LayeredWind> {
348        self.wind.as_ref()
349    }
350
351    /// The air at geometric height `height_msl_m` (see [`Atmosphere::air`]).
352    ///
353    /// # Errors
354    ///
355    /// [`AtmosError::Domain`] if the height is not finite, is at or below `−R(φ)`, or is so far
356    /// above the Earth that the standard atmosphere has no height for its geopotential.
357    pub fn sample(&self, height_msl_m: f64) -> Result<AirSample, AtmosError> {
358        let z = finite("height (m)", height_msl_m)?;
359        let n = self.heights_m.len();
360        let humidity = |i: usize| self.humidities.get(i).copied();
361        let geopotential = wmo_geopotential(self.gravity_ratio, self.radius_m, z)?;
362        if z < self.heights_m[0] {
363            let air = self
364                .below
365                .sample(geometric_from_geopotential_m(geopotential)?)?
366                .air;
367            let e = vapor(humidity(0), air.temperature_k);
368            return Ok(AirSample {
369                air: moist_air_unchecked(air.temperature_k, air.pressure_pa, e),
370                extrapolated: Some(Side::Below),
371            });
372        }
373        if z > self.heights_m[n - 1] {
374            let air = self
375                .above
376                .sample(geometric_from_geopotential_m(geopotential)?)?
377                .air;
378            let e = (self.top_vapor_fraction * air.pressure_pa)
379                .min(saturation_vapor_pressure_pa(air.temperature_k));
380            return Ok(AirSample {
381                air: moist_air_unchecked(air.temperature_k, air.pressure_pa, e),
382                extrapolated: Some(Side::Above),
383            });
384        }
385        // First level strictly above z, in 1..=n.
386        let upper = self.heights_m.partition_point(|&h| h <= z);
387        if upper >= n {
388            let t = self.temperatures_k[n - 1];
389            let e = vapor(humidity(n - 1), t);
390            return Ok(AirSample {
391                air: moist_air_unchecked(t, self.pressures_pa[n - 1], e),
392                extrapolated: None,
393            });
394        }
395        let i = upper - 1;
396        let (z0, z1) = (self.geopotentials_m[i], self.geopotentials_m[upper]);
397        let fraction = ((geopotential - z0) / (z1 - z0)).clamp(0.0, 1.0);
398        let (t0, t1) = (self.temperatures_k[i], self.temperatures_k[upper]);
399        let t = t0 + fraction * (t1 - t0);
400        let (p0, p1) = (self.pressures_pa[i], self.pressures_pa[upper]);
401        let r = (t1 - t0) / t0;
402        let shape = if r == 0.0 {
403            fraction
404        } else {
405            (fraction * r).ln_1p() / r.ln_1p()
406        };
407        let p = p0 * ((p1 / p0).ln() * shape).exp();
408        let e = match (humidity(i), humidity(upper)) {
409            (Some(u0), Some(u1)) => (u0 + fraction * (u1 - u0)) * saturation_vapor_pressure_pa(t),
410            _ => 0.0,
411        };
412        Ok(AirSample {
413            air: moist_air_unchecked(t, p, e),
414            extrapolated: None,
415        })
416    }
417}
418
419impl Atmosphere for SoundingProfile {
420    fn air(&self, height_msl_m: f64) -> Result<AirSample, AtmosError> {
421        self.sample(height_msl_m)
422    }
423}
424
425/// `γ₄₅ = 9.80665 m/s²`, the gravity that defines the geopotential meter.
426const GAMMA_45_MPS2: f64 = STANDARD_GRAVITY_MPS2;
427
428/// Eq. 12.15 with `γ_s(φ)/γ₄₅` and `R(φ)` already evaluated.
429fn wmo_geopotential(gravity_ratio: f64, radius_m: f64, height_m: f64) -> Result<f64, AtmosError> {
430    if height_m <= -radius_m {
431        return Err(AtmosError::Domain {
432            what: "geometric height (m)",
433            value: height_m,
434        });
435    }
436    Ok(gravity_ratio * radius_m * height_m / (radius_m + height_m))
437}
438
439/// `γ_s(φ)` and `R(φ)` of WMO-No. 8 (2023), Vol. I, eq. 12.16.
440fn wmo_gravity_and_radius(latitude_rad: f64) -> Result<(f64, f64), AtmosError> {
441    let phi = finite("latitude (rad)", latitude_rad)?;
442    if phi.abs() > std::f64::consts::FRAC_PI_2 {
443        return Err(AtmosError::Domain {
444            what: "latitude (rad)",
445            value: phi,
446        });
447    }
448    let s2 = phi.sin().powi(2);
449    let gamma_s = 9.780_325 * (1.0 + 0.001_931_85 * s2) / (1.0 - 0.006_694_35 * s2).sqrt();
450    let radius_m = 6_378_137.0 / (1.006_803 - 0.006_706 * s2);
451    Ok((gamma_s, radius_m))
452}
453
454/// WMO geopotential height `Z` (gpm) of geometric height `height_msl_m` at geodetic latitude
455/// `latitude_rad`, by WMO-No. 8 (2023), Vol. I, eqs. 12.15 and 12.16 (after Mahoney):
456///
457/// ```text
458/// Z = (γ_s(φ)/γ₄₅) · R(φ) z / (R(φ) + z)
459/// γ_s(φ) = 9.780325 (1 + 0.00193185 sin²φ) / (1 − 0.00669435 sin²φ)^½
460/// R(φ) = 6378.137 km / (1.006803 − 0.006706 sin²φ)
461/// ```
462///
463/// WMO puts 30 km at 29.7785 km of geopotential at the equator and 29.932 km at 80° N.
464///
465/// # Errors
466///
467/// [`AtmosError::Domain`] if a value is not finite, the latitude is beyond ±90°, or the height
468/// is at or below `−R(φ)`.
469pub fn wmo_geopotential_from_geometric_m(
470    height_msl_m: f64,
471    latitude_rad: f64,
472) -> Result<f64, AtmosError> {
473    let (gamma_s, radius) = wmo_gravity_and_radius(latitude_rad)?;
474    let z = finite("geometric height (m)", height_msl_m)?;
475    wmo_geopotential(gamma_s / GAMMA_45_MPS2, radius, z)
476}
477
478/// Geometric height above mean sea level of WMO geopotential height `geopotential_height_m`
479/// (gpm) at latitude `latitude_rad`: the inverse of [`wmo_geopotential_from_geometric_m`],
480/// `z = R Z′ / (R − Z′)` with `Z′ = Z γ₄₅/γ_s(φ)`.
481///
482/// # Errors
483///
484/// [`AtmosError::Domain`] if a value is not finite, the latitude is beyond ±90°, or `Z′` is at
485/// or above `R(φ)`.
486pub fn geometric_from_wmo_geopotential_m(
487    geopotential_height_m: f64,
488    latitude_rad: f64,
489) -> Result<f64, AtmosError> {
490    let (gamma_s, radius) = wmo_gravity_and_radius(latitude_rad)?;
491    let scaled =
492        finite("geopotential height (gpm)", geopotential_height_m)? * GAMMA_45_MPS2 / gamma_s;
493    if scaled >= radius {
494        return Err(AtmosError::Domain {
495            what: "geopotential height (gpm)",
496            value: geopotential_height_m,
497        });
498    }
499    Ok(radius * scaled / (radius - scaled))
500}
501
502#[cfg(test)]
503mod tests {
504    use hpr_core::gravity::NormalGravity;
505
506    use super::*;
507    use crate::moist::moist_air;
508    use crate::wind::Wind;
509
510    /// Spaceport America's latitude, for tests that don't care which latitude.
511    const LATITUDE_RAD: f64 = 32.99 * std::f64::consts::PI / 180.0;
512
513    fn level(z: f64, t: f64, p: Option<f64>, u: Option<f64>) -> SoundingLevel {
514        SoundingLevel {
515            height_msl_m: z,
516            temperature_k: t,
517            pressure_pa: p,
518            relative_humidity: u,
519            wind_speed_m_s: None,
520            wind_direction_from_rad: None,
521        }
522    }
523
524    fn profile_at(levels: Vec<SoundingLevel>, latitude_rad: f64) -> SoundingProfile {
525        SoundingProfile::new(levels, latitude_rad, WindInterpolation::default()).unwrap()
526    }
527
528    /// The standard atmosphere's geometric height at the WMO geopotential of `z`: where the
529    /// standard's air is the air a profile at `latitude_rad` continues with.
530    fn standard_height(z: f64, latitude_rad: f64) -> f64 {
531        geometric_from_geopotential_m(wmo_geopotential_from_geometric_m(z, latitude_rad).unwrap())
532            .unwrap()
533    }
534
535    /// `P(z₁)` by integrating `dP/dz = −ρ g` from `(z₀, P₀)` with the profile's own interpolated
536    /// temperature and humidity, by the second-order midpoint method on 20 000 steps. Gravity is
537    /// WGS 84 normal gravity at the profile's latitude (`hpr_core`'s Taylor form, independent of
538    /// the WMO geopotential formula), and density is evaluated at the running pressure, so the
539    /// integral uses neither the profile's geopotential nor its interpolated pressure.
540    fn integrate_pressure(profile: &SoundingProfile, z0: f64, p0: f64, z1: f64) -> f64 {
541        let gravity = NormalGravity::wgs84();
542        let steps = 20_000;
543        let dz = (z1 - z0) / f64::from(steps);
544        let vapor_pressure = |z: f64| {
545            // e from the profile's air: ρ R_d T / p = 1 − x_v (1 − M_v/M₀).
546            let air = profile.sample(z).unwrap().air;
547            let deficit = 1.0
548                - air.density_kg_m3 * DRY_AIR_GAS_CONSTANT_J_PER_KG_K * air.temperature_k
549                    / air.pressure_pa;
550            let x = deficit
551                / (1.0
552                    - crate::moist::WATER_VAPOR_MOLECULAR_WEIGHT_KG_PER_KMOL
553                        / crate::ussa76::SEA_LEVEL_MOLECULAR_WEIGHT_KG_PER_KMOL);
554            (air.temperature_k, x * air.pressure_pa)
555        };
556        let weight = |z: f64, p: f64| {
557            let (t, e) = vapor_pressure(z);
558            let g = gravity.taylor_mps2(profile.latitude_rad(), z).unwrap();
559            moist_air_unchecked(t, p, e.max(0.0)).density_kg_m3 * g
560        };
561        let mut p = p0;
562        for k in 0..steps {
563            let z = z0 + f64::from(k) * dz;
564            let half = p - 0.5 * dz * weight(z, p);
565            p -= dz * weight(z + 0.5 * dz, half);
566        }
567        p
568    }
569
570    /// Loft lesson L5: a sounding's measured temperatures (here a hot, dry-adiabatic afternoon
571    /// with an inversion aloft) replace the standard lapse from the field up, humidity lowers the
572    /// density, and the omitted pressures aloft follow hydrostatically from the field pressure.
573    #[test]
574    fn sounding_temperature_overrides_standard_lapse() {
575        let field = level(1400.0, 308.15, Some(85_500.0), Some(0.2));
576        let profile = profile_at(
577            vec![
578                field,
579                level(2400.0, 300.15, None, Some(0.15)),
580                level(3400.0, 301.15, None, Some(0.10)),
581            ],
582            LATITUDE_RAD,
583        );
584        let standard_lapse = Ussa76::anchored(1400.0, 308.15, 85_500.0).unwrap();
585
586        // Temperature follows the sounding: 8 K/km down to 2400 m, then a 1 K inversion. 2900 m is
587        // halfway in geometric height and 4e-5 past halfway in geopotential height.
588        let mid = profile.sample(2900.0).unwrap();
589        assert_eq!(mid.extrapolated, None);
590        let h = |z| wmo_geopotential_from_geometric_m(z, LATITUDE_RAD).unwrap();
591        let fraction = (h(2900.0) - h(2400.0)) / (h(3400.0) - h(2400.0));
592        assert!((fraction - 0.5 - 3.9e-5).abs() < 1e-6);
593        assert!((mid.air.temperature_k - (300.15 + fraction)).abs() < 1e-12);
594        let top = profile.sample(3400.0).unwrap().air;
595        assert!((top.temperature_k - 301.15).abs() < 1e-12);
596        let lapse_top = standard_lapse.sample(3400.0).unwrap().air;
597        assert!((lapse_top.temperature_k - (308.15 - 6.5 * 2.0)).abs() < 0.05);
598        assert!(top.temperature_k - lapse_top.temperature_k > 5.0);
599
600        // The filled pressures are hydrostatic for the sounding's temperatures and humidity. The
601        // fill takes virtual temperature linear in geopotential height, while the profile
602        // interpolates temperature and relative humidity linearly; vapor pressure is exponential
603        // in temperature, so the two differ by about 0.06 K mid-layer here, and the pressures by
604        // 1.1e-5 (a tenth of a meter of height). Dry air agrees to 2e-8 (next test).
605        for (z, p) in [
606            (2400.0, profile.pressures_pa()[1]),
607            (3400.0, profile.pressures_pa()[2]),
608        ] {
609            let integrated = integrate_pressure(&profile, 1400.0, 85_500.0, z);
610            assert!(
611                ((p - integrated) / integrated).abs() < 2e-5,
612                "{z}: {p} vs {integrated}"
613            );
614        }
615
616        // Humid air is lighter than dry air at the same temperature and pressure.
617        let dry = moist_air(top.temperature_k, top.pressure_pa, 0.0).unwrap();
618        let lighter = 1.0 - top.density_kg_m3 / dry.density_kg_m3;
619        assert!((0.0015..0.0035).contains(&lighter), "{lighter}");
620        // And the sounding's density at 3400 m differs from the standard-lapse guess by over 1%.
621        assert!((top.density_kg_m3 / lapse_top.density_kg_m3 - 1.0).abs() > 0.01);
622    }
623
624    /// Dry, the fill and the interpolation make the same assumption, so they agree with an
625    /// integration under WGS 84 normal gravity at the equator, mid-latitudes and the pole. The
626    /// bound is WMO eq. 12.16's rounded constants: its surface gravity is 3.4e-8 (equator) to
627    /// 5.2e-8 (pole) below WGS 84's, which over `ΔZ/H_s ≈ 0.23` is about 1e-8 in pressure.
628    #[test]
629    fn filled_pressures_are_hydrostatic_for_dry_air() {
630        for latitude_deg in [0.0_f64, 32.99, 90.0] {
631            let profile = profile_at(
632                vec![
633                    level(1400.0, 308.15, Some(85_500.0), None),
634                    level(2400.0, 300.15, None, None),
635                    level(3400.0, 301.15, None, None),
636                ],
637                latitude_deg.to_radians(),
638            );
639            for (z, p) in [
640                (2400.0, profile.pressures_pa()[1]),
641                (3400.0, profile.pressures_pa()[2]),
642            ] {
643                let integrated = integrate_pressure(&profile, 1400.0, 85_500.0, z);
644                assert!(
645                    ((p - integrated) / integrated).abs() < 2e-8,
646                    "{latitude_deg}° {z}: {p} vs {integrated}"
647                );
648            }
649        }
650    }
651
652    /// Gravity is 0.53% stronger at the poles than at the equator, so the same sounding's pressure
653    /// falls faster there. Over 2 km, about 0.23 scale heights at 293 K, that is
654    /// 0.53% × 0.23 = 0.12% lower.
655    #[test]
656    fn pressure_falls_faster_where_gravity_is_stronger() {
657        let levels = vec![
658            level(1400.0, 300.0, Some(85_500.0), None),
659            level(3400.0, 287.0, None, None),
660        ];
661        let equator = profile_at(levels.clone(), 0.0).pressures_pa()[1];
662        let pole = profile_at(levels, std::f64::consts::FRAC_PI_2).pressures_pa()[1];
663        let difference = pole / equator - 1.0;
664        assert!((-0.0014..-0.0011).contains(&difference), "{difference}");
665    }
666
667    /// Levels taken from the standard atmosphere, placed at the WMO heights of its geopotential
668    /// levels, reproduce it between them, because both are linear in geopotential: temperature to
669    /// rounding, and pressure and density to 1e-12.
670    #[test]
671    fn standard_levels_reproduce_the_standard_between_them() {
672        let standard = Ussa76::standard();
673        for latitude_deg in [0.0_f64, 45.0, 80.0] {
674            let latitude = latitude_deg.to_radians();
675            let heights: Vec<f64> = [0.0, 5_000.0, 11_000.0, 15_000.0, 20_000.0, 26_000.0]
676                .iter()
677                .map(|&geopotential| geometric_from_wmo_geopotential_m(geopotential, latitude))
678                .collect::<Result<_, _>>()
679                .unwrap();
680            let levels = heights
681                .iter()
682                .map(|&z| {
683                    let air = standard.sample(standard_height(z, latitude)).unwrap().air;
684                    level(z, air.temperature_k, Some(air.pressure_pa), None)
685                })
686                .collect();
687            let profile = profile_at(levels, latitude);
688            for z in heights
689                .iter()
690                .copied()
691                .chain([2_500.0, 8_000.0, 13_000.0, 17_500.0, 23_000.0])
692            {
693                let ours = profile.sample(z).unwrap().air;
694                let reference = standard.sample(standard_height(z, latitude)).unwrap().air;
695                assert!(
696                    (ours.temperature_k - reference.temperature_k).abs() < 1e-10,
697                    "{latitude_deg}° {z}"
698                );
699                for (a, b) in [
700                    (ours.pressure_pa, reference.pressure_pa),
701                    (ours.density_kg_m3, reference.density_kg_m3),
702                ] {
703                    assert!(
704                        ((a - b) / b).abs() < 1e-12,
705                        "{latitude_deg}° {z}: {a} vs {b}"
706                    );
707                }
708            }
709        }
710    }
711
712    /// A dry fill from sea level to the tropopause base (11 km of geopotential) gives the
713    /// standard's base pressure.
714    #[test]
715    fn hydrostatic_fill_matches_the_standard() {
716        let tropopause = geometric_from_wmo_geopotential_m(11_000.0, LATITUDE_RAD).unwrap();
717        let profile = profile_at(
718            vec![
719                level(0.0, 288.15, Some(101_325.0), None),
720                level(tropopause, 216.65, None, None),
721            ],
722            LATITUDE_RAD,
723        );
724        let p = profile.pressures_pa()[1];
725        let reference = Ussa76::standard()
726            .sample(geometric_from_geopotential_m(11_000.0).unwrap())
727            .unwrap()
728            .air
729            .pressure_pa;
730        assert!(
731            ((p - reference) / reference).abs() < 1e-12,
732            "{p} vs {reference}"
733        );
734    }
735
736    #[test]
737    fn beyond_the_levels_follows_the_offset_standard() {
738        let profile = profile_at(
739            vec![
740                level(500.0, 295.0, Some(95_000.0), Some(0.6)),
741                level(2_000.0, 288.0, Some(80_000.0), Some(1.0)),
742            ],
743            LATITUDE_RAD,
744        );
745        let top = profile.sample(2_000.0).unwrap().air;
746        let just_above = profile.sample(2_000.001).unwrap();
747        assert_eq!(just_above.extrapolated, Some(Side::Above));
748        assert!((just_above.air.temperature_k - top.temperature_k).abs() < 1e-4);
749        assert!((just_above.air.pressure_pa / top.pressure_pa - 1.0).abs() < 1e-6);
750        assert!((just_above.air.density_kg_m3 / top.density_kg_m3 - 1.0).abs() < 1e-5);
751        // Above, the standard lapse (6.5 K per geopotential km) continues from the top level.
752        let aloft = profile.sample(6_000.0).unwrap().air;
753        let h = |z| wmo_geopotential_from_geometric_m(z, LATITUDE_RAD).unwrap();
754        let expected = 288.0 - 0.0065 * (h(6_000.0) - h(2_000.0));
755        assert!((aloft.temperature_k - expected).abs() < 1e-9);
756        // The saturated top's vapor is capped at saturation in the cold air aloft.
757        let e_sat = saturation_vapor_pressure_pa(aloft.temperature_k);
758        let capped = moist_air(aloft.temperature_k, aloft.pressure_pa, e_sat).unwrap();
759        assert!((aloft.density_kg_m3 / capped.density_kg_m3 - 1.0).abs() < 1e-14);
760        // The continuation is the dry standard's pressure, so it is hydrostatic with the local
761        // gravity for dry air (to WMO's rounded gravity constants). With humid air it falls a
762        // little faster than hydrostatic: here, saturated at 288 K, 2.7e-4 low after 300 m.
763        let dry = profile_at(
764            vec![
765                level(500.0, 295.0, Some(95_000.0), None),
766                level(2_000.0, 288.0, Some(80_000.0), None),
767            ],
768            LATITUDE_RAD,
769        );
770        let integrated = integrate_pressure(&dry, 2_000.0, 80_000.0, 2_300.0);
771        let continued = dry.sample(2_300.0).unwrap().air.pressure_pa;
772        assert!(
773            (continued / integrated - 1.0).abs() < 1e-8,
774            "{continued} {integrated}"
775        );
776        let humid_integrated = integrate_pressure(&profile, 2_000.0, 80_000.0, 2_300.0);
777        let humid_continued = profile.sample(2_300.0).unwrap().air.pressure_pa;
778        let low = humid_continued / humid_integrated - 1.0;
779        assert!((-3e-4..-2.5e-4).contains(&low), "{low}");
780
781        let below = profile.sample(0.0).unwrap();
782        assert_eq!(below.extrapolated, Some(Side::Below));
783        assert!(below.air.pressure_pa > 95_000.0 && below.air.temperature_k > 295.0);
784        assert!(profile.sample(f64::NAN).is_err());
785    }
786
787    #[test]
788    fn a_single_level_is_an_anchored_standard_atmosphere() {
789        let profile = profile_at(
790            vec![level(1_000.0, 280.0, Some(90_000.0), None)],
791            LATITUDE_RAD,
792        );
793        let anchored =
794            Ussa76::anchored(standard_height(1_000.0, LATITUDE_RAD), 280.0, 90_000.0).unwrap();
795        assert_eq!(profile.sample(1_000.0).unwrap().extrapolated, None);
796        for z in [0.0, 3_000.0] {
797            let ours = profile.sample(z).unwrap().air;
798            let reference = anchored
799                .sample(standard_height(z, LATITUDE_RAD))
800                .unwrap()
801                .air;
802            assert!((ours.density_kg_m3 / reference.density_kg_m3 - 1.0).abs() < 1e-14);
803        }
804    }
805
806    #[test]
807    fn wind_columns_make_a_layered_wind() {
808        let mut low = level(0.0, 290.0, Some(100_000.0), None);
809        low.wind_speed_m_s = Some(3.0);
810        low.wind_direction_from_rad = Some(1.0);
811        let mut high = level(1_000.0, 283.0, None, None);
812        high.wind_speed_m_s = Some(9.0);
813        high.wind_direction_from_rad = Some(2.0);
814        let profile =
815            SoundingProfile::new(vec![low, high], LATITUDE_RAD, WindInterpolation::Components)
816                .unwrap();
817        let wind = profile.wind().unwrap();
818        assert_eq!(wind.interpolation(), WindInterpolation::Components);
819        assert_eq!(wind.levels().len(), 2);
820        assert!(wind.wind(500.0).is_ok());
821        let dry = profile_at(vec![level(0.0, 290.0, Some(100_000.0), None)], LATITUDE_RAD);
822        assert!(dry.wind().is_none());
823    }
824
825    #[test]
826    fn invalid_profiles_are_rejected() {
827        let ok = level(0.0, 290.0, Some(100_000.0), Some(0.5));
828        let build =
829            |levels| SoundingProfile::new(levels, LATITUDE_RAD, WindInterpolation::default());
830        assert!(matches!(build(vec![]), Err(AtmosError::NoLevels)));
831        assert!(matches!(
832            build(vec![level(0.0, 290.0, None, None)]),
833            Err(AtmosError::MissingBasePressure)
834        ));
835        assert!(matches!(
836            build(vec![ok, level(0.0, 280.0, None, Some(0.5))]),
837            Err(AtmosError::HeightsNotIncreasing { index: 1 })
838        ));
839        assert!(matches!(
840            build(vec![ok, level(100.0, 280.0, None, None)]),
841            Err(AtmosError::IncompleteColumn { index: 1, .. })
842        ));
843        let mut windless_direction = level(100.0, 280.0, None, Some(0.5));
844        windless_direction.wind_direction_from_rad = Some(0.0);
845        assert!(matches!(
846            build(vec![ok, windless_direction]),
847            Err(AtmosError::IncompleteColumn { index: 1, .. })
848        ));
849        // A pressure in hPa typed as Pa: the 850 at 1500 m is not below 101 325 Pa.
850        assert!(matches!(
851            build(vec![
852                level(0.0, 290.0, Some(101_325.0), None),
853                level(1_500.0, 280.0, Some(850.0), None),
854                level(3_000.0, 270.0, Some(70_000.0), None),
855            ]),
856            Err(AtmosError::PressureNotDecreasing { index: 2, .. })
857        ));
858        assert!(matches!(
859            build(vec![
860                level(0.0, 290.0, Some(101_325.0), None),
861                level(1_500.0, 280.0, Some(101_325.0), None),
862            ]),
863            Err(AtmosError::PressureNotDecreasing { index: 1, .. })
864        ));
865        // A given pressure above a filled one is caught too.
866        assert!(matches!(
867            build(vec![
868                level(0.0, 290.0, Some(101_325.0), None),
869                level(1_000.0, 283.0, None, None),
870                level(2_000.0, 276.0, Some(95_000.0), None),
871            ]),
872            Err(AtmosError::PressureNotDecreasing { index: 2, .. })
873        ));
874        assert!(build(vec![level(0.0, 290.0, Some(100_000.0), Some(1.5))]).is_err());
875        assert!(build(vec![level(0.0, -1.0, Some(100_000.0), None)]).is_err());
876        assert!(build(vec![level(0.0, 290.0, Some(0.0), None)]).is_err());
877        assert!(build(vec![level(f64::NAN, 290.0, Some(1e5), None)]).is_err());
878        let levels = vec![level(0.0, 290.0, Some(1e5), None)];
879        for latitude in [2.0, f64::NAN] {
880            assert!(
881                SoundingProfile::new(levels.clone(), latitude, WindInterpolation::default())
882                    .is_err()
883            );
884        }
885    }
886
887    #[test]
888    fn profiles_round_trip_through_json() {
889        let json = r#"{"latitude_rad":0.5758,"levels":[
890            {"height_msl_m":1400.0,"temperature_k":300.0,"pressure_pa":86000.0,
891             "relative_humidity":0.3,"wind_speed_m_s":4.0,"wind_direction_from_rad":3.0},
892            {"height_msl_m":3000.0,"temperature_k":290.0,
893             "relative_humidity":0.2,"wind_speed_m_s":10.0,"wind_direction_from_rad":3.5}
894        ]}"#;
895        let profile: SoundingProfile = serde_json::from_str(json).unwrap();
896        assert_eq!(
897            profile.wind_interpolation,
898            WindInterpolation::SpeedDirection
899        );
900        assert_eq!(profile.latitude_rad(), 0.5758);
901        let back: SoundingProfile =
902            serde_json::from_str(&serde_json::to_string(&profile).unwrap()).unwrap();
903        assert_eq!(back, profile);
904        let unknown = r#"{"latitude_rad":0.0,"levels":[{"height_msl_m":0.0,"temperature_k":300.0,"pressure_pa":1e5,"dew_point_k":280.0}]}"#;
905        assert!(serde_json::from_str::<SoundingProfile>(unknown).is_err());
906        let no_latitude =
907            r#"{"levels":[{"height_msl_m":0.0,"temperature_k":300.0,"pressure_pa":1e5}]}"#;
908        assert!(serde_json::from_str::<SoundingProfile>(no_latitude).is_err());
909    }
910
911    /// A profile `hpr weather --output` wrote opens with the program that wrote it, which reading
912    /// passes over: the same profile, and nothing written back.
913    #[test]
914    fn a_profile_reads_past_the_tool_that_wrote_it() {
915        let bare = r#"{"latitude_rad":0.5758,"levels":[
916            {"height_msl_m":1400.0,"temperature_k":300.0,"pressure_pa":86000.0}
917        ]}"#;
918        // This build's name and designation, the name builds wrote before ADR-199 renamed the
919        // program, and the designation builds wrote before ADR-198 retired it.
920        for (name, designation) in [
921            ("FusionSpace HPR", "FS-ACHERNAR · SW · TOOL 001"),
922            ("hpr-sim", "FS-ACHERNAR · SW · TOOL 001"),
923            ("hpr-sim", "FS · SW · TOOL 005"),
924        ] {
925            let json = bare.replacen(
926                '{',
927                &format!(
928                    r#"{{"tool":{{"name":"{name}","version":"0.1.0","designation":"{designation}"}},"#
929                ),
930                1,
931            );
932            let profile: SoundingProfile = serde_json::from_str(&json).unwrap();
933            assert_eq!(
934                profile,
935                serde_json::from_str(bare).unwrap(),
936                "{name}, {designation}"
937            );
938            assert!(!serde_json::to_string(&profile).unwrap().contains("tool"));
939        }
940        // Every other key at the top is still refused, a near miss of `tool` too.
941        for key in ["tools", "latitude_deg"] {
942            let unknown = bare.replacen('{', &format!("{{\"{key}\":{{}},"), 1);
943            assert!(
944                serde_json::from_str::<SoundingProfile>(&unknown).is_err(),
945                "{unknown}"
946            );
947        }
948    }
949
950    /// A profile `hpr weather --output` wrote carries its source's kind and how far to trust it
951    /// after `tool` (#409), which reading passes over too: the same profile, nothing written back.
952    #[test]
953    fn a_profile_reads_past_its_kind_and_trust_note() {
954        let bare = r#"{"latitude_rad":0.5758,"levels":[
955            {"height_msl_m":1400.0,"temperature_k":300.0,"pressure_pa":86000.0}
956        ]}"#;
957        let saved = bare.replacen(
958            '{',
959            r#"{"tool":{"name":"FusionSpace HPR","version":"0.1.0","designation":"FS-ACHERNAR · SW · TOOL 001"},"kind":"forecast","trust":"How far to trust it. A weather model's forecast.","#,
960            1,
961        );
962        let profile: SoundingProfile = serde_json::from_str(&saved).unwrap();
963        assert_eq!(profile, serde_json::from_str(bare).unwrap());
964        let written = serde_json::to_string(&profile).unwrap();
965        assert!(
966            !written.contains("kind") && !written.contains("trust"),
967            "{written}"
968        );
969        // A near miss of either key is still refused.
970        for key in ["kinds", "trusts"] {
971            let unknown = bare.replacen('{', &format!("{{\"{key}\":\"x\","), 1);
972            assert!(
973                serde_json::from_str::<SoundingProfile>(&unknown).is_err(),
974                "{unknown}"
975            );
976        }
977    }
978
979    /// WMO-No. 8 (2023), Vol. I, p. 416: 30 km geometric is 29.7785 km of geopotential at the
980    /// equator and 29.932 km at 80° N.
981    #[test]
982    fn wmo_geopotential_matches_the_guide() {
983        let equator = wmo_geopotential_from_geometric_m(30_000.0, 0.0).unwrap();
984        assert!((equator - 29_778.5).abs() <= 0.05, "{equator}");
985        let north = wmo_geopotential_from_geometric_m(30_000.0, 80_f64.to_radians()).unwrap();
986        assert!((north - 29_932.0).abs() <= 0.5, "{north}");
987        for latitude in [-90.0_f64, -33.0, 0.0, 32.9, 45.0, 89.0] {
988            for z in [-400.0, 0.0, 1_500.0, 12_000.0, 40_000.0] {
989                let gpm = wmo_geopotential_from_geometric_m(z, latitude.to_radians()).unwrap();
990                let back = geometric_from_wmo_geopotential_m(gpm, latitude.to_radians()).unwrap();
991                assert!((back - z).abs() < 1e-8, "{latitude} {z}");
992            }
993        }
994        assert!(wmo_geopotential_from_geometric_m(0.0, 2.0).is_err());
995        assert!(geometric_from_wmo_geopotential_m(1e8, 0.0).is_err());
996    }
997}