Skip to main content

hpr_atmos/
wind.rs

1//! Mean wind models: constant, power law, logarithmic law and tabulated layers.
2//!
3//! **Conventions** (`docs/physics/wind.md`):
4//!
5//! - A wind model returns the velocity of the air in the launch frame's East-North-Up axes, m/s.
6//!   Mean wind is horizontal, so the up component is zero.
7//! - Directions are **meteorological**: the direction the wind blows *from*, clockwise from true
8//!   north, in radians. A 10 m/s wind from the west (`3π/2`) has velocity `(+10, 0, 0)`:
9//!
10//! ```text
11//! v_E = −V sin θ_from,    v_N = −V cos θ_from
12//! ```
13//!
14//! - Models are queried with the geometric height above mean sea level, like the atmosphere
15//!   ([`crate::Atmosphere`]). Laws written in height above ground carry the ground's height.
16//!
17//! Turbulence is separate: see [`crate::dryden`].
18
19use std::f64::consts::{PI, TAU};
20use std::fmt;
21
22use hpr_core::DVec3;
23use hpr_core::interp::Side;
24use serde::{Deserialize, Serialize};
25
26use crate::error::{AtmosError, finite, positive};
27
28/// A wind velocity and whether the model extrapolated to produce it.
29#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
30pub struct WindSample {
31    /// Velocity of the air in East-North-Up axes, m/s.
32    pub velocity_enu_m_s: DVec3,
33    /// `Some` when the height was below or above a tabulated wind's levels, or below ground for
34    /// a law written above ground; `None` otherwise. The power and log laws are not flagged above
35    /// the surface layer they describe.
36    pub extrapolated: Option<Side>,
37}
38
39/// A mean wind model: the wind velocity as a function of height.
40pub trait Wind: fmt::Debug + Send + Sync {
41    /// The wind at geometric height `height_msl_m` above mean sea level.
42    ///
43    /// # Errors
44    ///
45    /// [`AtmosError::Domain`] if the height is not finite.
46    fn wind(&self, height_msl_m: f64) -> Result<WindSample, AtmosError>;
47
48    /// The spans over which the model turns the wind's direction by interpolating between two
49    /// tabulated levels' directions, lowest first, each with its two levels as the model flies
50    /// them. A model with no tabulated directions has none, the default; a [`LayeredWind`] whose
51    /// [`WindInterpolation::SpeedDirection`] turns between two levels, neither calm, has one per
52    /// such pair. A model that wraps another and changes its wind (scales or turns it) maps its
53    /// spans the same way, so that what it reports is what it flies.
54    ///
55    /// A flight reads them to warn of [issue #8](https://github.com/nrdptel/fusionspace-eridanus/issues/8):
56    /// a near-calm level's reported direction means little, yet it swings the interpolated
57    /// direction over the whole span ([`LayeredWind::wind`]).
58    fn direction_turns(&self) -> Vec<DirectionTurn> {
59        Vec::new()
60    }
61}
62
63/// Two adjacent levels of a tabulated wind between which its direction is interpolated from the
64/// lower level's to the upper's ([`Wind::direction_turns`]).
65#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
66pub struct DirectionTurn {
67    /// The lower level.
68    pub lower: WindLevel,
69    /// The upper level.
70    pub upper: WindLevel,
71}
72
73/// East-North-Up velocity of a horizontal wind of `speed_m_s` blowing from `direction_from_rad`.
74pub fn velocity_from_speed_direction(speed_m_s: f64, direction_from_rad: f64) -> DVec3 {
75    DVec3::new(
76        -speed_m_s * direction_from_rad.sin(),
77        -speed_m_s * direction_from_rad.cos(),
78        0.0,
79    )
80}
81
82/// Wraps an angle into `[0, 2π)`.
83fn wrap_direction(angle_rad: f64) -> f64 {
84    let wrapped = angle_rad.rem_euclid(TAU);
85    // rem_euclid can round up to exactly 2π for tiny negative inputs.
86    if wrapped >= TAU { 0.0 } else { wrapped }
87}
88
89fn check_direction(direction_from_rad: f64) -> Result<f64, AtmosError> {
90    Ok(wrap_direction(finite(
91        "wind direction (rad)",
92        direction_from_rad,
93    )?))
94}
95
96fn check_speed(speed_m_s: f64) -> Result<f64, AtmosError> {
97    let speed = finite("wind speed (m/s)", speed_m_s)?;
98    if speed < 0.0 {
99        return Err(AtmosError::Domain {
100            what: "wind speed (m/s)",
101            value: speed,
102        });
103    }
104    Ok(speed)
105}
106
107/// The same wind at every height.
108#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
109#[serde(try_from = "ConstantWindData", into = "ConstantWindData")]
110pub struct ConstantWind {
111    speed_m_s: f64,
112    direction_from_rad: f64,
113    /// The velocity of the two fields above, taken once rather than at every call of `wind`.
114    velocity_enu_m_s: DVec3,
115}
116
117#[derive(Serialize, Deserialize)]
118#[serde(deny_unknown_fields)]
119struct ConstantWindData {
120    speed_m_s: f64,
121    direction_from_rad: f64,
122}
123
124impl TryFrom<ConstantWindData> for ConstantWind {
125    type Error = AtmosError;
126
127    fn try_from(data: ConstantWindData) -> Result<Self, AtmosError> {
128        ConstantWind::new(data.speed_m_s, data.direction_from_rad)
129    }
130}
131
132impl From<ConstantWind> for ConstantWindData {
133    fn from(wind: ConstantWind) -> Self {
134        ConstantWindData {
135            speed_m_s: wind.speed_m_s,
136            direction_from_rad: wind.direction_from_rad,
137        }
138    }
139}
140
141impl ConstantWind {
142    /// A constant wind of `speed_m_s` from `direction_from_rad` (wrapped into `[0, 2π)`).
143    ///
144    /// # Errors
145    ///
146    /// [`AtmosError::Domain`] if the speed is negative or either value is not finite.
147    pub fn new(speed_m_s: f64, direction_from_rad: f64) -> Result<Self, AtmosError> {
148        let speed_m_s = check_speed(speed_m_s)?;
149        let direction_from_rad = check_direction(direction_from_rad)?;
150        Ok(ConstantWind {
151            speed_m_s,
152            direction_from_rad,
153            velocity_enu_m_s: velocity_from_speed_direction(speed_m_s, direction_from_rad),
154        })
155    }
156
157    /// Calm air.
158    pub fn calm() -> Self {
159        ConstantWind {
160            speed_m_s: 0.0,
161            direction_from_rad: 0.0,
162            velocity_enu_m_s: velocity_from_speed_direction(0.0, 0.0),
163        }
164    }
165
166    /// Wind speed, m/s.
167    pub fn speed_m_s(&self) -> f64 {
168        self.speed_m_s
169    }
170
171    /// Direction the wind blows from, in `[0, 2π)`, rad.
172    pub fn direction_from_rad(&self) -> f64 {
173        self.direction_from_rad
174    }
175}
176
177impl Wind for ConstantWind {
178    fn wind(&self, height_msl_m: f64) -> Result<WindSample, AtmosError> {
179        finite("height (m)", height_msl_m)?;
180        Ok(WindSample {
181            velocity_enu_m_s: self.velocity_enu_m_s,
182            extrapolated: None,
183        })
184    }
185}
186
187/// A wind whose speed grows with height above ground as a power law, from one direction:
188///
189/// ```text
190/// V(z) = V_ref (z / z_ref)^α,   z = H − H_ground > 0;   V = 0 for z ≤ 0
191/// ```
192///
193/// Source: NASA/TM-2008-215633, *Terrestrial Environment (Climatic) Criteria Guidelines for Use
194/// in Aerospace Vehicle Development* (2008), §2.2.5.2, eq. 2.1, pinned as `nasa-tm-2008-215633`.
195/// There it describes peak winds below 150 m, with `z_ref = 18.3 m` and exponents from 0.14 to
196/// about 0.2 (Table 2-1); `docs/physics/wind.md` says how to choose one. Heights below ground are
197/// flagged. Heights above the surface layer are not, although the law keeps growing there: pair
198/// it with winds aloft.
199#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
200#[serde(try_from = "PowerLawWindData", into = "PowerLawWindData")]
201pub struct PowerLawWind {
202    reference_speed_m_s: f64,
203    reference_height_agl_m: f64,
204    exponent: f64,
205    direction_from_rad: f64,
206    ground_msl_m: f64,
207}
208
209#[derive(Serialize, Deserialize)]
210#[serde(deny_unknown_fields)]
211struct PowerLawWindData {
212    reference_speed_m_s: f64,
213    reference_height_agl_m: f64,
214    exponent: f64,
215    direction_from_rad: f64,
216    ground_msl_m: f64,
217}
218
219impl TryFrom<PowerLawWindData> for PowerLawWind {
220    type Error = AtmosError;
221
222    fn try_from(d: PowerLawWindData) -> Result<Self, AtmosError> {
223        PowerLawWind::new(
224            d.reference_speed_m_s,
225            d.reference_height_agl_m,
226            d.exponent,
227            d.direction_from_rad,
228            d.ground_msl_m,
229        )
230    }
231}
232
233impl From<PowerLawWind> for PowerLawWindData {
234    fn from(w: PowerLawWind) -> Self {
235        PowerLawWindData {
236            reference_speed_m_s: w.reference_speed_m_s,
237            reference_height_agl_m: w.reference_height_agl_m,
238            exponent: w.exponent,
239            direction_from_rad: w.direction_from_rad,
240            ground_msl_m: w.ground_msl_m,
241        }
242    }
243}
244
245impl PowerLawWind {
246    /// A power-law profile through `reference_speed_m_s` at `reference_height_agl_m` above a
247    /// ground at `ground_msl_m`, with exponent `exponent`, blowing from `direction_from_rad`.
248    ///
249    /// # Errors
250    ///
251    /// [`AtmosError::Domain`] if the speed is negative, the reference height is not positive,
252    /// the exponent is negative, or any value is not finite.
253    pub fn new(
254        reference_speed_m_s: f64,
255        reference_height_agl_m: f64,
256        exponent: f64,
257        direction_from_rad: f64,
258        ground_msl_m: f64,
259    ) -> Result<Self, AtmosError> {
260        let exponent = finite("power-law exponent", exponent)?;
261        if exponent < 0.0 {
262            return Err(AtmosError::Domain {
263                what: "power-law exponent",
264                value: exponent,
265            });
266        }
267        Ok(PowerLawWind {
268            reference_speed_m_s: check_speed(reference_speed_m_s)?,
269            reference_height_agl_m: positive("reference height (m)", reference_height_agl_m)?,
270            exponent,
271            direction_from_rad: check_direction(direction_from_rad)?,
272            ground_msl_m: finite("ground height (m)", ground_msl_m)?,
273        })
274    }
275
276    /// Wind speed at the reference height, m/s.
277    pub fn reference_speed_m_s(&self) -> f64 {
278        self.reference_speed_m_s
279    }
280
281    /// Reference height above ground, m.
282    pub fn reference_height_agl_m(&self) -> f64 {
283        self.reference_height_agl_m
284    }
285
286    /// The exponent `α`.
287    pub fn exponent(&self) -> f64 {
288        self.exponent
289    }
290
291    /// Direction the wind blows from, in `[0, 2π)`, rad.
292    pub fn direction_from_rad(&self) -> f64 {
293        self.direction_from_rad
294    }
295
296    /// Height of the ground above mean sea level, m.
297    pub fn ground_msl_m(&self) -> f64 {
298        self.ground_msl_m
299    }
300}
301
302impl Wind for PowerLawWind {
303    fn wind(&self, height_msl_m: f64) -> Result<WindSample, AtmosError> {
304        let z = finite("height (m)", height_msl_m)? - self.ground_msl_m;
305        let (speed, extrapolated) = if z > 0.0 {
306            let ratio = z / self.reference_height_agl_m;
307            (self.reference_speed_m_s * ratio.powf(self.exponent), None)
308        } else {
309            (0.0, (z < 0.0).then_some(Side::Below))
310        };
311        Ok(WindSample {
312            velocity_enu_m_s: velocity_from_speed_direction(speed, self.direction_from_rad),
313            extrapolated,
314        })
315    }
316}
317
318/// A wind whose speed follows the neutral logarithmic law above ground, from one direction:
319///
320/// ```text
321/// V(z) = V_ref ln(z / z₀) / ln(z_ref / z₀),   z = H − H_ground > z₀;   V = 0 for 0 ≤ z ≤ z₀
322/// ```
323///
324/// with roughness length `z₀`. Sources: MIL-F-8785C §3.7.3.2 (with `z_ref = 20 ft`), and the
325/// neutral surface-layer law `V = (u*/κ) ln(z/z₀)` of WMO-No. 8 (2023), Vol. I, chapter 5 annex,
326/// whose Davenport–Wieringa classes give `z₀ = 0.03 m` for open grassland. Heights below ground
327/// are flagged; see `docs/physics/wind.md`.
328#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
329#[serde(try_from = "LogLawWindData", into = "LogLawWindData")]
330pub struct LogLawWind {
331    reference_speed_m_s: f64,
332    reference_height_agl_m: f64,
333    roughness_length_m: f64,
334    direction_from_rad: f64,
335    ground_msl_m: f64,
336}
337
338#[derive(Serialize, Deserialize)]
339#[serde(deny_unknown_fields)]
340struct LogLawWindData {
341    reference_speed_m_s: f64,
342    reference_height_agl_m: f64,
343    roughness_length_m: f64,
344    direction_from_rad: f64,
345    ground_msl_m: f64,
346}
347
348impl TryFrom<LogLawWindData> for LogLawWind {
349    type Error = AtmosError;
350
351    fn try_from(d: LogLawWindData) -> Result<Self, AtmosError> {
352        LogLawWind::new(
353            d.reference_speed_m_s,
354            d.reference_height_agl_m,
355            d.roughness_length_m,
356            d.direction_from_rad,
357            d.ground_msl_m,
358        )
359    }
360}
361
362impl From<LogLawWind> for LogLawWindData {
363    fn from(w: LogLawWind) -> Self {
364        LogLawWindData {
365            reference_speed_m_s: w.reference_speed_m_s,
366            reference_height_agl_m: w.reference_height_agl_m,
367            roughness_length_m: w.roughness_length_m,
368            direction_from_rad: w.direction_from_rad,
369            ground_msl_m: w.ground_msl_m,
370        }
371    }
372}
373
374impl LogLawWind {
375    /// A logarithmic profile through `reference_speed_m_s` at `reference_height_agl_m` above a
376    /// ground at `ground_msl_m` with roughness length `roughness_length_m`, blowing from
377    /// `direction_from_rad`.
378    ///
379    /// # Errors
380    ///
381    /// [`AtmosError::Domain`] if the speed is negative, the roughness length is not positive, the
382    /// reference height is not above the roughness length, or any value is not finite.
383    pub fn new(
384        reference_speed_m_s: f64,
385        reference_height_agl_m: f64,
386        roughness_length_m: f64,
387        direction_from_rad: f64,
388        ground_msl_m: f64,
389    ) -> Result<Self, AtmosError> {
390        let z0 = positive("roughness length (m)", roughness_length_m)?;
391        let z_ref = positive("reference height (m)", reference_height_agl_m)?;
392        if z_ref <= z0 {
393            return Err(AtmosError::Domain {
394                what: "reference height above the roughness length (m)",
395                value: z_ref,
396            });
397        }
398        Ok(LogLawWind {
399            reference_speed_m_s: check_speed(reference_speed_m_s)?,
400            reference_height_agl_m: z_ref,
401            roughness_length_m: z0,
402            direction_from_rad: check_direction(direction_from_rad)?,
403            ground_msl_m: finite("ground height (m)", ground_msl_m)?,
404        })
405    }
406
407    /// Wind speed at the reference height, m/s.
408    pub fn reference_speed_m_s(&self) -> f64 {
409        self.reference_speed_m_s
410    }
411
412    /// Reference height above ground, m.
413    pub fn reference_height_agl_m(&self) -> f64 {
414        self.reference_height_agl_m
415    }
416
417    /// Roughness length `z₀`, m.
418    pub fn roughness_length_m(&self) -> f64 {
419        self.roughness_length_m
420    }
421
422    /// Direction the wind blows from, in `[0, 2π)`, rad.
423    pub fn direction_from_rad(&self) -> f64 {
424        self.direction_from_rad
425    }
426
427    /// Height of the ground above mean sea level, m.
428    pub fn ground_msl_m(&self) -> f64 {
429        self.ground_msl_m
430    }
431}
432
433impl Wind for LogLawWind {
434    fn wind(&self, height_msl_m: f64) -> Result<WindSample, AtmosError> {
435        let z = finite("height (m)", height_msl_m)? - self.ground_msl_m;
436        let z0 = self.roughness_length_m;
437        let speed = if z > z0 {
438            self.reference_speed_m_s * (z / z0).ln() / (self.reference_height_agl_m / z0).ln()
439        } else {
440            0.0
441        };
442        Ok(WindSample {
443            velocity_enu_m_s: velocity_from_speed_direction(speed, self.direction_from_rad),
444            extrapolated: (z < 0.0).then_some(Side::Below),
445        })
446    }
447}
448
449/// How a [`LayeredWind`] fills in between its levels.
450#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
451#[serde(rename_all = "snake_case")]
452#[non_exhaustive]
453pub enum WindInterpolation {
454    /// Speed linearly in height, and direction linearly along the shorter arc between the two
455    /// levels (clockwise when they are exactly opposite). A wind that veers keeps its speed. A calm
456    /// level (speed 0, whose reported direction means nothing) takes the other level's direction,
457    /// so the wind grows out of calm without turning.
458    #[default]
459    SpeedDirection,
460    /// The East and North components linearly in height, as RocketPy does. Speed dips between
461    /// levels whose directions differ.
462    Components,
463}
464
465/// One level of a [`LayeredWind`].
466#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
467#[serde(deny_unknown_fields)]
468pub struct WindLevel {
469    /// Geometric height above mean sea level, m.
470    pub height_msl_m: f64,
471    /// Wind speed, m/s.
472    pub speed_m_s: f64,
473    /// Direction the wind blows from, clockwise from true north, rad.
474    pub direction_from_rad: f64,
475}
476
477/// A wind tabulated at levels, such as a sounding or a forecast, interpolated between them.
478///
479/// Below the lowest level and above the highest, it holds the end level's wind and flags the
480/// sample. Put the surface observation (for example the 10 m wind) in the table as its lowest
481/// level, so the profile blends from the surface up instead of stepping at the first level
482/// aloft ([Loft lesson L6][l6]: Loft's forecast profiles stepped at the lowest level).
483///
484/// [l6]: https://hpr.fusionspace.co/decisions-and-roadmap.html#l6
485#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
486#[serde(try_from = "LayeredWindData", into = "LayeredWindData")]
487pub struct LayeredWind {
488    levels: Vec<WindLevel>,
489    interpolation: WindInterpolation,
490}
491
492#[derive(Serialize, Deserialize)]
493#[serde(deny_unknown_fields)]
494struct LayeredWindData {
495    levels: Vec<WindLevel>,
496    #[serde(default)]
497    interpolation: WindInterpolation,
498}
499
500impl TryFrom<LayeredWindData> for LayeredWind {
501    type Error = AtmosError;
502
503    fn try_from(data: LayeredWindData) -> Result<Self, AtmosError> {
504        LayeredWind::new(data.levels, data.interpolation)
505    }
506}
507
508impl From<LayeredWind> for LayeredWindData {
509    fn from(wind: LayeredWind) -> Self {
510        LayeredWindData {
511            levels: wind.levels,
512            interpolation: wind.interpolation,
513        }
514    }
515}
516
517impl LayeredWind {
518    /// A tabulated wind from `levels`, with directions wrapped into `[0, 2π)`.
519    ///
520    /// # Errors
521    ///
522    /// - [`AtmosError::NoLevels`] with no levels.
523    /// - [`AtmosError::HeightsNotIncreasing`] unless heights strictly increase.
524    /// - [`AtmosError::Domain`] for a negative speed or any value that is not finite.
525    pub fn new(
526        levels: Vec<WindLevel>,
527        interpolation: WindInterpolation,
528    ) -> Result<Self, AtmosError> {
529        if levels.is_empty() {
530            return Err(AtmosError::NoLevels);
531        }
532        let mut checked = Vec::with_capacity(levels.len());
533        for (index, level) in levels.into_iter().enumerate() {
534            let height = finite("wind level height (m)", level.height_msl_m)?;
535            if let Some(previous) = checked.last().map(|l: &WindLevel| l.height_msl_m)
536                && height <= previous
537            {
538                return Err(AtmosError::HeightsNotIncreasing { index });
539            }
540            checked.push(WindLevel {
541                height_msl_m: height,
542                speed_m_s: check_speed(level.speed_m_s)?,
543                direction_from_rad: check_direction(level.direction_from_rad)?,
544            });
545        }
546        Ok(LayeredWind {
547            levels: checked,
548            interpolation,
549        })
550    }
551
552    /// The levels, lowest first.
553    pub fn levels(&self) -> &[WindLevel] {
554        &self.levels
555    }
556
557    /// How the table interpolates.
558    pub fn interpolation(&self) -> WindInterpolation {
559        self.interpolation
560    }
561}
562
563impl Wind for LayeredWind {
564    fn wind(&self, height_msl_m: f64) -> Result<WindSample, AtmosError> {
565        let z = finite("height (m)", height_msl_m)?;
566        let levels = &self.levels;
567        // `new` guarantees at least one level.
568        let (first, last) = match (levels.first(), levels.last()) {
569            (Some(first), Some(last)) => (first, last),
570            _ => return Err(AtmosError::NoLevels),
571        };
572        let hold = |level: &WindLevel, side| WindSample {
573            velocity_enu_m_s: velocity_from_speed_direction(
574                level.speed_m_s,
575                level.direction_from_rad,
576            ),
577            extrapolated: side,
578        };
579        if z < first.height_msl_m {
580            return Ok(hold(first, Some(Side::Below)));
581        }
582        if z > last.height_msl_m {
583            return Ok(hold(last, Some(Side::Above)));
584        }
585        // First level strictly above z; z ≥ first height, so upper ≥ 1.
586        let upper = levels.partition_point(|l| l.height_msl_m <= z);
587        if upper >= levels.len() {
588            return Ok(hold(last, None));
589        }
590        let (a, b) = (&levels[upper - 1], &levels[upper]);
591        let t = (z - a.height_msl_m) / (b.height_msl_m - a.height_msl_m);
592        let velocity = match self.interpolation {
593            WindInterpolation::SpeedDirection => {
594                let speed = a.speed_m_s + t * (b.speed_m_s - a.speed_m_s);
595                // A calm level's direction is meaningless (reports give 0): use the other's.
596                let (from_a, from_b) = match (a.speed_m_s == 0.0, b.speed_m_s == 0.0) {
597                    (true, false) => (b.direction_from_rad, b.direction_from_rad),
598                    (false, true) => (a.direction_from_rad, a.direction_from_rad),
599                    _ => (a.direction_from_rad, b.direction_from_rad),
600                };
601                let mut turn = from_b - from_a;
602                // Shorter arc, in (−π, π]: exactly opposite winds turn clockwise.
603                if turn > PI {
604                    turn -= TAU;
605                } else if turn <= -PI {
606                    turn += TAU;
607                }
608                velocity_from_speed_direction(speed, from_a + t * turn)
609            }
610            WindInterpolation::Components => {
611                let va = velocity_from_speed_direction(a.speed_m_s, a.direction_from_rad);
612                let vb = velocity_from_speed_direction(b.speed_m_s, b.direction_from_rad);
613                va + t * (vb - va)
614            }
615        };
616        Ok(WindSample {
617            velocity_enu_m_s: velocity,
618            extrapolated: None,
619        })
620    }
621
622    /// Each pair of adjacent levels that [`WindInterpolation::SpeedDirection`] turns between:
623    /// neither speed exactly 0 (a calm level takes the other's direction, so nothing turns) and
624    /// their directions differ. [`WindInterpolation::Components`] interpolates the velocity, not a
625    /// direction, so it has none.
626    fn direction_turns(&self) -> Vec<DirectionTurn> {
627        if self.interpolation != WindInterpolation::SpeedDirection {
628            return Vec::new();
629        }
630        self.levels
631            .windows(2)
632            .filter_map(|pair| {
633                let (lower, upper) = (pair[0], pair[1]);
634                let turns = lower.speed_m_s != 0.0
635                    && upper.speed_m_s != 0.0
636                    && lower.direction_from_rad != upper.direction_from_rad;
637                turns.then_some(DirectionTurn { lower, upper })
638            })
639            .collect()
640    }
641}
642
643/// Any of the mean wind models, tagged by `model` when serialized.
644#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
645#[serde(tag = "model", rename_all = "snake_case")]
646#[non_exhaustive]
647pub enum WindModel {
648    /// [`ConstantWind`].
649    Constant(ConstantWind),
650    /// [`PowerLawWind`].
651    PowerLaw(PowerLawWind),
652    /// [`LogLawWind`].
653    LogLaw(LogLawWind),
654    /// [`LayeredWind`].
655    Layered(LayeredWind),
656}
657
658impl Wind for WindModel {
659    fn wind(&self, height_msl_m: f64) -> Result<WindSample, AtmosError> {
660        match self {
661            WindModel::Constant(w) => w.wind(height_msl_m),
662            WindModel::PowerLaw(w) => w.wind(height_msl_m),
663            WindModel::LogLaw(w) => w.wind(height_msl_m),
664            WindModel::Layered(w) => w.wind(height_msl_m),
665        }
666    }
667
668    fn direction_turns(&self) -> Vec<DirectionTurn> {
669        match self {
670            WindModel::Constant(w) => w.direction_turns(),
671            WindModel::PowerLaw(w) => w.direction_turns(),
672            WindModel::LogLaw(w) => w.direction_turns(),
673            WindModel::Layered(w) => w.direction_turns(),
674        }
675    }
676}
677
678#[cfg(test)]
679mod tests {
680    use super::*;
681
682    fn deg(degrees: f64) -> f64 {
683        degrees.to_radians()
684    }
685
686    fn assert_close(actual: DVec3, expected: DVec3, tolerance: f64) {
687        assert!(
688            (actual - expected).length() <= tolerance,
689            "{actual:?} vs {expected:?}"
690        );
691    }
692
693    fn speed_and_direction_from(velocity: DVec3) -> (f64, f64) {
694        let speed = velocity.x.hypot(velocity.y);
695        (speed, wrap_direction((-velocity.x).atan2(-velocity.y)))
696    }
697
698    /// Loft lesson L6: a forecast profile blends from the surface wind up to the first level aloft
699    /// instead of stepping there, and it interpolates speed and heading, not just one vector.
700    #[test]
701    fn layered_wind_interpolates_speed_and_heading() {
702        // A 1000 m site: the 10 m wind is 4 m/s from 350°, and 12 m/s from 30° at 2010 m.
703        let wind = LayeredWind::new(
704            vec![
705                WindLevel {
706                    height_msl_m: 1010.0,
707                    speed_m_s: 4.0,
708                    direction_from_rad: deg(350.0),
709                },
710                WindLevel {
711                    height_msl_m: 2010.0,
712                    speed_m_s: 12.0,
713                    direction_from_rad: deg(30.0),
714                },
715            ],
716            WindInterpolation::SpeedDirection,
717        )
718        .unwrap();
719
720        // Halfway: 8 m/s from 10°, turning through north along the shorter arc.
721        let mid = wind.wind(1510.0).unwrap();
722        assert_eq!(mid.extrapolated, None);
723        let (speed, direction) = speed_and_direction_from(mid.velocity_enu_m_s);
724        assert!((speed - 8.0).abs() < 1e-12);
725        assert!((direction - deg(10.0)).abs() < 1e-12);
726
727        // A quarter of the way: 6 m/s from 0°.
728        let (speed, direction) =
729            speed_and_direction_from(wind.wind(1260.0).unwrap().velocity_enu_m_s);
730        assert!((speed - 6.0).abs() < 1e-12);
731        assert!(direction.min(TAU - direction) < 1e-12);
732
733        // No step: just above the surface level the wind is still the surface wind.
734        let near_surface = wind.wind(1010.001).unwrap().velocity_enu_m_s;
735        let surface = velocity_from_speed_direction(4.0, deg(350.0));
736        assert_close(near_surface, surface, 1e-4);
737        assert_close(wind.wind(1010.0).unwrap().velocity_enu_m_s, surface, 1e-15);
738        assert_close(
739            wind.wind(2010.0).unwrap().velocity_enu_m_s,
740            velocity_from_speed_direction(12.0, deg(30.0)),
741            1e-14,
742        );
743    }
744
745    #[test]
746    fn components_interpolation_averages_the_vectors() {
747        let levels = vec![
748            WindLevel {
749                height_msl_m: 0.0,
750                speed_m_s: 10.0,
751                direction_from_rad: deg(270.0),
752            },
753            WindLevel {
754                height_msl_m: 100.0,
755                speed_m_s: 10.0,
756                direction_from_rad: deg(0.0),
757            },
758        ];
759        let components = LayeredWind::new(levels.clone(), WindInterpolation::Components).unwrap();
760        // From the west (+E) and from the north (−N): the average is (5, −5), speed 7.07.
761        assert_close(
762            components.wind(50.0).unwrap().velocity_enu_m_s,
763            DVec3::new(5.0, -5.0, 0.0),
764            1e-14,
765        );
766        // The polar form keeps 10 m/s, from 315°.
767        let polar = LayeredWind::new(levels, WindInterpolation::SpeedDirection).unwrap();
768        let (speed, direction) =
769            speed_and_direction_from(polar.wind(50.0).unwrap().velocity_enu_m_s);
770        assert!((speed - 10.0).abs() < 1e-12);
771        assert!((direction - deg(315.0)).abs() < 1e-12);
772    }
773
774    /// A calm surface reported as "0 knots from 0°" does not make the wind turn on its way up to
775    /// the first level aloft: halfway to 10 m/s from the south it is 5 m/s from the south.
776    #[test]
777    fn wind_grows_out_of_calm_without_turning() {
778        for (calm_below, calm_height) in [(true, 0.0), (false, 1000.0)] {
779            let calm = WindLevel {
780                height_msl_m: calm_height,
781                speed_m_s: 0.0,
782                direction_from_rad: 0.0,
783            };
784            let windy = WindLevel {
785                height_msl_m: 1000.0 - calm_height,
786                speed_m_s: 10.0,
787                direction_from_rad: deg(180.0),
788            };
789            let levels = if calm_below {
790                vec![calm, windy]
791            } else {
792                vec![windy, calm]
793            };
794            let wind = LayeredWind::new(levels, WindInterpolation::SpeedDirection).unwrap();
795            assert_close(
796                wind.wind(500.0).unwrap().velocity_enu_m_s,
797                DVec3::new(0.0, 5.0, 0.0),
798                1e-12,
799            );
800        }
801    }
802
803    #[test]
804    fn opposite_directions_turn_clockwise() {
805        let wind = LayeredWind::new(
806            vec![
807                WindLevel {
808                    height_msl_m: 0.0,
809                    speed_m_s: 5.0,
810                    direction_from_rad: deg(90.0),
811                },
812                WindLevel {
813                    height_msl_m: 10.0,
814                    speed_m_s: 5.0,
815                    direction_from_rad: deg(270.0),
816                },
817            ],
818            WindInterpolation::SpeedDirection,
819        )
820        .unwrap();
821        let (_, direction) = speed_and_direction_from(wind.wind(5.0).unwrap().velocity_enu_m_s);
822        assert!((direction - deg(180.0)).abs() < 1e-12);
823    }
824
825    #[test]
826    fn layered_wind_holds_and_flags_beyond_its_levels() {
827        let wind = LayeredWind::new(
828            vec![
829                WindLevel {
830                    height_msl_m: 100.0,
831                    speed_m_s: 3.0,
832                    direction_from_rad: deg(180.0),
833                },
834                WindLevel {
835                    height_msl_m: 900.0,
836                    speed_m_s: 9.0,
837                    direction_from_rad: deg(200.0),
838                },
839            ],
840            WindInterpolation::default(),
841        )
842        .unwrap();
843        let below = wind.wind(0.0).unwrap();
844        assert_eq!(below.extrapolated, Some(Side::Below));
845        assert_close(below.velocity_enu_m_s, DVec3::new(0.0, 3.0, 0.0), 1e-14);
846        let above = wind.wind(5000.0).unwrap();
847        assert_eq!(above.extrapolated, Some(Side::Above));
848        assert_close(
849            above.velocity_enu_m_s,
850            velocity_from_speed_direction(9.0, deg(200.0)),
851            1e-15,
852        );
853        // A single level is a constant wind with flags.
854        let single = LayeredWind::new(
855            vec![WindLevel {
856                height_msl_m: 10.0,
857                speed_m_s: 2.0,
858                direction_from_rad: 0.0,
859            }],
860            WindInterpolation::default(),
861        )
862        .unwrap();
863        assert_eq!(single.wind(10.0).unwrap().extrapolated, None);
864        assert_eq!(single.wind(11.0).unwrap().extrapolated, Some(Side::Above));
865    }
866
867    #[test]
868    fn meteorological_direction_convention() {
869        // From the west blows toward the east; from the north blows toward the south.
870        let west = ConstantWind::new(10.0, deg(270.0)).unwrap();
871        assert_close(
872            west.wind(0.0).unwrap().velocity_enu_m_s,
873            DVec3::new(10.0, 0.0, 0.0),
874            1e-14,
875        );
876        let north = ConstantWind::new(10.0, 0.0).unwrap();
877        assert_close(
878            north.wind(123.0).unwrap().velocity_enu_m_s,
879            DVec3::new(0.0, -10.0, 0.0),
880            1e-14,
881        );
882        assert_eq!(
883            ConstantWind::calm().wind(0.0).unwrap().velocity_enu_m_s,
884            DVec3::ZERO
885        );
886        // Directions wrap.
887        let wrapped = ConstantWind::new(1.0, deg(-90.0)).unwrap();
888        assert!((wrapped.direction_from_rad - deg(270.0)).abs() < 1e-12);
889    }
890
891    #[test]
892    fn power_law_passes_through_its_reference() {
893        let wind = PowerLawWind::new(5.0, 10.0, 1.0 / 7.0, deg(270.0), 1400.0).unwrap();
894        let at_reference = wind.wind(1410.0).unwrap();
895        assert_close(
896            at_reference.velocity_enu_m_s,
897            DVec3::new(5.0, 0.0, 0.0),
898            1e-14,
899        );
900        let at_80 = wind.wind(1480.0).unwrap().velocity_enu_m_s.x;
901        assert!((at_80 - 5.0 * 8.0_f64.powf(1.0 / 7.0)).abs() < 1e-13);
902        assert_eq!(wind.wind(1400.0).unwrap().velocity_enu_m_s, DVec3::ZERO);
903        let below = wind.wind(1390.0).unwrap();
904        assert_eq!(below.velocity_enu_m_s, DVec3::ZERO);
905        assert_eq!(below.extrapolated, Some(Side::Below));
906    }
907
908    #[test]
909    fn log_law_passes_through_its_reference_and_vanishes_at_the_roughness_length() {
910        let wind = LogLawWind::new(6.0, 10.0, 0.03, deg(180.0), 0.0).unwrap();
911        assert_close(
912            wind.wind(10.0).unwrap().velocity_enu_m_s,
913            DVec3::new(0.0, 6.0, 0.0),
914            1e-14,
915        );
916        let at_100 = wind.wind(100.0).unwrap().velocity_enu_m_s.y;
917        let expected = 6.0 * (100.0_f64 / 0.03).ln() / (10.0_f64 / 0.03).ln();
918        assert!((at_100 - expected).abs() < 1e-13);
919        assert_eq!(wind.wind(0.03).unwrap().velocity_enu_m_s, DVec3::ZERO);
920        assert_eq!(wind.wind(-1.0).unwrap().extrapolated, Some(Side::Below));
921    }
922
923    #[test]
924    fn invalid_inputs_are_rejected() {
925        assert!(ConstantWind::new(-1.0, 0.0).is_err());
926        assert!(ConstantWind::new(1.0, f64::NAN).is_err());
927        assert!(PowerLawWind::new(1.0, 0.0, 0.14, 0.0, 0.0).is_err());
928        assert!(PowerLawWind::new(1.0, 10.0, -0.1, 0.0, 0.0).is_err());
929        assert!(LogLawWind::new(1.0, 0.01, 0.03, 0.0, 0.0).is_err());
930        assert!(LogLawWind::new(1.0, 10.0, 0.0, 0.0, 0.0).is_err());
931        assert!(matches!(
932            LayeredWind::new(vec![], WindInterpolation::default()),
933            Err(AtmosError::NoLevels)
934        ));
935        let level = |h| WindLevel {
936            height_msl_m: h,
937            speed_m_s: 1.0,
938            direction_from_rad: 0.0,
939        };
940        assert!(matches!(
941            LayeredWind::new(vec![level(0.0), level(0.0)], WindInterpolation::default()),
942            Err(AtmosError::HeightsNotIncreasing { index: 1 })
943        ));
944        assert!(ConstantWind::calm().wind(f64::INFINITY).is_err());
945    }
946
947    #[test]
948    fn wind_models_round_trip_through_json() {
949        let models = vec![
950            WindModel::Constant(ConstantWind::new(3.0, 1.0).unwrap()),
951            WindModel::PowerLaw(PowerLawWind::new(5.0, 10.0, 0.14, 2.0, 100.0).unwrap()),
952            WindModel::LogLaw(LogLawWind::new(5.0, 10.0, 0.05, 3.0, 100.0).unwrap()),
953            WindModel::Layered(
954                LayeredWind::new(
955                    vec![WindLevel {
956                        height_msl_m: 5.0,
957                        speed_m_s: 1.0,
958                        direction_from_rad: 0.5,
959                    }],
960                    WindInterpolation::Components,
961                )
962                .unwrap(),
963            ),
964        ];
965        for model in models {
966            let json = serde_json::to_string(&model).unwrap();
967            let back: WindModel = serde_json::from_str(&json).unwrap();
968            assert_eq!(back, model, "{json}");
969            assert_eq!(back.wind(50.0).unwrap(), model.wind(50.0).unwrap());
970        }
971        let negative = r#"{"model":"constant","speed_m_s":-3.0,"direction_from_rad":0.0}"#;
972        assert!(serde_json::from_str::<WindModel>(negative).is_err());
973        let unknown = r#"{"model":"constant","speed_m_s":3.0,"direction_from_rad":0.0,"x":1}"#;
974        assert!(serde_json::from_str::<WindModel>(unknown).is_err());
975    }
976
977    /// A table's direction turns ([`Wind::direction_turns`], issue #8): each pair of adjacent
978    /// levels, neither calm, whose directions differ, in speed-and-direction interpolation only.
979    /// The other models, and a wrapper of them, have none.
980    #[test]
981    fn a_table_reports_the_levels_it_turns_between() {
982        let level = |height_msl_m: f64, speed_m_s: f64, direction_from_deg: f64| WindLevel {
983            height_msl_m,
984            speed_m_s,
985            direction_from_rad: deg(direction_from_deg),
986        };
987        let levels = vec![
988            level(1000.0, 0.0, 90.0),
989            level(1100.0, 0.1, 0.0),
990            level(1400.0, 10.0, 270.0),
991            level(1800.0, 10.0, 270.0),
992            level(2000.0, f64::MIN_POSITIVE, 10.0),
993        ];
994        let polar = LayeredWind::new(levels.clone(), WindInterpolation::SpeedDirection).unwrap();
995        let turns = polar.direction_turns();
996        // Calm to 0.1 m/s takes the upper direction; 270° to 270° doesn't turn.
997        assert_eq!(
998            turns,
999            [
1000                DirectionTurn {
1001                    lower: levels[1],
1002                    upper: levels[2],
1003                },
1004                DirectionTurn {
1005                    lower: levels[3],
1006                    upper: levels[4],
1007                },
1008            ]
1009        );
1010        // The model flies what it reports: halfway up the first turn the direction is
1011        // interpolated from 0° to 270° along the shorter arc, so from 315°.
1012        let (_, direction) = speed_and_direction_from(polar.wind(1250.0).unwrap().velocity_enu_m_s);
1013        assert!((direction - deg(315.0)).abs() < 1e-12, "{direction}");
1014        assert_eq!(WindModel::Layered(polar).direction_turns(), turns);
1015        let components = LayeredWind::new(levels, WindInterpolation::Components).unwrap();
1016        assert!(components.direction_turns().is_empty());
1017        assert!(WindModel::Layered(components).direction_turns().is_empty());
1018        assert!(
1019            ConstantWind::new(3.0, 1.0)
1020                .unwrap()
1021                .direction_turns()
1022                .is_empty()
1023        );
1024        let law = PowerLawWind::new(5.0, 10.0, 0.14, 2.0, 100.0).unwrap();
1025        assert!(WindModel::PowerLaw(law).direction_turns().is_empty());
1026        // Directions a hair apart still turn.
1027        let close = LayeredWind::new(
1028            vec![
1029                level(0.0, 1.0, 0.0),
1030                WindLevel {
1031                    height_msl_m: 10.0,
1032                    speed_m_s: 1.0,
1033                    direction_from_rad: 1e-12,
1034                },
1035            ],
1036            WindInterpolation::SpeedDirection,
1037        )
1038        .unwrap();
1039        assert_eq!(close.direction_turns().len(), 1);
1040    }
1041}