1use hpr_core::interp::Side;
44use serde::{Deserialize, Serialize};
45
46use crate::air::{AirSample, Atmosphere};
47use crate::error::{AtmosError, finite, positive};
48use crate::moist::{check_relative_humidity, moist_air_unchecked, saturation_vapor_pressure_pa};
49use crate::ussa76::{DRY_AIR_GAS_CONSTANT_J_PER_KG_K, Ussa76, geometric_from_geopotential_m};
50use crate::wind::{LayeredWind, WindInterpolation, WindLevel};
51use hpr_core::gravity::STANDARD_GRAVITY_MPS2;
52
53const FILL_ITERATIONS: usize = 8;
57
58#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
60#[serde(deny_unknown_fields)]
61pub struct SoundingLevel {
62 pub height_msl_m: f64,
64 pub temperature_k: f64,
66 #[serde(default)]
68 pub pressure_pa: Option<f64>,
69 #[serde(default)]
72 pub relative_humidity: Option<f64>,
73 #[serde(default)]
75 pub wind_speed_m_s: Option<f64>,
76 #[serde(default)]
78 pub wind_direction_from_rad: Option<f64>,
79}
80
81#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
86#[serde(try_from = "SoundingProfileData", into = "SoundingProfileData")]
87pub struct SoundingProfile {
88 levels: Vec<SoundingLevel>,
89 latitude_rad: f64,
90 wind_interpolation: WindInterpolation,
91 gravity_ratio: f64,
93 radius_m: f64,
94 heights_m: Vec<f64>,
95 geopotentials_m: Vec<f64>,
97 temperatures_k: Vec<f64>,
98 pressures_pa: Vec<f64>,
99 humidities: Vec<f64>,
101 below: Ussa76,
102 above: Ussa76,
103 top_vapor_fraction: f64,
105 wind: Option<LayeredWind>,
106}
107
108#[derive(Serialize, Deserialize)]
109#[serde(deny_unknown_fields)]
110struct SoundingProfileData {
111 levels: Vec<SoundingLevel>,
112 latitude_rad: f64,
113 #[serde(default)]
114 wind_interpolation: WindInterpolation,
115 #[serde(default, skip_serializing)]
118 #[expect(
119 dead_code,
120 reason = "read only so that the key is not refused as unknown"
121 )]
122 tool: Option<serde::de::IgnoredAny>,
123 #[serde(default, skip_serializing)]
126 #[expect(
127 dead_code,
128 reason = "read only so that the key is not refused as unknown"
129 )]
130 kind: Option<serde::de::IgnoredAny>,
131 #[serde(default, skip_serializing)]
134 #[expect(
135 dead_code,
136 reason = "read only so that the key is not refused as unknown"
137 )]
138 trust: Option<serde::de::IgnoredAny>,
139}
140
141impl TryFrom<SoundingProfileData> for SoundingProfile {
142 type Error = AtmosError;
143
144 fn try_from(data: SoundingProfileData) -> Result<Self, AtmosError> {
145 SoundingProfile::new(data.levels, data.latitude_rad, data.wind_interpolation)
146 }
147}
148
149impl From<SoundingProfile> for SoundingProfileData {
150 fn from(profile: SoundingProfile) -> Self {
151 SoundingProfileData {
152 levels: profile.levels,
153 latitude_rad: profile.latitude_rad,
154 wind_interpolation: profile.wind_interpolation,
155 tool: None,
156 kind: None,
157 trust: None,
158 }
159 }
160}
161
162fn vapor(humidity: Option<f64>, t: f64) -> f64 {
164 humidity.map_or(0.0, |u| u * saturation_vapor_pressure_pa(t))
165}
166
167fn virtual_temperature(t: f64, p: f64, e: f64) -> f64 {
169 let air = moist_air_unchecked(t, p, e);
170 p / (DRY_AIR_GAS_CONSTANT_J_PER_KG_K * air.density_kg_m3)
171}
172
173fn inverse_log_mean(a: f64, b: f64) -> f64 {
176 let r = (b - a) / a;
177 if r == 0.0 {
178 1.0 / a
179 } else {
180 r.ln_1p() / (r * a)
181 }
182}
183
184impl SoundingProfile {
185 pub fn new(
201 levels: Vec<SoundingLevel>,
202 latitude_rad: f64,
203 wind_interpolation: WindInterpolation,
204 ) -> Result<Self, AtmosError> {
205 let (gamma_s, radius_m) = wmo_gravity_and_radius(latitude_rad)?;
206 let gravity_ratio = gamma_s / GAMMA_45_MPS2;
207 let Some(first) = levels.first() else {
208 return Err(AtmosError::NoLevels);
209 };
210 let has_humidity = first.relative_humidity.is_some();
211 let has_wind = first.wind_speed_m_s.is_some() || first.wind_direction_from_rad.is_some();
212 if first.pressure_pa.is_none() {
213 return Err(AtmosError::MissingBasePressure);
214 }
215
216 let n = levels.len();
217 let mut heights_m = Vec::with_capacity(n);
218 let mut geopotentials_m = Vec::with_capacity(n);
219 let mut temperatures_k = Vec::with_capacity(n);
220 let mut humidities = Vec::with_capacity(if has_humidity { n } else { 0 });
221 let mut wind_levels = Vec::with_capacity(if has_wind { n } else { 0 });
222 for (index, level) in levels.iter().enumerate() {
223 let z = finite("sounding level height (m)", level.height_msl_m)?;
224 if heights_m.last().is_some_and(|&previous| z <= previous) {
225 return Err(AtmosError::HeightsNotIncreasing { index });
226 }
227 heights_m.push(z);
228 geopotentials_m.push(wmo_geopotential(gravity_ratio, radius_m, z)?);
229 temperatures_k.push(positive("sounding temperature (K)", level.temperature_k)?);
230 if let Some(p) = level.pressure_pa {
231 positive("sounding pressure (Pa)", p)?;
232 }
233 match (has_humidity, level.relative_humidity) {
234 (true, Some(u)) => humidities.push(check_relative_humidity(u)?),
235 (false, None) => {}
236 _ => {
237 return Err(AtmosError::IncompleteColumn {
238 index,
239 column: "relative humidity",
240 });
241 }
242 }
243 match (
244 has_wind,
245 level.wind_speed_m_s,
246 level.wind_direction_from_rad,
247 ) {
248 (true, Some(speed), Some(direction)) => wind_levels.push(WindLevel {
249 height_msl_m: z,
250 speed_m_s: speed,
251 direction_from_rad: direction,
252 }),
253 (false, None, None) => {}
254 _ => {
255 return Err(AtmosError::IncompleteColumn {
256 index,
257 column: "wind speed and direction",
258 });
259 }
260 }
261 }
262
263 let humidity_at = |i: usize| humidities.get(i).copied();
264 let mut pressures_pa: Vec<f64> = Vec::with_capacity(n);
265 for (i, level) in levels.iter().enumerate() {
266 let pressure = match (level.pressure_pa, pressures_pa.last()) {
267 (Some(p), Some(&below)) if p >= below => {
268 return Err(AtmosError::PressureNotDecreasing {
269 index: i,
270 pressure_pa: p,
271 below_pa: below,
272 });
273 }
274 (Some(p), _) => p,
275 (None, Some(&below)) => {
276 let (t0, t1) = (temperatures_k[i - 1], temperatures_k[i]);
277 let dh = geopotentials_m[i] - geopotentials_m[i - 1];
278 let tv0 = virtual_temperature(t0, below, vapor(humidity_at(i - 1), t0));
279 let k = STANDARD_GRAVITY_MPS2 / DRY_AIR_GAS_CONSTANT_J_PER_KG_K * dh;
280 let mut p = below * (-k * inverse_log_mean(t0, t1)).exp();
281 if has_humidity {
282 for _ in 0..FILL_ITERATIONS {
283 let tv1 = virtual_temperature(t1, p, vapor(humidity_at(i), t1));
284 p = below * (-k * inverse_log_mean(tv0, tv1)).exp();
285 }
286 }
287 positive("filled sounding pressure (Pa)", p)?
288 }
289 (None, None) => return Err(AtmosError::MissingBasePressure),
291 };
292 pressures_pa.push(pressure);
293 }
294
295 let last = n - 1;
296 let below = Ussa76::anchored(
297 geometric_from_geopotential_m(geopotentials_m[0])?,
298 temperatures_k[0],
299 pressures_pa[0],
300 )?;
301 let above = Ussa76::anchored(
302 geometric_from_geopotential_m(geopotentials_m[last])?,
303 temperatures_k[last],
304 pressures_pa[last],
305 )?;
306 let top_vapor_fraction =
307 (vapor(humidity_at(last), temperatures_k[last]) / pressures_pa[last]).min(1.0);
308 let wind = if has_wind {
309 Some(LayeredWind::new(wind_levels, wind_interpolation)?)
310 } else {
311 None
312 };
313 Ok(SoundingProfile {
314 levels,
315 latitude_rad,
316 wind_interpolation,
317 gravity_ratio,
318 radius_m,
319 heights_m,
320 geopotentials_m,
321 temperatures_k,
322 pressures_pa,
323 humidities,
324 below,
325 above,
326 top_vapor_fraction,
327 wind,
328 })
329 }
330
331 pub fn levels(&self) -> &[SoundingLevel] {
333 &self.levels
334 }
335
336 pub fn latitude_rad(&self) -> f64 {
338 self.latitude_rad
339 }
340
341 pub fn pressures_pa(&self) -> &[f64] {
343 &self.pressures_pa
344 }
345
346 pub fn wind(&self) -> Option<&LayeredWind> {
348 self.wind.as_ref()
349 }
350
351 pub fn sample(&self, height_msl_m: f64) -> Result<AirSample, AtmosError> {
358 let z = finite("height (m)", height_msl_m)?;
359 let n = self.heights_m.len();
360 let humidity = |i: usize| self.humidities.get(i).copied();
361 let geopotential = wmo_geopotential(self.gravity_ratio, self.radius_m, z)?;
362 if z < self.heights_m[0] {
363 let air = self
364 .below
365 .sample(geometric_from_geopotential_m(geopotential)?)?
366 .air;
367 let e = vapor(humidity(0), air.temperature_k);
368 return Ok(AirSample {
369 air: moist_air_unchecked(air.temperature_k, air.pressure_pa, e),
370 extrapolated: Some(Side::Below),
371 });
372 }
373 if z > self.heights_m[n - 1] {
374 let air = self
375 .above
376 .sample(geometric_from_geopotential_m(geopotential)?)?
377 .air;
378 let e = (self.top_vapor_fraction * air.pressure_pa)
379 .min(saturation_vapor_pressure_pa(air.temperature_k));
380 return Ok(AirSample {
381 air: moist_air_unchecked(air.temperature_k, air.pressure_pa, e),
382 extrapolated: Some(Side::Above),
383 });
384 }
385 let upper = self.heights_m.partition_point(|&h| h <= z);
387 if upper >= n {
388 let t = self.temperatures_k[n - 1];
389 let e = vapor(humidity(n - 1), t);
390 return Ok(AirSample {
391 air: moist_air_unchecked(t, self.pressures_pa[n - 1], e),
392 extrapolated: None,
393 });
394 }
395 let i = upper - 1;
396 let (z0, z1) = (self.geopotentials_m[i], self.geopotentials_m[upper]);
397 let fraction = ((geopotential - z0) / (z1 - z0)).clamp(0.0, 1.0);
398 let (t0, t1) = (self.temperatures_k[i], self.temperatures_k[upper]);
399 let t = t0 + fraction * (t1 - t0);
400 let (p0, p1) = (self.pressures_pa[i], self.pressures_pa[upper]);
401 let r = (t1 - t0) / t0;
402 let shape = if r == 0.0 {
403 fraction
404 } else {
405 (fraction * r).ln_1p() / r.ln_1p()
406 };
407 let p = p0 * ((p1 / p0).ln() * shape).exp();
408 let e = match (humidity(i), humidity(upper)) {
409 (Some(u0), Some(u1)) => (u0 + fraction * (u1 - u0)) * saturation_vapor_pressure_pa(t),
410 _ => 0.0,
411 };
412 Ok(AirSample {
413 air: moist_air_unchecked(t, p, e),
414 extrapolated: None,
415 })
416 }
417}
418
419impl Atmosphere for SoundingProfile {
420 fn air(&self, height_msl_m: f64) -> Result<AirSample, AtmosError> {
421 self.sample(height_msl_m)
422 }
423}
424
425const GAMMA_45_MPS2: f64 = STANDARD_GRAVITY_MPS2;
427
428fn wmo_geopotential(gravity_ratio: f64, radius_m: f64, height_m: f64) -> Result<f64, AtmosError> {
430 if height_m <= -radius_m {
431 return Err(AtmosError::Domain {
432 what: "geometric height (m)",
433 value: height_m,
434 });
435 }
436 Ok(gravity_ratio * radius_m * height_m / (radius_m + height_m))
437}
438
439fn wmo_gravity_and_radius(latitude_rad: f64) -> Result<(f64, f64), AtmosError> {
441 let phi = finite("latitude (rad)", latitude_rad)?;
442 if phi.abs() > std::f64::consts::FRAC_PI_2 {
443 return Err(AtmosError::Domain {
444 what: "latitude (rad)",
445 value: phi,
446 });
447 }
448 let s2 = phi.sin().powi(2);
449 let gamma_s = 9.780_325 * (1.0 + 0.001_931_85 * s2) / (1.0 - 0.006_694_35 * s2).sqrt();
450 let radius_m = 6_378_137.0 / (1.006_803 - 0.006_706 * s2);
451 Ok((gamma_s, radius_m))
452}
453
454pub fn wmo_geopotential_from_geometric_m(
470 height_msl_m: f64,
471 latitude_rad: f64,
472) -> Result<f64, AtmosError> {
473 let (gamma_s, radius) = wmo_gravity_and_radius(latitude_rad)?;
474 let z = finite("geometric height (m)", height_msl_m)?;
475 wmo_geopotential(gamma_s / GAMMA_45_MPS2, radius, z)
476}
477
478pub fn geometric_from_wmo_geopotential_m(
487 geopotential_height_m: f64,
488 latitude_rad: f64,
489) -> Result<f64, AtmosError> {
490 let (gamma_s, radius) = wmo_gravity_and_radius(latitude_rad)?;
491 let scaled =
492 finite("geopotential height (gpm)", geopotential_height_m)? * GAMMA_45_MPS2 / gamma_s;
493 if scaled >= radius {
494 return Err(AtmosError::Domain {
495 what: "geopotential height (gpm)",
496 value: geopotential_height_m,
497 });
498 }
499 Ok(radius * scaled / (radius - scaled))
500}
501
502#[cfg(test)]
503mod tests {
504 use hpr_core::gravity::NormalGravity;
505
506 use super::*;
507 use crate::moist::moist_air;
508 use crate::wind::Wind;
509
510 const LATITUDE_RAD: f64 = 32.99 * std::f64::consts::PI / 180.0;
512
513 fn level(z: f64, t: f64, p: Option<f64>, u: Option<f64>) -> SoundingLevel {
514 SoundingLevel {
515 height_msl_m: z,
516 temperature_k: t,
517 pressure_pa: p,
518 relative_humidity: u,
519 wind_speed_m_s: None,
520 wind_direction_from_rad: None,
521 }
522 }
523
524 fn profile_at(levels: Vec<SoundingLevel>, latitude_rad: f64) -> SoundingProfile {
525 SoundingProfile::new(levels, latitude_rad, WindInterpolation::default()).unwrap()
526 }
527
528 fn standard_height(z: f64, latitude_rad: f64) -> f64 {
531 geometric_from_geopotential_m(wmo_geopotential_from_geometric_m(z, latitude_rad).unwrap())
532 .unwrap()
533 }
534
535 fn integrate_pressure(profile: &SoundingProfile, z0: f64, p0: f64, z1: f64) -> f64 {
541 let gravity = NormalGravity::wgs84();
542 let steps = 20_000;
543 let dz = (z1 - z0) / f64::from(steps);
544 let vapor_pressure = |z: f64| {
545 let air = profile.sample(z).unwrap().air;
547 let deficit = 1.0
548 - air.density_kg_m3 * DRY_AIR_GAS_CONSTANT_J_PER_KG_K * air.temperature_k
549 / air.pressure_pa;
550 let x = deficit
551 / (1.0
552 - crate::moist::WATER_VAPOR_MOLECULAR_WEIGHT_KG_PER_KMOL
553 / crate::ussa76::SEA_LEVEL_MOLECULAR_WEIGHT_KG_PER_KMOL);
554 (air.temperature_k, x * air.pressure_pa)
555 };
556 let weight = |z: f64, p: f64| {
557 let (t, e) = vapor_pressure(z);
558 let g = gravity.taylor_mps2(profile.latitude_rad(), z).unwrap();
559 moist_air_unchecked(t, p, e.max(0.0)).density_kg_m3 * g
560 };
561 let mut p = p0;
562 for k in 0..steps {
563 let z = z0 + f64::from(k) * dz;
564 let half = p - 0.5 * dz * weight(z, p);
565 p -= dz * weight(z + 0.5 * dz, half);
566 }
567 p
568 }
569
570 #[test]
574 fn sounding_temperature_overrides_standard_lapse() {
575 let field = level(1400.0, 308.15, Some(85_500.0), Some(0.2));
576 let profile = profile_at(
577 vec![
578 field,
579 level(2400.0, 300.15, None, Some(0.15)),
580 level(3400.0, 301.15, None, Some(0.10)),
581 ],
582 LATITUDE_RAD,
583 );
584 let standard_lapse = Ussa76::anchored(1400.0, 308.15, 85_500.0).unwrap();
585
586 let mid = profile.sample(2900.0).unwrap();
589 assert_eq!(mid.extrapolated, None);
590 let h = |z| wmo_geopotential_from_geometric_m(z, LATITUDE_RAD).unwrap();
591 let fraction = (h(2900.0) - h(2400.0)) / (h(3400.0) - h(2400.0));
592 assert!((fraction - 0.5 - 3.9e-5).abs() < 1e-6);
593 assert!((mid.air.temperature_k - (300.15 + fraction)).abs() < 1e-12);
594 let top = profile.sample(3400.0).unwrap().air;
595 assert!((top.temperature_k - 301.15).abs() < 1e-12);
596 let lapse_top = standard_lapse.sample(3400.0).unwrap().air;
597 assert!((lapse_top.temperature_k - (308.15 - 6.5 * 2.0)).abs() < 0.05);
598 assert!(top.temperature_k - lapse_top.temperature_k > 5.0);
599
600 for (z, p) in [
606 (2400.0, profile.pressures_pa()[1]),
607 (3400.0, profile.pressures_pa()[2]),
608 ] {
609 let integrated = integrate_pressure(&profile, 1400.0, 85_500.0, z);
610 assert!(
611 ((p - integrated) / integrated).abs() < 2e-5,
612 "{z}: {p} vs {integrated}"
613 );
614 }
615
616 let dry = moist_air(top.temperature_k, top.pressure_pa, 0.0).unwrap();
618 let lighter = 1.0 - top.density_kg_m3 / dry.density_kg_m3;
619 assert!((0.0015..0.0035).contains(&lighter), "{lighter}");
620 assert!((top.density_kg_m3 / lapse_top.density_kg_m3 - 1.0).abs() > 0.01);
622 }
623
624 #[test]
629 fn filled_pressures_are_hydrostatic_for_dry_air() {
630 for latitude_deg in [0.0_f64, 32.99, 90.0] {
631 let profile = profile_at(
632 vec![
633 level(1400.0, 308.15, Some(85_500.0), None),
634 level(2400.0, 300.15, None, None),
635 level(3400.0, 301.15, None, None),
636 ],
637 latitude_deg.to_radians(),
638 );
639 for (z, p) in [
640 (2400.0, profile.pressures_pa()[1]),
641 (3400.0, profile.pressures_pa()[2]),
642 ] {
643 let integrated = integrate_pressure(&profile, 1400.0, 85_500.0, z);
644 assert!(
645 ((p - integrated) / integrated).abs() < 2e-8,
646 "{latitude_deg}° {z}: {p} vs {integrated}"
647 );
648 }
649 }
650 }
651
652 #[test]
656 fn pressure_falls_faster_where_gravity_is_stronger() {
657 let levels = vec![
658 level(1400.0, 300.0, Some(85_500.0), None),
659 level(3400.0, 287.0, None, None),
660 ];
661 let equator = profile_at(levels.clone(), 0.0).pressures_pa()[1];
662 let pole = profile_at(levels, std::f64::consts::FRAC_PI_2).pressures_pa()[1];
663 let difference = pole / equator - 1.0;
664 assert!((-0.0014..-0.0011).contains(&difference), "{difference}");
665 }
666
667 #[test]
671 fn standard_levels_reproduce_the_standard_between_them() {
672 let standard = Ussa76::standard();
673 for latitude_deg in [0.0_f64, 45.0, 80.0] {
674 let latitude = latitude_deg.to_radians();
675 let heights: Vec<f64> = [0.0, 5_000.0, 11_000.0, 15_000.0, 20_000.0, 26_000.0]
676 .iter()
677 .map(|&geopotential| geometric_from_wmo_geopotential_m(geopotential, latitude))
678 .collect::<Result<_, _>>()
679 .unwrap();
680 let levels = heights
681 .iter()
682 .map(|&z| {
683 let air = standard.sample(standard_height(z, latitude)).unwrap().air;
684 level(z, air.temperature_k, Some(air.pressure_pa), None)
685 })
686 .collect();
687 let profile = profile_at(levels, latitude);
688 for z in heights
689 .iter()
690 .copied()
691 .chain([2_500.0, 8_000.0, 13_000.0, 17_500.0, 23_000.0])
692 {
693 let ours = profile.sample(z).unwrap().air;
694 let reference = standard.sample(standard_height(z, latitude)).unwrap().air;
695 assert!(
696 (ours.temperature_k - reference.temperature_k).abs() < 1e-10,
697 "{latitude_deg}° {z}"
698 );
699 for (a, b) in [
700 (ours.pressure_pa, reference.pressure_pa),
701 (ours.density_kg_m3, reference.density_kg_m3),
702 ] {
703 assert!(
704 ((a - b) / b).abs() < 1e-12,
705 "{latitude_deg}° {z}: {a} vs {b}"
706 );
707 }
708 }
709 }
710 }
711
712 #[test]
715 fn hydrostatic_fill_matches_the_standard() {
716 let tropopause = geometric_from_wmo_geopotential_m(11_000.0, LATITUDE_RAD).unwrap();
717 let profile = profile_at(
718 vec![
719 level(0.0, 288.15, Some(101_325.0), None),
720 level(tropopause, 216.65, None, None),
721 ],
722 LATITUDE_RAD,
723 );
724 let p = profile.pressures_pa()[1];
725 let reference = Ussa76::standard()
726 .sample(geometric_from_geopotential_m(11_000.0).unwrap())
727 .unwrap()
728 .air
729 .pressure_pa;
730 assert!(
731 ((p - reference) / reference).abs() < 1e-12,
732 "{p} vs {reference}"
733 );
734 }
735
736 #[test]
737 fn beyond_the_levels_follows_the_offset_standard() {
738 let profile = profile_at(
739 vec![
740 level(500.0, 295.0, Some(95_000.0), Some(0.6)),
741 level(2_000.0, 288.0, Some(80_000.0), Some(1.0)),
742 ],
743 LATITUDE_RAD,
744 );
745 let top = profile.sample(2_000.0).unwrap().air;
746 let just_above = profile.sample(2_000.001).unwrap();
747 assert_eq!(just_above.extrapolated, Some(Side::Above));
748 assert!((just_above.air.temperature_k - top.temperature_k).abs() < 1e-4);
749 assert!((just_above.air.pressure_pa / top.pressure_pa - 1.0).abs() < 1e-6);
750 assert!((just_above.air.density_kg_m3 / top.density_kg_m3 - 1.0).abs() < 1e-5);
751 let aloft = profile.sample(6_000.0).unwrap().air;
753 let h = |z| wmo_geopotential_from_geometric_m(z, LATITUDE_RAD).unwrap();
754 let expected = 288.0 - 0.0065 * (h(6_000.0) - h(2_000.0));
755 assert!((aloft.temperature_k - expected).abs() < 1e-9);
756 let e_sat = saturation_vapor_pressure_pa(aloft.temperature_k);
758 let capped = moist_air(aloft.temperature_k, aloft.pressure_pa, e_sat).unwrap();
759 assert!((aloft.density_kg_m3 / capped.density_kg_m3 - 1.0).abs() < 1e-14);
760 let dry = profile_at(
764 vec![
765 level(500.0, 295.0, Some(95_000.0), None),
766 level(2_000.0, 288.0, Some(80_000.0), None),
767 ],
768 LATITUDE_RAD,
769 );
770 let integrated = integrate_pressure(&dry, 2_000.0, 80_000.0, 2_300.0);
771 let continued = dry.sample(2_300.0).unwrap().air.pressure_pa;
772 assert!(
773 (continued / integrated - 1.0).abs() < 1e-8,
774 "{continued} {integrated}"
775 );
776 let humid_integrated = integrate_pressure(&profile, 2_000.0, 80_000.0, 2_300.0);
777 let humid_continued = profile.sample(2_300.0).unwrap().air.pressure_pa;
778 let low = humid_continued / humid_integrated - 1.0;
779 assert!((-3e-4..-2.5e-4).contains(&low), "{low}");
780
781 let below = profile.sample(0.0).unwrap();
782 assert_eq!(below.extrapolated, Some(Side::Below));
783 assert!(below.air.pressure_pa > 95_000.0 && below.air.temperature_k > 295.0);
784 assert!(profile.sample(f64::NAN).is_err());
785 }
786
787 #[test]
788 fn a_single_level_is_an_anchored_standard_atmosphere() {
789 let profile = profile_at(
790 vec![level(1_000.0, 280.0, Some(90_000.0), None)],
791 LATITUDE_RAD,
792 );
793 let anchored =
794 Ussa76::anchored(standard_height(1_000.0, LATITUDE_RAD), 280.0, 90_000.0).unwrap();
795 assert_eq!(profile.sample(1_000.0).unwrap().extrapolated, None);
796 for z in [0.0, 3_000.0] {
797 let ours = profile.sample(z).unwrap().air;
798 let reference = anchored
799 .sample(standard_height(z, LATITUDE_RAD))
800 .unwrap()
801 .air;
802 assert!((ours.density_kg_m3 / reference.density_kg_m3 - 1.0).abs() < 1e-14);
803 }
804 }
805
806 #[test]
807 fn wind_columns_make_a_layered_wind() {
808 let mut low = level(0.0, 290.0, Some(100_000.0), None);
809 low.wind_speed_m_s = Some(3.0);
810 low.wind_direction_from_rad = Some(1.0);
811 let mut high = level(1_000.0, 283.0, None, None);
812 high.wind_speed_m_s = Some(9.0);
813 high.wind_direction_from_rad = Some(2.0);
814 let profile =
815 SoundingProfile::new(vec![low, high], LATITUDE_RAD, WindInterpolation::Components)
816 .unwrap();
817 let wind = profile.wind().unwrap();
818 assert_eq!(wind.interpolation(), WindInterpolation::Components);
819 assert_eq!(wind.levels().len(), 2);
820 assert!(wind.wind(500.0).is_ok());
821 let dry = profile_at(vec![level(0.0, 290.0, Some(100_000.0), None)], LATITUDE_RAD);
822 assert!(dry.wind().is_none());
823 }
824
825 #[test]
826 fn invalid_profiles_are_rejected() {
827 let ok = level(0.0, 290.0, Some(100_000.0), Some(0.5));
828 let build =
829 |levels| SoundingProfile::new(levels, LATITUDE_RAD, WindInterpolation::default());
830 assert!(matches!(build(vec![]), Err(AtmosError::NoLevels)));
831 assert!(matches!(
832 build(vec![level(0.0, 290.0, None, None)]),
833 Err(AtmosError::MissingBasePressure)
834 ));
835 assert!(matches!(
836 build(vec![ok, level(0.0, 280.0, None, Some(0.5))]),
837 Err(AtmosError::HeightsNotIncreasing { index: 1 })
838 ));
839 assert!(matches!(
840 build(vec![ok, level(100.0, 280.0, None, None)]),
841 Err(AtmosError::IncompleteColumn { index: 1, .. })
842 ));
843 let mut windless_direction = level(100.0, 280.0, None, Some(0.5));
844 windless_direction.wind_direction_from_rad = Some(0.0);
845 assert!(matches!(
846 build(vec![ok, windless_direction]),
847 Err(AtmosError::IncompleteColumn { index: 1, .. })
848 ));
849 assert!(matches!(
851 build(vec![
852 level(0.0, 290.0, Some(101_325.0), None),
853 level(1_500.0, 280.0, Some(850.0), None),
854 level(3_000.0, 270.0, Some(70_000.0), None),
855 ]),
856 Err(AtmosError::PressureNotDecreasing { index: 2, .. })
857 ));
858 assert!(matches!(
859 build(vec![
860 level(0.0, 290.0, Some(101_325.0), None),
861 level(1_500.0, 280.0, Some(101_325.0), None),
862 ]),
863 Err(AtmosError::PressureNotDecreasing { index: 1, .. })
864 ));
865 assert!(matches!(
867 build(vec![
868 level(0.0, 290.0, Some(101_325.0), None),
869 level(1_000.0, 283.0, None, None),
870 level(2_000.0, 276.0, Some(95_000.0), None),
871 ]),
872 Err(AtmosError::PressureNotDecreasing { index: 2, .. })
873 ));
874 assert!(build(vec![level(0.0, 290.0, Some(100_000.0), Some(1.5))]).is_err());
875 assert!(build(vec![level(0.0, -1.0, Some(100_000.0), None)]).is_err());
876 assert!(build(vec![level(0.0, 290.0, Some(0.0), None)]).is_err());
877 assert!(build(vec![level(f64::NAN, 290.0, Some(1e5), None)]).is_err());
878 let levels = vec![level(0.0, 290.0, Some(1e5), None)];
879 for latitude in [2.0, f64::NAN] {
880 assert!(
881 SoundingProfile::new(levels.clone(), latitude, WindInterpolation::default())
882 .is_err()
883 );
884 }
885 }
886
887 #[test]
888 fn profiles_round_trip_through_json() {
889 let json = r#"{"latitude_rad":0.5758,"levels":[
890 {"height_msl_m":1400.0,"temperature_k":300.0,"pressure_pa":86000.0,
891 "relative_humidity":0.3,"wind_speed_m_s":4.0,"wind_direction_from_rad":3.0},
892 {"height_msl_m":3000.0,"temperature_k":290.0,
893 "relative_humidity":0.2,"wind_speed_m_s":10.0,"wind_direction_from_rad":3.5}
894 ]}"#;
895 let profile: SoundingProfile = serde_json::from_str(json).unwrap();
896 assert_eq!(
897 profile.wind_interpolation,
898 WindInterpolation::SpeedDirection
899 );
900 assert_eq!(profile.latitude_rad(), 0.5758);
901 let back: SoundingProfile =
902 serde_json::from_str(&serde_json::to_string(&profile).unwrap()).unwrap();
903 assert_eq!(back, profile);
904 let unknown = r#"{"latitude_rad":0.0,"levels":[{"height_msl_m":0.0,"temperature_k":300.0,"pressure_pa":1e5,"dew_point_k":280.0}]}"#;
905 assert!(serde_json::from_str::<SoundingProfile>(unknown).is_err());
906 let no_latitude =
907 r#"{"levels":[{"height_msl_m":0.0,"temperature_k":300.0,"pressure_pa":1e5}]}"#;
908 assert!(serde_json::from_str::<SoundingProfile>(no_latitude).is_err());
909 }
910
911 #[test]
914 fn a_profile_reads_past_the_tool_that_wrote_it() {
915 let bare = r#"{"latitude_rad":0.5758,"levels":[
916 {"height_msl_m":1400.0,"temperature_k":300.0,"pressure_pa":86000.0}
917 ]}"#;
918 for (name, designation) in [
921 ("FusionSpace HPR", "FS-ACHERNAR · SW · TOOL 001"),
922 ("hpr-sim", "FS-ACHERNAR · SW · TOOL 001"),
923 ("hpr-sim", "FS · SW · TOOL 005"),
924 ] {
925 let json = bare.replacen(
926 '{',
927 &format!(
928 r#"{{"tool":{{"name":"{name}","version":"0.1.0","designation":"{designation}"}},"#
929 ),
930 1,
931 );
932 let profile: SoundingProfile = serde_json::from_str(&json).unwrap();
933 assert_eq!(
934 profile,
935 serde_json::from_str(bare).unwrap(),
936 "{name}, {designation}"
937 );
938 assert!(!serde_json::to_string(&profile).unwrap().contains("tool"));
939 }
940 for key in ["tools", "latitude_deg"] {
942 let unknown = bare.replacen('{', &format!("{{\"{key}\":{{}},"), 1);
943 assert!(
944 serde_json::from_str::<SoundingProfile>(&unknown).is_err(),
945 "{unknown}"
946 );
947 }
948 }
949
950 #[test]
953 fn a_profile_reads_past_its_kind_and_trust_note() {
954 let bare = r#"{"latitude_rad":0.5758,"levels":[
955 {"height_msl_m":1400.0,"temperature_k":300.0,"pressure_pa":86000.0}
956 ]}"#;
957 let saved = bare.replacen(
958 '{',
959 r#"{"tool":{"name":"FusionSpace HPR","version":"0.1.0","designation":"FS-ACHERNAR · SW · TOOL 001"},"kind":"forecast","trust":"How far to trust it. A weather model's forecast.","#,
960 1,
961 );
962 let profile: SoundingProfile = serde_json::from_str(&saved).unwrap();
963 assert_eq!(profile, serde_json::from_str(bare).unwrap());
964 let written = serde_json::to_string(&profile).unwrap();
965 assert!(
966 !written.contains("kind") && !written.contains("trust"),
967 "{written}"
968 );
969 for key in ["kinds", "trusts"] {
971 let unknown = bare.replacen('{', &format!("{{\"{key}\":\"x\","), 1);
972 assert!(
973 serde_json::from_str::<SoundingProfile>(&unknown).is_err(),
974 "{unknown}"
975 );
976 }
977 }
978
979 #[test]
982 fn wmo_geopotential_matches_the_guide() {
983 let equator = wmo_geopotential_from_geometric_m(30_000.0, 0.0).unwrap();
984 assert!((equator - 29_778.5).abs() <= 0.05, "{equator}");
985 let north = wmo_geopotential_from_geometric_m(30_000.0, 80_f64.to_radians()).unwrap();
986 assert!((north - 29_932.0).abs() <= 0.5, "{north}");
987 for latitude in [-90.0_f64, -33.0, 0.0, 32.9, 45.0, 89.0] {
988 for z in [-400.0, 0.0, 1_500.0, 12_000.0, 40_000.0] {
989 let gpm = wmo_geopotential_from_geometric_m(z, latitude.to_radians()).unwrap();
990 let back = geometric_from_wmo_geopotential_m(gpm, latitude.to_radians()).unwrap();
991 assert!((back - z).abs() < 1e-8, "{latitude} {z}");
992 }
993 }
994 assert!(wmo_geopotential_from_geometric_m(0.0, 2.0).is_err());
995 assert!(geometric_from_wmo_geopotential_m(1e8, 0.0).is_err());
996 }
997}