use crate::gravity::Gravity;
use std::borrow::Cow;
use std::cmp::Ordering;
use std::fmt;
#[derive(Debug, Clone)]
struct AtmosphereLayer {
base_altitude: f64,
base_temperature: f64,
base_pressure: f64,
lapse_rate: f64,
}
const G_ACCEL_MPS2: f64 = crate::constants::G_ACCEL_MPS2;
pub(crate) const R_AIR: f64 = 287.0531;
pub(crate) const GAMMA: f64 = 1.4;
const GEOPOTENTIAL_EARTH_RADIUS_M: f64 = 6_356_766.0;
const MIN_GEOMETRIC_ALTITUDE_M: f64 = -5000.0;
const MAX_GEOMETRIC_ALTITUDE_M: f64 = 84000.0;
const MIN_STANDARD_GEOPOTENTIAL_HEIGHT_M: f64 = -5000.0;
const MAX_STANDARD_GEOPOTENTIAL_HEIGHT_M: f64 = 84000.0;
const R: f64 = 8.314472; const M_A: f64 = 28.96546e-3; const M_V: f64 = 18.01528e-3;
const ICAO_LAYERS: &[AtmosphereLayer] = &[
AtmosphereLayer {
base_altitude: 0.0,
base_temperature: 288.15, base_pressure: 101325.0, lapse_rate: -0.0065, },
AtmosphereLayer {
base_altitude: 11000.0,
base_temperature: 216.65, base_pressure: 22632.1, lapse_rate: 0.0, },
AtmosphereLayer {
base_altitude: 20000.0,
base_temperature: 216.65, base_pressure: 5474.89, lapse_rate: 0.001, },
AtmosphereLayer {
base_altitude: 32000.0,
base_temperature: 228.65, base_pressure: 868.02, lapse_rate: 0.0028, },
AtmosphereLayer {
base_altitude: 47000.0,
base_temperature: 270.65, base_pressure: 110.91, lapse_rate: 0.0, },
AtmosphereLayer {
base_altitude: 51000.0,
base_temperature: 270.65, base_pressure: 66.94, lapse_rate: -0.0028, },
AtmosphereLayer {
base_altitude: 71000.0,
base_temperature: 214.65, base_pressure: 3.96, lapse_rate: -0.002, },
];
pub(crate) fn calculate_icao_standard_atmosphere(altitude_m: f64) -> (f64, f64) {
let geometric_altitude = altitude_m.clamp(MIN_GEOMETRIC_ALTITUDE_M, MAX_GEOMETRIC_ALTITUDE_M);
let geopotential_height = geometric_to_geopotential_height_m(geometric_altitude).clamp(
MIN_STANDARD_GEOPOTENTIAL_HEIGHT_M,
MAX_STANDARD_GEOPOTENTIAL_HEIGHT_M,
);
let layer = ICAO_LAYERS
.iter()
.rev()
.find(|layer| geopotential_height >= layer.base_altitude)
.unwrap_or(&ICAO_LAYERS[0]);
let height_diff = geopotential_height - layer.base_altitude;
let temperature = layer.base_temperature + layer.lapse_rate * height_diff;
let pressure = if layer.lapse_rate.abs() < 1e-10 {
layer.base_pressure * (-G_ACCEL_MPS2 * height_diff / (R_AIR * layer.base_temperature)).exp()
} else {
let temp_ratio = temperature / layer.base_temperature;
layer.base_pressure * temp_ratio.powf(-G_ACCEL_MPS2 / (layer.lapse_rate * R_AIR))
};
(temperature, pressure)
}
#[inline]
fn geometric_to_geopotential_height_m(geometric_altitude_m: f64) -> f64 {
GEOPOTENTIAL_EARTH_RADIUS_M * geometric_altitude_m
/ (GEOPOTENTIAL_EARTH_RADIUS_M + geometric_altitude_m)
}
pub(crate) fn in_legacy_default_pressure_band(pressure_hpa: f64) -> bool {
const SEA_LEVEL_HPA: f64 = 1013.25;
(pressure_hpa - SEA_LEVEL_HPA).abs() < 0.5
}
pub(crate) fn in_legacy_default_temperature_band(temperature_c: f64) -> bool {
const SEA_LEVEL_TEMP_C: f64 = 15.0;
(temperature_c - SEA_LEVEL_TEMP_C).abs() < 0.1
}
pub fn resolve_station_pressure(pressure_hpa: f64, altitude_m: f64) -> Option<f64> {
if in_legacy_default_pressure_band(pressure_hpa) && altitude_m.abs() > 1.0 {
None } else {
Some(pressure_hpa) }
}
pub fn resolve_station_temperature(temperature_c: f64, altitude_m: f64) -> Option<f64> {
if in_legacy_default_temperature_band(temperature_c) && altitude_m.abs() > 1.0 {
None } else {
Some(temperature_c) }
}
pub fn resolve_station_conditions(
temperature_c: f64,
pressure_hpa: f64,
altitude_m: f64,
) -> (f64, f64) {
resolve_station_conditions_with_pressure_mode(
temperature_c,
pressure_hpa,
altitude_m,
PressureReferenceMode::Absolute,
)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
pub enum PressureReferenceMode {
#[default]
Absolute,
Qnh,
}
pub fn reduce_qnh_to_station_pressure(qnh_hpa: f64, altitude_m: f64) -> f64 {
let geometric_altitude = altitude_m.clamp(MIN_GEOMETRIC_ALTITUDE_M, MAX_GEOMETRIC_ALTITUDE_M);
let geopotential_height = geometric_to_geopotential_height_m(geometric_altitude).clamp(
MIN_STANDARD_GEOPOTENTIAL_HEIGHT_M,
MAX_STANDARD_GEOPOTENTIAL_HEIGHT_M,
);
let layer = &ICAO_LAYERS[0]; let height_term = layer.lapse_rate * geopotential_height / layer.base_temperature;
let exponent = -G_ACCEL_MPS2 / (layer.lapse_rate * R_AIR); let sea_level_hpa = layer.base_pressure / 100.0;
let setting_term = (sea_level_hpa / qnh_hpa).powf(exponent.recip()); qnh_hpa * (1.0 + height_term * setting_term).powf(exponent)
}
pub fn resolve_station_pressure_with_mode(
pressure_hpa: f64,
altitude_m: f64,
mode: PressureReferenceMode,
) -> Option<f64> {
match mode {
PressureReferenceMode::Absolute => resolve_station_pressure(pressure_hpa, altitude_m),
PressureReferenceMode::Qnh => {
Some(reduce_qnh_to_station_pressure(pressure_hpa, altitude_m))
}
}
}
pub fn resolve_station_conditions_with_pressure_mode(
temperature_c: f64,
pressure_hpa: f64,
altitude_m: f64,
pressure_mode: PressureReferenceMode,
) -> (f64, f64) {
resolve_station_conditions_with_presence(
temperature_c,
pressure_hpa,
altitude_m,
pressure_mode,
StationAtmospherePresence::NEITHER,
)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct StationAtmospherePresence {
pub temperature_supplied: bool,
pub pressure_supplied: bool,
}
impl StationAtmospherePresence {
pub const NEITHER: Self = Self::new(false, false);
pub const BOTH: Self = Self::new(true, true);
pub const fn new(temperature_supplied: bool, pressure_supplied: bool) -> Self {
Self {
temperature_supplied,
pressure_supplied,
}
}
pub const fn from_readings(temperature: StationReading, pressure: StationReading) -> Self {
Self::new(temperature.supplied, pressure.supplied)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StationReading {
pub value: f64,
pub supplied: bool,
}
impl StationReading {
pub const fn supplied(value: f64) -> Self {
Self {
value,
supplied: true,
}
}
pub const fn omitted(default_value: f64) -> Self {
Self {
value: default_value,
supplied: false,
}
}
pub fn is_omitted(&self) -> bool {
!self.supplied
}
}
impl serde::Serialize for StationReading {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_f64(self.value)
}
}
impl<'de> serde::Deserialize<'de> for StationReading {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
<f64 as serde::Deserialize>::deserialize(deserializer).map(Self::supplied)
}
}
pub fn resolve_station_conditions_with_presence(
temperature_c: f64,
pressure_hpa: f64,
altitude_m: f64,
pressure_mode: PressureReferenceMode,
presence: StationAtmospherePresence,
) -> (f64, f64) {
let temp_override = if presence.temperature_supplied {
Some(temperature_c)
} else {
resolve_station_temperature(temperature_c, altitude_m)
};
let press_override = if presence.pressure_supplied {
Some(match pressure_mode {
PressureReferenceMode::Absolute => pressure_hpa,
PressureReferenceMode::Qnh => reduce_qnh_to_station_pressure(pressure_hpa, altitude_m),
})
} else {
resolve_station_pressure_with_mode(pressure_hpa, altitude_m, pressure_mode)
};
if let (Some(temp_c), Some(pressure_hpa)) = (temp_override, press_override) {
return (temp_c, pressure_hpa);
}
let (std_temp_k, std_pressure_pa) = calculate_icao_standard_atmosphere(altitude_m);
(
temp_override.unwrap_or(std_temp_k - 273.15),
press_override.unwrap_or(std_pressure_pa / 100.0),
)
}
pub const STATION_PRESSURE_MIN_PLAUSIBLE_RATIO: f64 = 0.85;
pub const STATION_PRESSURE_MAX_PLAUSIBLE_RATIO: f64 = 1.08;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StationPressurePlausibility {
pub icao_standard_pa: f64,
pub ratio: f64,
pub implausible: bool,
}
pub fn station_pressure_plausibility(
station_pressure_pa: f64,
altitude_m: f64,
) -> StationPressurePlausibility {
let (_, icao_standard_pa) = calculate_icao_standard_atmosphere(altitude_m);
let ratio = station_pressure_pa / icao_standard_pa;
let implausible = !(STATION_PRESSURE_MIN_PLAUSIBLE_RATIO
..=STATION_PRESSURE_MAX_PLAUSIBLE_RATIO)
.contains(&ratio);
StationPressurePlausibility {
icao_standard_pa,
ratio,
implausible,
}
}
const DA_NWS_SEA_LEVEL_HPA: f64 = 1013.25;
const DA_NWS_PRESSURE_ALT_FT: f64 = 145_366.45;
const DA_NWS_EXPONENT: f64 = 0.190_284;
const DA_NWS_SEA_LEVEL_TEMP_F: f64 = 59.0;
const DA_NWS_LAPSE_F_PER_1000FT: f64 = 3.57;
const DA_FAA_RULE_FT_PER_DEG_F: f64 = 120.0 * 5.0 / 9.0;
const DA_FT_TO_M: f64 = 0.3048;
pub fn nws_pressure_altitude_ft(station_pressure_hpa: f64) -> f64 {
DA_NWS_PRESSURE_ALT_FT
* (1.0 - (station_pressure_hpa / DA_NWS_SEA_LEVEL_HPA).powf(DA_NWS_EXPONENT))
}
pub fn pressure_altitude_m(station_pressure_hpa: f64) -> f64 {
let nws_m = nws_pressure_altitude_ft(station_pressure_hpa) * DA_FT_TO_M;
if nws_m.is_nan() || (LOWEST_PRESSURE_ALTITUDE_M..=TROPOSPHERE_TOP_M).contains(&nws_m) {
return nws_m;
}
standard_pressure_altitude_m(station_pressure_hpa * 100.0)
}
fn standard_pressure_altitude_m(pressure_pa: f64) -> f64 {
let sea_level = &ICAO_LAYERS[0];
let mut base_pressure = sea_level.base_pressure;
for (index, layer) in ICAO_LAYERS.iter().enumerate() {
let (base, base_temperature, lapse) = (
layer.base_altitude,
layer.base_temperature,
layer.lapse_rate,
);
let isothermal = lapse.abs() < 1e-10;
let scale_height = R_AIR * base_temperature / G_ACCEL_MPS2;
let top = ICAO_LAYERS
.get(index + 1)
.map_or(f64::INFINITY, |next| next.base_altitude);
let top_pressure = if top.is_infinite() {
0.0
} else if isothermal {
base_pressure * (-(top - base) / scale_height).exp()
} else {
base_pressure
* (1.0 + lapse * (top - base) / base_temperature)
.powf(-G_ACCEL_MPS2 / (lapse * R_AIR))
};
if pressure_pa >= top_pressure || top.is_infinite() {
return if isothermal {
base + scale_height * (base_pressure / pressure_pa).ln()
} else {
let temperature = base_temperature
* (pressure_pa / base_pressure).powf(-lapse * R_AIR / G_ACCEL_MPS2);
base + (temperature - base_temperature) / lapse
};
}
base_pressure = top_pressure;
}
unreachable!("the last layer has no top")
}
pub fn faa_rule_density_altitude_ft(station_pressure_hpa: f64, temperature_f: f64) -> f64 {
let pressure_alt = nws_pressure_altitude_ft(station_pressure_hpa);
let isa_temp_f = DA_NWS_SEA_LEVEL_TEMP_F - (pressure_alt / 1000.0) * DA_NWS_LAPSE_F_PER_1000FT;
pressure_alt + DA_FAA_RULE_FT_PER_DEG_F * (temperature_f - isa_temp_f)
}
const ISA_SEA_LEVEL_TEMP_K: f64 = 288.15;
const ISA_LAPSE_K_PER_M: f64 = 0.0065;
const DENSITY_MATCH_REFERENCE_TEMP_C: f64 = 15.0;
const DENSITY_MATCH_REFERENCE_PRESSURE_HPA: f64 = 1013.25;
pub fn density_matched_altitude_m(
temperature_c: f64,
station_pressure_hpa: f64,
humidity_percent: f64,
) -> f64 {
let (density, _) = calculate_atmosphere(
0.0,
Some(temperature_c),
Some(station_pressure_hpa),
humidity_percent,
);
let (reference, _) = calculate_atmosphere(
0.0,
Some(DENSITY_MATCH_REFERENCE_TEMP_C),
Some(DENSITY_MATCH_REFERENCE_PRESSURE_HPA),
0.0,
);
let ratio = density / reference;
let exponent = G_ACCEL_MPS2 / (R_AIR * ISA_LAPSE_K_PER_M) - 1.0;
let troposphere =
(ISA_SEA_LEVEL_TEMP_K / ISA_LAPSE_K_PER_M) * (1.0 - ratio.powf(1.0 / exponent));
if troposphere.is_nan() || troposphere <= TROPOSPHERE_TOP_M {
return troposphere;
}
standard_altitude_above_tropopause_m(ratio, exponent)
}
fn standard_altitude_above_tropopause_m(ratio: f64, troposphere_exponent: f64) -> f64 {
let sea_level = &ICAO_LAYERS[0];
let mut base_ratio =
(ICAO_LAYERS[1].base_temperature / sea_level.base_temperature).powf(troposphere_exponent);
for (index, layer) in ICAO_LAYERS.iter().enumerate().skip(1) {
let (base, base_temperature, lapse) = (
layer.base_altitude,
layer.base_temperature,
layer.lapse_rate,
);
let isothermal = lapse.abs() < 1e-10;
let scale_height = R_AIR * base_temperature / G_ACCEL_MPS2;
let density_exponent = -G_ACCEL_MPS2 / (R_AIR * lapse) - 1.0;
let top = ICAO_LAYERS
.get(index + 1)
.map_or(f64::INFINITY, |next| next.base_altitude);
let top_ratio = if top.is_infinite() {
0.0
} else if isothermal {
base_ratio * (-(top - base) / scale_height).exp()
} else {
base_ratio * (1.0 + lapse * (top - base) / base_temperature).powf(density_exponent)
};
if ratio >= top_ratio || top.is_infinite() {
return if isothermal {
base + scale_height * (base_ratio / ratio).ln()
} else {
let temperature =
base_temperature * (ratio / base_ratio).powf(1.0 / density_exponent);
base + (temperature - base_temperature) / lapse
};
}
base_ratio = top_ratio;
}
unreachable!("the last layer has no top")
}
pub fn resolve_atmosphere_for_density_altitude(
density_altitude_m: f64,
explicit_temperature_c: Option<f64>,
) -> (f64, f64, f64) {
let density_altitude_ft = density_altitude_m / DA_FT_TO_M;
const K: f64 = DA_FAA_RULE_FT_PER_DEG_F;
let (pressure_alt_ft, temperature_c) = match explicit_temperature_c {
Some(temp_c) => {
let temp_f = temp_c * 9.0 / 5.0 + 32.0;
let denom = 1.0 + K * DA_NWS_LAPSE_F_PER_1000FT / 1000.0;
let pressure_alt_ft =
(density_altitude_ft - K * (temp_f - DA_NWS_SEA_LEVEL_TEMP_F)) / denom;
(pressure_alt_ft, temp_c)
}
None => {
let pressure_alt_ft = density_altitude_ft;
let isa_temp_f =
DA_NWS_SEA_LEVEL_TEMP_F - pressure_alt_ft / 1000.0 * DA_NWS_LAPSE_F_PER_1000FT;
let isa_temp_c = (isa_temp_f - 32.0) * 5.0 / 9.0;
(pressure_alt_ft, isa_temp_c)
}
};
let pressure_hpa = DA_NWS_SEA_LEVEL_HPA
* (1.0 - pressure_alt_ft / DA_NWS_PRESSURE_ALT_FT).powf(1.0 / DA_NWS_EXPONENT);
let altitude_m = pressure_alt_ft * DA_FT_TO_M;
(altitude_m, temperature_c, pressure_hpa)
}
fn nws_station_pressure_hpa(pressure_altitude_ft: f64) -> Option<f64> {
let pressure_hpa = DA_NWS_SEA_LEVEL_HPA
* (1.0 - pressure_altitude_ft / DA_NWS_PRESSURE_ALT_FT).powf(1.0 / DA_NWS_EXPONENT);
(pressure_hpa.is_finite() && pressure_hpa > 0.0).then_some(pressure_hpa)
}
pub fn station_for_density_altitude(
density_altitude_m: f64,
explicit_temperature_c: Option<f64>,
) -> Result<(f64, f64, f64), AtmosphereError> {
const FIELD: &str = "density_altitude_m";
if !density_altitude_m.is_finite() {
return Err(AtmosphereError::new(
FIELD,
density_altitude_m,
AtmosphereErrorReason::NotFinite,
));
}
if let Some(temperature_c) = explicit_temperature_c {
check_station_temperature_c(temperature_c)?;
}
let (altitude_m, temperature_c, pressure_hpa) =
resolve_atmosphere_for_density_altitude(density_altitude_m, explicit_temperature_c);
let exists = altitude_m.is_finite()
&& pressure_hpa.is_finite()
&& pressure_hpa > 0.0
&& temperature_c.is_finite()
&& temperature_c > ABSOLUTE_ZERO_C;
if !exists {
return Err(AtmosphereError {
altitude_m: Some(altitude_m),
..AtmosphereError::new(
FIELD,
density_altitude_m,
AtmosphereErrorReason::NoAirAtDensityAltitude,
)
});
}
Ok((altitude_m, temperature_c, pressure_hpa))
}
pub fn calculate_atmosphere(
altitude_m: f64,
temp_override_c: Option<f64>,
press_override_hpa: Option<f64>,
humidity_percent: f64,
) -> (f64, f64) {
let combined_overrides = temp_override_c.zip(press_override_hpa);
let (temp_k, pressure_pa) = if let Some((temp_c, pressure_hpa)) = combined_overrides {
(temp_c + 273.15, pressure_hpa * 100.0)
} else {
let (std_temp_k, std_pressure_pa) = calculate_icao_standard_atmosphere(altitude_m);
let final_temp_k = if let Some(temp_c) = temp_override_c {
temp_c + 273.15
} else {
std_temp_k
};
let final_pressure_pa = if let Some(press_hpa) = press_override_hpa {
press_hpa * 100.0
} else {
std_pressure_pa
};
(final_temp_k, final_pressure_pa)
};
let humidity_clamped = humidity_percent.clamp(0.0, 100.0);
let temp_c = temp_k - 273.15;
let density = calculate_air_density_cimp(temp_c, pressure_pa / 100.0, humidity_clamped);
let speed_of_sound = moist_speed_of_sound(temp_k, pressure_pa, humidity_clamped);
(density, speed_of_sound)
}
pub fn moist_speed_of_sound(temp_k: f64, pressure_pa: f64, humidity_percent: f64) -> f64 {
let mole_fraction_vapor = capped_vapor_mole_fraction(moist_air_vapor_mole_fraction(
temp_k,
pressure_pa,
humidity_percent,
));
moist_sound_speed_at_mole_fraction(temp_k, mole_fraction_vapor)
}
#[inline(always)]
fn moist_sound_speed_at_mole_fraction(temp_k: f64, mole_fraction_vapor: f64) -> f64 {
let gamma_moist = GAMMA * (1.0 - mole_fraction_vapor * 0.062);
let r_moist = R_AIR * (1.0 + 0.378 * mole_fraction_vapor);
(gamma_moist * r_moist * temp_k).sqrt()
}
#[inline(always)]
fn moist_molar_mass_ratio(mole_fraction_vapor: f64) -> f64 {
1.0 - mole_fraction_vapor * (1.0 - M_V / M_A)
}
#[inline(always)]
fn governing_vapor_mole_fraction(temp_c: f64, pressure_hpa: f64, humidity_percent: f64) -> f64 {
capped_vapor_mole_fraction(moist_air_vapor_mole_fraction(
temp_c + 273.15,
pressure_hpa * 100.0,
humidity_percent,
))
}
#[inline(always)]
fn capped_vapor_mole_fraction(mole_fraction_vapor: f64) -> f64 {
if mole_fraction_vapor > 1.0 {
1.0
} else {
mole_fraction_vapor
}
}
pub fn calculate_air_density_cimp(temp_c: f64, pressure_hpa: f64, humidity_percent: f64) -> f64 {
let t_k = temp_c + 273.15;
let p_sv = enhanced_saturation_vapor_pressure(t_k);
let pressure_pa = pressure_hpa * 100.0;
let f = enhanced_enhancement_factor(pressure_pa, temp_c);
let p_pa = pressure_pa.max(f64::MIN_POSITIVE);
let x_v = capped_vapor_mole_fraction(vapor_mole_fraction(p_sv, f, humidity_percent, p_pa));
let z = enhanced_compressibility_factor(p_pa, t_k, x_v);
((p_pa * M_A) / (z * R * t_k)) * moist_molar_mass_ratio(x_v)
}
pub(crate) fn water_vapor_mole_fraction_uncapped(
temp_c: f64,
pressure_hpa: f64,
humidity_percent: f64,
) -> f64 {
let t_k = temp_c + 273.15;
let p_sv = enhanced_saturation_vapor_pressure(t_k);
let pressure_pa = pressure_hpa * 100.0;
let f = enhanced_enhancement_factor(pressure_pa, temp_c);
vapor_mole_fraction(
p_sv,
f,
humidity_percent,
pressure_pa.max(f64::MIN_POSITIVE),
)
}
#[inline(always)]
fn moist_air_vapor_mole_fraction(temp_k: f64, pressure_pa: f64, humidity_percent: f64) -> f64 {
let temp_c = temp_k - 273.15;
let p_sv_hpa = enhanced_saturation_vapor_pressure(temp_k);
let f = enhanced_enhancement_factor(pressure_pa, temp_c);
vapor_mole_fraction(
p_sv_hpa,
f,
humidity_percent,
pressure_pa.max(f64::MIN_POSITIVE),
)
}
#[inline(always)]
pub(crate) fn vapor_mole_fraction(p_sv_hpa: f64, f: f64, humidity_percent: f64, p_pa: f64) -> f64 {
let humidity_percent = humidity_percent.clamp(0.0, 100.0);
if humidity_percent == 0.0 {
return humidity_percent * f / p_pa;
}
let p_v = humidity_percent / 100.0 * f * p_sv_hpa;
let p_v_pa = p_v * 100.0;
p_v_pa / p_pa
}
#[inline(always)]
fn enhanced_saturation_vapor_pressure(t_k: f64) -> f64 {
#[cfg(test)]
air_trace::count_saturation_pressure();
const A: [f64; 6] = [
-7.85951783,
1.84408259,
-11.7866497,
22.6807411,
-15.9618719,
1.80122502,
];
let t_k_safe = t_k.max(173.15);
let tau = 1.0 - t_k_safe / 647.096; let ln_p_ratio = (647.096 / t_k_safe)
* (A[0] * tau
+ A[1] * tau.powf(1.5)
+ A[2] * tau.powf(3.0)
+ A[3] * tau.powf(3.5)
+ A[4] * tau.powf(4.0)
+ A[5] * tau.powf(7.5));
220640.0 * ln_p_ratio.exp() }
#[inline(always)]
fn enhanced_enhancement_factor(p: f64, t: f64) -> f64 {
const ALPHA: f64 = 1.00062;
const BETA: f64 = 3.14e-8;
const GAMMA: f64 = 5.6e-7;
ALPHA + BETA * p + GAMMA * t * t
}
#[inline(always)]
fn enhanced_compressibility_factor(p: f64, t_k: f64, x_v: f64) -> f64 {
const A0: f64 = 1.58123e-6;
const A1: f64 = -2.9331e-8;
const A2: f64 = 1.1043e-10;
const B0: f64 = 5.707e-6;
const B1: f64 = -2.051e-8;
const C0: f64 = 1.9898e-4;
const C1: f64 = -2.376e-6;
const D: f64 = 1.83e-11;
const E: f64 = -0.765e-8;
let t_k_safe = t_k.max(173.15); let t = t_k_safe - 273.15;
let p_t = p / t_k_safe;
let z_second_order =
1.0 - p_t * (A0 + A1 * t + A2 * t * t + (B0 + B1 * t) * x_v + (C0 + C1 * t) * x_v * x_v);
let z_third_order = p_t * p_t * (D + E * x_v * x_v);
z_second_order + z_third_order
}
#[inline]
pub(crate) fn shot_frame_altitude(
base_altitude_m: f64,
downrange_m: f64,
shot_y_m: f64,
shooting_angle_rad: f64,
) -> f64 {
base_altitude_m + downrange_m * shooting_angle_rad.sin() + shot_y_m * shooting_angle_rad.cos()
}
#[deprecated(
since = "0.50.0",
note = "dry air by contract; use air_at(&KernelAtmosphere::Station(StationAir::new(..)?), None, 0.0, altitude_m), or StationAir::with_density_ratio for a caller-held density ratio"
)]
pub fn get_local_atmosphere(
altitude_m: f64,
base_alt: f64,
base_temp_c: f64,
base_press_hpa: f64,
base_ratio: f64,
) -> (f64, f64) {
let air = compose_local_air(
altitude_m,
base_alt,
&GoverningAir::new(
base_temp_c,
base_press_hpa,
base_ratio,
RelativeHumidity::DRY.percent(),
),
Gravity::EARTH,
);
(air.density_kg_m3, air.speed_of_sound_mps)
}
pub fn get_local_atmosphere_humid(
altitude_m: f64,
base_alt: f64,
base_temp_c: f64,
base_press_hpa: f64,
base_ratio: f64,
humidity_percent: f64,
) -> (f64, f64) {
get_local_atmosphere_humid_with_gravity(
altitude_m,
base_alt,
base_temp_c,
base_press_hpa,
base_ratio,
humidity_percent,
Gravity::EARTH,
)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn get_local_atmosphere_humid_with_gravity(
altitude_m: f64,
base_alt: f64,
base_temp_c: f64,
base_press_hpa: f64,
base_ratio: f64,
humidity_percent: f64,
gravity: Gravity,
) -> (f64, f64) {
let air = compose_local_air(
altitude_m,
base_alt,
&GoverningAir::new(base_temp_c, base_press_hpa, base_ratio, humidity_percent),
gravity,
);
(air.density_kg_m3, air.speed_of_sound_mps)
}
pub const DEFAULT_HUMIDITY_PERCENT: f64 = 50.0;
pub const HUMIDITY_SENSOR_TOLERANCE_PERCENT: f64 = 5.0;
const HUMIDITY_PERCENT_BAND: (f64, f64) = (
-HUMIDITY_SENSOR_TOLERANCE_PERCENT,
100.0 + HUMIDITY_SENSOR_TOLERANCE_PERCENT,
);
const HUMIDITY_FRACTION_BAND: (f64, f64) = (
-HUMIDITY_SENSOR_TOLERANCE_PERCENT / 100.0,
1.0 + HUMIDITY_SENSOR_TOLERANCE_PERCENT / 100.0,
);
const ABSOLUTE_ZERO_C: f64 = -273.15;
const MAX_STATION_DENSITY_RATIO: f64 = 2.0;
const MAX_UNIFORM_DENSITY_KG_M3: f64 = 2.0;
const MIN_UNIFORM_SPEED_OF_SOUND_MPS: f64 = 200.0;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RelativeHumidity(f64);
impl RelativeHumidity {
pub const DEFAULT: Self = Self(DEFAULT_HUMIDITY_PERCENT);
pub const DRY: Self = Self(0.0);
pub const FRACTION_BAND: (f64, f64) = HUMIDITY_FRACTION_BAND;
pub fn try_percent(percent: f64) -> Result<Self, AtmosphereError> {
sensor_band(
percent,
HUMIDITY_PERCENT_BAND,
100.0,
"humidity_percent",
AtmosphereErrorReason::HumidityPercentOutOfRange,
)
.map(Self)
}
pub fn try_fraction(fraction: f64) -> Result<Self, AtmosphereError> {
Self::snap_fraction(fraction).map(|fraction| Self(fraction * 100.0))
}
pub(crate) fn snap_fraction(fraction: f64) -> Result<f64, AtmosphereError> {
sensor_band(
fraction,
HUMIDITY_FRACTION_BAND,
1.0,
"relative_humidity",
AtmosphereErrorReason::HumidityFractionOutOfRange,
)
}
pub(crate) fn is_physical_fraction(fraction: f64) -> bool {
matches!(Self::snap_fraction(fraction), Ok(snapped) if snapped == fraction)
}
pub const fn percent(self) -> f64 {
self.0
}
pub const fn fraction(self) -> f64 {
self.0 / 100.0
}
}
fn sensor_band(
value: f64,
(lowest, highest): (f64, f64),
saturated: f64,
field: &'static str,
out_of_band: AtmosphereErrorReason,
) -> Result<f64, AtmosphereError> {
let unit = match out_of_band {
AtmosphereErrorReason::HumidityFractionOutOfRange => HumidityUnit::Fraction,
_ => HumidityUnit::Percent,
};
if !value.is_finite() {
return Err(
AtmosphereError::new(field, value, AtmosphereErrorReason::NotFinite).of_humidity(unit),
);
}
if !(lowest..=highest).contains(&value) {
return Err(AtmosphereError::new(field, value, out_of_band).of_humidity(unit));
}
Ok(if value <= 0.0 {
0.0
} else if value > saturated {
saturated
} else {
value
})
}
fn humidity_percent_range() -> String {
format!(
"percent from 0 to 100 (a sensor reading from {} to {} is read as 0 or 100)",
HUMIDITY_PERCENT_BAND.0, HUMIDITY_PERCENT_BAND.1
)
}
fn humidity_fraction_range() -> String {
format!(
"fraction from 0 to 1 (0.5 = 50 %; a sensor reading from {} to {} is read as 0 or 1)",
HUMIDITY_FRACTION_BAND.0, HUMIDITY_FRACTION_BAND.1
)
}
pub fn parse_humidity_percent_text(raw: &str) -> Result<RelativeHumidity, String> {
let value: f64 = raw.trim().parse().map_err(|_| {
format!(
"not a number; relative humidity is a {}",
humidity_percent_range()
)
})?;
RelativeHumidity::try_percent(value).map_err(|error| error.explanation())
}
#[cfg(any(target_arch = "wasm32", test))]
pub(crate) fn parse_humidity_percent_arg(flag: &str, raw: &str) -> Result<f64, String> {
match raw.trim().parse::<f64>() {
Ok(value) => RelativeHumidity::try_percent(value)
.map(RelativeHumidity::percent)
.map_err(|error| error.at_field(flag.to_string()).to_string()),
Err(_) => Err(format!(
"{flag} = {raw}: {}",
parse_humidity_percent_text(raw).expect_err("text that is no number")
)),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AtmosphereErrorReason {
NotFinite,
HumidityPercentOutOfRange,
HumidityFractionOutOfRange,
AtOrBelowAbsoluteZero,
NonPositivePressure,
ImpossibleAir,
DensityRatioOutOfRange,
UniformDensityOutOfRange,
UniformSpeedOfSoundOutOfRange,
NonPositiveZoneThreshold,
AirAloftBelowAbsoluteZero,
NoAirAtDensityAltitude,
}
impl fmt::Display for AtmosphereErrorReason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::NotFinite => "must be finite",
Self::HumidityPercentOutOfRange => {
return write!(
f,
"relative humidity must be a {}",
humidity_percent_range()
)
}
Self::HumidityFractionOutOfRange => {
return write!(
f,
"relative humidity must be a {}",
humidity_fraction_range()
)
}
Self::AtOrBelowAbsoluteZero => "temperature must be above absolute zero (-273.15 °C)",
Self::NonPositivePressure => "pressure must be greater than 0",
Self::ImpossibleAir => {
"no such air exists: at this temperature and pressure the humidity needs a \
water-vapour mole fraction of 1 or more (more vapour pressure than the total), \
or the air is humid above water's critical point, or too hot or too dense to \
have a density"
}
Self::DensityRatioOutOfRange => {
"density ratio (density / 1.225 kg/m^3) must be greater than 0 and less than 2"
}
Self::UniformDensityOutOfRange => {
"air density must be at least 0 (a vacuum) and less than 2 kg/m^3"
}
Self::UniformSpeedOfSoundOutOfRange => "speed of sound must be greater than 200 m/s",
Self::NonPositiveZoneThreshold => {
"an atmosphere zone's until_distance_m must be greater than 0"
}
Self::AirAloftBelowAbsoluteZero => "the air aloft would fall below absolute zero",
Self::NoAirAtDensityAltitude => "no air has this density altitude by the FAA rule",
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum HumidityUnit {
Percent,
Fraction,
}
#[derive(Debug, Clone, PartialEq)]
pub struct AtmosphereError {
field: Cow<'static, str>,
value: f64,
reason: AtmosphereErrorReason,
humidity_unit: Option<HumidityUnit>,
altitude_m: Option<f64>,
}
impl AtmosphereError {
pub fn in_error<'a>(error: &'a (dyn std::error::Error + 'static)) -> Option<&'a Self> {
let mut current = Some(error);
while let Some(error) = current {
if let Some(air) = error.downcast_ref::<Self>() {
return Some(air);
}
current = error.source();
}
None
}
pub fn temperature_refusal(&self, field: AirField<'_>, units: AirUnits) -> AirRefusal {
self.temperature_refusal_from(field, units, StationTemperatureOrigin::Reading)
}
pub fn temperature_refusal_from(
&self,
field: AirField<'_>,
units: AirUnits,
origin: StationTemperatureOrigin,
) -> AirRefusal {
let reading = match origin {
StationTemperatureOrigin::Reading => {
format!("{} = {}", field.name, units.temperature.text(self.value))
}
StationTemperatureOrigin::DensityAltitude => format!(
"{} gives a station temperature of {}",
field.name,
units.temperature.text(self.value)
),
};
AirRefusal {
path: field.path.to_string(),
message: format!("{reading}: {}", self.explanation_in(units.altitude)),
reason: self.reason,
}
}
fn new(field: &'static str, value: f64, reason: AtmosphereErrorReason) -> Self {
Self {
field: Cow::Borrowed(field),
value,
reason,
humidity_unit: None,
altitude_m: None,
}
}
fn aloft(temperature_c: f64, altitude_m: f64) -> Self {
Self {
altitude_m: Some(altitude_m),
..Self::new(
"temperature_c",
temperature_c,
AtmosphereErrorReason::AirAloftBelowAbsoluteZero,
)
}
}
fn of_humidity(mut self, unit: HumidityUnit) -> Self {
self.humidity_unit = Some(unit);
self
}
pub fn explanation(&self) -> String {
self.explanation_in(AltitudeUnit::Meters)
}
pub fn explanation_in(&self, altitude_unit: AltitudeUnit) -> String {
match (self.reason, self.humidity_unit) {
(AtmosphereErrorReason::NotFinite, Some(HumidityUnit::Percent)) => format!(
"relative humidity must be a finite {}",
humidity_percent_range()
),
(AtmosphereErrorReason::NotFinite, Some(HumidityUnit::Fraction)) => format!(
"relative humidity must be a finite {}",
humidity_fraction_range()
),
(reason @ AtmosphereErrorReason::AirAloftBelowAbsoluteZero, _) => {
match self.altitude_m {
Some(altitude_m) => format!(
"{reason}: from this temperature the standard lapse reaches 0 K at {} \
above mean sea level, which this flight reaches (check the temperature \
and its unit)",
altitude_unit.text(altitude_m)
),
None => reason.to_string(),
}
}
(AtmosphereErrorReason::NoAirAtDensityAltitude, _) => match self.altitude_m {
Some(pressure_altitude_m) => {
let cause =
if nws_station_pressure_hpa(pressure_altitude_m / DA_FT_TO_M).is_some() {
"the rule's standard temperature is at or below absolute zero"
} else {
"the NWS pressure formula gives no finite pressure above 0"
};
format!(
"no air has this density altitude: at its pressure altitude by the FAA \
rule, {}, {cause} (check the density altitude and its unit)",
altitude_unit.text(pressure_altitude_m)
)
}
None => AtmosphereErrorReason::NoAirAtDensityAltitude.to_string(),
},
(reason, _) => reason.to_string(),
}
}
pub fn altitude_m(&self) -> Option<f64> {
self.altitude_m
}
pub fn field(&self) -> &str {
&self.field
}
pub fn value(&self) -> f64 {
self.value
}
pub fn reason(&self) -> AtmosphereErrorReason {
self.reason
}
pub fn at_field(mut self, field: impl Into<Cow<'static, str>>) -> Self {
self.field = field.into();
self
}
}
impl fmt::Display for AtmosphereError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{} = {}: {}",
self.field,
echo_number(self.value),
self.explanation()
)
}
}
impl std::error::Error for AtmosphereError {}
pub(crate) const LOWEST_PRESSURE_ALTITUDE_M: f64 = -5_000.0;
pub(crate) const TROPOSPHERE_TOP_M: f64 = 11_000.0;
pub(crate) fn pressure_altitude_outside_troposphere_m(station_pressure_hpa: f64) -> Option<f64> {
let nws_m = nws_pressure_altitude_ft(station_pressure_hpa) * DA_FT_TO_M;
(!(LOWEST_PRESSURE_ALTITUDE_M..=TROPOSPHERE_TOP_M).contains(&nws_m))
.then(|| pressure_altitude_m(station_pressure_hpa))
}
const KELVIN_OFFSET: f64 = 273.15;
const WATER_CRITICAL_TEMPERATURE_K: f64 = 647.096;
pub(crate) const HUMID_AIR_MODEL_MIN_K: f64 = 173.15;
pub(crate) const HUMID_AIR_MODEL_MAX_K: f64 = 373.15;
pub(crate) fn outside_humid_air_model_range(temperature_k: f64) -> bool {
!(HUMID_AIR_MODEL_MIN_K..=HUMID_AIR_MODEL_MAX_K).contains(&temperature_k)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum StationPressureOrigin {
#[default]
Reading,
Standard,
Qnh,
DensityAltitude,
}
impl StationPressureOrigin {
pub fn of(given_hpa: Option<f64>, mode: PressureReferenceMode) -> Self {
match (given_hpa, mode) {
(None, _) => Self::Standard,
(Some(qnh_hpa), PressureReferenceMode::Qnh)
if pressure_altitude_outside_troposphere_m(qnh_hpa).is_none() =>
{
Self::Qnh
}
(Some(_), _) => Self::Reading,
}
}
pub fn resolving(
pressure_hpa: f64,
altitude_m: f64,
mode: PressureReferenceMode,
presence: StationAtmospherePresence,
) -> Self {
let given = presence.pressure_supplied
|| resolve_station_pressure_with_mode(pressure_hpa, altitude_m, mode).is_some();
Self::of(given.then_some(pressure_hpa), mode)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum StationTemperatureOrigin {
#[default]
Reading,
DensityAltitude,
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct StationOrigin {
pub pressure: StationPressureOrigin,
pub qnh_hpa: Option<f64>,
pub temperature: StationTemperatureOrigin,
}
impl StationOrigin {
pub fn of(given_hpa: Option<f64>, mode: PressureReferenceMode) -> Self {
Self {
pressure: StationPressureOrigin::of(given_hpa, mode),
qnh_hpa: given_hpa.filter(|_| mode == PressureReferenceMode::Qnh),
temperature: StationTemperatureOrigin::Reading,
}
}
pub fn resolving(
pressure_hpa: f64,
altitude_m: f64,
mode: PressureReferenceMode,
presence: StationAtmospherePresence,
) -> Self {
let pressure = StationPressureOrigin::resolving(pressure_hpa, altitude_m, mode, presence);
Self {
pressure,
qnh_hpa: (mode == PressureReferenceMode::Qnh
&& pressure != StationPressureOrigin::Standard)
.then_some(pressure_hpa),
temperature: StationTemperatureOrigin::Reading,
}
}
pub fn density_altitude(temperature_given: bool) -> Self {
Self {
pressure: StationPressureOrigin::DensityAltitude,
qnh_hpa: None,
temperature: if temperature_given {
StationTemperatureOrigin::Reading
} else {
StationTemperatureOrigin::DensityAltitude
},
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AirField<'a> {
pub name: &'a str,
pub path: &'a str,
}
impl<'a> AirField<'a> {
pub const fn named(name: &'a str) -> Self {
Self { name, path: name }
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct AirSpelling<'a> {
pub humidity: AirField<'a>,
pub temperature: AirField<'a>,
pub pressure: AirField<'a>,
pub altitude: AirField<'a>,
pub humidity_sent: f64,
pub temperature_text: String,
pub temperature_unit: TemperatureUnit,
pub temperature_origin: StationTemperatureOrigin,
pub pressure_text: String,
pub pressure_origin: StationPressureOrigin,
pub qnh_text: Option<String>,
pub altitude_unit: AltitudeUnit,
}
impl AirSpelling<'_> {
fn qnh_named(&self) -> String {
match &self.qnh_text {
Some(qnh) => format!("{} is a QNH of {qnh}", self.pressure.name),
None => format!("{} is a QNH", self.pressure.name),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AltitudeUnit {
#[default]
Meters,
Feet,
}
impl AltitudeUnit {
pub fn text(self, altitude_m: f64) -> String {
let (value, unit) = match self {
Self::Meters => (altitude_m, "m"),
Self::Feet => (altitude_m / 0.3048, "ft"),
};
if value.is_finite() && value.abs() >= EXPONENT_FROM {
format!("{} {unit}", exponent_text(value))
} else {
format!("{value:.0} {unit}")
}
}
pub fn reading(self, altitude_m: f64) -> String {
match self {
Self::Meters => reading_text(altitude_m, "m"),
Self::Feet => reading_text(altitude_m / 0.3048, "ft"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TemperatureUnit {
#[default]
Celsius,
Fahrenheit,
Kelvin,
}
impl TemperatureUnit {
pub fn text(self, temperature_c: f64) -> String {
match self {
Self::Celsius => reading_text(temperature_c, "°C"),
Self::Fahrenheit => reading_text(temperature_c * 9.0 / 5.0 + 32.0, "°F"),
Self::Kelvin => reading_text(temperature_c + KELVIN_OFFSET, "K"),
}
}
pub fn absolute_zero_text(self) -> &'static str {
match self {
Self::Celsius => "-273.15 °C",
Self::Fahrenheit => "-459.67 °F",
Self::Kelvin => "0 K",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PressureUnit {
#[default]
Hectopascals,
InchesOfMercury,
}
impl PressureUnit {
pub fn text(self, pressure_hpa: f64) -> String {
let (value, unit) = match self {
Self::Hectopascals => (pressure_hpa, "hPa"),
Self::InchesOfMercury => (pressure_hpa / 33.8639, "inHg"),
};
let text = reading_text(value, unit);
if value != 0.0 && value.is_finite() && text == format!("0 {unit}") {
format!("{} {unit}", exponent_text(value))
} else {
text
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct AirUnits {
pub temperature: TemperatureUnit,
pub pressure: PressureUnit,
pub altitude: AltitudeUnit,
}
impl AirUnits {
pub const METRIC: Self = Self {
temperature: TemperatureUnit::Celsius,
pressure: PressureUnit::Hectopascals,
altitude: AltitudeUnit::Meters,
};
pub const IMPERIAL: Self = Self {
temperature: TemperatureUnit::Fahrenheit,
pressure: PressureUnit::InchesOfMercury,
altitude: AltitudeUnit::Feet,
};
}
pub fn reading_text(value: f64, unit: &str) -> String {
if value.is_finite() && value.abs() >= EXPONENT_FROM {
return format!("{} {unit}", exponent_text(value));
}
let rounded = format!("{value:.2}");
let trimmed = if rounded.contains('.') {
rounded.trim_end_matches('0').trim_end_matches('.')
} else {
rounded.as_str()
};
let trimmed = if trimmed == "-0" { "0" } else { trimmed };
format!("{trimmed} {unit}")
}
const EXPONENT_FROM: f64 = 1e7;
fn exponent_text(value: f64) -> String {
let text = format!("{value:.5e}");
match text.split_once('e') {
Some((mantissa, exponent)) if mantissa.contains('.') => format!(
"{}e{exponent}",
mantissa.trim_end_matches('0').trim_end_matches('.')
),
_ => text,
}
}
pub fn echo_number(value: f64) -> String {
if value == 0.0 || !value.is_finite() || (1e-3..EXPONENT_FROM).contains(&value.abs()) {
format!("{value}")
} else {
format!("{value:e}")
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AirRefusal {
path: String,
message: String,
reason: AtmosphereErrorReason,
}
impl AirRefusal {
pub fn reason(&self) -> AtmosphereErrorReason {
self.reason
}
pub fn path(&self) -> &str {
&self.path
}
pub fn message(&self) -> &str {
&self.message
}
}
impl fmt::Display for AirRefusal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for AirRefusal {}
impl AtmosphereError {
pub fn refusal_in(
&self,
spelling: &AirSpelling<'_>,
station_altitude_m: f64,
station_temperature_c: f64,
station_pressure_hpa: f64,
) -> AirRefusal {
let (path, message) = self.refusal_parts(
spelling,
station_altitude_m,
station_temperature_c,
station_pressure_hpa,
);
AirRefusal {
path,
message,
reason: self.reason,
}
}
fn refusal_parts(
&self,
spelling: &AirSpelling<'_>,
station_altitude_m: f64,
station_temperature_c: f64,
station_pressure_hpa: f64,
) -> (String, String) {
let explanation = self.explanation_in(spelling.altitude_unit);
let altitude = |altitude_m: f64| spelling.altitude_unit.text(altitude_m);
if self.reason == AtmosphereErrorReason::ImpossibleAir {
let air = format!(
"{} = {} at {} and {}: {explanation}",
spelling.humidity.name,
echo_number(spelling.humidity_sent),
spelling.temperature_text,
spelling.pressure_text
);
if self.field == "temperature_c"
|| outside_humid_air_model_range(station_temperature_c + KELVIN_OFFSET)
{
let range = format!(
"outside {} to {}, where the humid-air formulas hold",
spelling
.temperature_unit
.text(HUMID_AIR_MODEL_MIN_K - KELVIN_OFFSET),
spelling
.temperature_unit
.text(HUMID_AIR_MODEL_MAX_K - KELVIN_OFFSET)
);
let blame = match spelling.temperature_origin {
StationTemperatureOrigin::Reading => format!(
"{} = {} is {range}: check the temperature and its unit",
spelling.temperature.name, spelling.temperature_text
),
StationTemperatureOrigin::DensityAltitude => format!(
"{} gives a station temperature of {}, {range}: check the density \
altitude's unit",
spelling.temperature.name, spelling.temperature_text
),
};
return (
spelling.temperature.path.to_string(),
format!("{air}; {blame}"),
);
}
if let Some(altitude_m) = pressure_altitude_outside_troposphere_m(station_pressure_hpa)
{
let troposphere = format!(
"a pressure altitude of {}, outside the troposphere ({} to {})",
altitude(altitude_m),
altitude(LOWEST_PRESSURE_ALTITUDE_M),
altitude(TROPOSPHERE_TOP_M)
);
let reduced = |unit: &str| {
format!(
"{air}; {}, and reduced to the station altitude of {} it is a station \
pressure of {}, {troposphere}: check the {unit}'s unit",
spelling.qnh_named(),
altitude(station_altitude_m),
spelling.pressure_text
)
};
return match spelling.pressure_origin {
StationPressureOrigin::Reading if spelling.qnh_text.is_some() => {
(spelling.pressure.path.to_string(), reduced("pressure"))
}
StationPressureOrigin::Reading => (
spelling.pressure.path.to_string(),
format!(
"{air}; {} = {} is {troposphere}: check the pressure's unit",
spelling.pressure.name, spelling.pressure_text
),
),
StationPressureOrigin::Standard => (
spelling.altitude.path.to_string(),
format!(
"{air}; no {} was given, and the standard pressure at the station \
altitude of {} is {troposphere}: check the altitude's unit",
spelling.pressure.name,
altitude(station_altitude_m)
),
),
StationPressureOrigin::Qnh => {
(spelling.altitude.path.to_string(), reduced("altitude"))
}
StationPressureOrigin::DensityAltitude => (
spelling.pressure.path.to_string(),
format!(
"{air}; {} gives a station pressure of {}, {troposphere}: check the \
density altitude's unit",
spelling.pressure.name, spelling.pressure_text
),
),
};
}
return (spelling.humidity.path.to_string(), air);
}
if self.field == "pressure_hpa"
&& matches!(
self.reason,
AtmosphereErrorReason::NotFinite | AtmosphereErrorReason::NonPositivePressure
)
&& (spelling.pressure_origin == StationPressureOrigin::Qnh
|| spelling.qnh_text.is_some())
{
let (path, unit) = if spelling.pressure_origin == StationPressureOrigin::Qnh {
(spelling.altitude.path, "altitude")
} else {
(spelling.pressure.path, "pressure")
};
return (
path.to_string(),
format!(
"{}, and reduced to the station altitude of {} it leaves no station \
pressure: the altimeter-setting relation has none that high (check the \
{unit}'s unit)",
spelling.qnh_named(),
altitude(station_altitude_m)
),
);
}
let explanation = match self.reason {
AtmosphereErrorReason::AtOrBelowAbsoluteZero => format!(
"temperature must be above absolute zero ({})",
spelling.temperature_unit.absolute_zero_text()
),
_ => explanation,
};
let (field, value) = match &*self.field {
"temperature_c"
if spelling.temperature_origin == StationTemperatureOrigin::DensityAltitude =>
{
return (
spelling.temperature.path.to_string(),
format!(
"{} gives a station temperature of {}: {explanation}",
spelling.temperature.name, spelling.temperature_text
),
);
}
"pressure_hpa"
if spelling.pressure_origin == StationPressureOrigin::DensityAltitude =>
{
return (
spelling.pressure.path.to_string(),
format!(
"{} gives a station pressure of {}: {explanation}",
spelling.pressure.name, spelling.pressure_text
),
);
}
"temperature_c" => (spelling.temperature, spelling.temperature_text.clone()),
"pressure_hpa" => (spelling.pressure, spelling.pressure_text.clone()),
"altitude_m" => (spelling.altitude, echo_number(self.value)),
"density_altitude_m" => (
spelling.altitude,
spelling.altitude_unit.reading(self.value),
),
_ => (spelling.humidity, echo_number(self.value)),
};
(
field.path.to_string(),
format!("{} = {value}: {explanation}", field.name),
)
}
}
#[derive(Clone, Copy, PartialEq)]
pub struct StationAir {
altitude_m: f64,
temperature_c: f64,
pressure_hpa: f64,
humidity: RelativeHumidity,
density_ratio: f64,
density_kg_m3: f64,
speed_of_sound_mps: f64,
vapor_mole_fraction: f64,
}
impl fmt::Debug for StationAir {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("StationAir")
.field("altitude_m", &self.altitude_m)
.field("temperature_c", &self.temperature_c)
.field("pressure_hpa", &self.pressure_hpa)
.field("humidity", &self.humidity)
.field("density_ratio", &self.density_ratio)
.field("density_kg_m3", &self.density_kg_m3)
.field("speed_of_sound_mps", &self.speed_of_sound_mps)
.finish()
}
}
impl StationAir {
pub fn new(
altitude_m: f64,
temperature_c: f64,
pressure_hpa: f64,
humidity: RelativeHumidity,
) -> Result<Self, AtmosphereError> {
check_station_state(altitude_m, temperature_c, pressure_hpa)?;
refuse_impossible_air(temperature_c, pressure_hpa, humidity)?;
Ok(Self::from_calculate_atmosphere(
altitude_m,
temperature_c,
pressure_hpa,
humidity,
))
}
pub fn with_density_ratio(
altitude_m: f64,
temperature_c: f64,
pressure_hpa: f64,
density_ratio: f64,
humidity: RelativeHumidity,
) -> Result<Self, AtmosphereError> {
const FIELD: &str = "density_ratio";
check_station_state(altitude_m, temperature_c, pressure_hpa)?;
if !density_ratio.is_finite() {
return Err(AtmosphereError::new(
FIELD,
density_ratio,
AtmosphereErrorReason::NotFinite,
));
}
if !(density_ratio > 0.0 && density_ratio < MAX_STATION_DENSITY_RATIO) {
return Err(AtmosphereError::new(
FIELD,
density_ratio,
AtmosphereErrorReason::DensityRatioOutOfRange,
));
}
refuse_impossible_air(temperature_c, pressure_hpa, humidity)?;
Ok(Self {
altitude_m,
temperature_c,
pressure_hpa,
humidity,
density_ratio,
density_kg_m3: density_ratio * 1.225,
speed_of_sound_mps: moist_speed_of_sound(
temperature_c + 273.15,
pressure_hpa * 100.0,
humidity.percent(),
),
vapor_mole_fraction: governing_vapor_mole_fraction(
temperature_c,
pressure_hpa,
humidity.percent(),
),
})
}
fn from_calculate_atmosphere(
altitude_m: f64,
temperature_c: f64,
pressure_hpa: f64,
humidity: RelativeHumidity,
) -> Self {
let (density_kg_m3, speed_of_sound_mps) = calculate_atmosphere(
altitude_m,
Some(temperature_c),
Some(pressure_hpa),
humidity.percent(),
);
Self {
altitude_m,
temperature_c,
pressure_hpa,
humidity,
density_ratio: density_kg_m3 / 1.225,
density_kg_m3,
speed_of_sound_mps,
vapor_mole_fraction: governing_vapor_mole_fraction(
temperature_c,
pressure_hpa,
humidity.percent(),
),
}
}
#[inline(always)]
fn governing_air(&self) -> GoverningAir {
GoverningAir {
temperature_c: self.temperature_c,
pressure_hpa: self.pressure_hpa,
density_ratio: self.density_ratio,
vapor_mole_fraction: self.vapor_mole_fraction,
#[cfg(test)]
humidity_percent: self.humidity.percent(),
}
}
pub fn altitude_m(&self) -> f64 {
self.altitude_m
}
pub fn temperature_c(&self) -> f64 {
self.temperature_c
}
pub fn pressure_hpa(&self) -> f64 {
self.pressure_hpa
}
pub fn humidity(&self) -> RelativeHumidity {
self.humidity
}
pub fn density_ratio(&self) -> f64 {
self.density_ratio
}
pub fn density_kg_m3(&self) -> f64 {
self.density_kg_m3
}
pub fn speed_of_sound_mps(&self) -> f64 {
self.speed_of_sound_mps
}
}
pub fn check_station_temperature_c(temperature_c: f64) -> Result<(), AtmosphereError> {
if !temperature_c.is_finite() {
return Err(AtmosphereError::new(
"temperature_c",
temperature_c,
AtmosphereErrorReason::NotFinite,
));
}
if temperature_c <= ABSOLUTE_ZERO_C {
return Err(AtmosphereError::new(
"temperature_c",
temperature_c,
AtmosphereErrorReason::AtOrBelowAbsoluteZero,
));
}
Ok(())
}
pub fn check_temperature_flag(flag: &str, value: f64, fahrenheit: bool) -> Result<(), String> {
let (celsius, unit, absolute_zero) = if fahrenheit {
((value - 32.0) * 5.0 / 9.0, "F", "-459.67 F")
} else {
(value, "C", "-273.15 C")
};
check_station_temperature_c(celsius).map_err(|error| match error.reason() {
AtmosphereErrorReason::NotFinite => {
format!(
"{flag} {} {unit} is not a finite number",
echo_number(value)
)
}
_ => format!(
"{flag} {} {unit} is at or below absolute zero ({absolute_zero})",
echo_number(value)
),
})
}
pub fn check_station_pressure_hpa(pressure_hpa: f64) -> Result<(), AtmosphereError> {
if !pressure_hpa.is_finite() {
return Err(AtmosphereError::new(
"pressure_hpa",
pressure_hpa,
AtmosphereErrorReason::NotFinite,
));
}
if pressure_hpa <= 0.0 {
return Err(AtmosphereError::new(
"pressure_hpa",
pressure_hpa,
AtmosphereErrorReason::NonPositivePressure,
));
}
Ok(())
}
pub fn check_pressure_flag(flag: &str, value: f64, inhg: bool) -> Result<(), String> {
let (hpa, unit) = if inhg {
(value * 33.8639, "inHg")
} else {
(value, "hPa")
};
check_station_pressure_hpa(hpa).map_err(|error| match error.reason() {
AtmosphereErrorReason::NotFinite => {
format!(
"{flag} {} {unit} is not a finite number",
echo_number(value)
)
}
_ => format!("{flag} {} {unit} is at or below zero", echo_number(value)),
})
}
pub fn check_altitude_flag(flag: &str, value: f64, feet: bool) -> Result<(), String> {
let (metres, unit) = if feet {
(value * DA_FT_TO_M, "ft")
} else {
(value, "m")
};
if metres.is_finite() {
Ok(())
} else {
Err(format!(
"{flag} {} {unit} is not a finite number",
echo_number(value)
))
}
}
fn check_station_state(
altitude_m: f64,
temperature_c: f64,
pressure_hpa: f64,
) -> Result<(), AtmosphereError> {
if !altitude_m.is_finite() {
return Err(AtmosphereError::new(
"altitude_m",
altitude_m,
AtmosphereErrorReason::NotFinite,
));
}
check_station_temperature_c(temperature_c)?;
check_station_pressure_hpa(pressure_hpa)
}
fn refuse_impossible_air(
temperature_c: f64,
pressure_hpa: f64,
humidity: RelativeHumidity,
) -> Result<(), AtmosphereError> {
let x_v = water_vapor_mole_fraction_uncapped(temperature_c, pressure_hpa, humidity.percent());
if x_v.is_nan() {
return Err(AtmosphereError::new(
"temperature_c",
temperature_c,
AtmosphereErrorReason::ImpossibleAir,
));
}
if x_v >= 1.0 {
return Err(AtmosphereError::new(
"humidity_percent",
humidity.percent(),
AtmosphereErrorReason::ImpossibleAir,
));
}
let density = calculate_air_density_cimp(temperature_c, pressure_hpa, humidity.percent());
if !(density.is_finite() && density > 0.0) {
let hot = temperature_c + KELVIN_OFFSET > WATER_CRITICAL_TEMPERATURE_K;
return Err(if hot {
AtmosphereError::new(
"temperature_c",
temperature_c,
AtmosphereErrorReason::ImpossibleAir,
)
} else {
AtmosphereError::new(
"pressure_hpa",
pressure_hpa,
AtmosphereErrorReason::ImpossibleAir,
)
});
}
Ok(())
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LocalAir {
pub density_kg_m3: f64,
pub speed_of_sound_mps: f64,
pub temperature_k: f64,
pub pressure_pa: f64,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum KernelAtmosphere {
Station(StationAir),
#[non_exhaustive]
Uniform {
density_kg_m3: f64,
speed_of_sound_mps: f64,
},
}
impl KernelAtmosphere {
pub fn uniform(density_kg_m3: f64, speed_of_sound_mps: f64) -> Result<Self, AtmosphereError> {
if !density_kg_m3.is_finite() {
return Err(AtmosphereError::new(
"density_kg_m3",
density_kg_m3,
AtmosphereErrorReason::NotFinite,
));
}
if !(0.0..MAX_UNIFORM_DENSITY_KG_M3).contains(&density_kg_m3) {
return Err(AtmosphereError::new(
"density_kg_m3",
density_kg_m3,
AtmosphereErrorReason::UniformDensityOutOfRange,
));
}
let density_kg_m3 = density_kg_m3 + 0.0;
if !speed_of_sound_mps.is_finite() {
return Err(AtmosphereError::new(
"speed_of_sound_mps",
speed_of_sound_mps,
AtmosphereErrorReason::NotFinite,
));
}
if speed_of_sound_mps <= MIN_UNIFORM_SPEED_OF_SOUND_MPS {
return Err(AtmosphereError::new(
"speed_of_sound_mps",
speed_of_sound_mps,
AtmosphereErrorReason::UniformSpeedOfSoundOutOfRange,
));
}
Ok(Self::Uniform {
density_kg_m3,
speed_of_sound_mps,
})
}
pub fn from_legacy_params(
params: (f64, f64, f64, f64),
humidity: RelativeHumidity,
) -> Result<Self, AtmosphereError> {
let (first, second, third, fourth) = params;
if third == 0.0 && fourth == 0.0 {
return Self::uniform(first, second);
}
let density_ratio = if fourth.is_finite() && fourth <= 0.0 {
1.0
} else {
fourth
};
StationAir::with_density_ratio(first, second, third, density_ratio, humidity)
.map(Self::Station)
}
pub(crate) fn reference_altitude_m(&self, uniform_fallback: f64) -> f64 {
match self {
Self::Station(station) => station.altitude_m,
Self::Uniform { .. } => uniform_fallback,
}
}
}
#[derive(Debug, Clone, Copy)]
struct GoverningAir {
temperature_c: f64,
pressure_hpa: f64,
density_ratio: f64,
vapor_mole_fraction: f64,
#[cfg(test)]
humidity_percent: f64,
}
impl GoverningAir {
#[inline]
fn new(
temperature_c: f64,
pressure_hpa: f64,
density_ratio: f64,
humidity_percent: f64,
) -> Self {
Self {
temperature_c,
pressure_hpa,
density_ratio,
vapor_mole_fraction: governing_vapor_mole_fraction(
temperature_c,
pressure_hpa,
humidity_percent,
),
#[cfg(test)]
humidity_percent,
}
}
fn zone(&(temperature_c, pressure_hpa, humidity_percent, _): &AtmoSegment) -> Self {
Self::new(
temperature_c,
pressure_hpa,
calculate_air_density_cimp(temperature_c, pressure_hpa, humidity_percent) / 1.225,
humidity_percent,
)
}
}
pub fn air_at(
atmosphere: &KernelAtmosphere,
zones: Option<&AtmoSock>,
downrange_m: f64,
altitude_m: f64,
) -> LocalAir {
air_at_with_gravity(atmosphere, zones, downrange_m, altitude_m, Gravity::EARTH)
}
pub(crate) fn air_at_with_gravity(
atmosphere: &KernelAtmosphere,
zones: Option<&AtmoSock>,
downrange_m: f64,
altitude_m: f64,
gravity: Gravity,
) -> LocalAir {
match atmosphere {
KernelAtmosphere::Uniform {
density_kg_m3,
speed_of_sound_mps,
} => LocalAir {
density_kg_m3: *density_kg_m3,
speed_of_sound_mps: *speed_of_sound_mps,
temperature_k: speed_of_sound_mps * speed_of_sound_mps / (GAMMA * R_AIR),
pressure_pa: 0.0,
},
KernelAtmosphere::Station(station) => {
#[cfg(test)]
let saturation_pressures_before = air_trace::saturation_pressures();
let base = match zones.and_then(|sock| sock.governing_air_for_range(downrange_m)) {
Some(zone) => *zone,
None => station.governing_air(),
};
let air = compose_local_air(altitude_m, station.altitude_m, &base, gravity);
#[cfg(test)]
air_trace::attribute_lookup_saturation_pressures(saturation_pressures_before);
air
}
}
}
fn absolute_zero_altitudes_m(base_temp_k: f64, base_alt_m: f64) -> (f64, f64) {
let base = geometric_to_geopotential_height_m(base_alt_m);
let to_geometric = |geopotential_m: f64| {
if geopotential_m >= GEOPOTENTIAL_EARTH_RADIUS_M {
f64::INFINITY
} else {
GEOPOTENTIAL_EARTH_RADIUS_M * geopotential_m
/ (GEOPOTENTIAL_EARTH_RADIUS_M - geopotential_m)
}
};
let mut ceiling = f64::INFINITY;
let (mut height, mut temperature) = (base, base_temp_k);
let mut index = ICAO_LAYERS
.iter()
.rposition(|layer| height >= layer.base_altitude)
.unwrap_or(0);
loop {
let lapse = ICAO_LAYERS[index].lapse_rate;
let end = ICAO_LAYERS
.get(index + 1)
.map_or(f64::INFINITY, |next| next.base_altitude);
if lapse < 0.0 {
let zero = height + temperature / -lapse;
if zero <= end {
ceiling = to_geometric(zero);
break;
}
}
if end.is_infinite() {
break;
}
temperature += lapse * (end - height);
height = end;
index += 1;
}
let mut floor = f64::NEG_INFINITY;
let (mut height, mut temperature) = (base, base_temp_k);
let mut index = ICAO_LAYERS
.iter()
.rposition(|layer| height > layer.base_altitude)
.unwrap_or(0);
loop {
let lapse = ICAO_LAYERS[index].lapse_rate;
let end = if index == 0 {
f64::NEG_INFINITY
} else {
ICAO_LAYERS[index].base_altitude
};
if lapse > 0.0 {
let zero = height - temperature / lapse;
if zero >= end {
floor = to_geometric(zero);
break;
}
}
if index == 0 {
break;
}
temperature -= lapse * (height - end);
height = end;
index -= 1;
}
(floor, ceiling)
}
pub(crate) fn air_aloft_refusal(
atmosphere: &KernelAtmosphere,
zones: Option<&AtmoSock>,
downrange_m: f64,
altitude_m: f64,
reach_m: f64,
) -> Option<AtmosphereError> {
let KernelAtmosphere::Station(station) = atmosphere else {
return None;
};
if !(downrange_m.is_finite() && altitude_m.is_finite() && reach_m.is_finite()) {
return None;
}
let reach_m = reach_m.abs();
[downrange_m, downrange_m + reach_m]
.into_iter()
.find_map(|downrange_m| {
let temperature_c = zones
.and_then(|sock| sock.governing_air_for_range(downrange_m))
.map_or(station.temperature_c, |zone| zone.temperature_c);
let (floor, ceiling) =
absolute_zero_altitudes_m(temperature_c + KELVIN_OFFSET, station.altitude_m);
if altitude_m + reach_m >= ceiling {
Some(AtmosphereError::aloft(temperature_c, ceiling))
} else if altitude_m - reach_m <= floor {
Some(AtmosphereError::aloft(temperature_c, floor))
} else {
None
}
})
}
#[inline]
fn compose_local_air(
altitude_m: f64,
base_alt: f64,
base: &GoverningAir,
gravity: Gravity,
) -> LocalAir {
let (temperature_k, pressure_pa, density_kg_m3) = local_temp_pressure_density_with_gravity(
altitude_m,
base_alt,
base.temperature_c,
base.pressure_hpa,
base.density_ratio,
base.vapor_mole_fraction,
gravity,
);
let air = LocalAir {
density_kg_m3,
speed_of_sound_mps: moist_sound_speed_at_mole_fraction(
temperature_k,
base.vapor_mole_fraction,
),
temperature_k,
pressure_pa,
};
#[cfg(test)]
air_trace::record(air_trace::AirTraceEntry {
altitude_m,
base_alt_m: base_alt,
base_temp_c: base.temperature_c,
base_press_hpa: base.pressure_hpa,
base_ratio: base.density_ratio,
humidity_percent: base.humidity_percent,
gravity_mps2: gravity.magnitude(),
air,
lookup_saturation_pressures: None,
consumed: None,
consumptions: 0,
});
air
}
#[cfg(test)]
pub(crate) mod air_trace {
use super::LocalAir;
use std::cell::{Cell, RefCell};
#[derive(Debug, Clone, Copy)]
pub(crate) struct AirTraceEntry {
pub altitude_m: f64,
pub base_alt_m: f64,
pub base_temp_c: f64,
pub base_press_hpa: f64,
pub base_ratio: f64,
pub humidity_percent: f64,
pub gravity_mps2: f64,
pub air: LocalAir,
pub lookup_saturation_pressures: Option<u64>,
pub consumed: Option<ConsumedAir>,
pub consumptions: u32,
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct ConsumedAir {
pub density_kg_m3: f64,
pub airspeed_mps: f64,
pub mach: f64,
}
thread_local! {
static TRACE: RefCell<Option<Vec<AirTraceEntry>>> = const { RefCell::new(None) };
static SATURATION_PRESSURES: Cell<u64> = const { Cell::new(0) };
}
#[inline(always)]
pub(super) fn count_saturation_pressure() {
SATURATION_PRESSURES.with(|count| count.set(count.get() + 1));
}
pub(crate) fn saturation_pressures() -> u64 {
SATURATION_PRESSURES.with(Cell::get)
}
pub(super) fn attribute_lookup_saturation_pressures(before: u64) {
let evaluated = saturation_pressures() - before;
TRACE.with(|trace| {
if let Some(last) = trace
.borrow_mut()
.as_mut()
.and_then(|entries| entries.last_mut())
{
last.lookup_saturation_pressures = Some(evaluated);
}
});
}
pub(crate) fn record_consumed(density_kg_m3: f64, airspeed_mps: f64, mach: f64) {
TRACE.with(|trace| {
if let Some(last) = trace
.borrow_mut()
.as_mut()
.and_then(|entries| entries.last_mut())
{
last.consumed = Some(ConsumedAir {
density_kg_m3,
airspeed_mps,
mach,
});
last.consumptions += 1;
}
});
}
pub(super) fn record(entry: AirTraceEntry) {
TRACE.with(|trace| {
if let Some(entries) = trace.borrow_mut().as_mut() {
entries.push(entry);
}
});
}
struct Restore(Option<Vec<AirTraceEntry>>);
impl Drop for Restore {
fn drop(&mut self) {
let previous = self.0.take();
TRACE.with(|trace| *trace.borrow_mut() = previous);
}
}
pub(crate) fn traced<R>(run: impl FnOnce() -> R) -> (R, Vec<AirTraceEntry>) {
let restore = Restore(TRACE.with(|trace| trace.borrow_mut().replace(Vec::new())));
let result = run();
let entries = TRACE
.with(|trace| trace.borrow_mut().take())
.unwrap_or_default();
drop(restore);
(result, entries)
}
}
#[cfg(test)]
fn local_temp_pressure_density(
altitude_m: f64,
base_alt: f64,
base_temp_c: f64,
base_press_hpa: f64,
base_ratio: f64,
) -> (f64, f64, f64) {
local_temp_pressure_density_with_gravity(
altitude_m,
base_alt,
base_temp_c,
base_press_hpa,
base_ratio,
0.0,
Gravity::EARTH,
)
}
fn local_temp_pressure_density_with_gravity(
altitude_m: f64,
base_alt: f64,
base_temp_c: f64,
base_press_hpa: f64,
base_ratio: f64,
vapor_mole_fraction: f64,
gravity: Gravity,
) -> (f64, f64, f64) {
let base_temp_k = base_temp_c + 273.15;
if !altitude_m.is_finite() || !base_alt.is_finite() {
return (f64::NAN, f64::NAN, f64::NAN);
}
let gas_constant = R_AIR / moist_molar_mass_ratio(vapor_mole_fraction);
let base_geopotential_m = geometric_to_geopotential_height_m(base_alt);
let target_geopotential_m = geometric_to_geopotential_height_m(altitude_m);
let (temp_k, pressure_hpa) = integrate_local_atmosphere_layers(
base_geopotential_m,
target_geopotential_m,
base_temp_k,
base_press_hpa,
gas_constant,
gravity,
);
let density_ratio = base_ratio * (base_temp_k * pressure_hpa) / (base_press_hpa * temp_k);
let density = density_ratio * 1.225;
(temp_k, pressure_hpa * 100.0, density)
}
fn integrate_local_atmosphere_layers(
base_geopotential_m: f64,
target_geopotential_m: f64,
mut temp_k: f64,
mut pressure_hpa: f64,
gas_constant: f64,
gravity: Gravity,
) -> (f64, f64) {
let mut current_alt = base_geopotential_m;
if target_geopotential_m > current_alt {
while current_alt < target_geopotential_m {
let layer_index = ICAO_LAYERS
.iter()
.rposition(|layer| current_alt >= layer.base_altitude)
.unwrap_or(0);
let segment_end = ICAO_LAYERS
.get(layer_index + 1)
.map_or(target_geopotential_m, |next| {
target_geopotential_m.min(next.base_altitude)
});
(temp_k, pressure_hpa) = integrate_local_atmosphere_segment(
temp_k,
pressure_hpa,
segment_end - current_alt,
ICAO_LAYERS[layer_index].lapse_rate,
gas_constant,
gravity,
);
current_alt = segment_end;
}
} else {
while current_alt > target_geopotential_m {
let layer_index = ICAO_LAYERS
.iter()
.rposition(|layer| current_alt > layer.base_altitude)
.unwrap_or(0);
let segment_end = if layer_index == 0 {
target_geopotential_m
} else {
target_geopotential_m.max(ICAO_LAYERS[layer_index].base_altitude)
};
(temp_k, pressure_hpa) = integrate_local_atmosphere_segment(
temp_k,
pressure_hpa,
segment_end - current_alt,
ICAO_LAYERS[layer_index].lapse_rate,
gas_constant,
gravity,
);
current_alt = segment_end;
}
}
(temp_k, pressure_hpa)
}
#[inline]
fn integrate_local_atmosphere_segment(
base_temp_k: f64,
base_pressure_hpa: f64,
height_diff: f64,
lapse_rate: f64,
gas_constant: f64,
gravity: Gravity,
) -> (f64, f64) {
let temp_k = base_temp_k + lapse_rate * height_diff;
let pressure_hpa = if lapse_rate.abs() < 1e-10 {
base_pressure_hpa
* (-gravity.magnitude() * height_diff / (gas_constant * base_temp_k)).exp()
} else {
let temp_ratio = temp_k / base_temp_k;
base_pressure_hpa * temp_ratio.powf(-gravity.magnitude() / (lapse_rate * gas_constant))
};
(temp_k, pressure_hpa)
}
#[cfg(test)]
mod uniform_gravity_tests {
use super::*;
#[test]
fn uniform_gravity_controls_hydrostatic_pressure_without_moving_the_station_anchor() {
for magnitude in [0.0, 1.62, 9.80665, 20.0] {
let gravity = Gravity::new(magnitude).unwrap();
let (temperature, pressure) =
integrate_local_atmosphere_segment(280.0, 900.0, 100.0, 0.0, R_AIR, gravity);
assert_eq!(temperature, 280.0);
assert!(
(pressure / 900.0 - (-magnitude * 100.0 / (R_AIR * 280.0)).exp()).abs() < 1e-14
);
let station = local_temp_pressure_density_with_gravity(
300.0, 300.0, 20.0, 900.0, 0.9, 0.0, gravity,
);
assert_eq!(
station,
local_temp_pressure_density(300.0, 300.0, 20.0, 900.0, 0.9)
);
}
let (_, pressure, _) = local_temp_pressure_density_with_gravity(
25_000.0,
0.0,
20.0,
900.0,
0.9,
0.0,
Gravity::new(0.0).unwrap(),
);
assert_eq!(pressure, 90_000.0);
}
}
#[cfg(test)]
#[inline(always)]
fn determine_local_lapse_rate(altitude_m: f64) -> f64 {
let layer = ICAO_LAYERS
.iter()
.rev()
.find(|layer| altitude_m >= layer.base_altitude)
.unwrap_or(&ICAO_LAYERS[0]);
layer.lapse_rate
}
#[inline(always)]
pub fn get_direct_atmosphere(density: f64, speed_of_sound: f64) -> (f64, f64) {
(density, speed_of_sound)
}
pub fn calculate_air_density_cipm(temp_c: f64, pressure_hpa: f64, humidity_percent: f64) -> f64 {
calculate_air_density_cimp(temp_c, pressure_hpa, humidity_percent)
}
pub type AtmoSegment = (f64, f64, f64, f64);
#[derive(Clone)]
pub struct AtmoSock {
segments: Vec<AtmoSegment>,
governing: Vec<GoverningAir>,
}
impl fmt::Debug for AtmoSock {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AtmoSock")
.field("segments", &self.segments)
.finish()
}
}
impl AtmoSock {
pub fn new(mut segments: Vec<AtmoSegment>) -> Self {
segments.sort_by(|a, b| match (a.3.is_nan(), b.3.is_nan()) {
(true, true) => Ordering::Equal,
(true, false) => Ordering::Greater,
(false, true) => Ordering::Less,
(false, false) => a.3.partial_cmp(&b.3).unwrap(),
});
let governing = segments.iter().map(GoverningAir::zone).collect();
AtmoSock {
segments,
governing,
}
}
pub fn is_empty(&self) -> bool {
self.segments.is_empty()
}
pub fn validate(&self) -> Result<(), AtmosphereError> {
for (index, &(temperature_c, pressure_hpa, humidity_percent, until_m)) in
self.segments.iter().enumerate()
{
let at = |error: AtmosphereError| {
let field = format!("atmo_sock.zones[{index}].{}", error.field());
error.at_field(field)
};
check_station_state(0.0, temperature_c, pressure_hpa).map_err(at)?;
let humidity = RelativeHumidity::try_percent(humidity_percent).map_err(at)?;
refuse_impossible_air(temperature_c, pressure_hpa, humidity).map_err(at)?;
if until_m.is_nan() || until_m <= 0.0 {
return Err(at(AtmosphereError::new(
"until_distance_m",
until_m,
AtmosphereErrorReason::NonPositiveZoneThreshold,
)));
}
}
Ok(())
}
pub fn atmo_for_range(&self, downrange_m: f64) -> (f64, f64, f64) {
match self.zone_index(downrange_m) {
Some(index) => {
let (temp_c, pressure_hpa, humidity_percent, _) = self.segments[index];
(temp_c, pressure_hpa, humidity_percent)
}
None => (15.0, 1013.25, DEFAULT_HUMIDITY_PERCENT),
}
}
#[inline]
fn governing_air_for_range(&self, downrange_m: f64) -> Option<&GoverningAir> {
self.zone_index(downrange_m)
.map(|index| &self.governing[index])
}
#[inline]
fn zone_index(&self, downrange_m: f64) -> Option<usize> {
let last = self.segments.len().checked_sub(1)?;
if downrange_m.is_nan() {
return Some(0);
}
Some(
self.segments
.iter()
.position(|segment| downrange_m < segment.3)
.unwrap_or(last),
)
}
}
#[cfg(test)]
mod humidity_model_tests;
#[cfg(test)]
mod aloft_vapour_tests;
#[cfg(test)]
mod nan_humidity_tests;
#[cfg(test)]
mod held_vapour_tests;
#[cfg(test)]
mod temperature_rule_tests;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn inclined_shot_frame_position_maps_to_world_altitude() {
let base_altitude = 100.0;
let downrange = 1_000.0;
let shot_y = 10.0;
let angle = std::f64::consts::FRAC_PI_6;
let expected = base_altitude + downrange * angle.sin() + shot_y * angle.cos();
let actual = shot_frame_altitude(base_altitude, downrange, shot_y, angle);
assert!(
(actual - expected).abs() < 1e-12,
"30-degree shot at x=1000/y=10 should be at {expected} m, got {actual} m"
);
assert_eq!(
shot_frame_altitude(base_altitude, downrange, shot_y, 0.0),
base_altitude + shot_y,
"flat-fire altitude must remain byte-identical"
);
let downhill = shot_frame_altitude(base_altitude, downrange, shot_y, -angle);
let expected_downhill = base_altitude - downrange * angle.sin() + shot_y * angle.cos();
assert!((downhill - expected_downhill).abs() < 1e-12);
}
#[test]
fn test_mba1136_dry_sea_level_reference() {
let (density, sos) = calculate_atmosphere(0.0, Some(15.0), Some(1013.25), 0.0);
assert!(
(density - 1.225).abs() < 0.002,
"dry sea-level density {density} not within 1.225 +- 0.002"
);
assert!(
(sos - 340.3).abs() < 0.6,
"dry sea-level speed of sound {sos} not within 340.3 +- 0.6"
);
}
#[test]
fn test_mba1136_humid_lighter_than_dry() {
let (dry_rho, dry_sos) = calculate_atmosphere(0.0, Some(15.0), Some(1013.25), 0.0);
let (moist_rho, moist_sos) = calculate_atmosphere(0.0, Some(15.0), Some(1013.25), 50.0);
assert!(
(moist_rho - 1.2211).abs() < 0.002,
"50% RH density {moist_rho} not within CIPM 1.2211 +- 0.002"
);
assert!(
moist_rho < dry_rho,
"moist air ({moist_rho}) must be lighter than dry ({dry_rho})"
);
assert!(
moist_sos > dry_sos,
"moist speed of sound ({moist_sos}) must exceed dry ({dry_sos})"
);
}
#[test]
fn test_mba1136_density_monotone_in_humidity() {
let (rho_0, _) = calculate_atmosphere(0.0, Some(15.0), Some(1013.25), 0.0);
let (rho_50, _) = calculate_atmosphere(0.0, Some(15.0), Some(1013.25), 50.0);
let (rho_100, _) = calculate_atmosphere(0.0, Some(15.0), Some(1013.25), 100.0);
assert!(
rho_100 < rho_50 && rho_50 < rho_0,
"humidity monotonicity violated: 100%={rho_100}, 50%={rho_50}, 0%={rho_0}"
);
}
#[test]
fn test_mba1136_atmosphere_density_is_cipm() {
for (t, p, h) in [
(15.0, 1013.25, 0.0),
(15.0, 1013.25, 50.0),
(30.0, 1000.0, 80.0),
(-10.0, 1020.0, 20.0),
] {
let (density, _) = calculate_atmosphere(0.0, Some(t), Some(p), h);
let cipm = calculate_air_density_cimp(t, p, h);
assert_eq!(
density, cipm,
"calculate_atmosphere density must equal CIPM at {t}C/{p}hPa/{h}%"
);
}
}
#[test]
fn test_mba1136_moist_speed_of_sound_extraction() {
for (t, p, h) in [
(15.0, 1013.25, 0.0),
(15.0, 1013.25, 50.0),
(25.0, 900.0, 100.0),
] {
let (_, sos) = calculate_atmosphere(0.0, Some(t), Some(p), h);
let extracted = moist_speed_of_sound(t + 273.15, p * 100.0, h);
assert_eq!(
sos, extracted,
"extracted moist_speed_of_sound must match calculate_atmosphere at {t}C/{p}hPa/{h}%"
);
}
}
#[test]
#[allow(deprecated)] fn test_mba1136_get_local_atmosphere_reference() {
let (d0, c0) = get_local_atmosphere(500.0, 500.0, 10.0, 950.0, 1.05);
assert!(
(d0 - 1.286250000000).abs() < 1e-9,
"local density@500m drifted: {d0}"
);
assert!(
(c0 - 337.328800091246).abs() < 1e-9,
"local sos@500m drifted: {c0}"
);
let (d1, c1) = get_local_atmosphere(1500.0, 500.0, 10.0, 950.0, 1.05);
assert!(
(d1 - 1.165238292559).abs() < 1e-9,
"local density@1500m drifted: {d1}"
);
assert!(
(c1 - 333.435687667240).abs() < 1e-9,
"local sos@1500m drifted: {c1}"
);
}
#[test]
#[allow(deprecated)] fn fractional_station_altitude_is_not_quantized() {
let station_altitude_m = 500.25;
let station_temp_c = 10.0;
let station_pressure_hpa = 950.0;
let station_density_ratio = 1.05;
let (density, speed_of_sound) = get_local_atmosphere(
station_altitude_m,
station_altitude_m,
station_temp_c,
station_pressure_hpa,
station_density_ratio,
);
let expected_density = station_density_ratio * 1.225;
let expected_speed_of_sound = (GAMMA * R_AIR * (station_temp_c + 273.15)).sqrt();
assert!((density - expected_density).abs() < 1e-12);
assert!((speed_of_sound - expected_speed_of_sound).abs() < 1e-12);
}
#[test]
#[allow(deprecated)] fn test_mba1136_get_local_atmosphere_humid() {
let (d_dry, c_dry) = get_local_atmosphere(1500.0, 500.0, 10.0, 950.0, 1.05);
let (d_h0, c_h0) = get_local_atmosphere_humid(1500.0, 500.0, 10.0, 950.0, 1.05, 0.0);
assert_eq!(d_dry, d_h0, "humid variant must not change density");
assert_eq!(
c_h0.to_bits(),
c_dry.to_bits(),
"0% RH humid sos {c_h0} must be the dry sos {c_dry}"
);
let (_, c_h80) = get_local_atmosphere_humid(1500.0, 500.0, 10.0, 950.0, 1.05, 80.0);
assert!(c_h80 > c_dry, "humid sos {c_h80} should exceed dry {c_dry}");
}
#[test]
fn test_icao_standard_atmosphere() {
let (temp, press) = calculate_icao_standard_atmosphere(0.0);
assert!((temp - 288.15).abs() < 0.01);
assert!((press - 101325.0).abs() < 1.0);
let geometric_tropopause_m =
GEOPOTENTIAL_EARTH_RADIUS_M * 11000.0 / (GEOPOTENTIAL_EARTH_RADIUS_M - 11000.0);
let (temp_11km, press_11km) = calculate_icao_standard_atmosphere(geometric_tropopause_m);
assert!((temp_11km - 216.65).abs() < 0.01);
assert!((press_11km - 22632.1).abs() < 1.0);
let (temp_25km, _) = calculate_icao_standard_atmosphere(25000.0);
assert!(temp_25km > 216.65); }
#[test]
fn standard_atmosphere_extends_below_sea_level() {
let altitude_m = -430.0;
let (temp_k, pressure_pa) = calculate_icao_standard_atmosphere(altitude_m);
assert!((temp_k - 290.945_189_079_054).abs() < 1e-9);
assert!((pressure_pa - 106_598.763_552_437).abs() < 0.1);
let (station_temp_c, station_pressure_hpa) =
resolve_station_conditions(15.0, 1013.25, altitude_m);
assert!((station_temp_c - 17.795_189_079_054).abs() < 1e-9);
assert!((station_pressure_hpa - 1_065.987_635_524).abs() < 1e-6);
let (sea_density, _) = calculate_atmosphere(0.0, None, None, 0.0);
let (below_sea_density, _) = calculate_atmosphere(altitude_m, None, None, 0.0);
assert!((below_sea_density - 1.276_908_642_79).abs() < 1e-6);
assert!(below_sea_density > sea_density * 1.04);
assert_eq!(
calculate_icao_standard_atmosphere(-6000.0),
calculate_icao_standard_atmosphere(MIN_GEOMETRIC_ALTITUDE_M)
);
}
#[test]
fn standard_atmosphere_converts_geometric_to_geopotential_height() {
let cases: [(f64, f64, f64); 3] = [
(10_000.0, 223.252_092_647_979, 26_499.901_600_244),
(30_000.0, 226.509_083_611_330, 1_197.032_108_466),
(84_000.0, 190.841_043_736_102, 0.531_525_514_935),
];
for (geometric_m, expected_temp_k, expected_pressure_pa) in cases {
let (temp_k, pressure_pa) = calculate_icao_standard_atmosphere(geometric_m);
let pressure_tolerance = expected_pressure_pa.max(1.0_f64) * 1e-6;
assert!((temp_k - expected_temp_k).abs() < 1e-9);
assert!((pressure_pa - expected_pressure_pa).abs() < pressure_tolerance);
}
}
#[test]
#[allow(deprecated)] fn local_atmosphere_walks_icao_layers_continuously() {
for altitude_m in [
10999.0, 11000.0, 11001.0, 11050.0, 19999.0, 20000.0, 20001.0, 25000.0,
] {
let (local_temp_k, local_pressure_pa, _) =
local_temp_pressure_density(altitude_m, 0.0, 15.0, 1013.25, 1.0);
let (standard_temp_k, standard_pressure_pa) =
calculate_icao_standard_atmosphere(altitude_m);
assert!(
(local_temp_k - standard_temp_k).abs() < 1e-9,
"local temperature diverged from ICAO at {altitude_m} m: local={local_temp_k}, standard={standard_temp_k}"
);
assert!(
((local_pressure_pa - standard_pressure_pa) / standard_pressure_pa).abs() < 5e-5,
"local pressure diverged from ICAO at {altitude_m} m: local={local_pressure_pa}, standard={standard_pressure_pa}"
);
}
let (density_below, sound_below) = get_local_atmosphere(10999.0, 0.0, 15.0, 1013.25, 1.0);
let (density_above, sound_above) = get_local_atmosphere(11001.0, 0.0, 15.0, 1013.25, 1.0);
assert!(
(density_below - density_above).abs() < 0.001,
"density jumped across 11 km: below={density_below}, above={density_above}"
);
assert!(
(sound_below - sound_above).abs() < 0.1,
"speed of sound jumped across 11 km: below={sound_below}, above={sound_above}"
);
}
#[test]
fn local_atmosphere_preserves_nonstandard_station_offset_and_round_trips() {
let base_alt = 7500.0;
let base_temp_c = 5.0;
let base_pressure_hpa = 410.0;
let base_ratio = 0.72;
let (high_temp_k, high_pressure_pa, high_density) = local_temp_pressure_density(
25000.0,
base_alt,
base_temp_c,
base_pressure_hpa,
base_ratio,
);
assert!((high_temp_k - 260.244_615_053_376).abs() < 1e-9);
assert!((high_pressure_pa / 100.0 - 40.964_358_485_456).abs() < 1e-9);
assert!((high_density - 0.094_186_400_274).abs() < 1e-9);
let (back_temp_k, back_pressure_pa, back_density) = local_temp_pressure_density(
base_alt,
25000.0,
high_temp_k - 273.15,
high_pressure_pa / 100.0,
high_density / 1.225,
);
assert!((back_temp_k - (base_temp_c + 273.15)).abs() < 1e-9);
assert!((back_pressure_pa / 100.0 - base_pressure_hpa).abs() < 1e-8);
assert!((back_density - base_ratio * 1.225).abs() < 1e-9);
}
#[test]
fn test_enhanced_atmosphere_sea_level() {
let (density, speed) = calculate_atmosphere(0.0, None, None, 0.0);
assert!((density - 1.225).abs() < 0.01);
assert!((speed - 340.0).abs() < 1.0);
}
#[test]
fn station_pressure_plausibility_band_edges_are_inside_the_band() {
let at_sea_level = |pa| station_pressure_plausibility(pa, 0.0);
assert_eq!(at_sea_level(101_325.0).icao_standard_pa, 101_325.0);
let high_edge = at_sea_level(109_431.0);
assert_eq!(high_edge.ratio, STATION_PRESSURE_MAX_PLAUSIBLE_RATIO);
assert!(!high_edge.implausible, "{high_edge:?}");
assert!(at_sea_level(109_432.0).implausible);
let low_edge = at_sea_level(86_126.25);
assert_eq!(low_edge.ratio, STATION_PRESSURE_MIN_PLAUSIBLE_RATIO);
assert!(!low_edge.implausible, "{low_edge:?}");
assert!(at_sea_level(86_126.0).implausible);
for altitude_m in [-400.0, 1500.0, 3310.128] {
let (_, icao_pa) = calculate_icao_standard_atmosphere(altitude_m);
for (ratio, implausible) in [
(STATION_PRESSURE_MAX_PLAUSIBLE_RATIO * (1.0 - 1e-9), false),
(STATION_PRESSURE_MAX_PLAUSIBLE_RATIO * (1.0 + 1e-9), true),
(STATION_PRESSURE_MIN_PLAUSIBLE_RATIO * (1.0 + 1e-9), false),
(STATION_PRESSURE_MIN_PLAUSIBLE_RATIO * (1.0 - 1e-9), true),
] {
let p = station_pressure_plausibility(ratio * icao_pa, altitude_m);
assert_eq!(p.icao_standard_pa, icao_pa);
assert_eq!(
p.implausible, implausible,
"{altitude_m} m, ratio {ratio}: {p:?}"
);
}
}
assert!(station_pressure_plausibility(f64::NAN, 0.0).implausible);
}
#[test]
fn station_pressure_plausibility_passes_record_weather_and_flags_a_placeholder() {
for record_hpa in [870.0, 1083.8, 1089.1] {
let p = station_pressure_plausibility(record_hpa * 100.0, 0.0);
assert!(!p.implausible, "{record_hpa} hPa: {p:?}");
}
let placeholder = station_pressure_plausibility(101_325.0, 3310.128);
assert!(placeholder.implausible, "{placeholder:?}");
assert!((placeholder.ratio - 1.503).abs() < 5e-4, "{placeholder:?}");
assert!(!station_pressure_plausibility(68_830.0, 3310.128).implausible);
assert!(station_pressure_plausibility(68_830.0, 0.0).implausible);
assert!(!station_pressure_plausibility(101_325.0, 640.0).implausible);
assert!(station_pressure_plausibility(101_325.0, 650.0).implausible);
}
#[test]
fn test_resolve_station_pressure_contract() {
assert_eq!(resolve_station_pressure(1013.25, 2000.0), None);
assert_eq!(resolve_station_pressure(1013.21, 2000.0), None);
assert_eq!(resolve_station_pressure(850.0, 2000.0), Some(850.0));
assert_eq!(resolve_station_pressure(1013.25, 0.0), Some(1013.25));
}
#[test]
fn qnh_reduction_matches_hand_computed_value_at_nonzero_altitude() {
let reduced = reduce_qnh_to_station_pressure(1030.0, 1500.0);
assert!(
(reduced - 860.068_111_433_278_3).abs() < 1e-9,
"reduced={reduced}"
);
assert!(reduced < 1030.0);
}
#[test]
fn qnh_reduction_is_identity_at_sea_level() {
assert_eq!(reduce_qnh_to_station_pressure(1030.0, 0.0), 1030.0);
assert_eq!(reduce_qnh_to_station_pressure(950.5, 0.0), 950.5);
}
#[test]
fn qnh_sea_level_standard_matches_icao_standard_atmosphere_at_every_altitude() {
for altitude_m in [0.0, 500.0, 2000.0, 4500.0] {
let (_, std_pressure_pa) = calculate_icao_standard_atmosphere(altitude_m);
let reduced = reduce_qnh_to_station_pressure(1013.25, altitude_m);
assert!(
(reduced - std_pressure_pa / 100.0).abs() < 1e-9,
"altitude={altitude_m} reduced={reduced} std={}",
std_pressure_pa / 100.0
);
}
}
#[test]
fn qnh_reduction_differs_from_nws_asos_by_the_documented_amounts() {
let nws_station_hpa = |qnh_hpa: f64, elevation_m: f64| {
(qnh_hpa.powf(0.190284) - 8.4228807e-5 * elevation_m).powf(1.0 / 0.190284)
};
for (altitude_m, low, high) in [
(1500.0, 0.09, 0.11),
(4000.0, 0.3, 0.45),
(5000.0, 0.3, 0.45),
] {
for qnh_hpa in [950.0, 980.0, 1013.25, 1030.0, 1050.0] {
let gap = reduce_qnh_to_station_pressure(qnh_hpa, altitude_m)
- nws_station_hpa(qnh_hpa, altitude_m);
assert!(
(low..=high).contains(&gap),
"QNH {qnh_hpa} at {altitude_m} m: this function is {gap} hPa above NWS/ASOS"
);
}
}
}
#[test]
fn qnh_reduction_adds_the_station_height_to_the_qnhs_pressure_altitude() {
let layer = &ICAO_LAYERS[0];
let n = -layer.lapse_rate * R_AIR / G_ACCEL_MPS2;
let p0_hpa = layer.base_pressure / 100.0;
let pressure_altitude_m = |pressure_hpa: f64| {
layer.base_temperature / -layer.lapse_rate * (1.0 - (pressure_hpa / p0_hpa).powf(n))
};
for (qnh_hpa, altitude_m) in [
(1030.0, 1500.0),
(1033.0, 3310.0),
(1038.0, 4061.0),
(1000.0, 2000.0),
(980.0, 1500.0),
(1040.0, 4500.0),
(1013.25, 3000.0),
(1030.0, -400.0),
] {
let station_hpa = reduce_qnh_to_station_pressure(qnh_hpa, altitude_m);
let added_m = pressure_altitude_m(station_hpa) - pressure_altitude_m(qnh_hpa);
let height_m = geometric_to_geopotential_height_m(altitude_m);
assert!(
(added_m - height_m).abs() < 1e-6,
"QNH {qnh_hpa} hPa at {altitude_m} m: station {station_hpa} hPa adds \
{added_m} m of pressure altitude, expected {height_m} m"
);
}
}
#[test]
fn qnh_reduction_is_nan_where_no_station_pressure_exists() {
assert!(reduce_qnh_to_station_pressure(500.0, 40_000.0).is_nan());
assert!(reduce_qnh_to_station_pressure(-1030.0, 1500.0).is_nan());
for qnh_step in 0..=24 {
let qnh_hpa = 850.0 + 10.0 * f64::from(qnh_step);
for altitude_step in 0..=20 {
let altitude_m = -1000.0 + 500.0 * f64::from(altitude_step);
let station_hpa = reduce_qnh_to_station_pressure(qnh_hpa, altitude_m);
assert!(
station_hpa.is_finite() && station_hpa > 0.0,
"QNH {qnh_hpa} hPa at {altitude_m} m gave {station_hpa} hPa"
);
assert_eq!(
station_hpa.partial_cmp(&qnh_hpa),
0.0.partial_cmp(&altitude_m),
"QNH {qnh_hpa} hPa at {altitude_m} m gave {station_hpa} hPa"
);
}
}
}
#[test]
fn resolve_station_pressure_with_mode_absolute_matches_resolve_station_pressure() {
for (pressure_hpa, altitude_m) in [
(1013.25, 2000.0),
(1013.21, 2000.0),
(850.0, 2000.0),
(1013.25, 0.0),
] {
assert_eq!(
resolve_station_pressure_with_mode(
pressure_hpa,
altitude_m,
PressureReferenceMode::Absolute
),
resolve_station_pressure(pressure_hpa, altitude_m)
);
}
}
#[test]
fn resolve_station_pressure_with_mode_qnh_bypasses_the_default_sentinel() {
let qnh = 1030.0;
let altitude_m = 138.078_300_203_223_02;
let reduced = reduce_qnh_to_station_pressure(qnh, altitude_m);
assert!(
(reduced - 1013.25).abs() < 0.5,
"test fixture must land inside the sentinel band; reduced={reduced}"
);
assert_eq!(
resolve_station_pressure_with_mode(qnh, altitude_m, PressureReferenceMode::Qnh),
Some(reduced)
);
assert_eq!(resolve_station_pressure(reduced, altitude_m), None);
let (_, std_pressure_pa) = calculate_icao_standard_atmosphere(altitude_m);
assert!(
(std_pressure_pa / 100.0 - reduced).abs() > 10.0,
"fixture must show the sentinel misfire actually changes the answer materially"
);
}
#[test]
fn resolve_station_conditions_with_pressure_mode_absolute_matches_resolve_station_conditions() {
for (temp_c, pressure_hpa, altitude_m) in [
(15.0, 1013.25, 2000.0),
(-5.0, 850.0, 2000.0),
(15.0, 1013.25, 0.0),
] {
assert_eq!(
resolve_station_conditions_with_pressure_mode(
temp_c,
pressure_hpa,
altitude_m,
PressureReferenceMode::Absolute
),
resolve_station_conditions(temp_c, pressure_hpa, altitude_m)
);
}
}
#[test]
fn resolve_station_conditions_with_pressure_mode_qnh_reduces_pressure_only() {
let (temp_c, pressure_hpa) = resolve_station_conditions_with_pressure_mode(
-5.0,
1030.0,
1500.0,
PressureReferenceMode::Qnh,
);
assert_eq!(temp_c, -5.0);
assert!((pressure_hpa - 860.068_111_433_278_3).abs() < 1e-9);
}
#[test]
fn test_altitude_affects_density_with_default_pressure() {
let press = resolve_station_pressure(1013.25, 0.0);
let (rho_sea, _) = calculate_atmosphere(0.0, Some(15.0), press, 50.0);
let press_alt = resolve_station_pressure(1013.25, 2000.0);
let (rho_2km, _) = calculate_atmosphere(2000.0, Some(15.0), press_alt, 50.0);
assert!(
rho_2km < rho_sea * 0.9,
"density at 2000 m ({rho_2km}) should be well below sea level ({rho_sea})"
);
let p = resolve_station_pressure(900.0, 2000.0);
let (rho_a, _) = calculate_atmosphere(2000.0, Some(15.0), p, 50.0);
let (rho_b, _) = calculate_atmosphere(0.0, Some(15.0), p, 50.0);
assert!(
(rho_a - rho_b).abs() < 1e-9,
"explicit pressure must ignore altitude"
);
}
#[test]
fn test_resolve_station_temperature_contract() {
assert_eq!(resolve_station_temperature(15.0, 2000.0), None);
assert_eq!(resolve_station_temperature(-5.0, 2000.0), Some(-5.0));
assert_eq!(resolve_station_temperature(30.0, 2000.0), Some(30.0));
assert_eq!(resolve_station_temperature(15.0, 0.0), Some(15.0));
}
#[test]
fn test_altitude_only_default_matches_full_icao_standard() {
for alt in [1000.0, 2000.0, 2500.0, 3000.0] {
let t = resolve_station_temperature(15.0, alt);
let p = resolve_station_pressure(1013.25, alt);
let (rho_resolved, _) = calculate_atmosphere(alt, t, p, 0.0);
let (rho_std, _) = calculate_atmosphere(alt, None, None, 0.0);
assert!(
(rho_resolved - rho_std).abs() < 1e-9,
"alt {alt}: altitude-only default density {rho_resolved} should equal the full \
ICAO standard {rho_std}"
);
let (rho_warm, _) = calculate_atmosphere(alt, Some(15.0), p, 0.0);
assert!(
rho_resolved > rho_warm,
"alt {alt}: lapse-temperature density {rho_resolved} should exceed 15 C-held {rho_warm}"
);
}
}
#[test]
fn test_enhanced_atmosphere_with_humidity() {
let (density_dry, speed_dry) = calculate_atmosphere(0.0, None, None, 0.0);
let (density_humid, speed_humid) = calculate_atmosphere(0.0, None, None, 80.0);
assert!(density_humid < density_dry);
assert!(speed_humid > speed_dry);
}
#[test]
fn test_enhanced_atmosphere_stratosphere() {
let (density_20km, speed_20km) = calculate_atmosphere(20000.0, None, None, 0.0);
let (density_30km, speed_30km) = calculate_atmosphere(30000.0, None, None, 0.0);
assert!(density_30km < density_20km);
assert!(speed_30km > speed_20km);
}
#[test]
fn test_enhanced_cimp_density() {
let density = calculate_air_density_cimp(15.0, 1013.25, 0.0);
assert!((density - 1.225).abs() < 0.01);
let density_humid = calculate_air_density_cimp(15.0, 1013.25, 50.0);
assert!(density_humid < density);
}
#[test]
fn test_cipm_moist_air_matches_python_reference() {
let cases = [
(15.0, 1013.25, 50.0, 1.221125867723075),
(30.0, 1000.0, 80.0, 1.1344071877123691),
(-10.0, 1020.0, 20.0, 1.3500610713710515),
];
for (temp_c, pressure_hpa, humidity_pct, expected) in cases {
let density = calculate_air_density_cipm(temp_c, pressure_hpa, humidity_pct);
let rel_err = ((density - expected) / expected).abs();
assert!(
rel_err < 1e-3,
"CIPM density at {temp_c} C / {pressure_hpa} hPa / {humidity_pct}% RH: \
got {density}, expected {expected} (rel err {rel_err:.2e} >= 1e-3)"
);
}
let dry = calculate_air_density_cipm(15.0, 1013.25, 0.0);
let moist = calculate_air_density_cipm(15.0, 1013.25, 50.0);
assert!(
dry - moist > 3e-3,
"humidity effect too small: dry {dry} vs 50% RH {moist}"
);
}
#[test]
fn test_variable_lapse_rates() {
let lapse_tropo = determine_local_lapse_rate(5000.0);
let lapse_strato = determine_local_lapse_rate(25000.0);
assert!((lapse_tropo - (-0.0065)).abs() < 0.0001);
assert!(lapse_strato > 0.0); }
#[test]
fn test_atmo_sock_empty_falls_back_to_isa() {
let sock = AtmoSock::new(vec![]);
assert!(sock.is_empty());
assert_eq!(
sock.atmo_for_range(0.0),
(15.0, 1013.25, DEFAULT_HUMIDITY_PERCENT)
);
assert_eq!(
sock.atmo_for_range(500.0),
(15.0, 1013.25, DEFAULT_HUMIDITY_PERCENT)
);
}
#[test]
fn test_atmo_sock_single_segment_holds_beyond_last() {
let sock = AtmoSock::new(vec![(25.0, 1000.0, 30.0, 100.0)]);
assert_eq!(sock.atmo_for_range(50.0), (25.0, 1000.0, 30.0));
assert_eq!(sock.atmo_for_range(100.0), (25.0, 1000.0, 30.0)); assert_eq!(sock.atmo_for_range(5000.0), (25.0, 1000.0, 30.0));
}
#[test]
fn test_atmo_sock_boundary_is_upper_exclusive() {
let sock = AtmoSock::new(vec![
(30.0, 1010.0, 80.0, 100.0), (-5.0, 900.0, 10.0, 200.0), ]);
assert_eq!(sock.atmo_for_range(99.999), (30.0, 1010.0, 80.0));
assert_eq!(sock.atmo_for_range(100.0), (-5.0, 900.0, 10.0));
assert_eq!(sock.atmo_for_range(200.0), (-5.0, 900.0, 10.0));
assert_eq!(sock.atmo_for_range(1e6), (-5.0, 900.0, 10.0));
}
#[test]
fn test_atmo_sock_sorts_unordered_segments() {
let sock = AtmoSock::new(vec![
(-5.0, 900.0, 10.0, 200.0),
(30.0, 1010.0, 80.0, 100.0),
]);
assert_eq!(sock.atmo_for_range(50.0), (30.0, 1010.0, 80.0));
assert_eq!(sock.atmo_for_range(150.0), (-5.0, 900.0, 10.0));
}
#[test]
fn test_atmo_sock_orders_nan_thresholds_last() {
let positive_nan = f64::from_bits(0x7ff8_0000_0000_0001);
let negative_nan = f64::from_bits(0xfff8_0000_0000_0002);
let sock = AtmoSock::new(vec![
(97.0, 997.0, 97.0, positive_nan),
(30.0, 1030.0, 30.0, 300.0),
(98.0, 998.0, 98.0, negative_nan),
(10.0, 1010.0, 10.0, 100.0),
(99.0, 999.0, 99.0, f64::NAN),
(20.0, 1020.0, 20.0, 200.0),
]);
let thresholds: Vec<_> = sock.segments.iter().map(|segment| segment.3).collect();
assert_eq!(&thresholds[..3], &[100.0, 200.0, 300.0]);
assert!(thresholds[3..].iter().all(|threshold| threshold.is_nan()));
assert_eq!(sock.atmo_for_range(f64::NAN), (10.0, 1010.0, 10.0));
assert_eq!(sock.atmo_for_range(350.0), (99.0, 999.0, 99.0));
}
#[test]
fn test_atmo_sock_nan_uses_first_zone() {
let sock = AtmoSock::new(vec![
(30.0, 1010.0, 80.0, 100.0),
(-5.0, 900.0, 10.0, 200.0),
]);
assert_eq!(sock.atmo_for_range(f64::NAN), (30.0, 1010.0, 80.0));
}
#[test]
fn density_altitude_default_temp_pressure_alt_equals_density_alt() {
for da_ft in [0.0_f64, 1000.0, 3000.0, 7500.0, -500.0] {
let da_m = da_ft * DA_FT_TO_M;
let (altitude_m, temp_c, pressure_hpa) =
resolve_atmosphere_for_density_altitude(da_m, None);
assert!(
(altitude_m - da_m).abs() < 1e-6,
"da_ft={da_ft}: altitude_m {altitude_m} should equal da_m {da_m}"
);
assert!(pressure_hpa > 0.0 && pressure_hpa < 1100.0);
assert!(temp_c.is_finite());
}
let (alt0, temp0, press0) = resolve_atmosphere_for_density_altitude(0.0, None);
assert!(alt0.abs() < 1e-9);
assert!((temp0 - 15.0).abs() < 1e-6);
assert!((press0 - 1013.25).abs() < 1e-6);
}
#[test]
fn density_altitude_pressure_decreases_monotonically() {
let (_, _, p0) = resolve_atmosphere_for_density_altitude(0.0, None);
let (_, _, p1) = resolve_atmosphere_for_density_altitude(1000.0, None);
let (_, _, p2) = resolve_atmosphere_for_density_altitude(3000.0, None);
assert!(p1 < p0);
assert!(p2 < p1);
}
#[test]
fn density_altitude_explicit_temperature_overrides_isa_default_but_honors_density() {
let da_m = 1000.0 * DA_FT_TO_M;
let (default_alt_m, default_temp_c, default_pressure_hpa) =
resolve_atmosphere_for_density_altitude(da_m, None);
let hot_temp_c = default_temp_c + 20.0;
let (hot_alt_m, hot_temp_out, hot_pressure_hpa) =
resolve_atmosphere_for_density_altitude(da_m, Some(hot_temp_c));
assert_eq!(
hot_temp_out, hot_temp_c,
"explicit temperature must be honored exactly"
);
assert!(
hot_alt_m < default_alt_m,
"hotter station temp at same DA should imply a lower pressure altitude: \
hot={hot_alt_m} default={default_alt_m}"
);
assert!(hot_pressure_hpa > default_pressure_hpa);
let cold_temp_c = default_temp_c - 20.0;
let (cold_alt_m, cold_temp_out, cold_pressure_hpa) =
resolve_atmosphere_for_density_altitude(da_m, Some(cold_temp_c));
assert_eq!(cold_temp_out, cold_temp_c);
assert!(cold_alt_m > default_alt_m);
assert!(cold_pressure_hpa < default_pressure_hpa);
}
#[test]
fn density_altitude_round_trips_through_hand_derived_forward_formula() {
fn forward_density_altitude_ft(pressure_hpa: f64, temp_c: f64) -> f64 {
let pressure_alt_ft = 145_366.45 * (1.0 - (pressure_hpa / 1013.25).powf(0.190_284));
let isa_temp_f = 59.0 - (pressure_alt_ft / 1000.0) * 3.57;
let temp_f = temp_c * 9.0 / 5.0 + 32.0;
pressure_alt_ft + (120.0 * 5.0 / 9.0) * (temp_f - isa_temp_f)
}
for da_ft in [0.0_f64, 500.0, 2500.0, 6000.0] {
let da_m = da_ft * DA_FT_TO_M;
let (_, temp_c, pressure_hpa) = resolve_atmosphere_for_density_altitude(da_m, None);
let round_tripped_ft = forward_density_altitude_ft(pressure_hpa, temp_c);
assert!(
(round_tripped_ft - da_ft).abs() < 1e-6,
"da_ft={da_ft}: round-tripped {round_tripped_ft} (temp_c={temp_c}, pressure_hpa={pressure_hpa})"
);
let explicit_temp_c = 25.0;
let (_, temp_out, pressure_hpa_explicit) =
resolve_atmosphere_for_density_altitude(da_m, Some(explicit_temp_c));
assert_eq!(temp_out, explicit_temp_c);
let round_tripped_explicit_ft =
forward_density_altitude_ft(pressure_hpa_explicit, temp_out);
assert!(
(round_tripped_explicit_ft - da_ft).abs() < 1e-6,
"da_ft={da_ft} (explicit {explicit_temp_c}C): round-tripped {round_tripped_explicit_ft}"
);
}
}
}
#[cfg(test)]
mod station_presence_tests {
use super::*;
fn legacy_resolve_ab4eb0c(
temperature_c: f64,
pressure_hpa: f64,
altitude_m: f64,
pressure_mode: PressureReferenceMode,
) -> (f64, f64) {
let temp_override = resolve_station_temperature(temperature_c, altitude_m);
let press_override =
resolve_station_pressure_with_mode(pressure_hpa, altitude_m, pressure_mode);
let (std_temp_k, std_pressure_pa) = calculate_icao_standard_atmosphere(altitude_m);
let temp_c = temp_override.unwrap_or(std_temp_k - 273.15);
let pressure_hpa = press_override.unwrap_or(std_pressure_pa / 100.0);
(temp_c, pressure_hpa)
}
const TEMPERATURES_C: [f64; 10] = [
-40.0, 14.89, 14.9, 14.95, 15.0, 15.05, 15.0999, 15.1, 15.2, 30.0,
];
const PRESSURES_HPA: [f64; 11] = [
1012.7,
1012.75,
1012.8562053925472,
1013.0,
1013.2079,
1013.25,
1013.5,
1013.75,
1014.0,
850.0,
1031.0,
];
const ALTITUDES_M: [f64; 13] = [
-2.0, -1.0, -0.5, 0.0, 0.5, 1.0, 1.0000001, 3.0, 10.0, 150.0, 1500.0, 1524.0, 5000.0,
];
const MODES: [PressureReferenceMode; 2] =
[PressureReferenceMode::Absolute, PressureReferenceMode::Qnh];
fn assert_bits(actual: (f64, f64), expected: (f64, f64), context: &str) {
assert_eq!(
actual.0.to_bits(),
expected.0.to_bits(),
"temperature {context}: {actual:?} vs {expected:?}"
);
assert_eq!(
actual.1.to_bits(),
expected.1.to_bits(),
"pressure {context}: {actual:?} vs {expected:?}"
);
}
#[test]
fn neither_is_bit_identical_to_ab4eb0c() {
for t in TEMPERATURES_C {
for p in PRESSURES_HPA {
for alt in ALTITUDES_M {
for mode in MODES {
let expected = legacy_resolve_ab4eb0c(t, p, alt, mode);
let context = format!("({t}, {p}, {alt}, {mode:?})");
assert_bits(
resolve_station_conditions_with_presence(
t,
p,
alt,
mode,
StationAtmospherePresence::NEITHER,
),
expected,
&context,
);
assert_bits(
resolve_station_conditions_with_pressure_mode(t, p, alt, mode),
expected,
&context,
);
}
}
}
}
let pinned = [
(
(15.05, 1013.0, 150.0, PressureReferenceMode::Absolute),
(
f64::from_bits(0x402c0ccfd0c49b20),
f64::from_bits(0x408f1ae13f434f1f),
),
),
(
(15.0, 1013.25, 1500.0, PressureReferenceMode::Absolute),
(
f64::from_bits(0x4015025af8d136c0),
f64::from_bits(0x408a6cc6358cefbd),
),
),
(
(15.0, 1013.25, 10.0, PressureReferenceMode::Qnh),
(
f64::from_bits(0x402ddeb85559de00),
f64::from_bits(0x408fa064e4e5f101),
),
),
(
(15.0, 1013.2079, 1524.0, PressureReferenceMode::Qnh),
(
f64::from_bits(0x401462aff47e8bc0),
f64::from_bits(0x408a58982cf0204f),
),
),
(
(
14.95,
1012.8562053925472,
1.0000001,
PressureReferenceMode::Absolute,
),
(
f64::from_bits(0x402dfcac08345a20),
f64::from_bits(0x408fa909fb979713),
),
),
(
(15.0, 1013.25, 3.0, PressureReferenceMode::Absolute),
(
f64::from_bits(0x402df60418e281e0),
f64::from_bits(0x408fa71e04fe2409),
),
),
];
for ((t, p, alt, mode), expected) in pinned {
let context = format!("pinned ({t}, {p}, {alt}, {mode:?})");
assert_bits(
resolve_station_conditions_with_presence(
t,
p,
alt,
mode,
StationAtmospherePresence::NEITHER,
),
expected,
&context,
);
assert_bits(
resolve_station_conditions_with_pressure_mode(t, p, alt, mode),
expected,
&context,
);
}
}
#[test]
fn both_returns_the_supplied_pair() {
for t in TEMPERATURES_C {
for p in PRESSURES_HPA {
for alt in ALTITUDES_M {
let context = format!("({t}, {p}, {alt})");
assert_bits(
resolve_station_conditions_with_presence(
t,
p,
alt,
PressureReferenceMode::Absolute,
StationAtmospherePresence::BOTH,
),
(t, p),
&context,
);
assert_bits(
resolve_station_conditions_with_presence(
t,
p,
alt,
PressureReferenceMode::Qnh,
StationAtmospherePresence::BOTH,
),
(t, reduce_qnh_to_station_pressure(p, alt)),
&context,
);
}
}
}
let (_, p) = resolve_station_conditions_with_presence(
20.0,
1031.0,
150.0,
PressureReferenceMode::Qnh,
StationAtmospherePresence::BOTH,
);
assert_eq!(p.to_bits(), 1012.8562053925472_f64.to_bits(), "{p:?}");
}
#[test]
fn presence_is_per_field() {
let (icao_t_k, icao_p_pa) = calculate_icao_standard_atmosphere(1500.0);
let temperature_only = resolve_station_conditions_with_presence(
15.0,
1013.25,
1500.0,
PressureReferenceMode::Absolute,
StationAtmospherePresence::new(true, false),
);
assert_bits(temperature_only, (15.0, icao_p_pa / 100.0), "(true, false)");
let pressure_only = resolve_station_conditions_with_presence(
15.0,
1013.0,
1500.0,
PressureReferenceMode::Absolute,
StationAtmospherePresence::new(false, true),
);
assert_bits(pressure_only, (icao_t_k - 273.15, 1013.0), "(false, true)");
}
#[test]
fn presence_constructors_agree() {
assert_eq!(
StationAtmospherePresence::default(),
StationAtmospherePresence::NEITHER
);
assert_eq!(
StationAtmospherePresence::NEITHER,
StationAtmospherePresence::new(false, false)
);
assert_eq!(
StationAtmospherePresence::BOTH,
StationAtmospherePresence::new(true, true)
);
assert_eq!(
StationAtmospherePresence::from_readings(
StationReading::supplied(15.0),
StationReading::omitted(1013.25)
),
StationAtmospherePresence::new(true, false)
);
assert_eq!(
StationAtmospherePresence::from_readings(
StationReading::omitted(59.0),
StationReading::supplied(29.92)
),
StationAtmospherePresence::new(false, true)
);
assert!(StationReading::omitted(29.92).is_omitted());
assert!(!StationReading::supplied(29.92).is_omitted());
assert_eq!(
StationReading::omitted(29.92).value.to_bits(),
29.92_f64.to_bits()
);
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct Probe {
#[serde(
default = "probe_default",
skip_serializing_if = "StationReading::is_omitted"
)]
pressure_inhg: StationReading,
}
fn probe_default() -> StationReading {
StationReading::omitted(29.92)
}
#[test]
fn station_reading_serde() {
let absent: Probe = serde_json::from_str("{}").unwrap();
assert!(!absent.pressure_inhg.supplied);
assert_eq!(absent.pressure_inhg.value.to_bits(), 29.92_f64.to_bits());
let present: Probe = serde_json::from_str(r#"{"pressure_inhg": 29.92}"#).unwrap();
assert!(present.pressure_inhg.supplied);
assert_eq!(present.pressure_inhg.value.to_bits(), 29.92_f64.to_bits());
assert_eq!(serde_json::to_string(&absent).unwrap(), "{}");
assert_eq!(
serde_json::to_string(&present).unwrap(),
r#"{"pressure_inhg":29.92}"#
);
assert!(serde_json::from_str::<Probe>(r#"{"pressure_inhg": null}"#).is_err());
assert!(serde_json::from_str::<Probe>(r#"{"pressure_inhg": "29.92"}"#).is_err());
}
}