stable_flight/estimation/wind.rs
1//! Wind from the air's push on a rotor-borne vehicle: drag inverted to air velocity, one axis
2//! at a time, and filtered on world wind.
3//!
4//! Thrust acts along the thrust frame's `z`, so the specific force along its `x` and `y` is
5//! the air's push alone. Each axis's drag model, a bluff-body term `½ρv²/B` plus rotor
6//! momentum drag `μv` (ArduPilot's and PX4's drag fusion: `AirDataFusion.cpp:380-445`,
7//! `drag_fusion.cpp:83-140`), is inverted to the air velocity along it; the wind along it is
8//! the ground velocity's component less that. A two-state Kalman filter on wind (north, east)
9//! takes each axis as a scalar measurement whose noise is the force noise over the drag's
10//! slope there, so an axis with little drag (a tailsitter's span in hover) counts for little,
11//! and the wind across it is learned once a turn puts more drag on it. Both stacks fit the
12//! drag frame to the body with thrust along `z` and treat X and Y alike apart from their
13//! coefficients; per-axis noise is what lets a flat-plate airframe use it.
14//!
15//! The measurement is averaged over [`UPDATE_PERIOD_S`], as both stacks do, before each
16//! update. Allocation-free and fixed-size.
17
18use nalgebra::{Matrix2, UnitQuaternion};
19
20use crate::controllers::{InvalidConfig, check_limit, check_positive};
21use crate::math::neu_to_ned;
22use crate::{GRAVITY, Vec2, Vec3, VehicleState};
23
24#[cfg(test)]
25mod tests;
26
27/// Sea-level air density, in kg/m³ (ISA).
28pub const AIR_DENSITY_KGPM3: f32 = 1.225;
29
30/// Seconds the measurement is averaged over before each update: about 5 Hz, as both stacks
31/// average their specific force (`Measurements.cpp:1492-1535`, `estimator_interface.cpp:518-570`).
32pub const UPDATE_PERIOD_S: f32 = 0.2;
33
34/// Default [`WindConfig::force_noise_mps2`]: ArduPilot's `EK3_DRAG_M_NSE` (`AP_NavEKF3.cpp:714`).
35pub const DEFAULT_FORCE_NOISE_MPS2: f32 = 0.5;
36
37/// Default [`WindConfig::process_noise_mps_per_rt_s`]: lets a steady wind's estimate move about
38/// 0.1 m/s a second, slow beside a hover's drift.
39pub const DEFAULT_PROCESS_NOISE_MPS_PER_RT_S: f32 = 0.1;
40
41/// Standard deviation of each wind component, in m/s, before any update.
42pub const INITIAL_SD_MPS: f32 = 10.0;
43
44/// Innovations past this many standard deviations are rejected, as both stacks gate drag
45/// (`AirDataFusion.cpp:595-599`, `drag_fusion.cpp:123`).
46const GATE_SIGMA: f32 = 5.0;
47
48/// Cosine of the most tilt, thrust axis from vertical, a tick is used at: 45°. The drag model
49/// is a hover's; tilted further (a tailsitter pitching over, a hard maneuver) the wing's lift
50/// and the thrust's own tilt dominate the push.
51const MIN_TILT_COSINE: f32 = core::f32::consts::FRAC_1_SQRT_2;
52
53/// Least drag slope, in 1/s, an axis's noise is divided by: below it the axis tells almost
54/// nothing about the wind, and the noise stays finite.
55const MIN_DRAG_SLOPE_PER_S: f32 = 1e-3;
56
57/// The drag model, per thrust-frame axis (`x`, `y`), and the filter's noise.
58///
59/// With every coefficient 0 (the default, as both stacks ship drag fusion off) the estimator
60/// never updates.
61#[derive(Debug, Clone, Copy, PartialEq)]
62#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
63pub struct WindConfig {
64 /// Ballistic coefficient along `x` and `y`, in kg/m²: mass over drag coefficient times
65 /// area, so the bluff-body drag is `½ρv²/B` per kg. 0 leaves the term out. Must be
66 /// non-negative and finite.
67 pub ballistic_kgpm2: Vec2,
68 /// Momentum drag along `x` and `y`, in 1/s: drag acceleration per m/s of air velocity.
69 /// 0 leaves the term out. Must be non-negative and finite.
70 pub momentum_per_s: Vec2,
71 /// Specific-force noise on each averaged measurement, in m/s². Must be positive and
72 /// finite. Defaults to [`DEFAULT_FORCE_NOISE_MPS2`].
73 pub force_noise_mps2: f32,
74 /// How fast the wind may wander, in m/s per √s (process noise). Must be non-negative and
75 /// finite. Defaults to [`DEFAULT_PROCESS_NOISE_MPS_PER_RT_S`].
76 pub process_noise_mps_per_rt_s: f32,
77}
78
79impl Default for WindConfig {
80 /// No drag model (the estimator off), and the default noises.
81 fn default() -> Self {
82 WindConfig {
83 ballistic_kgpm2: Vec2::zeros(),
84 momentum_per_s: Vec2::zeros(),
85 force_noise_mps2: DEFAULT_FORCE_NOISE_MPS2,
86 process_noise_mps_per_rt_s: DEFAULT_PROCESS_NOISE_MPS_PER_RT_S,
87 }
88 }
89}
90
91impl WindConfig {
92 /// Checks that the coefficients and `process_noise_mps_per_rt_s` are non-negative and finite and
93 /// that `force_noise_mps2` is positive and finite.
94 ///
95 /// # Examples
96 ///
97 /// ```
98 /// use stable_flight::estimation::wind::WindConfig;
99 ///
100 /// let mut config = WindConfig::default();
101 /// assert!(config.validate().is_ok());
102 /// config.force_noise_mps2 = 0.0;
103 /// assert!(config.validate().is_err());
104 /// ```
105 pub fn validate(&self) -> Result<(), InvalidConfig> {
106 check_limit("ballistic_kgpm2.x", self.ballistic_kgpm2.x)?;
107 check_limit("ballistic_kgpm2.y", self.ballistic_kgpm2.y)?;
108 check_limit("momentum_per_s.x", self.momentum_per_s.x)?;
109 check_limit("momentum_per_s.y", self.momentum_per_s.y)?;
110 check_positive("force_noise_mps2", self.force_noise_mps2)?;
111 check_limit(
112 "process_noise_mps_per_rt_s",
113 self.process_noise_mps_per_rt_s,
114 )
115 }
116
117 /// Whether any drag coefficient is set, so the estimator can update.
118 pub fn is_on(&self) -> bool {
119 self.ballistic_kgpm2
120 .iter()
121 .chain(&self.momentum_per_s)
122 .any(|c| *c > 0.0)
123 }
124}
125
126/// The wind and its uncertainty.
127#[derive(Debug, Clone, Copy, PartialEq)]
128#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
129pub struct WindEstimate {
130 /// The air mass's velocity (north, east), in m/s: where the wind blows toward.
131 pub velocity_mps: Vec2,
132 /// Covariance of `velocity_mps`, in m²/s².
133 pub covariance_m2ps2: Matrix2<f32>,
134}
135
136impl WindEstimate {
137 /// Standard deviation of the wind along the horizontal unit vector `direction`, in m/s.
138 pub fn sd_along_mps(&self, direction: Vec2) -> f32 {
139 libm::sqrtf(
140 (direction.transpose() * self.covariance_m2ps2 * direction)
141 .x
142 .max(0.0),
143 )
144 }
145}
146
147/// Estimates the wind from the vehicle state while the caller says it is airborne on rotors.
148///
149/// The config is passed to each call rather than stored, so the owner's config stays the
150/// single source of truth.
151///
152/// # Examples
153///
154/// ```
155/// use stable_flight::estimation::wind::{WindConfig, WindEstimator};
156/// use stable_flight::{Vec2, Vec3, VehicleState};
157///
158/// // A level quad with momentum drag 0.3/s, not moving, pushed east at 0.6 m/s²: the air
159/// // moves east at 2 m/s.
160/// let config = WindConfig {
161/// momentum_per_s: Vec2::new(0.3, 0.3),
162/// ..Default::default()
163/// };
164/// let state = VehicleState {
165/// acceleration_mps2: Vec3::new(0.0, 0.6, 0.0),
166/// ..Default::default()
167/// };
168/// let mut estimator = WindEstimator::default();
169/// for _ in 0..2500 {
170/// estimator.update(0.004, &config, &state);
171/// }
172/// let wind = estimator.estimate().expect("updated").velocity_mps;
173/// assert!((wind - Vec2::new(0.0, 2.0)).norm() < 0.01);
174/// ```
175#[derive(Debug, Clone, Copy, PartialEq)]
176pub struct WindEstimator {
177 /// Wind (north, east), in m/s.
178 wind_mps: Vec2,
179 /// Its covariance, in m²/s².
180 covariance_m2ps2: Matrix2<f32>,
181 /// A measurement has been taken.
182 updated: bool,
183 /// The measurement being averaged.
184 window: Window,
185}
186
187/// Sums over one averaging period.
188#[derive(Debug, Clone, Copy, Default, PartialEq)]
189struct Window {
190 elapsed_s: f32,
191 ticks: u32,
192 /// Specific force along the thrust frame's `x` and `y`, in m/s².
193 specific_force_mps2: Vec2,
194 /// Ground velocity along each axis, in m/s.
195 ground_along_mps: Vec2,
196 /// Each axis's horizontal part (north, east).
197 axis_x: Vec2,
198 axis_y: Vec2,
199}
200
201impl Default for WindEstimator {
202 fn default() -> Self {
203 WindEstimator {
204 wind_mps: Vec2::zeros(),
205 covariance_m2ps2: Matrix2::identity() * (INITIAL_SD_MPS * INITIAL_SD_MPS),
206 updated: false,
207 window: Window::default(),
208 }
209 }
210}
211
212impl WindEstimator {
213 /// Adds this tick's state, `state.attitude` taken as the thrust frame (thrust along its
214 /// `z`), and once [`UPDATE_PERIOD_S`] has gathered, updates the wind from the period's
215 /// average. A tick with a non-finite attitude, velocity, or acceleration, or with the
216 /// thrust axis tilted more than 45° from vertical, is skipped. Does nothing while `config`
217 /// has no drag coefficient.
218 pub fn update(&mut self, dt: f32, config: &WindConfig, state: &VehicleState) {
219 if !config.is_on() {
220 return;
221 }
222 let Some(sample) = Sample::from_state(state) else {
223 return;
224 };
225 let window = &mut self.window;
226 window.elapsed_s += dt;
227 window.ticks += 1;
228 window.specific_force_mps2 += sample.specific_force_mps2;
229 window.ground_along_mps += sample.ground_along_mps;
230 window.axis_x += sample.axis_x;
231 window.axis_y += sample.axis_y;
232 if window.elapsed_s < UPDATE_PERIOD_S {
233 return;
234 }
235 let window = core::mem::take(&mut self.window);
236 let n = window.ticks as f32;
237 self.predict(window.elapsed_s, config);
238 let force = window.specific_force_mps2 / n;
239 let ground = window.ground_along_mps / n;
240 let axes = [window.axis_x / n, window.axis_y / n];
241 for (i, axis) in axes.into_iter().enumerate() {
242 let drag = AxisDrag::new(config, i);
243 if let Some((air_mps, slope_per_s)) = drag.air_velocity(force[i]) {
244 let noise_mps = config.force_noise_mps2 / slope_per_s.max(MIN_DRAG_SLOPE_PER_S);
245 self.correct(axis, ground[i] - air_mps, noise_mps * noise_mps);
246 }
247 }
248 self.updated = true;
249 }
250
251 /// The wind, once a measurement has been taken.
252 pub fn estimate(&self) -> Option<WindEstimate> {
253 self.updated.then_some(WindEstimate {
254 velocity_mps: self.wind_mps,
255 covariance_m2ps2: self.covariance_m2ps2,
256 })
257 }
258
259 /// Forgets the wind and any partial average.
260 pub fn reset(&mut self) {
261 *self = Self::default();
262 }
263
264 /// Grows the covariance for `elapsed_s` of wandering wind.
265 fn predict(&mut self, elapsed_s: f32, config: &WindConfig) {
266 let q = config.process_noise_mps_per_rt_s;
267 self.covariance_m2ps2 += Matrix2::identity() * (q * q * elapsed_s);
268 }
269
270 /// Fuses `measured_mps`, the wind along `axis` (horizontal, not unit: a tilted axis
271 /// reaches less of it), with variance `variance_m2ps2`; rejected past the gate.
272 fn correct(&mut self, axis: Vec2, measured_mps: f32, variance_m2ps2: f32) {
273 let p_h = self.covariance_m2ps2 * axis;
274 let innovation_variance = axis.dot(&p_h) + variance_m2ps2;
275 let innovation = measured_mps - axis.dot(&self.wind_mps);
276 let gate = GATE_SIGMA * GATE_SIGMA * innovation_variance;
277 let within_gate = innovation * innovation <= gate;
278 // `<=` is false for a NaN innovation: rejected.
279 if !within_gate || !innovation_variance.is_finite() {
280 return;
281 }
282 let gain = p_h / innovation_variance;
283 self.wind_mps += gain * innovation;
284 self.covariance_m2ps2 -= gain * p_h.transpose();
285 // Symmetric against rounding.
286 let off = 0.5 * (self.covariance_m2ps2[(0, 1)] + self.covariance_m2ps2[(1, 0)]);
287 self.covariance_m2ps2[(0, 1)] = off;
288 self.covariance_m2ps2[(1, 0)] = off;
289 }
290}
291
292/// The specific force on the vehicle (what an accelerometer reads: acceleration less gravity),
293/// in m/s², in NED, the frame `state.attitude` rotates the body into: `(0, 0, −g)` at rest.
294///
295/// # Examples
296///
297/// ```
298/// use stable_flight::estimation::wind::specific_force_ned;
299/// use stable_flight::{GRAVITY, Vec3, VehicleState};
300///
301/// let resting = specific_force_ned(&VehicleState::default());
302/// assert_eq!(resting, Vec3::new(0.0, 0.0, -GRAVITY));
303/// ```
304pub fn specific_force_ned(state: &VehicleState) -> Vec3 {
305 let a = state.acceleration_mps2;
306 Vec3::new(a.x, a.y, -a.z - GRAVITY)
307}
308
309/// One tick's measurement.
310struct Sample {
311 specific_force_mps2: Vec2,
312 ground_along_mps: Vec2,
313 axis_x: Vec2,
314 axis_y: Vec2,
315}
316
317impl Sample {
318 /// From `state`, its attitude taken as the thrust frame; `None` if anything used is
319 /// non-finite.
320 fn from_state(state: &VehicleState) -> Option<Self> {
321 let attitude: &UnitQuaternion<f32> = &state.attitude;
322 // NED, as the attitude rotates the FRD body into it.
323 let specific_force_ned = specific_force_ned(state);
324 let velocity_ned = neu_to_ned(state.velocity_mps);
325 // One matrix serves all three: its columns are the body axes in NED.
326 let rotation = attitude.to_rotation_matrix();
327 // `<` is false for NaN; the finiteness check below catches it.
328 if rotation.matrix()[(2, 2)] < MIN_TILT_COSINE {
329 return None;
330 }
331 let force = rotation.inverse_transform_vector(&specific_force_ned);
332 let axis_x: Vec3 = rotation.matrix().column(0).into();
333 let axis_y: Vec3 = rotation.matrix().column(1).into();
334 let sample = Sample {
335 specific_force_mps2: force.xy(),
336 ground_along_mps: Vec2::new(axis_x.dot(&velocity_ned), axis_y.dot(&velocity_ned)),
337 axis_x: axis_x.xy(),
338 axis_y: axis_y.xy(),
339 };
340 let finite = [
341 sample.specific_force_mps2,
342 sample.ground_along_mps,
343 sample.axis_x,
344 sample.axis_y,
345 ]
346 .iter()
347 .all(|v| v.iter().all(|c| c.is_finite()));
348 finite.then_some(sample)
349 }
350}
351
352/// One axis's drag per kg against air velocity `v`: `−(k|v| + μ)v`, `k = ½ρ/B`.
353struct AxisDrag {
354 /// Bluff-body term, in 1/m (0 without one).
355 k_per_m: f32,
356 /// Momentum term, in 1/s.
357 mu_per_s: f32,
358}
359
360impl AxisDrag {
361 /// Axis `i` (0 `x`, 1 `y`) of `config`.
362 fn new(config: &WindConfig, i: usize) -> Self {
363 let ballistic = config.ballistic_kgpm2[i];
364 AxisDrag {
365 k_per_m: if ballistic > 0.0 {
366 0.5 * AIR_DENSITY_KGPM3 / ballistic
367 } else {
368 0.0
369 },
370 mu_per_s: config.momentum_per_s[i],
371 }
372 }
373
374 /// The air velocity, in m/s, along the axis that the drag `force_mps2` comes from, and
375 /// the drag's slope there, in 1/s; `None` without a drag model on the axis.
376 fn air_velocity(&self, force_mps2: f32) -> Option<(f32, f32)> {
377 let (k, mu) = (self.k_per_m, self.mu_per_s);
378 let push = force_mps2.abs();
379 let speed = if k > 0.0 {
380 // k·s² + μ·s = |f|, the positive root.
381 (libm::sqrtf(mu * mu + 4.0 * k * push) - mu) / (2.0 * k)
382 } else if mu > 0.0 {
383 push / mu
384 } else {
385 return None;
386 };
387 // Drag opposes the air velocity.
388 let air = if force_mps2 > 0.0 { -speed } else { speed };
389 Some((air, 2.0 * k * speed + mu))
390 }
391}