stable_flight/math.rs
1//! Small numeric helpers shared by guidance, stabilizers, controllers, commanders, and mixers:
2//! [`saturate_unit`], [`saturate_symmetric`], [`saturate_throttle`], [`desaturate`],
3//! [`cap_magnitude`], [`clamp_symmetric`] and its per-component [`clamp_symmetric_each`],
4//! [`limit_or_zero`], [`all_finite`], [`neu_to_ned`], [`assert_dt`], [`tilt_boost`], [`guard_sink`],
5//! [`shaped_closing_speed`], [`twist_angle_rad`], and
6//! [`wrap_angle`] and [`euler_angles`] (both public at the crate root).
7//!
8//! They implement the per-tick input policy (saturate, NaN → neutral, never let a non-finite
9//! error into controller state, wrap angles), which is specified in `architecture.md`,
10//! "Input Policy (no panics in the tick)". [`assert_dt`] is the policy's one per-tick panic.
11
12use core::f32::consts::{PI, TAU};
13
14use nalgebra::{SVector, UnitQuaternion};
15
16use crate::{Vec2, Vec3};
17
18#[cfg(test)]
19mod tests;
20
21/// Panics unless `dt` is positive and finite: the one per-tick assert the input policy allows.
22/// Runners guarantee it; a zero, negative, NaN, or infinite `dt` is a caller bug, and an
23/// infinite one would poison integrals (`0 · ∞ = NaN`).
24#[track_caller]
25pub(crate) fn assert_dt(dt: f32) {
26 assert!(dt > 0.0 && dt.is_finite(), "dt must be positive and finite");
27}
28
29/// How far [`desaturate`] may shift outputs up, per unit of collective: up to twice the
30/// collective. Keeps nearly the full moment split at flying throttle (a hover collective of
31/// ~0.55 allows 1.1, more than any split needs) while fading airmode out toward idle.
32const MAX_RAISE_PER_COLLECTIVE: f32 = 2.0;
33
34/// Fits mixer outputs into `[0, 1]`, keeping the moments (attitude over thrust), like PX4's
35/// airmode. Each output is `collective` plus its moment share.
36///
37/// 1. If the outputs span more than 1, the moment shares are scaled down about `collective`
38/// until they span exactly 1, keeping their ratios.
39/// 2. All outputs then shift by the smallest amount that fits them in `[0, 1]`: down if one
40/// is above 1, up if one is below 0. Collective thrust gives way.
41///
42/// Shifting up is limited to [`MAX_RAISE_PER_COLLECTIVE`] times `collective`, so it fades in
43/// from zero throttle instead of switching on at the first bit of it: at zero (or negative)
44/// collective nothing rises and the shares below 0 are clipped, so an armed vehicle at idle
45/// on the ground isn't lifted, or tipped, by wound-up moments. Outputs are then clamped to
46/// `[0, 1]`. Inputs are expected finite (the mixer saturates them); a NaN output stays NaN.
47///
48/// Returns what it gave up, for saturation reporting.
49pub(crate) fn desaturate(outputs: &mut [f32], collective: f32) -> Desaturation {
50 let (low, high) = outputs
51 .iter()
52 .fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), &o| {
53 (lo.min(o), hi.max(o))
54 });
55 let spread = high - low;
56 let scale = if spread > 1.0 { 1.0 / spread } else { 1.0 };
57 let scaled_low = collective + scale * (low - collective);
58 let scaled_high = collective + scale * (high - collective);
59
60 let shift = if scaled_high > 1.0 {
61 1.0 - scaled_high
62 } else if scaled_low < 0.0 {
63 (-scaled_low).min(MAX_RAISE_PER_COLLECTIVE * limit_or_zero(collective))
64 } else {
65 0.0
66 };
67
68 for output in outputs.iter_mut() {
69 *output = (collective + scale * (*output - collective) + shift).clamp(0.0, 1.0);
70 }
71
72 Desaturation {
73 lowered: shift < -CLIP_TOLERANCE,
74 // Scaled down, or still outside [0, 1] after the shift (a limited raise, or zero
75 // collective) and clipped. The tolerance absorbs rounding in a shift that lands an
76 // output exactly on a bound.
77 moments_lost: scale < 1.0
78 || scaled_low + shift < -CLIP_TOLERANCE
79 || scaled_high + shift > 1.0 + CLIP_TOLERANCE,
80 }
81}
82
83/// How far past `[0, 1]` an output may land after [`desaturate`]'s shift before it counts as
84/// clipped rather than float rounding.
85const CLIP_TOLERANCE: f32 = 1e-6;
86
87/// What [`desaturate`] gave up to fit the outputs.
88#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
89pub(crate) struct Desaturation {
90 /// Outputs were shifted down: collective thrust gave way to keep the moments.
91 pub(crate) lowered: bool,
92 /// Moments weren't delivered in full: scaled down, or an output clipped.
93 pub(crate) moments_lost: bool,
94}
95
96/// Scales `v` down, keeping its direction, so its length is at most `max`. Unlike per-axis
97/// saturation, a diagonal request stays diagonal. A non-finite `v` has no direction, so it
98/// becomes zero (neutral), per the input policy.
99pub(crate) fn cap_magnitude(v: Vec2, max: f32) -> Vec2 {
100 let length = v.norm();
101 if !length.is_finite() {
102 Vec2::zeros()
103 } else if length > max {
104 v * (max / length)
105 } else {
106 v
107 }
108}
109
110/// Saturates a normalized command to [-1, 1]; NaN becomes 0 (neutral).
111pub(crate) fn saturate_unit(value: f32) -> f32 {
112 saturate_symmetric(value, 1.0)
113}
114
115/// The pitch limit for a setpoint: the stabilizer's `limit_rad`, or ±π/2 for a tailsitter
116/// transition ramp, whose pitch is bounded by its own config and must reach its handover.
117pub(crate) fn pitch_limit_rad(limit_rad: f32, transition: bool) -> f32 {
118 if transition {
119 core::f32::consts::FRAC_PI_2
120 } else {
121 limit_rad
122 }
123}
124
125/// Saturates `value` to `[-limit, limit]`; NaN becomes 0 (neutral), and a negative or NaN
126/// `limit` acts as 0, so neither a bad input nor a bad config panics the loop.
127pub(crate) fn saturate_symmetric(value: f32, limit: f32) -> f32 {
128 if value.is_nan() {
129 0.0
130 } else {
131 clamp_symmetric(value, limit)
132 }
133}
134
135/// Clamps `value` to `[-limit, limit]`; NaN `value` stays NaN, like `f32::clamp`.
136///
137/// Unlike `f32::clamp`, it never panics: a negative or NaN `limit` acts as 0 (neutral output).
138/// Limits come from config passed in every tick, so a bad config must not panic the loop.
139pub(crate) fn clamp_symmetric(value: f32, limit: f32) -> f32 {
140 let limit = limit_or_zero(limit);
141 value.clamp(-limit, limit)
142}
143
144/// `value` moved toward `target` by a first-order lag of `time_constant_s` over `dt` (all the
145/// way when `dt` reaches the time constant).
146pub(crate) fn lagged(value: f32, target: f32, dt: f32, time_constant_s: f32) -> f32 {
147 value + (target - value) * (dt / time_constant_s).min(1.0)
148}
149
150/// A config limit as given when it is non-negative, else 0 (neutral); NaN also becomes 0.
151pub(crate) fn limit_or_zero(limit: f32) -> f32 {
152 // `>=` is false for NaN.
153 if limit >= 0.0 { limit } else { 0.0 }
154}
155
156/// [`clamp_symmetric`] applied to each component.
157pub(crate) fn clamp_symmetric_each<const D: usize>(
158 value: SVector<f32, D>,
159 limit: f32,
160) -> SVector<f32, D> {
161 value.map(|component| clamp_symmetric(component, limit))
162}
163
164/// True when every component is finite.
165pub(crate) fn all_finite<const D: usize>(value: &SVector<f32, D>) -> bool {
166 value.iter().all(|component| component.is_finite())
167}
168
169/// A position or velocity from the state's north-east-up frame into NED, the frame the
170/// attitude rotates the body into ([frame contract](crate::VehicleState#frame-contract)).
171pub(crate) fn neu_to_ned(v: Vec3) -> Vec3 {
172 Vec3::new(v.x, v.y, -v.z)
173}
174
175/// ZYX Euler angles `(roll, pitch, yaw)` in radians of an attitude quaternion, in the
176/// [frame contract](crate::VehicleState#frame-contract)'s convention (the same as
177/// `UnitQuaternion::euler_angles`). Use this rather than nalgebra's method to read Euler angles
178/// from [`VehicleState::attitude`](crate::VehicleState::attitude).
179///
180/// It is a closed form on the quaternion. nalgebra's goes through a rotation matrix and `cos`
181/// (more flash on target), and its gimbal-lock branch reports a finite pitch of -π/2 and yaw 0
182/// for a NaN attitude. Here NaN in gives NaN out, which the controllers treat as neutral. Near
183/// ±90° pitch the `asin` argument is clamped, so float rounding can't turn a valid attitude
184/// into NaN.
185///
186/// # Examples
187///
188/// ```
189/// use stable_flight::euler_angles;
190/// use stable_flight::nalgebra::UnitQuaternion;
191///
192/// let attitude = UnitQuaternion::from_euler_angles(0.1, -0.2, 1.5);
193/// let (roll, pitch, yaw) = euler_angles(&attitude);
194/// assert!((roll - 0.1).abs() < 1e-6 && (pitch + 0.2).abs() < 1e-6 && (yaw - 1.5).abs() < 1e-6);
195/// ```
196pub fn euler_angles(attitude: &UnitQuaternion<f32>) -> (f32, f32, f32) {
197 let (w, x, y, z) = (attitude.w, attitude.i, attitude.j, attitude.k);
198 let roll = libm::atan2f(2.0 * (y * z + w * x), w * w - x * x - y * y + z * z);
199 // `clamp` passes NaN through, so a NaN attitude still gives NaN pitch.
200 let pitch = libm::asinf(nose_up_cosine(attitude).clamp(-1.0, 1.0));
201 let yaw = libm::atan2f(2.0 * (x * y + w * z), w * w + x * x - y * y - z * z);
202 (roll, pitch, yaw)
203}
204
205/// Floor on the tilt cosine [`tilt_boost`] divides by: past 60° of tilt the boost stops
206/// growing (2×), so a steep estimate can't demand unbounded thrust.
207const MIN_TILT_COSINE: f32 = 0.5;
208
209/// Tilt cosine below which [`tilt_boost`] fades to zero (about 84°–90° of tilt), so an
210/// inverted vehicle gets no thrust from the boost, as ArduPilot's angle boost does.
211const INVERTED_FADE_COSINE: f32 = 0.1;
212
213/// Thrust multiplier that keeps a level thrust's vertical component while tilted:
214/// `1 / cos(tilt)`, with `cos(tilt) = cos(roll) · cos(pitch)` (yaw doesn't change it).
215///
216/// Floored at [`MIN_TILT_COSINE`] (at most 2× past 60°), and faded linearly to 0 as the
217/// cosine falls from [`INVERTED_FADE_COSINE`] to 0: at 90° and beyond (inverted) the
218/// multiplier is 0, so thrust never pushes an upside-down vehicle toward the ground. A
219/// non-finite attitude counts as level (1, no boost).
220///
221/// The cosine is read from the quaternion directly (`1 − 2(x² + y²)`, the rotation matrix's
222/// `(2, 2)` entry): no trig, no matrix.
223pub(crate) fn tilt_boost(attitude: &UnitQuaternion<f32>) -> f32 {
224 let (x, y) = (attitude.i, attitude.j);
225 let cosine = 1.0 - 2.0 * (x * x + y * y);
226 if !cosine.is_finite() {
227 return 1.0;
228 }
229 let upright = (cosine / INVERTED_FADE_COSINE).clamp(0.0, 1.0);
230 upright / cosine.max(MIN_TILT_COSINE)
231}
232
233/// The cosine of the nose's (body `x`) tilt from vertical: `1` pointing straight up, `0`
234/// level, `−1` straight down; the sine of the pitch, read from the quaternion directly (the
235/// rotation matrix's `(2, 0)` entry, negated for NED's down `z`), so it stays well defined at
236/// ±90° pitch where the Euler angles don't. NaN for a non-finite attitude.
237pub(crate) fn nose_up_cosine(attitude: &UnitQuaternion<f32>) -> f32 {
238 let (w, x, y, z) = (attitude.w, attitude.i, attitude.j, attitude.k);
239 2.0 * (w * y - x * z)
240}
241
242/// The attitude error a roll/pitch/heading setpoint asks of `current`, in `current`'s body
243/// axes (`x` roll, `y` pitch, `z` yaw), in radians: what the attitude loops act on.
244///
245/// Tilt first, as PX4's multicopter attitude control does (`mc_att_control`,
246/// `AttitudeControl.cpp`, reduced attitude): roll and pitch are taken at the vehicle's current
247/// heading, as guidance and pilots set them, and `x`/`y` are the shortest rotation that turns
248/// the body `z` (thrust) axis onto the setpoint's. `z` is the heading error, wrapped to the
249/// short way round, weighted by the cosine of the current tilt (0 past 90°): the yaw loop turns
250/// about the thrust axis, and far over that axis is nearly horizontal, where a turn about it
251/// tips the vehicle more than it changes heading. Near level each component is the Euler
252/// difference of its axis, but as body rates, so the loops' outputs are body rates at any
253/// attitude; a setpoint equal to the current Euler angles gives zero.
254///
255/// The heading is the frame contract's ([`euler_angles`]), so it matches guidance's heading
256/// targets. It degenerates only at exactly ±90° pitch, where the weighting has already zeroed
257/// the heading term and a tailsitter's transition doesn't reach (its ramp stops short of it).
258///
259/// A non-finite `current` gives NaN components; a NaN `heading_rad` gives a NaN `z` only.
260pub(crate) fn attitude_error(
261 current: &UnitQuaternion<f32>,
262 roll_rad: f32,
263 pitch_rad: f32,
264 heading_rad: f32,
265) -> Vec3 {
266 if !current.coords.iter().all(|c| c.is_finite()) {
267 return Vec3::repeat(f32::NAN);
268 }
269 let rotation = current.to_rotation_matrix();
270 let m = rotation.matrix();
271
272 // The current heading's cosine and sine from the matrix (no trig); at exactly ±90° pitch
273 // there is none, and any will do.
274 let (north, east) = (m[(0, 0)], m[(1, 0)]);
275 let current_heading_rad = libm::atan2f(east, north);
276 let horizontal = libm::sqrtf(north * north + east * east);
277 let (cos_h, sin_h) = if horizontal > 1e-6 {
278 (north / horizontal, east / horizontal)
279 } else {
280 (1.0, 0.0)
281 };
282
283 // The setpoint's body z axis in the world (the third column of the ZYX rotation at the
284 // current heading), then seen from the current body.
285 let (sin_r, cos_r) = (libm::sinf(roll_rad), libm::cosf(roll_rad));
286 let (sin_p, cos_p) = (libm::sinf(pitch_rad), libm::cosf(pitch_rad));
287 let desired_z = Vec3::new(
288 cos_h * sin_p * cos_r + sin_h * sin_r,
289 sin_h * sin_p * cos_r - cos_h * sin_r,
290 cos_p * cos_r,
291 );
292 let z = m.tr_mul(&desired_z);
293
294 // The rotation onto it is about z × it, by the angle between them.
295 let axis = Vec2::new(-z.y, z.x);
296 let sine = axis.norm();
297 // Below this the cross product is the angle itself to f32 precision (sin x ≈ x), except
298 // exactly upside down from the setpoint, where it vanishes too: turn about body x (roll
299 // back over), so a vehicle inverted by a maneuver still recovers.
300 let tilt = if sine < 1e-6 && z.z < 0.0 {
301 Vec2::new(PI, 0.0)
302 } else if sine < 1e-6 {
303 axis
304 } else {
305 axis * (libm::atan2f(sine, z.z) / sine)
306 };
307
308 // The matrix's (2, 2) entry: the body z axis's share of the vertical.
309 let upright = m[(2, 2)].max(0.0);
310 Vec3::new(
311 tilt.x,
312 tilt.y,
313 wrap_angle(heading_rad - current_heading_rad) * upright,
314 )
315}
316
317/// Radians per degree, for constants written in degrees.
318pub(crate) const DEG: f32 = PI / 180.0;
319
320/// `rates` saturated per axis to `limits` (rad/s), NaN as zero (hold no rate).
321pub(crate) fn saturate_rates(rates: Vec3, limits: Vec3) -> Vec3 {
322 Vec3::new(
323 saturate_symmetric(rates.x, limits.x),
324 saturate_symmetric(rates.y, limits.y),
325 saturate_symmetric(rates.z, limits.z),
326 )
327}
328
329/// A stabilizer's thrust curve: linear thrust (saturated to [0, 1], NaN as 0) raised to
330/// `exponent`, the motor command that gives it (2 when thrust goes as the square of the motor
331/// command, 1 for a throttle passed through).
332pub(crate) fn thrust_curve(linear_thrust: f32, exponent: f32) -> f32 {
333 libm::powf(saturate_throttle(linear_thrust), exponent).clamp(0.0, 1.0)
334}
335
336/// The bank: roll about the nose, from the rotation matrix's bottom row (`cos θ sin φ`,
337/// `cos θ cos φ`), so it reads past ±90° (inverted is ±π) and needs no Euler angles. Ill-defined
338/// only with the nose straight up or down. NaN for a non-finite attitude.
339pub(crate) fn bank_rad(attitude: &UnitQuaternion<f32>) -> f32 {
340 let m = attitude.to_rotation_matrix();
341 libm::atan2f(m[(2, 1)], m[(2, 2)])
342}
343
344/// The angle `rotation` turns about the unit `axis`: its twist in a swing-twist split,
345/// `2·atan2(v·axis, w)` for the quaternion `(w, v)`, in `(-2π, 2π]`. A quaternion and its
346/// negation (the same rotation) differ by 2π, so callers that track a turn compare
347/// consecutive readings through [`wrap_angle`]. NaN for a non-finite rotation; undefined (0) for
348/// a half turn about an axis square to `axis`.
349pub(crate) fn twist_angle_rad(rotation: &UnitQuaternion<f32>, axis: &Vec3) -> f32 {
350 2.0 * libm::atan2f(rotation.imag().dot(axis), rotation.w)
351}
352
353/// Saturates a throttle or thrust command to [0, 1]; NaN becomes 0 (no thrust).
354pub(crate) fn saturate_throttle(value: f32) -> f32 {
355 if value.is_nan() {
356 0.0
357 } else {
358 value.clamp(0.0, 1.0)
359 }
360}
361
362/// `thrust` raised by `gain` per m/s of sink past `limit_mps`, saturated to `[0, 1]`, or
363/// `None` when the guard doesn't act: not sinking past the limit, a NaN `climb_mps`, or a
364/// `limit_mps` of 0 (disabled). Keeps air over a tailsitter's elevons, which a sink turns
365/// against the propwash.
366pub(crate) fn guard_sink(thrust: f32, climb_mps: f32, limit_mps: f32, gain: f32) -> Option<f32> {
367 let excess_mps = -limit_mps - climb_mps;
368 (limit_mps > 0.0 && excess_mps > 0.0).then(|| saturate_throttle(thrust + gain * excess_mps))
369}
370
371/// The speed toward a target `distance_m` away that `accel_mps2` of deceleration can still
372/// bring to zero at the target: `p · distance` within `accel / p²` of it, `√(2 · accel ·
373/// (distance − accel / 2p²))` beyond, the two meeting with the same value and slope (the shape
374/// of ArduPilot's `sqrt_controller`, `libraries/AP_Math/control.cpp:575`). A non-positive or
375/// NaN distance gives 0; a non-positive `accel_mps2` gives the linear speed alone, and a
376/// non-positive `p` the square root alone.
377pub(crate) fn shaped_closing_speed(distance_m: f32, p: f32, accel_mps2: f32) -> f32 {
378 if distance_m.is_nan() || distance_m <= 0.0 {
379 return 0.0;
380 }
381 // NaN or non-positive: no deceleration limit.
382 let accel_mps2 = if accel_mps2 > 0.0 { accel_mps2 } else { 0.0 };
383 if p.is_nan() || p <= 0.0 {
384 return libm::sqrtf(2.0 * accel_mps2 * distance_m);
385 }
386 let linear_m = accel_mps2 / (p * p);
387 if accel_mps2 == 0.0 || distance_m <= linear_m {
388 return p * distance_m;
389 }
390 libm::sqrtf(2.0 * accel_mps2 * (distance_m - linear_m / 2.0))
391}
392
393/// Wraps an angle in radians to [-π, π); non-finite input gives NaN.
394///
395/// Float rounding can return exactly `+π` for inputs just below an odd multiple of π, so
396/// treat the range as closed, [-π, π], when that matters.
397///
398/// # Examples
399///
400/// ```
401/// use core::f32::consts::{FRAC_PI_2, PI};
402/// use stable_flight::wrap_angle;
403///
404/// assert!((wrap_angle(3.0 * FRAC_PI_2) + FRAC_PI_2).abs() < 1e-6); // 270° → -90°
405/// assert_eq!(wrap_angle(PI), -PI);
406/// assert!(wrap_angle(f32::NAN).is_nan());
407/// ```
408pub fn wrap_angle(angle: f32) -> f32 {
409 rem_euclid(angle + PI, TAU) - PI
410}
411
412/// `f32::rem_euclid` for a positive `divisor`, which `core` lacks: the remainder in
413/// [0, divisor). `%` truncates toward zero, so a negative remainder is shifted up.
414fn rem_euclid(value: f32, divisor: f32) -> f32 {
415 let remainder = value % divisor;
416 if remainder < 0.0 {
417 remainder + divisor
418 } else {
419 remainder
420 }
421}