Skip to main content

stable_flight/
math.rs

1//! Small numeric helpers shared by guidance, stabilizers, controllers, 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`], [`assert_dt`], [`tilt_boost`], and [`wrap_angle`] and
5//! [`euler_angles`] (both public at the crate root).
6//!
7//! They implement the per-tick input policy (saturate, NaN → neutral, never let a non-finite
8//! error into controller state, wrap angles), which is specified in `architecture.md`,
9//! "Input Policy (no panics in the tick)". [`assert_dt`] is the policy's one per-tick panic.
10
11use core::f32::consts::{PI, TAU};
12
13use nalgebra::{SVector, UnitQuaternion};
14
15use crate::Vec2;
16
17#[cfg(test)]
18mod tests;
19
20/// Panics unless `dt` is positive and finite: the one per-tick assert the input policy allows.
21/// Runners guarantee it; a zero, negative, NaN, or infinite `dt` is a caller bug, and an
22/// infinite one would poison integrals (`0 · ∞ = NaN`).
23#[track_caller]
24pub(crate) fn assert_dt(dt: f32) {
25    assert!(dt > 0.0 && dt.is_finite(), "dt must be positive and finite");
26}
27
28/// How far [`desaturate`] may shift outputs up, per unit of collective: up to twice the
29/// collective. Keeps nearly the full moment split at flying throttle (a hover collective of
30/// ~0.55 allows 1.1, more than any split needs) while fading airmode out toward idle.
31const MAX_RAISE_PER_COLLECTIVE: f32 = 2.0;
32
33/// Fits mixer outputs into `[0, 1]`, keeping the moments (attitude over thrust), like PX4's
34/// airmode. Each output is `collective` plus its moment share.
35///
36/// 1. If the outputs span more than 1, the moment shares are scaled down about `collective`
37///    until they span exactly 1, keeping their ratios.
38/// 2. All outputs then shift by the smallest amount that fits them in `[0, 1]`: down if one
39///    is above 1, up if one is below 0. Collective thrust gives way.
40///
41/// Shifting up is limited to [`MAX_RAISE_PER_COLLECTIVE`] times `collective`, so it fades in
42/// from zero throttle instead of switching on at the first bit of it: at zero (or negative)
43/// collective nothing rises and the shares below 0 are clipped, so an armed vehicle at idle
44/// on the ground isn't lifted, or tipped, by wound-up moments. Outputs are then clamped to
45/// `[0, 1]`. Inputs are expected finite (the mixer saturates them); a NaN output stays NaN.
46///
47/// Returns what it gave up, for saturation reporting.
48pub(crate) fn desaturate(outputs: &mut [f32], collective: f32) -> Desaturation {
49    let (low, high) = outputs
50        .iter()
51        .fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), &o| {
52            (lo.min(o), hi.max(o))
53        });
54    let spread = high - low;
55    let scale = if spread > 1.0 { 1.0 / spread } else { 1.0 };
56    let scaled_low = collective + scale * (low - collective);
57    let scaled_high = collective + scale * (high - collective);
58
59    let shift = if scaled_high > 1.0 {
60        1.0 - scaled_high
61    } else if scaled_low < 0.0 {
62        (-scaled_low).min(MAX_RAISE_PER_COLLECTIVE * limit_or_zero(collective))
63    } else {
64        0.0
65    };
66
67    for output in outputs.iter_mut() {
68        *output = (collective + scale * (*output - collective) + shift).clamp(0.0, 1.0);
69    }
70
71    Desaturation {
72        lowered: shift < -CLIP_TOLERANCE,
73        // Scaled down, or still outside [0, 1] after the shift (a limited raise, or zero
74        // collective) and clipped. The tolerance absorbs rounding in a shift that lands an
75        // output exactly on a bound.
76        moments_lost: scale < 1.0
77            || scaled_low + shift < -CLIP_TOLERANCE
78            || scaled_high + shift > 1.0 + CLIP_TOLERANCE,
79    }
80}
81
82/// How far past `[0, 1]` an output may land after [`desaturate`]'s shift before it counts as
83/// clipped rather than float rounding.
84const CLIP_TOLERANCE: f32 = 1e-6;
85
86/// What [`desaturate`] gave up to fit the outputs.
87#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
88pub(crate) struct Desaturation {
89    /// Outputs were shifted down: collective thrust gave way to keep the moments.
90    pub(crate) lowered: bool,
91    /// Moments weren't delivered in full: scaled down, or an output clipped.
92    pub(crate) moments_lost: bool,
93}
94
95/// Scales `v` down, keeping its direction, so its length is at most `max`. Unlike per-axis
96/// saturation, a diagonal request stays diagonal. A non-finite `v` has no direction, so it
97/// becomes zero (neutral), per the input policy.
98pub(crate) fn cap_magnitude(v: Vec2, max: f32) -> Vec2 {
99    let length = v.norm();
100    if !length.is_finite() {
101        Vec2::zeros()
102    } else if length > max {
103        v * (max / length)
104    } else {
105        v
106    }
107}
108
109/// Saturates a normalized command to [-1, 1]; NaN becomes 0 (neutral).
110pub(crate) fn saturate_unit(value: f32) -> f32 {
111    saturate_symmetric(value, 1.0)
112}
113
114/// Saturates `value` to `[-limit, limit]`; NaN becomes 0 (neutral), and a negative or NaN
115/// `limit` acts as 0, so neither a bad input nor a bad config panics the loop.
116pub(crate) fn saturate_symmetric(value: f32, limit: f32) -> f32 {
117    if value.is_nan() {
118        0.0
119    } else {
120        clamp_symmetric(value, limit)
121    }
122}
123
124/// Clamps `value` to `[-limit, limit]`; NaN `value` stays NaN, like `f32::clamp`.
125///
126/// Unlike `f32::clamp`, it never panics: a negative or NaN `limit` acts as 0 (neutral output).
127/// Limits come from config passed in every tick, so a bad config must not panic the loop.
128pub(crate) fn clamp_symmetric(value: f32, limit: f32) -> f32 {
129    let limit = limit_or_zero(limit);
130    value.clamp(-limit, limit)
131}
132
133/// A config limit as given when it is non-negative, else 0 (neutral); NaN also becomes 0.
134pub(crate) fn limit_or_zero(limit: f32) -> f32 {
135    // `>=` is false for NaN.
136    if limit >= 0.0 { limit } else { 0.0 }
137}
138
139/// [`clamp_symmetric`] applied to each component.
140pub(crate) fn clamp_symmetric_each<const D: usize>(
141    value: SVector<f32, D>,
142    limit: f32,
143) -> SVector<f32, D> {
144    value.map(|component| clamp_symmetric(component, limit))
145}
146
147/// True when every component is finite.
148pub(crate) fn all_finite<const D: usize>(value: &SVector<f32, D>) -> bool {
149    value.iter().all(|component| component.is_finite())
150}
151
152/// ZYX Euler angles `(roll, pitch, yaw)` in radians of an attitude quaternion, in the
153/// [frame contract](crate::VehicleState#frame-contract)'s convention (the same as
154/// `UnitQuaternion::euler_angles`). Use this rather than nalgebra's method to read Euler angles
155/// from [`VehicleState::attitude`](crate::VehicleState::attitude).
156///
157/// It is a closed form on the quaternion. nalgebra's goes through a rotation matrix and `cos`
158/// (more flash on target), and its gimbal-lock branch reports a finite pitch of -π/2 and yaw 0
159/// for a NaN attitude. Here NaN in gives NaN out, which the controllers treat as neutral. Near
160/// ±90° pitch the `asin` argument is clamped, so float rounding can't turn a valid attitude
161/// into NaN.
162///
163/// # Examples
164///
165/// ```
166/// use stable_flight::euler_angles;
167/// use stable_flight::nalgebra::UnitQuaternion;
168///
169/// let attitude = UnitQuaternion::from_euler_angles(0.1, -0.2, 1.5);
170/// let (roll, pitch, yaw) = euler_angles(&attitude);
171/// assert!((roll - 0.1).abs() < 1e-6 && (pitch + 0.2).abs() < 1e-6 && (yaw - 1.5).abs() < 1e-6);
172/// ```
173pub fn euler_angles(attitude: &UnitQuaternion<f32>) -> (f32, f32, f32) {
174    let (w, x, y, z) = (attitude.w, attitude.i, attitude.j, attitude.k);
175    let roll = libm::atan2f(2.0 * (y * z + w * x), w * w - x * x - y * y + z * z);
176    // `clamp` passes NaN through, so a NaN attitude still gives NaN pitch.
177    let pitch = libm::asinf((-2.0 * (x * z - w * y)).clamp(-1.0, 1.0));
178    let yaw = libm::atan2f(2.0 * (x * y + w * z), w * w + x * x - y * y - z * z);
179    (roll, pitch, yaw)
180}
181
182/// Floor on the tilt cosine [`tilt_boost`] divides by: past 60° of tilt the boost stops
183/// growing (2×), so a steep estimate can't demand unbounded thrust.
184const MIN_TILT_COSINE: f32 = 0.5;
185
186/// Tilt cosine below which [`tilt_boost`] fades to zero (about 84°–90° of tilt), so an
187/// inverted vehicle gets no thrust from the boost, as ArduPilot's angle boost does.
188const INVERTED_FADE_COSINE: f32 = 0.1;
189
190/// Thrust multiplier that keeps a level thrust's vertical component while tilted:
191/// `1 / cos(tilt)`, with `cos(tilt) = cos(roll) · cos(pitch)` (yaw doesn't change it).
192///
193/// Floored at [`MIN_TILT_COSINE`] (at most 2× past 60°), and faded linearly to 0 as the
194/// cosine falls from [`INVERTED_FADE_COSINE`] to 0: at 90° and beyond (inverted) the
195/// multiplier is 0, so thrust never pushes an upside-down vehicle toward the ground. A
196/// non-finite attitude counts as level (1, no boost).
197///
198/// The cosine is read from the quaternion directly (`1 − 2(x² + y²)`, the rotation matrix's
199/// `(2, 2)` entry): no trig, no matrix.
200pub(crate) fn tilt_boost(attitude: &UnitQuaternion<f32>) -> f32 {
201    let (x, y) = (attitude.i, attitude.j);
202    let cosine = 1.0 - 2.0 * (x * x + y * y);
203    if !cosine.is_finite() {
204        return 1.0;
205    }
206    let upright = (cosine / INVERTED_FADE_COSINE).clamp(0.0, 1.0);
207    upright / cosine.max(MIN_TILT_COSINE)
208}
209
210/// Saturates a throttle or thrust command to [0, 1]; NaN becomes 0 (no thrust).
211pub(crate) fn saturate_throttle(value: f32) -> f32 {
212    if value.is_nan() {
213        0.0
214    } else {
215        value.clamp(0.0, 1.0)
216    }
217}
218
219/// Wraps an angle in radians to [-π, π); non-finite input gives NaN.
220///
221/// Float rounding can return exactly `+π` for inputs just below an odd multiple of π, so
222/// treat the range as closed, [-π, π], when that matters.
223///
224/// # Examples
225///
226/// ```
227/// use core::f32::consts::{FRAC_PI_2, PI};
228/// use stable_flight::wrap_angle;
229///
230/// assert!((wrap_angle(3.0 * FRAC_PI_2) + FRAC_PI_2).abs() < 1e-6); // 270° → -90°
231/// assert_eq!(wrap_angle(PI), -PI);
232/// assert!(wrap_angle(f32::NAN).is_nan());
233/// ```
234pub fn wrap_angle(angle: f32) -> f32 {
235    rem_euclid(angle + PI, TAU) - PI
236}
237
238/// `f32::rem_euclid` for a positive `divisor`, which `core` lacks: the remainder in
239/// [0, divisor). `%` truncates toward zero, so a negative remainder is shifted up.
240fn rem_euclid(value: f32, divisor: f32) -> f32 {
241    let remainder = value % divisor;
242    if remainder < 0.0 {
243        remainder + divisor
244    } else {
245        remainder
246    }
247}