MJKPhysics
MJKPhysics is a six-degree-of-freedom flight dynamics engine for small unmanned aircraft, written in Rust and rendered in the browser. This book is its engineering record. For every physical model it gives the equations, the assumptions behind them, the range where they hold, the sources of every parameter, and how the implementation was checked.
Status: pre-alpha. Milestone M0, the foundations, is complete: the workspace and its layering, CI with the engineering standards enforced, this book, and the error and configuration model. Milestone M1, the math and rigid-body core, is complete: frame-typed math, the SO(3) maps, rigid-body dynamics, the integrators including the Lie-group method, the world loop, determinism and replay, gravity and the standard atmosphere, the analytic validation suite and the command-line tool. Milestone M2, the multirotor, is under way: the airframe format and the motor and ESC model are done, and the battery model (#20) is next. The book grows with the roadmap; pages for models that don’t exist yet are listed with the issue that will add them.
How the book is organized
- Foundations. Conventions and notation fixes frames, rotation conventions, signs, units and symbols; everything else uses them. Architecture describes the crates, their layering and the rules the engine follows.
- Physics. Models has one page per physical model. Validation collects the evidence that each model is implemented correctly. Airframes documents the four modeled aircraft and the source of every parameter.
- Project. Decision records explain significant design choices and the alternatives that were rejected. Engineering standards gives the rules the code follows, how CI enforces each one, and how the tests themselves are tested. Writing documentation covers the house style for pages, equations and citations.
Equations and citations
Display equations carry stable IDs such as (CONV-3), and each one has an anchor: this book links
to it as conventions.html#eq-CONV-3. Code cites equations in comments as // Eq. (CONV-3), and
cargo xtask equations fails if a citation points to an equation that doesn’t exist, or if two
equations share an ID.
Building the book locally
cargo install mdbook --version 0.5.4 --locked
mdbook serve docs --open
Conventions and notation
This page is the single authority for reference frames, rotation conventions, signs, units and symbols in MJKPhysics. Every model page links here and uses these symbols; code follows the same names. If a source paper uses a different convention, its model page states the mapping explicitly instead of silently adopting the paper’s convention.
Equations carry stable IDs such as (CONV-3) so code comments can cite them.
1. Notation
| Kind | Typeface | Example |
|---|---|---|
| Scalar | italic | $m$, $V_a$, $\alpha$ |
| Vector | bold lowercase | $\mathbf{v}$, $\boldsymbol{\omega}$ |
| Matrix | bold uppercase | $\mathbf{R}$, $\mathbf{J}$ |
| Quaternion | bold lowercase $\mathbf{q}$ with components $(q_0, q_1, q_2, q_3)$, scalar first | $\mathbf{q}_{WB}$ |
| Frame | upright capital | $W$, $B$, $S$, $A$ |
- A superscript names the frame a vector is resolved in: $
\mathbf{v}^B$ is $\mathbf{v}$ expressed in body axes. - A rotation or quaternion with two subscripts maps coordinates from the right frame to the left
frame: $
\mathbf{x}^W = \mathbf{R}_{WB} \mathbf{x}^B$. Subscripts cancel inward under composition: $\mathbf{R}_{WS} = \mathbf{R}_{WB} \mathbf{R}_{BS}$. - $
[\mathbf{a}]_\times$ is the skew-symmetric matrix with $[\mathbf{a}]_\times\mathbf{b} = \mathbf{a}\times\mathbf{b}$. - $
\otimes$ is the quaternion product and $\mathbf{q}^{\ast}$ the conjugate. - A dot is a time derivative taken in the world frame unless stated otherwise.
In code, q_wb is $\mathbf{q}_{WB}$ (“world from body”), and vectors carry their frame in their
type, as in Vec3<Body> and Vec3<World>; the attitude is a Rotation<World, Body>
(see Math types).
2. Reference frames
| Frame | Symbol | Code marker | Origin | Axes |
|---|---|---|---|---|
| World | $W$ | World | Scenario reference point on the ground | North, East, Down (local level) |
| Body | $B$ | Body | Vehicle center of mass | Forward, Right, Down |
| Stability | $S$ | Stability | Center of mass | $\mathbf{x}_S$ along the relative wind projected onto the body $x$–$z$ plane; $\mathbf{y}_S = \mathbf{y}_B$ |
| Wind (air-relative) | $A$ | Wind | Center of mass | $\mathbf{x}_A$ along the relative wind; $\mathbf{z}_A$ in the body plane of symmetry |
| Part | $P$ | Part | Center of one component | The component’s own axes, for building mass properties (Rigid-body dynamics) |
| Render | $\mathcal{R}$ | viewer only | Same as $W$ | East, Up, South (Y-up, right-handed) |
The wind axes are written $A$, not $W$, so they cannot be confused with the world frame. All
frames are right-handed.
2.1 World frame and the flat-earth assumption
The world frame is a local-level North-East-Down frame fixed to the ground at a reference point
with WGS-84 geodetic coordinates $(\text{lat}_0, \text{lon}_0, h_0)$. The equations of motion treat
it as inertial and flat: no earth rotation, no curvature, gravity along $+\mathbf{z}_W$.
This is appropriate for small unmanned aircraft operating within about 10 km of the reference point. At that range:
| Neglected effect | Size at 10 km or 40 m/s |
|---|---|
Earth curvature: surface drop $d^2/2R_E$ | 7.85 m |
Change in gravity direction $d/R_E$ | 0.090° |
Coriolis acceleration $2 \Omega_E V$ | $5.8\times10^{-3}$ m/s² (0.06 % of $g$) |
Centripetal acceleration from earth rotation is not neglected: it is already included in normal gravity when the WGS-84 gravity model is selected (#15). Geodetic coordinates appear only at the edges: GNSS output (#73) and terrain placement (#62).
Altitude is $h = h_0 - p_D$, where $h_0$ is the field elevation above mean sea level and $p_D$
is the Down component of the position. The atmosphere reads it as height above mean sea level;
WGS-84 gravity uses the same value as height above the ellipsoid, neglecting the geoid height,
at most about 100 m (Atmosphere and gravity).
2.2 Body frame
The body frame is fixed to the airframe with its origin at the center of mass: $\mathbf{x}_B$ out
of the nose, $\mathbf{y}_B$ out of the right side, $\mathbf{z}_B$ down. For a multirotor, “nose” is
the forward direction declared in the airframe file; for the quad-X layout it bisects motors 1
and 3 (section 6).
The rotation from body to world is defined by its columns, which are the body axes expressed in world coordinates:
\mathbf{R}_{WB} = \begin{bmatrix} \mathbf{x}_B^W & \mathbf{y}_B^W & \mathbf{z}_B^W \end{bmatrix},
\qquad \mathbf{x}^W = \mathbf{R}_{WB}\,\mathbf{x}^B,
\qquad \mathbf{R}_{BW} = \mathbf{R}_{WB}^{\top}
\qquad\text{(CONV-1)}
2.3 Stability and wind axes
With the air-relative velocity resolved in body axes as $\mathbf{v}_a^B = (u_a, v_a, w_a)$ and
airspeed $V_a = \lVert \mathbf{v}_a \rVert$:
\alpha = \mathrm{atan2}(w_a,\, u_a), \qquad \beta = \arcsin\!\left(\frac{v_a}{V_a}\right)
\qquad\text{(CONV-2)}
\mathbf{R}_{BS} = \mathbf{R}_y(-\alpha), \qquad \mathbf{R}_{SA} = \mathbf{R}_z(\beta), \qquad
\mathbf{v}_a^B = \mathbf{R}_{BS}\,\mathbf{R}_{SA} \begin{bmatrix} V_a \\ 0 \\ 0 \end{bmatrix}
\qquad\text{(CONV-3)}
Positive $\alpha$ means the relative wind meets the aircraft from below. Positive $\beta$ means it
meets the aircraft from the right. Both angles are undefined as $V_a \to 0$; models that use them
must define their behavior below a stated airspeed
(#44).
2.4 Render frame
The viewer uses a right-handed Y-up frame. One module, and only that module, converts from world coordinates:
\mathbf{C} = \begin{bmatrix} 0 & 1 & 0 \\ 0 & 0 & -1 \\ -1 & 0 & 0 \end{bmatrix},
\qquad \mathbf{p}^{\mathcal{R}} = \mathbf{C}\,\mathbf{p}^W = (p_E,\, -p_D,\, -p_N)
\qquad\text{(CONV-4)}
Because $\mathbf{C}$ is a proper rotation ($\det\mathbf{C} = +1$), a world-frame attitude maps to
$\mathbf{C} \mathbf{R} \mathbf{C}^{\top}$, which in quaternion form is
\mathbf{q}^{\mathcal{R}} = (q_0,\; q_2,\; -q_3,\; -q_1)
\qquad\text{(CONV-5)}
Meshes authored in body FRD coordinates go through the same $\mathbf{C}$, so positions and
orientations always convert the same way (#34).
3. Rotations and quaternions
3.1 Quaternion convention
MJKPhysics uses Hamilton quaternions ($ij = k$), stored scalar first:
\mathbf{q} = \begin{bmatrix} q_0 \\ \mathbf{q}_v \end{bmatrix}
= \begin{bmatrix} \cos(\theta/2) \\ \mathbf{u}\,\sin(\theta/2) \end{bmatrix},
\qquad \lVert \mathbf{q} \rVert = 1
\qquad\text{(CONV-6)}
This is a right-handed rotation by $\theta$ about the unit axis $\mathbf{u}$. The product is
\mathbf{p}\otimes\mathbf{q} =
\begin{bmatrix}
p_0 q_0 - \mathbf{p}_v\cdot\mathbf{q}_v \\
p_0\,\mathbf{q}_v + q_0\,\mathbf{p}_v + \mathbf{p}_v\times\mathbf{q}_v
\end{bmatrix}
\qquad\text{(CONV-7)}
The attitude state is the unit quaternion $\mathbf{q}_{WB}$. It acts on vectors as
$\mathbf{x}^W = \mathbf{q}_{WB}\otimes\mathbf{x}^B\otimes\mathbf{q}_{WB}^{\ast}$, using pure
quaternions $(0, \mathbf{x})$, and corresponds to
\mathbf{R}_{WB} =
\begin{bmatrix}
1 - 2(q_2^2 + q_3^2) & 2(q_1 q_2 - q_0 q_3) & 2(q_1 q_3 + q_0 q_2) \\
2(q_1 q_2 + q_0 q_3) & 1 - 2(q_1^2 + q_3^2) & 2(q_2 q_3 - q_0 q_1) \\
2(q_1 q_3 - q_0 q_2) & 2(q_2 q_3 + q_0 q_1) & 1 - 2(q_1^2 + q_2^2)
\end{bmatrix}
\qquad\text{(CONV-8)}
Composition follows the matrix order: $\mathbf{q}_{WS} = \mathbf{q}_{WB}\otimes\mathbf{q}_{BS}$.
$\mathbf{q}$ and $-\mathbf{q}$ are the same rotation. The state is never sign-flipped, to keep it
continuous in time, and attitude errors are compared with the rotation angle
$2\arccos\lvert(\mathbf{p}^{\ast}\otimes\mathbf{q})_0\rvert$, which is independent of sign.
Why Hamilton, scalar first. It matches PX4 and MAVLink and the Lie-group literature this
project builds on (Solà 2017; Solà, Deray & Atchuthan 2018), and its composition order equals the
matrix order. The JPL convention ($ij = -k$, usually scalar last)
reverses composition order and is common in older spacecraft-navigation papers; any source
using it is converted at the model boundary and the conversion is tested.
3.2 Attitude kinematics
The angular velocity of the body relative to the world, resolved in body axes, is
$\boldsymbol{\omega}^B = (p, q, r)$: roll, pitch and yaw rates. The italic scalar $q$ (pitch
rate) is unrelated to the bold quaternion $\mathbf{q}$.
\dot{\mathbf{q}}_{WB} = \tfrac{1}{2}\,\mathbf{q}_{WB}\otimes\begin{bmatrix} 0 \\ \boldsymbol{\omega}^B \end{bmatrix},
\qquad
\dot{\mathbf{R}}_{WB} = \mathbf{R}_{WB}\,[\boldsymbol{\omega}^B]_\times
\qquad\text{(CONV-9)}
The exponential map is $\mathrm{Exp}(\boldsymbol{\theta}) = (\cos\tfrac{\theta}{2}, \tfrac{\boldsymbol{\theta}}{\theta}\sin\tfrac{\theta}{2})$ with $\theta = \lVert\boldsymbol{\theta}\rVert$.
Increments and perturbations are applied on the right, in body axes:
\mathbf{q}_{WB}(t + \Delta t) = \mathbf{q}_{WB}(t)\otimes\mathrm{Exp}(\boldsymbol{\omega}^B\,\Delta t)
\quad\text{for constant } \boldsymbol{\omega}^B
\qquad\text{(CONV-10)}
Small-angle and $\theta\to 0$ handling of these maps is specified in
#9.
3.3 Euler angles (input and output only)
Euler angles never appear in the state and their rates are never integrated. They exist for
human-facing input and output: scenario files, logs, the HUD. The sequence is 3-2-1: yaw
$\psi$, then pitch $\theta$, then roll $\phi$, using elementary rotations that act on vectors:
\mathbf{R}_{WB} = \mathbf{R}_z(\psi)\,\mathbf{R}_y(\theta)\,\mathbf{R}_x(\phi)
\qquad\text{(CONV-11)}
\mathbf{R}_x(\phi) = \begin{bmatrix} 1 & 0 & 0 \\ 0 & \cos\phi & -\sin\phi \\ 0 & \sin\phi & \cos\phi \end{bmatrix},\;
\mathbf{R}_y(\theta) = \begin{bmatrix} \cos\theta & 0 & \sin\theta \\ 0 & 1 & 0 \\ -\sin\theta & 0 & \cos\theta \end{bmatrix},\;
\mathbf{R}_z(\psi) = \begin{bmatrix} \cos\psi & -\sin\psi & 0 \\ \sin\psi & \cos\psi & 0 \\ 0 & 0 & 1 \end{bmatrix}
Ranges are $\psi\in(-\pi,\pi]$, $\theta\in[-\tfrac{\pi}{2},\tfrac{\pi}{2}]$, $\phi\in(-\pi,\pi]$.
Extraction, with $R_{ij}$ the entries of $\mathbf{R}_{WB}$:
\theta = -\arcsin R_{31}, \qquad \phi = \mathrm{atan2}(R_{32}, R_{33}), \qquad \psi = \mathrm{atan2}(R_{21}, R_{11})
\qquad\text{(CONV-12)}
The code evaluates these in an equivalent, better-conditioned form that stays exact near ±90°
(SO3-11 on the SO(3) maps page). At $\lvert\theta\rvert = \tfrac{\pi}{2}$ only $\psi \mp \phi$ is defined. The convention there
is $\phi = 0$ and $\psi = \mathrm{atan2}(-R_{12}, R_{22})$, which holds for both signs of
$\theta$.
3.4 Positive rotations and moments
By the right-hand rule about the body axes:
| Rotation or moment | Axis | Positive sense |
|---|---|---|
Roll $\phi$, rate $p$, moment $M_x$ | $+\mathbf{x}_B$ | right wing down |
Pitch $\theta$, rate $q$, moment $M_y$ | $+\mathbf{y}_B$ | nose up |
Yaw $\psi$, rate $r$, moment $M_z$ | $+\mathbf{z}_B$ | nose right (clockwise seen from above) |
Moments are written $(M_x, M_y, M_z)$ rather than $(\ell, m, n)$ so they cannot be confused with
mass $m$. The aerodynamic coefficients keep their standard names $C_l$, $C_m$, $C_n$.
4. Forces, aerodynamics and controls
4.1 Aerodynamic forces
Lift and drag are defined in stability axes and side force in body axes, as in Beard & McLain (2012, ch. 4):
- Drag $
D$ acts along $-\mathbf{x}_S$. - Lift $
L$ acts along $-\mathbf{z}_S$ (upward in upright flight). - Side force $
Y$ acts along $+\mathbf{y}_B$.
Stevens, Lewis & Johnson define drag along the wind axis $-\mathbf{x}_A$. The two definitions
differ at order $\beta$, and each model page states which one its source uses.
Coefficients are nondimensionalized by the dynamic pressure $\bar{q} = \tfrac12\rho V_a^2$, the
reference area $S$, the span $b$ (roll and yaw) and the mean aerodynamic chord $\bar{c}$ (pitch).
Rates enter as $\tfrac{pb}{2V_a}$, $\tfrac{q\bar{c}}{2V_a}$ and $\tfrac{rb}{2V_a}$.
4.2 Control-surface deflections
Virtual controls are defined by the moment they produce. This matches the Beard & McLain parameter set, so the Aerosonde derivatives are used without sign changes; every airframe’s validation checks the sign of each control derivative (#50, #51).
| Control | Symbol | Positive deflection | Primary effect |
|---|---|---|---|
| Elevator | $\delta_e$ | trailing edge down | nose-down pitching moment ($C_{m_{\delta_e}} < 0$) |
| Aileron | $\delta_a$ | left trailing edge down, right trailing edge up | right-wing-down rolling moment ($C_{l_{\delta_a}} > 0$) |
| Rudder | $\delta_r$ | trailing edge left | nose-left yawing moment ($C_{n_{\delta_r}} < 0$) |
| Throttle | $\delta_t$ | $0 \le \delta_t \le 1$ | — |
A physical surface is positive when its trailing edge moves down, or left for a vertical
surface. Mixed surfaces such as elevons and ruddervators are declared in the airframe file as a
linear map from $(\delta_e, \delta_a, \delta_r)$ to physical deflections
(#45). With that definition,
$\delta_a = \tfrac12(\delta_{\text{left}} - \delta_{\text{right}})$ for conventional ailerons.
5. Gravity and atmosphere
Gravity acts along $+\mathbf{z}_W$ with magnitude $g_0 = 9.80665$ m/s² (standard gravity), or
WGS-84 normal gravity as a function of latitude and altitude when that model is selected.
Atmospheric quantities follow the U.S. Standard Atmosphere 1976: temperature $T$ in kelvin,
pressure $P$ in pascals, density $\rho$ in kg/m³, speed of sound $a$, dynamic viscosity $\mu$
(Atmosphere and gravity).
6. Rotors and propellers
- Geometry. Each rotor $
i$ has a hub position $\mathbf{r}_i^B$ relative to the center of mass and a unit thrust axis $\mathbf{n}_i^B$; for a flat multirotor, $\mathbf{n}_i^B = -\mathbf{z}_B$. - Speed. $
\omega_i \ge 0$ is the rotor’s speed magnitude in rad/s. RPM appears only in input and output (_rpmsuffix). - Spin direction. $
s_i = +1$ for counter-clockwise and $s_i = -1$ for clockwise, both as seen from above (looking along $+\mathbf{z}_B$). The rotor’s angular velocity is $s_i \omega_i \mathbf{n}_i$. - Quad-X numbering follows PX4: motor 1 front-right counter-clockwise, motor 2 rear-left counter-clockwise, motor 3 front-left clockwise, motor 4 rear-right clockwise. Airframe files list rotors with explicit IDs, so other layouts need no special cases.
Yaw reaction. The motor’s reaction on the airframe opposes the torque that spins the rotor,
so a counter-clockwise rotor produces a positive (nose-right) yaw moment. With $Q_i \ge 0$ the
aerodynamic torque magnitude:
\mathbf{M}_{\text{reaction},i}^B = -s_i\,Q_i\,\mathbf{n}_i^B
\qquad\left(= +s_i\,Q_i\,\mathbf{z}_B \text{ for } \mathbf{n}_i = -\mathbf{z}_B\right)
\qquad\text{(CONV-13)}
To yaw right, speed up the counter-clockwise rotors.
6.1 Propeller and rotor coefficients
Two nondimensionalizations are in common use, and they differ by large constant factors. Propeller
data (UIUC Propeller Data Site; Brandt & Selig) uses revolutions per second $n$ and diameter $D$,
with disk area $A = \pi R^2$; rotorcraft theory (Leishman) uses $\Omega$ and radius $R$.
(CONV-16) converts between the two.
C_{T,\text{prop}} = \frac{T}{\rho n^2 D^4},\qquad C_{P,\text{prop}} = \frac{P}{\rho n^3 D^5},\qquad J = \frac{V}{nD}
\qquad\text{(CONV-14)}
C_{T,\text{rotor}} = \frac{T}{\rho A (\Omega R)^2},\qquad C_{P,\text{rotor}} = \frac{P}{\rho A (\Omega R)^3}
\qquad\text{(CONV-15)}
C_{T,\text{rotor}} = \frac{4}{\pi^3}\,C_{T,\text{prop}}, \qquad C_{P,\text{rotor}} = \frac{4}{\pi^4}\,C_{P,\text{prop}}
\qquad\text{(CONV-16)}
Code names them ct_prop and ct_rotor (likewise cp_prop and cp_rotor) and never uses a
bare ct.
7. Units, numbers and time
-
SI throughout, with angles in radians. Degrees, RPM and other display units appear only in input and output.
-
Unit suffixes on every physical field and variable whose unit is not obvious:
Suffix Unit Suffix Unit _mmeter _nnewton _m_sm/s _n_mnewton-meter _m_s2m/s² _papascal _radradian _kkelvin _rad_srad/s _vvolt _kgkilogram _aampere _kg_m2kg·m² _ohmohm _ssecond _deg,_rpminput/output only -
Floating point. The engine computes in
f64. Transcendental functions go throughlibmso native and WebAssembly builds agree bit for bit, and Clippy rejects the standard library’s versions. Rust never fusesa * b + cinto one operation on its own; an explicit fused multiply-add is writtenlibm::fma. Arithmetic andsqrtare correctly rounded by IEEE 754 (Determinism and replay). -
Time. Simulation time is an integer tick count; seconds are derived as $
k \Delta t$ and never accumulated by repeated addition.
8. Interoperability
Conversions to external conventions happen only at the boundary: bridges, file import and export, and the renderer.
| System | World / body frames | Quaternion | Conversion |
|---|---|---|---|
| MJKPhysics | NED / FRD | Hamilton, scalar first, body → world | — |
| PX4, MAVLink | NED / FRD | Hamilton, scalar first, body → NED | none |
| ArduPilot | NED / FRD | — | none for frames |
| ROS (REP 103) | ENU / FLU | Hamilton, stored $(x, y, z, w)$ | ENU→NED: $(N, E, D) = (y, x, -z)$; FLU→FRD: $(x, -y, -z)$ |
| three.js viewer | East-Up-South | Hamilton, $(x, y, z, w)$ | (CONV-4), (CONV-5) |
9. Symbol table
| Symbol | Meaning | Unit | Code |
|---|---|---|---|
$\mathbf{p}^W = (p_N, p_E, p_D)$ | Position of the center of mass | m | position_m: Vec3<World> |
$\mathbf{v}^W$ | Velocity of the center of mass relative to $W$ | m/s | velocity_m_s: Vec3<World> |
$\mathbf{q}_{WB}$ | Attitude, body to world | — | q_wb: Rotation<World, Body> |
$\boldsymbol{\omega}^B = (p, q, r)$ | Body angular velocity relative to $W$, in body axes | rad/s | omega_rad_s: Vec3<Body> |
$\mathbf{v}_{\text{wind}}^W$ | Wind velocity | m/s | wind_m_s: Vec3<World> |
$\mathbf{v}_a = \mathbf{v} - \mathbf{v}_{\text{wind}}$, $(u_a, v_a, w_a)$ | Air-relative velocity and its body components | m/s | v_air_m_s: Vec3<Body> |
$V_a$ | Airspeed | m/s | airspeed_m_s |
$\alpha$, $\beta$ | Angle of attack, sideslip (CONV-2) | rad | alpha_rad, beta_rad |
$\psi, \theta, \phi$ | Yaw, pitch, roll (I/O only) | rad | yaw_rad, pitch_rad, roll_rad |
$m$ | Mass | kg | mass_kg |
$\mathbf{J}^B$ | Inertia tensor about the center of mass, body axes | kg·m² | inertia_kg_m2: Mat3<Body> |
$\mathbf{F}$, $\mathbf{M} = (M_x, M_y, M_z)$ | Force; moment about the center of mass | N, N·m | Wrench<F> |
$L$, $D$, $Y$ | Lift, drag, side force | N | lift_n, drag_n, side_force_n |
$C_L, C_D, C_Y, C_l, C_m, C_n$ | Force and moment coefficients | — | c_lift, c_drag, … |
$\bar{q} = \tfrac12\rho V_a^2$ | Dynamic pressure | Pa | dynamic_pressure_pa |
$S$, $b$, $\bar{c}$ | Reference area, span, mean aerodynamic chord | m², m, m | area_m2, span_m, chord_m |
$\delta_e, \delta_a, \delta_r, \delta_t$ | Elevator, aileron, rudder, throttle | rad, rad, rad, — | elevator_rad, … |
$\omega_i$, $s_i$ | Rotor speed, spin direction | rad/s, — | omega_rad_s, spin |
$T_i$, $Q_i$ | Rotor thrust, rotor torque magnitude | N, N·m | thrust_n, torque_n_m |
$\rho$, $T$, $P$, $a$, $\mu$ | Density, temperature, pressure, speed of sound, viscosity | kg/m³, K, Pa, m/s, Pa·s | density_kg_m3, … |
$g_0$ | Standard gravity, 9.80665 | m/s² | G0_M_S2 |
$\Delta t$, $k$ | Physics step, tick index | s, — | dt_s, tick |
References
- J. Solà, “Quaternion kinematics for the error-state Kalman filter,” arXiv:1711.02508, 2017.
- J. Solà, J. Deray, D. Atchuthan, “A micro Lie theory for state estimation in robotics,” arXiv:1812.01537, 2018.
- B. L. Stevens, F. L. Lewis, E. N. Johnson, Aircraft Control and Simulation, 3rd ed., Wiley, 2015.
- R. W. Beard, T. W. McLain, Small Unmanned Aircraft: Theory and Practice, Princeton University Press, 2012.
- J. G. Leishman, Principles of Helicopter Aerodynamics, 2nd ed., Cambridge University Press, 2006.
- PX4 documentation: coordinate frames, and multicopter geometry and motor numbering.
- ROS REP 103, “Standard Units of Measure and Coordinate Conventions.”
Math types
mjk-math is the hand-written linear algebra underneath the engine
(ADR 0001). Its defining feature is that every vector, matrix
and rotation carries its reference frame in its type, so a frame mistake fails to compile instead
of producing a plausible wrong answer.
The types
| Type | Meaning | Notation |
|---|---|---|
Vec3<F> | A vector resolved in frame F | $\mathbf{v}^F$ |
Mat3<F> | A linear operator on Vec3<F>, such as an inertia tensor in body axes | $\mathbf{J}^B$ |
Rotation<To, From> | Maps Vec3<From> to Vec3<To> | $\mathbf{q}_{\text{To},\text{From}}$, $\mathbf{R}_{\text{To},\text{From}}$ |
Quat | A general Hamilton quaternion, scalar first, for algebra such as $\dot{\mathbf{q}}$ | $\mathbf{q}$ |
UnitQuat | A unit quaternion: a rotation with no frame attached | $\lVert\mathbf{q}\rVert = 1$ |
The frame markers are World, Body, Stability and Wind, as defined in the
conventions. Other crates can define more frames, such as a
rotor hub frame, by implementing the Frame trait on a marker type.
Types that read like the notation
Rotation<To, From> puts the target frame first, matching the subscripts in the conventions:
q_wb: Rotation<World, Body> is $\mathbf{q}_{WB}$, and q_wb.rotate(v_b) is
$\mathbf{x}^W = \mathbf{R}_{WB}\,\mathbf{x}^B$. Composition type-checks exactly when the inner
subscripts cancel:
let q_ws: Rotation<World, Stability> = q_wb * q_bs; // W←B ∘ B←S = W←S
Mat3<F> only acts on vectors in its own frame. Moving a tensor to another frame goes through a
rotation, q_wb.transform(j_b), which computes $\mathbf{R}\,\mathbf{J}\,\mathbf{R}^\top$.
What the compiler rejects
Each of these is a compile_fail documentation test, so CI proves it stays a compile error:
| Mistake | Compiler error |
|---|---|
| Adding a body-frame vector to a world-frame vector | expected Vec3<Body>, found Vec3<World> |
Rotating a vector from the wrong frame with q_wb.rotate(v_w) | expected Vec3<Body>, found Vec3<World> |
Composing rotations whose inner frames differ, q_wb * q_ws | expected Rotation<Body, _>, found Rotation<World, Stability> |
| Applying a body-frame inertia tensor to a world-frame rate | no implementation for Mat3<Body> * Vec3<World> |
Construction is where meaning is asserted: Vec3::new and Rotation::from_unit_quat take the
frame from the type the caller writes. After that, the compiler keeps the frames straight.
Numerics
- Bit-identical everywhere. Arithmetic and square roots are rounded exactly by IEEE 754, and
every transcendental function (
sin,cos,atan2) comes fromlibm, so results match on every platform, including WebAssembly. The maps built on them are on the SO(3) maps page. - Rotating a vector uses $
\mathbf{v}' = \mathbf{v} + 2q_0(\mathbf{q}_v\times\mathbf{v}) + 2\,\mathbf{q}_v\times(\mathbf{q}_v\times\mathbf{v})$, which equals $\mathbf{q}\otimes\mathbf{v}\otimes\mathbf{q}^{\ast}$ for a unit quaternion and is tested against the matrix form (CONV-8). - Inverse.
Mat3::inverseuses the adjugate (cross products of columns over the determinant) and returnsNonefor singular or non-finite matrices. - Symmetric eigen-decomposition.
Mat3::symmetric_eigenuses the cyclic Jacobi method (Golub & Van Loan, §8.5). It stops when the off-diagonal norm falls below $10^{-15}$ times the largest entry. Convergence is quadratic, so 3×3 matrices need a few sweeps; after 32 sweeps it returns a convergence error rather than looping. Eigenvalues come back in ascending order, with eigenvectors forming a right-handed orthonormal basis, ready to serve as principal axes.
How it is tested
- Property tests (proptest, 512 random cases per property per run):
- rotations preserve norm, and $
\mathbf{q}\otimes\mathbf{q}^{-1} = 1$; - quaternion composition equals the matrix product, and quaternion rotation equals its matrix;
- typed composition applies the right operand first, and inverses round-trip;
- tensor transforms act consistently;
- the cross product is antisymmetric, bit for bit, and orthogonal to its operands;
- skew and outer products, transpose, determinant and inverse behave as they should;
- for symmetric matrices: eigenpairs satisfy $
\mathbf{A}\mathbf{v} = \lambda\mathbf{v}$, are orthonormal and right-handed, and rebuild the matrix.
- rotations preserve norm, and $
- Mutation checks. Flipping a sign in the Hamilton product, or in either Jacobi update, makes the properties fail. This confirms they actually constrain the implementation.
compile_failtests for every frame mistake in the table above.
References
- G. H. Golub, C. F. Van Loan, Matrix Computations, 4th ed., Johns Hopkins University Press, 2013, §8.5.
- J. Solà, “Quaternion kinematics for the error-state Kalman filter,” arXiv:1711.02508, 2017.
SO(3) maps
- Issue: #9
- Code:
mjk_math::so3,mjk_math::EulerAngles,Rotation::{exp, log, plus, minus, slerp, from_matrix, to_euler} - Equation prefix:
SO3
Summary
The exponential and logarithm maps connect rotation vectors, three numbers that can be added and
scaled, to rotations, which cannot. Integrators (#11, #12), interpolation and attitude errors are
all built on them. This page also covers the SO(3) Jacobians, the $\oplus$ and $\ominus$
operators, spherical interpolation, conversion from rotation matrices, and Euler-angle extraction.
Notation and conventions follow the conventions page; Hamilton quaternions,
scalar first.
Assumptions
- Rotation vectors are $
\boldsymbol\theta = \theta\,\mathbf{u}$ with unit axis $\mathbf{u}$ and angle $\theta$ in radians, right-handed. - Increments are applied on the right, in the local frame (CONV-10).
- Every transcendental function comes from
libm, so results are bit-identical on every platform.
Exponential and logarithm
\mathrm{Exp}(\boldsymbol\theta) = \Big(\cos\tfrac{\theta}{2},\ \tfrac{\sin(\theta/2)}{\theta}\,\boldsymbol\theta\Big)
\qquad\text{(SO3-1)}
\mathrm{Log}(\mathbf{q}) = \frac{2\,\mathrm{atan2}(\lVert\mathbf{q}_v\rVert,\ q_0)}{\lVert\mathbf{q}_v\rVert}\,\mathbf{q}_v,
\qquad \mathbf{q} \leftarrow -\mathbf{q}\ \text{if}\ q_0 < 0
\qquad\text{(SO3-2)}
The sign flip picks the shortest rotation, so the angle of $\mathrm{Log}(\mathbf{q})$ is in
$[0, \pi]$, and $\mathbf{q}$ and $-\mathbf{q}$ give the same answer. The atan2 form stays
accurate near $\pi$, where $\arccos q_0$ would lose half its digits.
Small angles
Each ratio is evaluated in the form that keeps full precision.
\frac{\sin(\theta/2)}{\theta} \approx \tfrac12 - \tfrac{\theta^2}{48} + \tfrac{\theta^4}{3840},
\qquad
\frac{\theta - \sin\theta}{\theta^3} = \sum_{k\ge0}\frac{(-1)^k\,\theta^{2k}}{(2k+3)!},
\qquad
\frac{1}{\theta^2} - \frac{\cot(\theta/2)}{2\theta} = \sum_{n\ge1}\frac{(-1)^{n+1}B_{2n}\,\theta^{2n-2}}{(2n)!}
\qquad\text{(SO3-3)}
| Quantity | Problem with the closed form | What the code does |
|---|---|---|
$\sin(\theta/2)/\theta$ | 0/0 at $\theta = 0$ only | Series below $10^{-3}$ rad; closed form above |
$2\,\mathrm{atan2}(n, q_0)/n$ | 0/0 at $n = 0$ only | Below $n = 10^{-6}$, the series $(2/q_0)(1 - n^2/3)$; since $q_0^2 = 1 - n^2$, the omitted terms are $O(n^4)$, under $10^{-24}$ |
$(1-\cos\theta)/\theta^2$ | Cancellation: loses about $2\varepsilon/\theta^2$ | Computed as $2\,(\sin(\theta/2)/\theta)^2$, with no cancellation anywhere |
$(\theta-\sin\theta)/\theta^3$ | Cancellation: loses about $6\varepsilon/\theta^2$, about 9 digits at $\theta = 10^{-3}$ | 8-term series below 1 rad |
$1/\theta^2 - \cot(\theta/2)/(2\theta)$ | Cancellation: loses about $12\varepsilon/\theta^2$ | 11-term series below 1 rad ($B_{2n}$ are the Bernoulli numbers) |
The series coefficients were generated exactly in rational arithmetic. A unit test checks all
three coefficients against 40-digit references at eight angles from $10^{-6}$ to 3 rad, to a
relative error below $10^{-15}$. The obvious closed forms fail that test by nine orders of
magnitude at the $\theta \approx 10^{-3}$ of a typical integrator step.
Jacobians
\mathbf{J}_r(\boldsymbol\theta) = \mathbf{I} - \frac{1-\cos\theta}{\theta^2}[\boldsymbol\theta]_\times + \frac{\theta-\sin\theta}{\theta^3}[\boldsymbol\theta]_\times^2
\qquad\text{(SO3-4)}
\mathbf{J}_r^{-1}(\boldsymbol\theta) = \mathbf{I} + \tfrac12[\boldsymbol\theta]_\times + \Big(\frac{1}{\theta^2} - \frac{\cot(\theta/2)}{2\theta}\Big)[\boldsymbol\theta]_\times^2
\qquad\text{(SO3-5)}
\mathbf{J}_l(\boldsymbol\theta) = \mathbf{J}_r(-\boldsymbol\theta) = \mathbf{J}_r(\boldsymbol\theta)^\top,
\qquad
\mathbf{J}_l^{-1}(\boldsymbol\theta) = \mathbf{J}_r^{-1}(-\boldsymbol\theta)
\qquad\text{(SO3-6)}
They are defined by how a small change in the rotation vector moves the rotation:
\mathrm{Exp}(\boldsymbol\theta + \delta\boldsymbol\theta) \approx \mathrm{Exp}(\boldsymbol\theta)\,\mathrm{Exp}\big(\mathbf{J}_r(\boldsymbol\theta)\,\delta\boldsymbol\theta\big),
\qquad
\mathrm{Log}\big(\mathrm{Exp}(\boldsymbol\theta)\,\mathrm{Exp}(\delta\boldsymbol\theta)\big) \approx \boldsymbol\theta + \mathbf{J}_r^{-1}(\boldsymbol\theta)\,\delta\boldsymbol\theta
\qquad\text{(SO3-7)}
The Lie-group integrator (#12) uses $\mathbf{J}_r^{-1}$. Writing the inverse coefficient with
$\cot(\theta/2)$ keeps it finite at $\theta = \pi$. The Jacobians are valid for
$\theta < 2\pi$.
Composition operators and interpolation
\mathbf{R}\oplus\boldsymbol\tau = \mathbf{R}\,\mathrm{Exp}(\boldsymbol\tau),
\qquad
\mathbf{S}\ominus\mathbf{R} = \mathrm{Log}(\mathbf{R}^{-1}\mathbf{S}),
\qquad
\mathbf{R}\oplus(\mathbf{S}\ominus\mathbf{R}) = \mathbf{S}
\qquad\text{(SO3-8)}
\mathrm{slerp}(\mathbf{R}_0, \mathbf{R}_1, t) = \mathbf{R}_0 \oplus t\,(\mathbf{R}_1 \ominus \mathbf{R}_0)
\qquad\text{(SO3-9)}
The vector $\boldsymbol\tau$ is in the rotation’s From frame, so in code
q_wb.plus(tau_b) type-checks only with a body-frame increment. Interpolation follows the
shortest arc at a constant angular rate.
From a rotation matrix
Shepperd’s method takes the square root of the largest of
$4q_0^2 = 1 + \mathrm{tr}\,\mathbf{R}$, $4q_1^2 = 1 + 2R_{11} - \mathrm{tr}\,\mathbf{R}$,
$4q_2^2 = 1 + 2R_{22} - \mathrm{tr}\,\mathbf{R}$ and $4q_3^2 = 1 + 2R_{33} - \mathrm{tr}\,\mathbf{R}$.
It then recovers the other three components from sums and differences of off-diagonal entries.
For example, when $q_0$ is the largest:
q_0 = \tfrac12\sqrt{1+\mathrm{tr}\,\mathbf{R}},\quad
q_1 = \frac{R_{32}-R_{23}}{4q_0},\quad
q_2 = \frac{R_{13}-R_{31}}{4q_0},\quad
q_3 = \frac{R_{21}-R_{12}}{4q_0}
\qquad\text{(SO3-10)}
Choosing the largest component avoids dividing by a small number. The input must be a proper
rotation, orthonormal to $10^{-9}$ and with determinant $+1$; anything else is rejected.
Euler angles
The definition and the gimbal-lock convention are in the conventions (CONV-11, CONV-12). The extraction is arranged so that the rebuilt rotation is exact, even close to ±90° of pitch:
\begin{aligned}
\psi &= \mathrm{atan2}(R_{21}, R_{11}), \qquad \theta = \mathrm{atan2}\big(-R_{31},\ \sqrt{R_{11}^2+R_{21}^2}\big), \\
\phi &= \mathrm{atan2}(\sin\psi\,R_{13} - \cos\psi\,R_{23},\ \cos\psi\,R_{22} - \sin\psi\,R_{12})
\end{aligned}
\qquad\text{(SO3-11)}
The textbook roll, $\mathrm{atan2}(R_{32}, R_{33})$, divides two entries that both shrink with
$\cos\theta$. Near gimbal lock, yaw and roll then pick up independent errors of about
$\varepsilon/\cos\theta$. The property tests caught this: at $\cos\theta \approx 2\times10^{-6}$
the rebuilt rotation was off by $5\times10^{-11}$. Computing roll from the yaw already found
uses entries that don’t shrink, so roll absorbs any error in yaw, and the round trip stays at
rounding level, about $10^{-16}$.
Gimbal lock is declared only when $\cos\theta < 10^{-15}$, just above rounding noise, which
catches pitch at exactly ±90° in floating point. There, roll is zero and yaw is
$\mathrm{atan2}(-R_{12}, R_{22})$. A wider threshold would only discard information: with
$10^{-10}$, the round-trip error inside the threshold grew to $10^{-10}$.
Validation
| Check | Tolerance | Result |
|---|---|---|
$\mathrm{Log}(\mathrm{Exp}(\boldsymbol\theta)) = \boldsymbol\theta$ for $\lvert\boldsymbol\theta\rvert$ log-uniform in $[10^{-12}, \pi - 10^{-6}]$ | $10^{-12}$ absolute and relative | Pass |
$\mathrm{Exp}(\mathrm{Log}(\mathbf{q})) = \mathbf{q}$; $\mathrm{Log}$ takes the short way; $\mathrm{Log}(-\mathbf{q}) = \mathrm{Log}(\mathbf{q})$ | $8\varepsilon$ | Pass |
$\mathbf{J}_r\mathbf{J}_r^{-1} = \mathbf{I}$, $\mathbf{J}_l = \mathbf{J}_r^\top = \mathbf{R}\,\mathbf{J}_r$ | $10^{-13}$ | Pass |
SO3-7 by finite differences, $\lvert\delta\boldsymbol\theta\rvert = 10^{-5}$ | $10^{-9}$ (second-order) | Pass |
$\oplus$ and $\ominus$ invert each other | $10^{-12}$ | Pass |
| slerp: endpoints, constant rate, short arc | $10^{-13}$ | Pass |
Euler round trip, pitch at least $10^{-3}$ rad from ±90° | $10^{-11}$ per angle | Pass |
| Euler-to-rotation round trip for all pitch, including exactly ±90° | $10^{-14}$ | Pass |
Euler matches $\mathbf{R}_z\mathbf{R}_y\mathbf{R}_x$ | $8\varepsilon$ | Pass |
| Shepperd round trip; scaled and reflected matrices rejected | $8\varepsilon$ | Pass |
| Jacobian coefficients against 40-digit references | $10^{-15}$ relative | Pass |
The property tests run 512 random cases per property on every CI run. Every one of eight
deliberate mutants is caught: sign errors in Exp, Log, $\mathbf{J}_r$ and Shepperd’s method,
a dropped factor, a perturbed series coefficient, the textbook roll formula, and the old lock
threshold.
References
- J. Solà, J. Deray, D. Atchuthan, “A micro Lie theory for state estimation in robotics,” arXiv:1812.01537, 2018.
- T. D. Barfoot, State Estimation for Robotics, Cambridge University Press, 2017.
- S. W. Shepperd, “Quaternion from rotation matrix,” Journal of Guidance and Control, 1978.
- J. Solà, “Quaternion kinematics for the error-state Kalman filter,” arXiv:1711.02508, 2017.
Architecture
Crates and layers
The workspace is split into crates whose dependency graph encodes the engine’s layers. A crate may
depend only on the layers beneath it, and cargo xtask layering enforces this on every pull
request.
mjk-core engine error model (used by every engine crate)
|
mjk-math frame-tagged vectors, quaternions, SO(3)
/ \
mjk-dynamics mjk-env rigid body, integrators, world loop | atmosphere, wind
/ | \ |
mjk-contact | mjk-control | collision and contact | allocation, controllers
\ | | |
\ mjk-aero | | rotors, propulsion, fixed-wing aerodynamics
\ | | |
mjk-sensors | IMU, GNSS, barometer, magnetometer, range, airspeed
\ |
mjk-sim ---------- world composition, airframes, scenarios
/ \
mjk-cli mjk-wasm front ends: command line | browser bindings
|
viewer TypeScript renderer (reads snapshots only)
The exact allowed edges are the rule table in xtask/src/layering.rs. Engine crates, everything
from mjk-core to mjk-sim, may use only libm, serde, serde_path_to_error and toml as
external dependencies outside of tests (ADR 0001,
ADR 0006). The coding rules every crate follows, and how
CI enforces them, are on the Engineering standards page.
Rules the engine follows
- No I/O in engine crates. Files, terminals, sockets and the browser belong to front ends. Engine crates take configuration as text and return results as data (Configuration files).
- Fixed-step and deterministic. Physics advances in fixed steps, with subsystems at integer rate divisors. The same inputs and seed produce bit-identical state on every platform, and a recorded run replays exactly (ADR 0002, Determinism and replay).
- No heap allocation per step. Everything
World::stepneeds is allocated when the world is built; a counting allocator proves it in CI (Engineering standards). - No panics. Fallible operations return
Result<_, EngineError>frommjk-core. Configuration errors name the exact field; numerical failures report the simulation time and the offending quantity (ADR 0006). - Rendering never feeds back. The viewer receives state snapshots and pilot inputs flow the other way; nothing the renderer does can change a simulated result (ADR 0004).
One simulation step
World::step (mjk_dynamics::World) advances the state in this order, each stage reading only
results from earlier stages:
- Discrete subsystems due on this tick, through
Model::update: sensors first, then controllers, reading the state at the start of the step. The inputs they set are held constant for the whole step (zero-order hold). - Continuous dynamics, through one integrator step (ADR 0002). Inside every integrator stage the system evaluates, in order: the environment (atmosphere and wind at each point), actuators (motors, ESCs and control surfaces responding to the held commands), and forces and moments (rotors, aerodynamics and gravity, summed about the center of mass).
- After the step, through
Model::after_step, with the clock already at the new tick: contact detection and impulse resolution (ADR 0003), then logging into preallocated buffers. Both attach here when they land; until then the hook does nothing.
Time and rates
Time is an integer tick count at a fixed physics rate, 1 kHz by default; seconds are the tick
divided by the rate, a single correctly rounded division, never a running sum. A subsystem’s rate
must divide the physics rate exactly: it runs on tick zero and then every physics/rate ticks, so
a 500 Hz controller and a 50 Hz barometer run on every second and every twentieth tick. A rate
that does not divide the physics rate is rejected, never rounded.
Real time
A real-time front end calls World::advance(real_dt), which takes as many whole steps as fit,
carries the remainder to the next call, and returns alpha, how far real time has moved past the
last step as a fraction of one. The viewer draws the state interpolated between the previous and
current steps by alpha. If more steps are due than a cap allows (a quarter of a second of steps
by default), the whole backlog is dropped and reported, so a slow frame cannot make the next one
slower (the “spiral of death”).
Determinism and replay
The same scenario, seed and inputs produce the same state, to the bit, on every run and platform, natively and in WebAssembly. A recorded run replays exactly. This page shows how each source of difference is closed, how a state is fingerprinted, and the reference run that CI checks on every change (#14).
Summary
- Arithmetic: every floating-point operation either is correctly rounded by IEEE 754 or comes
from
libm, which is the same Rust code on every target. Clippy rejects the standard library’s versions. - Random numbers: a hand-written xoshiro256** generator (DET-1). Each subsystem draws from its own stream, seeded from the run’s master seed and the stream’s name (DET-2), so adding a sensor cannot change the turbulence a run sees.
- Fingerprints: a 64-bit FNV-1a hash of the raw bits of everything that determines the steps to come (DET-5), recorded at a fixed checkpoint rate.
- Replay: inputs are applied between steps and logged with their tick, and a replay hands each one back on the same tick.
- Proof: the reference run below is published as a table of checkpoint hashes. Tests require it to match the code, and CI requires a WebAssembly build to print the same bytes as the native build.
Where differences come from
| Source | Rule | Enforced by |
|---|---|---|
Transcendental functions (sin, atan2, exp, powi and the rest) | Only through libm. The standard library leaves their accuracy unspecified, so results could differ between targets | Clippy disallowed-methods (clippy.toml), for f64 and f32 |
| Fused multiply-add | Never implicit: Rust does not contract a * b + c. Explicit fused multiply-adds go through libm::fma, since without a hardware instruction mul_add calls the platform’s C library | The same Clippy list includes mul_add |
+, −, ×, ÷, sqrt | Correctly rounded by IEEE 754 on every target, so they need no rule | — |
| Time | An integer tick count; seconds are derived, never summed (Architecture) | Tests |
| Random numbers | Seeded streams only; nothing reads the clock or the operating system’s entropy | Tests, review |
| Order of evaluation | One thread; subsystems run in the fixed order of Model::update; no hash-map iteration in the engine | Review |
The platforms agreed on the first comparison. The integrator study, which predates this page,
already matched to the bit on Linux, Windows and macOS (arm64) and in WebAssembly. Moving three
explicit fused multiply-adds from mul_add to libm::fma changed no published number, as
expected when both are correctly rounded.
Random numbers
xoshiro256** keeps four 64-bit words $s_0 \ldots s_3$ and has period $2^{256}-1$
(Blackman and Vigna, 2021). Each draw returns
x = \mathrm{rotl}(5\,s_1,\ 7)\cdot 9 \bmod 2^{64}
\qquad\text{(DET-1)}
and then advances the state with shifts, rotations and exclusive-ors. A stream is seeded from the
master seed $S$ and its name $n$ through SplitMix64, as the generator’s authors recommend
(Steele, Lea and Flood, 2014). One output mixes the seed into $m$; a second SplitMix64,
seeded with the name’s hash chained to $m$, gives four outputs $c_1 \ldots c_4$:
m = \mathrm{SplitMix64}(S),\qquad
(c_1, c_2, c_3, c_4) = \mathrm{SplitMix64}^{4}\big(\mathrm{FNV}(n) \oplus m\big),\qquad
(s_0, s_1, s_2, s_3) = (m \oplus c_4,\ c_1,\ c_2,\ c_3)
\qquad\text{(DET-2)}
Each property follows from one step of the construction:
- No two pairs share a stream.
SplitMix64’s first output is a bijection of its seed, so $s_1$ gives back $\mathrm{FNV}(n) \oplus m$, which determines $c_4$; then $s_0$ gives back $m$, so $S$, and with it $\mathrm{FNV}(n)$. Two streams start from the same state only if their seeds and their name hashes are both equal. - No word is shared. Every word depends on both the seed and the name, so the streams of one run have nothing in common to correlate through.
- Streams start differently. The first draw depends on $
s_1$ alone (DET-1), and $s_1$ depends on both the seed and the name through a nonlinear mix. Streams in one run, and one stream in different runs, start with different draws. - Never all zero. $
s_1$ and $s_2$ come from two differentSplitMix64states, so at most one of them is zero. - Independent of other streams. A stream depends only on $
S$ and $n$, not on how many other streams exist or the order they were made. The generator’s jump function was not used because it would tie each stream to its creation order.
The first version of this page seeded a stream with $\mathrm{SplitMix64}^{4}(S \oplus \mathrm{FNV}(n))$. Squeezing the seed and the name into one 64-bit value made some pairs collide:
seed 7’s gyro stream was the same as the pilot stream of seed
$7 \oplus \mathrm{FNV}(\texttt{gyro}) \oplus \mathrm{FNV}(\texttt{pilot})$.
A split layout, with the seed in the first two words and the name in the last two, ruled that
out but gave every stream in a run the same first draw, because $s_1$ came from the seed
alone. A third version set $s_0 = m$, which every stream of a run then shared; no test found a
correlation through it, but $s_0 = m \oplus c_4$ removes the shared word rather than relying on
that. Tests now pin each of these properties.
Independence between streams is measured as well as argued. For every pair of the reference
run’s streams, and for one stream at adjacent seeds, as a Monte Carlo sweep would use them, the
tests compare $10^5$ samples:
- Correlation: at lags from −4 to +4, the worst is 0.0074, or 2.3 standard deviations
($
\sigma = 1/\sqrt{10^5}$). The tests fail above 6σ. - Bit balance: for each of the 64 bits of the two streams’ XOR, the worst imbalance between zeros and ones is 3.0σ.
Those are the largest values expected by chance from that many comparisons. Each week, PractRand
(Doty-Humphrey) tests eight streams of one run, interleaved, to 32 GB, far past what $10^5$
samples can see. mjk random <seed> <name>... --bytes <n> writes the interleaved streams.
Uniform samples take the top 53 bits of a draw:
u = \big\lfloor x / 2^{11} \big\rfloor \cdot 2^{-53} \in [0, 1)
\qquad\text{(DET-3)}
Each of the $2^{53}$ values is equally likely, and the conversion is exact. Normal samples use
the Box–Muller transform (Box and Muller, 1958):
z = \sqrt{-2\ln(1-u_1)}\,\cos(2\pi u_2)
\qquad\text{(DET-4)}
$1 - u_1$ lies in $(0, 1]$, so the logarithm is finite. Each sample draws two uniforms and
keeps one normal. Keeping the second normal would save draws but would add a cached value to the
generator’s state.
State fingerprints
A StateHasher folds bytes $b_i$ into a 64-bit FNV-1a hash, little-endian on every platform:
h_0 = \mathtt{cbf29ce484222325}_{16},\qquad
h_{i+1} = (h_i \oplus b_i)\cdot \mathtt{100000001b3}_{16} \bmod 2^{64}
\qquad\text{(DET-5)}
Each f64 goes in as its raw bits, so 0.0 and -0.0 hash differently. Each step is a
bijection of $h$, so changing any single byte always changes the hash. FNV-1a is a fingerprint
for comparing honest runs, not a cryptographic hash.
World::state_hash covers everything that determines the steps to come:
- the clock (tick and rate);
- the current state;
- the model’s own state: held commands, sensor readings and the state of every random stream.
A model provides the last of these by implementing StateHash with every field that can affect
the future, in a fixed order. The previous state and the real-time remainder affect only what is
drawn, so they are left out.
Checkpoints and replay
Checkpoints records the hash at a fixed rate, such as once a second, from tick 0. An input
changes a model between steps: World::apply logs it with the current tick, then applies it, and
it holds from the next step on. World::replay_due, called before each step, applies the logged
inputs for that tick in their recorded order:
let mut world = World::new(model, Rkmk4, y0, 1000)?;
let mut replay = Replay::new(&log);
for _ in 0..ticks {
world.replay_due(&mut replay);
world.checkpoint(&mut checkpoints)?;
world.step();
}
Both records are sized when they are made and never grow, so recording allocates nothing inside a step. The allocation test records 1000 checkpoints and 1000 inputs, then replays them. A full record, or a checkpoint that is not later than the last one, is an error, never a silent drop. An input that cannot be logged is not applied, so the log always describes the run.
The reference run
A tumbling 2 kg body is flown by random pilot commands through a rate controller that reads a noisy gyro, with a noisy accelerometer alongside. It is integrated with RKMK4 at 1 kHz for 10 s, with a checkpoint every second.
| Parameter | Value |
|---|---|
| Master seed | 14 |
| Streams | gyro, accelerometer, pilot |
| Gyro | 500 Hz, white noise σ = 0.01 rad/s |
| Accelerometer | 250 Hz, white noise σ = 0.05 m/s² |
| Rate controller | 250 Hz, $\mathbf{M} = k\,\mathbf{J}\,(\boldsymbol{\omega}_{cmd} - \tilde{\boldsymbol{\omega}})$, $k$ = 8 s⁻¹ |
| Pilot | A command every 0.5 s: body rates with σ = 0.5 rad/s, thrust within σ = 5 % of hover |
| Initial state | At rest 10 m up, ω = (0.4, −0.3, 1.5) rad/s |
The run’s state hash at each checkpoint, beside the hash from a replay of its 20 recorded commands:
| Time (s) | Tick | Recorded run | Replay of its inputs |
|---|---|---|---|
| 0 | 0 | ec970e54e8b17c5e | ec970e54e8b17c5e |
| 1 | 1000 | a57bf55881486988 | a57bf55881486988 |
| 2 | 2000 | c91c3b64ec587b92 | c91c3b64ec587b92 |
| 3 | 3000 | 18584c7ec22c7c0b | 18584c7ec22c7c0b |
| 4 | 4000 | 984ca2390c99d02d | 984ca2390c99d02d |
| 5 | 5000 | 85e33c0fc9a89b2c | 85e33c0fc9a89b2c |
| 6 | 6000 | 9fba8fcc671dcae0 | 9fba8fcc671dcae0 |
| 7 | 7000 | 13fba57b0fea01ce | 13fba57b0fea01ce |
| 8 | 8000 | c1aee0670879a860 | c1aee0670879a860 |
| 9 | 9000 | 3416ffc5f53af107 | 3416ffc5f53af107 |
| 10 | 10000 | ba6762fb8571ca0f | ba6762fb8571ca0f |
Generated by mjk validate determinism. A test fails if this table no longer matches the code,
and CI fails unless the native build and a WebAssembly build print it byte for byte.
The two hash columns are equal at every checkpoint, so replaying the 20 recorded commands reproduces the run, final state included. Running the scenario twice gives the same table. Tests also show that the hashes respond to every change:
- another seed changes every checkpoint;
- raising one command’s thrust by one part in $
10^9$ changes every checkpoint from that command’s tick on, and none before it.
A fingerprint is exact, so it also shows what rounding absorbs. Changing a 0.01 N·m moment
command by one ulp did not change the final hash. Held for 0.25 s on a 0.02 kg·m² axis, the
change moves ω by about $2\times10^{-17}$ rad/s. That is below the resolution of an ω near
1 rad/s, so once the next command replaced it, the two runs were in the same state to the bit.
Validation
| Check | Criterion | Test |
|---|---|---|
SplitMix64, xoshiro256** and FNV-1a against the published reference algorithms | every value equal | splitmix64_matches_the_reference, xoshiro256_star_star_matches_the_reference, the_hasher_is_fnv_1a_64 |
| A new stream leaves another’s sequence unchanged | 100 draws identical, interleaved or alone | adding_a_stream_does_not_change_another |
| No two seed-and-name pairs share a stream; the state is built as in DET-2 | the pair that collided under XOR seeding now differs; state equal word for word | no_two_seed_and_name_pairs_share_a_stream, a_stream_state_is_the_name_chained_to_the_mixed_seed |
| No state word is shared by the streams of a run | all four words differ, pair by pair | no_word_is_shared_by_the_streams_of_a_run |
| Streams of one run, and one stream at adjacent seeds, are uncorrelated | correlation at lags −4 to +4 below 0.019 (6σ); every bit of their XOR balanced within 6σ, over $10^5$ samples | streams_in_a_run_are_uncorrelated, adjacent_seeds_are_uncorrelated; the_independence_checks_detect_a_dependent_stream shows both checks fail on a dependent pair |
| Eight interleaved streams of one run | no PractRand failure to 32 GB | weekly deep-analysis.yml, job Random streams (PractRand) |
| Streams start with different draws | distinct first draws for three streams in one run, and for one stream over three seeds | streams_start_with_different_draws |
| The reference run’s stream names | distinct FNV-1a hashes | every_stream_name_hashes_differently |
| Uniform samples: endpoints and moments | exact at 0 and $1-2^{-53}$; mean and variance within 0.005 and 0.002 | a_uniform_sample_is_the_top_53_bits_scaled_into_the_unit_interval, uniform_samples_have_the_right_mean_and_spread |
| Normal samples: values and moments | within $10^{-14}$ of a reference; variance within 0.03 of 1; 68.27 % within one σ | gaussian_samples_match_the_box_muller_reference, gaussian_samples_have_unit_variance_and_normal_tails |
| Two runs of the reference scenario | identical at every checkpoint | two_runs_agree_at_every_checkpoint |
| Replaying the recorded inputs | identical checkpoints and final hash | replaying_the_inputs_reproduces_the_final_hash |
| An altered input | every hash from its tick on differs, none before | an_altered_input_changes_every_hash_from_its_tick_on |
Native and WebAssembly (wasm32-wasip1 under Node) | both studies’ output identical to each other and to the book | CI job Native and WebAssembly agree |
| Windows and macOS (arm64) | the published tables reproduce | weekly cross-platform.yml |
| Recording and replay | no allocation | allocations (harness-free test) |
Limitations
- Logs live in memory until the run ends.
mjk runthen writes them to a file andmjk replaychecks a file against a new run, to the bit (Command-line tool). - Only logged inputs replay. A change made through
World::model_mutbypasses the log. - NaN payloads. WebAssembly may give a NaN a different payload or sign than native code does. A NaN in the state already means the run has failed (a degenerate attitude makes every rate NaN, see Integrators), so only failed runs can hash differently.
- Targets. Supported targets compute in IEEE 754 double precision: x86-64, arm64 and
WebAssembly. Targets that compute with the x87’s extended precision, such as
i586, are not supported.
References
- D. Blackman, S. Vigna, “Scrambled linear pseudorandom number generators,” ACM Transactions on
Mathematical Software, 2021. Reference code:
xoshiro256starstar.c,splitmix64.c. - G. L. Steele Jr., D. Lea, C. H. Flood, “Fast splittable pseudorandom number generators,” OOPSLA, 2014.
- G. E. P. Box, M. E. Muller, “A note on the generation of random normal deviates,” Annals of Mathematical Statistics 29(2), 1958.
- G. Fowler, L. C. Noll, K.-P. Vo, D. Eastlake, T. Hansen, “The FNV non-cryptographic hash
algorithm,” IETF Internet-Draft
draft-eastlake-fnv. - IEEE 754-2019, Standard for Floating-Point Arithmetic: correct rounding of the basic operations, square root and fused multiply-add.
- C. Doty-Humphrey, PractRand, version 0.96, a test suite for random number generators (pracrand.sourceforge.net).
Configuration files
Airframes, and later scenarios, are written as TOML documents. This page covers the rules every document follows, the airframe format, units and sources, and what error messages look like. ADR 0006 records why it works this way.
Who reads the file
Engine crates do no I/O. A front end, such as the command-line tool or the browser viewer, reads the file and passes its text to a loader together with a name for error messages, usually the file path:
let loaded = mjk_sim::config::load_airframe("airframes/example-quadrotor.toml", &text)?;
Loading checks, in order:
- TOML syntax.
- The header:
schema_version, thenkind. - The shape of the document: required fields present, no unknown fields, values of the right type and length, and a unit on every number.
- Each parameter: its unit is known and of the right quantity, its value and uncertainty are finite, and its source is in the file’s bibliography. Then each value is converted to SI.
- Physical plausibility of each value: a positive mass, a realizable inertia, a nonzero rotor axis, and so on.
- The whole airframe: it can lift itself, and its rotor disks do not overlap.
The first error found is returned. If none is found, the result holds:
- the airframe, in SI units;
- every parameter as written, for the airframe’s generated page;
- the warnings, such as a number without a source.
Rules
-
Every document starts with a header:
schema_version = 1 kind = "airframe" -
Unknown fields are errors. A misspelled key such as
masis reported, never silently ignored. -
Every number is a parameter, a table
{ value, unit, source, uncertainty }(#18):mass = { value = 350, unit = "g", source = "datasheet", uncertainty = 5 }unitis required. A bare number, or a table withoutunit, is an error naming the field.sourceis the key of an entry in the file’s[sources]. A number without a source loads, with a warning.uncertaintyis optional, in the same unit as the value, and never negative.
-
Vectors and tensors are arrays in body axes (FRD). Matrices are arrays of rows:
inertia.value[row][col]. -
Machine output is JSON, written by front ends: run logs, for example (Command-line tool). Configuration types implement serde’s
Serializefor that purpose.
Units in Rust identifiers still follow the conventions:
mass_kg, kv_rad_s_v. In a file, the unit is written next to the number instead, so a value
can be copied from a datasheet exactly as printed.
Units
A unit is a product of symbols, each with an optional integer power, divided by others:
kg m^2andkg·m²are the same unit;rpm/V,N m s/radand1/sshow the division;1is a pure number.
Symbols are separated by spaces, · or *. Powers are written ^2, ^-1, ² or ³. Each
field states the quantity it needs. A unit of another dimension is an error that names the
quantity and suggests units.
Only these symbols are known. There is no general prefix rule, so min is always a minute:
| Quantity | Symbols |
|---|---|
| Length | m, cm, mm, km, in, ft |
| Mass | kg, g, lb, oz |
| Time | s, ms, us or µs, min, h |
| Current | A, mA |
| Angle | rad, deg, rev |
| Angular rate, frequency | rpm; Hz |
| Force | N, gf, kgf, lbf |
| Energy, power | J; W |
| Voltage | V, mV |
| Resistance | ohm or Ω, mohm |
| Charge | Ah, mAh |
Each symbol’s factor is its definition.
- Exact factors: the inch (0.0254 m), the pound (0.453 592 37 kg) and standard gravity behind the gram-force (9.806 65 m/s²) are exact.
- Rounded factors: those involving π round once to double precision.
Angle is its own dimension, although SI counts it as dimensionless. That keeps an rpm from
being mistaken for a Hz, and it means a speed constant must be given per volt as an angular
rate (rpm/V or rad/s/V).
Sources
[sources.<key>] tables form the file’s bibliography, and parameters cite them by key:
[sources.datasheet]
title = "2212 920 KV motor datasheet"
author = "Example Motors"
year = 2024
url = "https://example.com/2212-datasheet.pdf"
note = "Table 2, at 11.1 V."
| Field | Rule |
|---|---|
title | Required, not empty. |
author, url, doi, note | Optional text. |
year | Optional whole number. |
A parameter that cites a key with no entry is an error. An entry that no parameter cites gets a warning.
The airframe format
airframes/example-quadrotor.toml
uses every table below, and its page is what
mjk airframe generates from it. Required fields are in bold.
Top level:
schema_version,kind: the header.name: not empty.mass: the mass properties.rotors: at least one.- The optional tables:
sources,propellers,motors,escs,battery,drag,controllerandvisual.
Mass properties
Give either mass, cg and inertia directly, or a list of [[mass.components]]
built up by the parallel-axis theorem. Giving both is an error.
| Field | Quantity | Rule |
|---|---|---|
mass | mass | Positive and finite. |
cg | length, vector | Center of mass from the airframe’s reference point. Finite. |
inertia | moment of inertia, 3×3 | About the center of mass. Finite; symmetric to a relative tolerance of $10^{-9}$; positive definite; physically realizable. |
Each component:
| Field | Quantity | Rule |
|---|---|---|
name | text | Not empty. |
mass | mass | Positive. |
position | length, vector | Its center from the reference point. |
shape | point, box or cylinder | A box needs size; a cylinder needs radius and length, along its own z axis. A shape with fields of another shape is an error. |
size, radius, length | length | Not negative. |
orientation | angle, vector | Roll, pitch and yaw of the part’s axes from body axes. |
“Physically realizable” means some mass distribution actually has this inertia. For a symmetric
tensor that holds exactly when the second-moment matrix $\tfrac12\mathrm{tr}(\mathbf{J})\,\mathbf{I} - \mathbf{J}$
is positive semidefinite. This is the matrix form of the triangle inequality on the principal
moments, $J_1 + J_2 \ge J_3$ (Wensing, Kim & Slotine, 2018). Both conditions are tested with
principal minors, so no eigen-decomposition is needed. A thin plate, with
$J_3 = J_1 + J_2$ exactly, is accepted. A rod with a zero principal moment is rejected, because it
makes the rotational dynamics singular.
Rotors and propellers
Each [[rotors]] entry:
| Field | Quantity | Rule |
|---|---|---|
name | text | Not empty. |
position | length, vector | The hub, from the reference point. |
axis | pure number, vector | The direction of thrust: up is [0, 0, -1]. Not zero; normalized when read. |
spin | cw or ccw | Seen from the side the thrust points to. A ccw rotor’s angular velocity points along axis. |
propeller | key | An entry in [propellers]. |
motor, esc | key | Entries in [motors] and [escs]. |
Each [propellers.<key>] entry:
| Field | Quantity | Rule |
|---|---|---|
diameter | length | Positive. |
pitch | length | Positive. |
blades | count | Unit 1; at least 1. |
max_thrust | force | Largest static thrust with its motor. Positive. |
mass | mass | Positive. |
inertia | moment of inertia | About the spin axis. Positive. |
data | text | Where its measured performance is, such as a UIUC propeller database entry. |
Two checks cover the whole airframe:
- Thrust-to-weight. The rotors’ summed
max_thrust, divided by the weight at standard gravity, must exceed 1. - Rotor disks. Two rotors whose hubs are at least the sum of their radii apart are clear.
Closer than that:
- Parallel rotors whose disk planes are more than 1 mm apart are stacked, as in a coaxial pair, and pass. In the same plane, their disks overlap, which is an error.
- Tilted rotors are an error, because this version cannot verify their clearance.
Motors, ESCs and the battery
A motor is described by its electrical constants, or by a time constant and a top speed for airframes where only those are published. The Motor and ESC page gives the models that use them; the battery’s arrives with #20.
- An electrical motor needs the inertia it turns: the motor’s
inertia, its propeller’s, or both. A rotor whose electrical motor has neither is refused. - Given both descriptions, the electrical one is used.
- A rotor without an ESC gets an ideal one: no latency, no slew limit, active braking, and
the motor’s own
max_current. - The current limit is the smaller of the motor’s and the ESC’s
max_current. - An ESC’s latency is rounded to the nearest whole physics step at the run’s rate, halves up.
| Table | Field | Quantity | Rule |
|---|---|---|---|
[motors.<key>] | kv | speed constant, such as rpm/V | kv, resistance and no_load_current together, or time_constant and max_speed together, or both. All positive. |
resistance | resistance | ||
no_load_current | current | ||
time_constant | time | ||
max_speed | angular rate, such as rpm | Speed at full duty: the time-constant tier’s speed follows the duty cycle times this. | |
max_current | current | Positive. | |
inertia | moment of inertia | Rotor, about the spin axis. Positive. | |
mass | mass | Positive. | |
[escs.<key>] | braking | active or none | What the motor does when the command drops. |
latency | time | Positive. | |
slew_rate | rate, 1/s | Fastest change, in full scale per second. Positive. | |
max_current | current | Positive. | |
[battery] | cells | count | Cells in series. |
capacity | charge, such as mAh | Positive. | |
internal_resistance | resistance | Of the whole pack. Positive. |
Drag, controller and visual hints
These tables are stored and their units checked. Body aerodynamics (#24), the flight controllers (#26, #27) and the renderer (M3) define how they are used.
| Table | Field | Quantity | Rule |
|---|---|---|---|
[drag] | area | area, vector | Drag coefficient times reference area along each body axis. Not negative. |
[controller] | kind | text | Which controller, such as cascaded-pid. Not empty. |
gains.<name> | any | Each gain in its own unit, such as N m s/rad or 1/s. | |
[visual] | body_size | length, vector | Positive. |
arm_width | length | Positive. | |
color | text | # and six hexadecimal digits. |
Warnings
A file with warnings still loads. mjk airframe prints each warning to standard error, and the
generated page lists them. A warning is given for:
- a number without a source;
- a source that no parameter cites;
- a propeller, motor or ESC that no rotor uses.
Error messages
Every error reads document: field: reason and names the exact field, using the same path
syntax as the file. A key that is not a bare TOML key is quoted, as in
propellers."10x4.5".diameter. These are real messages from the test fixtures in
crates/mjk-sim/tests/fixtures/airframe/:
example.toml: (document): invalid TOML: invalid basic string, expected `"` (line 4, column 26)
example.toml: schema_version: missing; documents start with `schema_version = 1`
example.toml: schema_version: this file uses schema version 2, but this build reads version 1; update MJKPhysics
example.toml: kind: expected "airframe" for this loader; found "scenario"
example.toml: mass.mas: unknown field `mas`, expected one of `mass`, `cg`, `inertia`, `components` (line 10, column 1)
example.toml: mass: missing `inertia`: give mass, cg and inertia, or [[mass.components]]
example.toml: mass.mass: missing `unit`: every number in an airframe file carries one, as in { value = 1.2, unit = "kg", source = "maker" } (line 10, column 8)
example.toml: mass.mass.unit: `m` is not a mass; use a unit such as kg or g
example.toml: mass.mass.unit: unknown unit `stone`
example.toml: mass.mass.source: no entry `manual` in [sources]
example.toml: mass.mass.value: invalid type: string "heavy", expected f64 (line 10, column 18)
example.toml: mass.inertia.value[2]: invalid length 2, expected an array of length 3 (line 17, column 3)
example.toml: mass.mass.value: must be a positive, finite mass in kilograms; found -1.5
example.toml: mass.cg.value[1]: must be finite; found NaN
example.toml: mass.inertia.value[0][1]: not symmetric: [0][1] = 0.001 but [1][0] = 0
example.toml: mass.inertia.value: principal moments violate the triangle inequality, so no rigid body has this inertia (½·tr(J)·I − J has a principal minor of -5.500e-3)
example.toml: rotors: thrust-to-weight is 0.666667: the rotors' 9.80665 N of maximum thrust cannot lift 14.71 N
example.toml: rotors[1]: its disk overlaps rotors[0]'s: their hubs are 0.21 m apart, less than the 0.254 m their radii add up to
And the warning for a number without a source:
warning: example.toml: mass.mass: no source
Versions and migration
schema_version is the format version of the document. A file newer than the build is refused
with a request to update MJKPhysics. A file older than the oldest supported version is refused
with a pointer to this section.
Version 1 is the only version so far, and no migrations exist yet. Until v0.1.0 (#85), version 1 may change as the formats grow, and files that no longer fit fail with a clear error.
- #18 used that latitude: it replaced the first slice’s bare SI fields, such as
mass_kg, with parameter tables carrying units and sources. - From v0.1.0 on, any change that breaks existing files bumps the version and adds a migration note here.
References
- P. M. Wensing, S. Kim, J.-J. E. Slotine, “Linear matrix inequalities for physically consistent inertial parameter identification: a statistical perspective on the mass distribution,” IEEE Robotics and Automation Letters, 2018.
Command-line tool
mjk runs the engine without a window. It writes the validation tables this book includes, flies
the reference scenario and writes its log, and replays a log to check it to the bit
(#17). Engine crates do no I/O, so mjk
reads and writes every file and turns engine errors into messages and exit codes.
Commands
| Command | What it does |
|---|---|
mjk validate [--out <dir>] | Runs every validation study and writes each table into <dir>, by default docs/src/validation, the book’s copy. Lists each table with pass or FAIL. |
mjk validate <study> | Prints one study’s table: integrators, determinism, atmosphere or analytic. |
mjk validate integrators --timing | Prints the wall-clock time per step of each integration method. These numbers depend on the machine. |
mjk run reference [--seed <n>] [--log <file.json>] [--csv <file.csv>] | Flies the reference scenario for 10 s and prints a summary. Writes the run log as JSON and the state log as CSV. |
mjk replay <file.json> | Flies a recorded run again with its recorded inputs and checks every sample and fingerprint. |
mjk airframe <file.toml> | Loads an airframe file and prints its page: every parameter with its unit, SI value, uncertainty and source (Configuration files). Warnings go to standard error. |
mjk random <seed> <name>... --bytes <n> | Writes named random streams for statistical test suites (Determinism). |
A file named - is standard input or standard output. When a log goes to standard output, the
summary moves to standard error. Scenario files, and with them mjk run <scenario.toml>, arrive
with #28.
Record the reference run, then replay it:
cargo run -p mjk-cli --release -- run reference --log run.json --csv run.csv
cargo run -p mjk-cli --release -- replay run.json
Regenerate the book’s validation tables from the repository root:
cargo run -p mjk-cli --release -- validate
Exit codes
| Code | Meaning |
|---|---|
| 0 | Done: every check passed, or the replay matched its record. |
| 1 | Done, but a validation check failed or the replay diverged. The table or report is still written. |
| 2 | The command line is wrong. The usage follows the message. |
| 3 | An input file is malformed, unsupported or physically implausible: an EngineError::Config. The message names the file and the field, for example run.json: inputs[2].tick. |
| 4 | The simulation failed: a numerical or convergence error, or a built-in scenario that could not run. |
| 5 | A file could not be read or written. |
Every error is one line on standard error, starting error:.
Run logs
A run log is one JSON document holding what it takes to fly the run again and check it:
| Field | Contents |
|---|---|
format_version | 1 |
scenario | "reference" |
seed | The master seed of every random stream |
physics_hz, ticks | The physics rate and the run’s length in steps: 1000 Hz and 10 000 |
sample_hz | Rows of the state log per second: 100 |
inputs | Each pilot command, in order: tick, rate_rad_s and thrust_n |
checkpoints | The state fingerprint once a second: tick and hash |
final_hash | The fingerprint after the last step |
channels | The state log, one entry per channel: name, unit and values |
The state log has 14 channels and 1001 rows, at tick 0 and every 10 ticks to the end:
| Channels | Unit | Quantity |
|---|---|---|
time | s | Simulation time |
north, east, down | m | Position, world axes (NED) |
velocity_north, velocity_east, velocity_down | m/s | Velocity, world axes |
attitude_w, attitude_x, attitude_y, attitude_z | 1 | Attitude quaternion, body to world |
roll_rate, pitch_rate, yaw_rate | rad/s | Body angular velocity |
Numbers read back exactly.
- How numbers are written: each one is the shortest decimal that reads back to the same double.
- How they are read:
mjkparses them exactly.serde_json’s default float parser is not exact, so a test checks 10⁵ random doubles; with the default parser, the first one that comes back wrong is-2.1513850520192137e121. - Non-finite samples: JSON has no NaN or infinity, so these are written as the strings
"NaN","inf"and"-inf". - Fingerprints: these are 16 hexadecimal digits, because many JSON readers lose integers above 2⁵³.
The CSV export has a header of name (unit) fields and one line per row. It uses the same
shortest decimals, with an exponent for very small and very large values, and NaN, inf and
-inf.
How a replay decides
- Refuse what it cannot fly. Each of these exits with code 3 and names the field:
- another format version, scenario, rate or length;
- other channels;
- inputs out of order;
- a fingerprint that is not 16 hexadecimal digits;
- a record with fewer checkpoints or samples than the run produces. That is a truncated file, not a divergence.
- Fly it again from the recorded seed, applying each recorded input on its tick.
- Compare everything: every sample bit for bit (NaN equals NaN), every checkpoint, and the final fingerprint.
- Report the earliest difference. If a sample and a fingerprint differ at the same tick, the sample is reported, because it names the quantity.
Changing one pilot command’s thrust by one part in 10⁹ at tick 500 is found at tick 510, the first sample after the change:
replay diverged at tick 510: north was 0.06303508229555076 and is 0.06303508229555473 on replay
Across platforms
CI’s Native and WebAssembly agree job records the reference run natively and as a
WebAssembly module (wasm32-wasip1 under Node), and requires the two logs to be identical byte
for byte. It then replays each log with the other build. A run recorded on one platform
reproduces on the other to the bit, as Determinism and replay promises.
The log writer
The state log is a ColumnLog in mjk_sim::log.
- Storage: it has a fixed list of channels, each with its own column, sized for the whole run when it is made.
- Logging a row allocates nothing. A test logs 10⁵ rows under a counting allocator and finds no allocation.
- A full log is an error, never a silent drop, as with checkpoints and recorded inputs.
- Writing happens off the step path. The log is written after the run, so writing never slows a step.
Limitations
- Logs live in memory until the run ends. The reference run’s log is 261 KB. Streaming long runs to disk, in MCAP with typed channels, is #79.
- One scenario.
runandreplayknow only the built-in reference scenario until scenario files arrive with #28, which also widens the log’s inputs beyond pilot commands. - A log does not record the build that wrote it. A build with different physics replays it and reports a divergence, as it should, but cannot say which build recorded the log.
Models
Each physical model gets one page that follows the model page template: equations with IDs, assumptions, validity range, parameters, implementation notes, validation and references.
Equation IDs use a prefix unique to their page. The registry below reserves prefixes for the planned pages so IDs never collide.
| Model | Equation prefix | Issue |
|---|---|---|
| Conventions and notation | CONV | #5, page |
| SO(3) maps | SO3 | #9, page |
| Analytic validation | VAL | #16, page |
| Determinism and replay | DET | #14, page |
| Rigid-body dynamics | RB | #10, page |
| Integrators, including the Lie-group method | INT | #11, #12, page |
| Atmosphere and gravity | ATM | #15, page |
| Brushless motor and ESC | MOT | #19, page |
| Battery | BAT | #20 |
| Blade element momentum theory | BEMT | #21 |
| Rotor in edgewise and oblique flow | ROTF | #22 |
| Rotor fidelity tiers | ROTT | #23 |
| Multirotor body aerodynamics and ground effect | BODY | #24 |
| Control allocation | ALLOC | #25 |
| Multirotor controllers | MRC | #26, #27 |
| Trajectories | TRAJ | #28 |
| Fixed-wing aerodynamics | FWA | #44 |
| Control-surface actuators | ACT | #45 |
| Fixed-wing propulsion | FWP | #46 |
| Trim | TRIM | #47 |
| Linearization and modes | LIN | #48 |
| Fixed-wing autopilot | FWC | #49 |
| Wind and turbulence | WIND | #53 |
| Collision detection | COL | #55 |
| Contact solver | CON | #57 |
| Joints and slung payloads | JNT | #59 |
| Inertial sensors | IMU | #72 |
| Other sensors | SNS | #73 |
A new model reserves its prefix here in the same pull request that adds its page.
Rigid-body dynamics
- Issue: #10
- Code:
mjk_dynamics::{RigidBodyState, StateDerivative, derivative, Wrench},mjk_dynamics::mass::{MassProperties, Component, Shape, composite} - Equation prefix:
RB
Summary
Every aircraft in the engine is one rigid body with six degrees of freedom. This page gives the state, the Newton–Euler equations that advance it, how loads are combined, and how mass properties are built from simple components. Integrators (#11, #12) step these equations in time. Frames, symbols and quaternion conventions follow the conventions page.
Assumptions
- The airframe is rigid: no flexing wings or arms, and rotors are modeled as forces and moments, not as separate bodies.
- Mass and inertia are constant during a flight. The aircraft are electric, so no fuel burns; a released or slung payload is a separate body (M5).
- The world frame is flat, non-rotating and inertial (see the conventions page). Neglecting the
Earth’s rotation, $
\Omega_E = 7.29\times10^{-5}$ rad/s, drops a Coriolis acceleration of at most $2\Omega_E v = 4.4\times10^{-3}$ m/s² at 30 m/s, under 0.05 % of gravity. - The body frame’s origin is the center of mass, so translation and rotation decouple.
State
| Symbol | Meaning | Unit | Code |
|---|---|---|---|
$\mathbf{p}^W$ | Position of the center of mass | m | position_m: Vec3<World> |
$\mathbf{v}^W$ | Velocity of the center of mass | m/s | velocity_m_s: Vec3<World> |
$\mathbf{q}_{WB}$ | Attitude, body to world | — | q_wb: Rotation<World, Body> |
$\boldsymbol\omega^B$ | Angular velocity, body axes | rad/s | omega_rad_s: Vec3<Body> |
Equations of motion
Translation, with $\mathbf{F}^W$ the total force including gravity:
\dot{\mathbf{p}}^W = \mathbf{v}^W, \qquad m\,\dot{\mathbf{v}}^W = \mathbf{F}^W
\qquad\text{(RB-1)}
Rotation (Euler’s equations), with $\mathbf{M}^B$ the total moment about the center of mass and
$\mathbf{J}$ the full inertia tensor, products of inertia included:
\mathbf{J}\,\dot{\boldsymbol\omega}^B = \mathbf{M}^B - \boldsymbol\omega^B \times \big(\mathbf{J}\,\boldsymbol\omega^B\big)
\qquad\text{(RB-2)}
The attitude follows the kinematics of (CONV-9), $\dot{\mathbf{q}}_{WB} = \tfrac12\,\mathbf{q}_{WB}\otimes(0,\ \boldsymbol\omega^B)$.
The derivative returns $\boldsymbol\omega^B$ itself as the attitude rate: it is the tangent of the
attitude on SO(3), from which an integrator either forms $\dot{\mathbf{q}}$ or steps on the group
with the exponential map (CONV-10).
Loads
Each model reports a wrench: a force and a moment about the center of mass. A force
$\mathbf{F}$ applied at a point $\mathbf{r}$ from the center of mass, such as a rotor’s thrust at
its hub, exerts the moment
\mathbf{M} = \mathbf{r} \times \mathbf{F}
\qquad\text{(RB-3)}
Points given from the airframe reference point are first measured from the center of mass:
$\mathbf{r} = \mathbf{r}_P - \mathbf{c}$. Wrenches add component by component. Body-axis forces
are rotated into world axes with $\mathbf{R}_{WB}$ (CONV-1) before (RB-1).
Mass properties from components
A body can be described by components: point masses, solid boxes and solid cylinders of uniform
density, each with a mass $m_i$, a center $\mathbf{r}_i$ from the reference point, and an
orientation $\mathbf{R}_i$ from its own part axes to body axes. The whole has
m = \sum_i m_i, \qquad \mathbf{c} = \frac{1}{m}\sum_i m_i\,\mathbf{r}_i
\qquad\text{(RB-4)}
and, by the parallel-axis theorem with offsets $\mathbf{d}_i = \mathbf{r}_i - \mathbf{c}$ from the
composite center of mass,
\mathbf{J} = \sum_i \Big[\mathbf{R}_i\,\mathbf{J}_i\,\mathbf{R}_i^\top + m_i\big(\lVert\mathbf{d}_i\rVert^2\,\mathbf{I} - \mathbf{d}_i\,\mathbf{d}_i^\top\big)\Big]
\qquad\text{(RB-5)}
The central inertia $\mathbf{J}_i$ of each shape, in its part axes, is zero for a point mass, and
for a box with edges $a, b, c$ along $x, y, z$ and a cylinder of radius $r$ and length $L$
along $z$:
\mathbf{J}_{\text{box}} = \frac{m}{12}\,\mathrm{diag}\big(b^2 + c^2,\ a^2 + c^2,\ a^2 + b^2\big)
\qquad\text{(RB-6)}
\mathbf{J}_{\text{cyl}} = \mathrm{diag}\Big(\frac{m\,(3r^2 + L^2)}{12},\ \frac{m\,(3r^2 + L^2)}{12},\ \frac{m\,r^2}{2}\Big)
\qquad\text{(RB-7)}
Energy and momentum
T = \tfrac12\,m\,\lVert\mathbf{v}^W\rVert^2 + \tfrac12\,\boldsymbol\omega^{B\top}\mathbf{J}\,\boldsymbol\omega^B,
\qquad
\mathbf{H}^W = \mathbf{R}_{WB}\,\mathbf{J}\,\boldsymbol\omega^B
\qquad\text{(RB-8)}
From (RB-1) and (RB-2), $\dot T = \mathbf{F}\cdot\mathbf{v} + \mathbf{M}\cdot\boldsymbol\omega$: the
gyroscopic term $\boldsymbol\omega \times \mathbf{J}\boldsymbol\omega$ is perpendicular to
$\boldsymbol\omega$ and does no work. Without a moment, $\mathbf{H}^W$ is constant. Both
identities are tested, and later used to measure integrator drift.
Validity range
The equations are exact for a rigid body under the assumptions above. Inputs are checked when mass properties are built:
- the mass must be positive and finite, and the center of mass finite;
- the tensor must be finite, symmetric to a relative $
10^{-9}$, positive definite, and satisfy the triangle inequality on its principal moments, $J_1 \le J_2 + J_3$ and cyclically; otherwise no mass distribution has it (Wensing, Kim & Slotine 2018); - components need a positive mass, finite position and non-negative dimensions. A flat plate of zero thickness is accepted; point masses on one line are not, since their inertia is singular.
Configuration files report any violation as an EngineError::Config naming the field, for
example mass.inertia.value.
Parameters
| Symbol | Meaning | Unit | Source |
|---|---|---|---|
$m$ | Mass | kg | Airframe file |
$\mathbf{c}$ | Center of mass from the airframe reference point, body axes | m | Airframe file, or (RB-4) |
$\mathbf{J}$ | Inertia tensor about the center of mass, body axes | kg·m² | Airframe file, or (RB-5) |
Each airframe’s values and their sources are on its airframe page.
Implementation notes
- No inversion per step. $
\mathbf{J}^{-1}$ is computed once, whenMassPropertiesis built, soderivativeis a few matrix-vector products. It allocates nothing. - Symmetric storage. The stored tensor is $
\tfrac12(\mathbf{J} + \mathbf{J}^\top)$, so rounding-level asymmetry in published values cannot make (RB-2) non-conservative. - Composites about the center of mass. (RB-5) is accumulated about the composite center of mass from each component’s offset to it. Accumulating about the reference point and shifting afterward would subtract two large terms when offsets are much larger than the components, as for a thin battery far from the center.
- Part axes. Component orientations are typed
Rotation<Body, Part>, so a component’s inertia cannot be added to body-axis quantities before it is rotated. - Code comments cite (RB-1) to (RB-7) at the lines that implement them.
Validation
| Check | Tolerance | Test |
|---|---|---|
| A box plus a point mass against a tensor computed by hand, products of inertia included | $10^{-14}$ relative | two_component_body_matches_the_hand_computed_tensor |
| Box and cylinder against (RB-6) and (RB-7) | $10^{-15}$ relative | box_and_cylinder_match_their_formulas |
| Cutting any box or cylinder in half leaves mass, center of mass and inertia unchanged | $10^{-12}$ relative | cutting_a_component_in_half_changes_nothing (512 random cases) |
Rotating every component rotates the composite: $\mathbf{c}' = \mathbf{Q}\mathbf{c}$, $\mathbf{J}' = \mathbf{Q}\mathbf{J}\mathbf{Q}^\top$ | $10^{-12}$ relative | turning_every_component_turns_the_whole (512) |
| Euler’s equations in principal axes, against their closed form | $10^{-12}$ | euler_equations_in_principal_axes |
Power balance $\dot T = \mathbf{F}\cdot\mathbf{v} + \mathbf{M}\cdot\boldsymbol\omega$ for any state, inertia and loads | $10^{-12}$ relative | power_balance (512) |
Torque-free motion conserves $\mathbf{H}^W$ | $10^{-12}$ relative | torque_free_motion_conserves_angular_momentum (512) |
Non-physical inertia in a configuration file is an EngineError::Config naming the field | exact | every_malformed_sample_names_the_exact_field |
Limitations. These checks test the derivative at one instant. Behavior over time, such as the torque-free precession and the intermediate-axis flip, is validated with the integrators in #16.
References
- R. W. Beard and T. W. McLain, Small Unmanned Aircraft: Theory and Practice, Princeton University Press, 2012, chapter 3.
- B. L. Stevens, F. L. Lewis and E. N. Johnson, Aircraft Control and Simulation, 3rd ed., Wiley, 2016, chapter 1.
- H. Goldstein, C. Poole and J. Safko, Classical Mechanics, 3rd ed., Addison-Wesley, 2002, chapters 4 and 5.
- P. M. Wensing, S. Kim and J.-J. E. Slotine, “Linear matrix inequalities for physically consistent inertial parameter identification: a statistical perspective on the mass distribution,” IEEE Robotics and Automation Letters 3(1), 2018.
Integrators
- Issues: #11, #12 (the Lie-group method and the study)
- Code:
mjk_dynamics::{Integrator, ExplicitEuler, SemiImplicitEuler, Rk4, Rkmk4},mjk_dynamics::{System, LieSystem, Coordinates},mjk_dynamics::{RigidBodySystem, RigidBodyCoordinates, RigidBodyTangent, LoadModel, Loads},mjk_sim::validation::integrators - Equation prefix:
INT - Decision record: ADR 0002
Summary
The engine advances in fixed steps (ADR 0002). An integrator
takes a system of ordinary differential equations $\dot{\mathbf{y}} = \mathbf{f}(t, \mathbf{y})$
and returns $\mathbf{y}$ one step $h$ later. Four methods are provided: explicit Euler and
semi-implicit Euler as references; the classical fourth-order Runge–Kutta method (RK4), which
integrates the quaternion’s components and renormalizes; and the Runge–Kutta–Munthe-Kaas method
(RKMK4), which steps the attitude on the rotation group itself. A study at the end of the page
measures what the group method buys. The rigid body is the first system; motor and battery states
join it later without changing the integrators.
Assumptions
- The step $
h$ is fixed for a run, and loads are pure functions of time and state during a step: inputs such as controller commands change only between steps. - The coordinates form a vector space, so stages can be added and scaled. The attitude is integrated as four quaternion components, which is a vector space; the unit-norm constraint is restored after each step (INT-4).
- The position-like part of the rate (positions and attitude) depends only on the coordinates: it is kinematics. Semi-implicit Euler relies on this.
Methods
Explicit (forward) Euler evaluates the rate once, at the start of the step:
\mathbf{y}_{n+1} = \mathbf{y}_n + h\,\mathbf{f}(t_n, \mathbf{y}_n)
\qquad\text{(INT-1)}
Semi-implicit (symplectic) Euler splits the coordinates into position-like parts $\mathbf{x}$
and velocity-like parts $\mathbf{u}$. It updates the velocities first, then the positions from
the new velocities:
\mathbf{u}_{n+1} = \mathbf{u}_n + h\,\mathbf{a}(t_n, \mathbf{x}_n, \mathbf{u}_n),
\qquad
\mathbf{x}_{n+1} = \mathbf{x}_n + h\,\mathbf{g}(\mathbf{x}_n, \mathbf{u}_{n+1})
\qquad\text{(INT-2)}
Both are first order. Explicit Euler adds energy to an undamped oscillator every step; semi-implicit Euler keeps the energy error bounded, because it exactly conserves a nearby modified energy (Hairer, Lubich & Wanner 2006).
The classical RK4 method evaluates the rate four times per step:
\begin{aligned}
\mathbf{k}_1 &= \mathbf{f}(t_n, \mathbf{y}_n), &
\mathbf{k}_2 &= \mathbf{f}\big(t_n + \tfrac h2,\ \mathbf{y}_n + \tfrac h2\,\mathbf{k}_1\big), \\
\mathbf{k}_3 &= \mathbf{f}\big(t_n + \tfrac h2,\ \mathbf{y}_n + \tfrac h2\,\mathbf{k}_2\big), &
\mathbf{k}_4 &= \mathbf{f}\big(t_n + h,\ \mathbf{y}_n + h\,\mathbf{k}_3\big), \\
\mathbf{y}_{n+1} &= \mathbf{y}_n + \tfrac h6\,\big(\mathbf{k}_1 + 2\mathbf{k}_2 + 2\mathbf{k}_3 + \mathbf{k}_4\big)
\end{aligned}
\qquad\text{(INT-3)}
Its global error is $O(h^4)$. For a rate that depends on time only, it reduces to Simpson’s rule
and integrates cubics exactly.
Attitude
The attitude is integrated as the raw quaternion components $\mathbf{q}$, with the kinematics of
(CONV-9), and normalized once at the end of each step:
\dot{\mathbf{q}} = \tfrac12\,\mathbf{q}\otimes\begin{bmatrix} 0 \\ \boldsymbol\omega^B \end{bmatrix},
\qquad
\mathbf{q}_{n+1} \leftarrow \frac{\mathbf{q}_{n+1}}{\lVert\mathbf{q}_{n+1}\rVert}
\qquad\text{(INT-4)}
Two details keep RK4 at fourth order:
- No normalization between stages. A stage such as $
\mathbf{q}_n + \tfrac h2\mathbf{k}_1$ lies slightly off the unit sphere, by $O(h^2)$. Normalizing it would scale the next stage’s rate by $1 - O(h^2)$ along the direction of rotation, an $O(h^3)$ error per step, and the method would drop to second order. The final normalization is a projection onto the exact solution’s manifold and does not lower the order. - The physics sees the normalized attitude. Loads and the Newton–Euler equations receive
$
\mathbf{q}/\lVert\mathbf{q}\rVert$, since rotating a vector with a non-unit quaternion would scale it by $\lVert\mathbf{q}\rVert^2$. The kinematics (INT-4) uses the raw $\mathbf{q}$, which keeps the whole right-hand side a smooth function of the coordinates.
Renormalizing is the baseline against which the Lie-group method below, which stays on SO(3) by construction, is compared.
Lie-group method (RKMK4)
Near the attitude $\mathbf{q}_0$ at the start of a step, write the attitude as a rotation
$\boldsymbol\theta$ applied on the right, as in (CONV-10). Differentiating
$\mathbf{q}_0\otimes\mathrm{Exp}(\boldsymbol\theta)$ gives
$\boldsymbol\omega = \mathbf{J}_r(\boldsymbol\theta)\,\dot{\boldsymbol\theta}$ (SO3-4), so in
this chart the attitude obeys an ordinary differential equation in a vector space:
\mathbf{q}(t) = \mathbf{q}_0 \otimes \mathrm{Exp}\big(\boldsymbol\theta(t)\big),
\qquad
\dot{\boldsymbol\theta} = \mathbf{J}_r^{-1}(\boldsymbol\theta)\,\boldsymbol\omega^B,
\qquad \boldsymbol\theta(0) = \mathbf{0}
\qquad\text{(INT-6)}
with $\mathbf{J}_r^{-1}$ from (SO3-5). RKMK4 applies classical RK4 to $\boldsymbol\theta$ and,
in the same stages, to position, velocity and angular velocity, then maps back with the
exponential:
\begin{aligned}
\mathbf{k}_i &= \mathbf{J}_r^{-1}(\boldsymbol\theta_i)\,\boldsymbol\omega\big(\mathbf{q}_0\otimes\mathrm{Exp}(\boldsymbol\theta_i)\big),
\quad \boldsymbol\theta_1 = \mathbf{0},\ \boldsymbol\theta_2 = \tfrac h2\mathbf{k}_1,\ \boldsymbol\theta_3 = \tfrac h2\mathbf{k}_2,\ \boldsymbol\theta_4 = h\,\mathbf{k}_3, \\
\mathbf{q}_{n+1} &= \mathbf{q}_n \otimes \mathrm{Exp}\Big(\tfrac h6\,\big(\mathbf{k}_1 + 2\mathbf{k}_2 + 2\mathbf{k}_3 + \mathbf{k}_4\big)\Big)
\end{aligned}
\qquad\text{(INT-7)}
The new attitude is a product of unit quaternions, so in exact arithmetic it is a unit quaternion; in floating point its norm only wanders by rounding, and nothing is renormalized. Two closed-form cases check the implementation:
\boldsymbol\omega \parallel \text{a principal axis}
\;\Rightarrow\;
\boldsymbol\theta_i \parallel \boldsymbol\omega,\ \
\mathbf{J}_r^{-1}(\boldsymbol\theta_i)\,\boldsymbol\omega = \boldsymbol\omega
\;\Rightarrow\;
\mathbf{q}_{n+1} = \mathbf{q}_n\otimes\mathrm{Exp}(h\,\boldsymbol\omega)\ \text{exactly}
\qquad\text{(INT-8)}
RKMK4 therefore reproduces steady spin about a principal axis to rounding, where RK4 on the
quaternion components has an $O(h^4)$ phase error; and with no rotation it reduces to RK4, so it
is exact for constant acceleration.
Study: RK4 with renormalization against RKMK4
A torque-free body with an X500-class inertia tensor, products of inertia included,
$\mathbf{J} = [0.021, 0.0004, -0.0006;\ 0.0004, 0.024, 0.0002;\ -0.0006, 0.0002, 0.040]$ kg·m²,
spins at $\boldsymbol\omega_0 = (0.2, 6.0, 0.3)$ rad/s, almost about its intermediate axis, so it
tumbles and every component of $\boldsymbol\omega$ changes sign. Each method runs for 100 s at
three step sizes. With no moment, kinetic energy and the angular-momentum vector in world axes
are conserved exactly, so any change is integration error. The table gives the largest relative
change over the run and the largest deviation of $\lVert\mathbf{q}\rVert$ from 1. RK4 is also run
without renormalization to show what renormalization corrects.
| Method | h (s) | Steps | Energy drift | Angular-momentum drift | Unit-norm error | Rate evaluations per step | Exp maps per step | J_r⁻¹ per step |
|---|---|---|---|---|---|---|---|---|
| RK4, not renormalized | 0.001 | 100000 | 7.3e-14 | 1.5e-12 | 7.3e-13 | 4 | 0 | 0 |
| RK4, renormalized | 0.001 | 100000 | 7.3e-14 | 1.5e-12 | 2.2e-16 | 4 | 0 | 0 |
| RKMK4 | 0.001 | 100000 | 7.3e-14 | 1.4e-12 | 1.1e-14 | 4 | 5 | 4 |
| RK4, not renormalized | 0.01 | 10000 | 7.8e-10 | 1.5e-8 | 5.5e-8 | 4 | 0 | 0 |
| RK4, renormalized | 0.01 | 10000 | 7.8e-10 | 1.5e-8 | 2.2e-16 | 4 | 0 | 0 |
| RKMK4 | 0.01 | 10000 | 7.8e-10 | 1.4e-8 | 5.6e-15 | 4 | 5 | 4 |
| RK4, not renormalized | 0.05 | 2000 | 1.8e-6 | 9.4e-6 | 1.7e-4 | 4 | 0 | 0 |
| RK4, renormalized | 0.05 | 2000 | 1.8e-6 | 9.4e-6 | 3.3e-16 | 4 | 0 | 0 |
| RKMK4 | 0.05 | 2000 | 1.8e-6 | 8.9e-6 | 2.7e-15 | 4 | 5 | 4 |
Generated by mjk validate integrators; a test fails if this table no longer matches the code.
What the study shows:
- The norm. RKMK4 holds $
\lVert\mathbf{q}\rVert$ to $10^{-14}$ with no renormalization: rounding only. RK4 without renormalization drifts off the sphere by up to $1.7\times10^{-4}$ at $h = 0.05$ s; renormalizing removes that, as intended. - Energy. Identical for both methods. Kinetic energy depends only on $
\boldsymbol\omega$, whose equation lives in a vector space where RKMK4 is RK4. - Angular momentum. RKMK4 is slightly better, by about 5 % at the larger steps
($
8.9\times10^{-6}$ against $9.4\times10^{-6}$ at $h = 0.05$ s): its attitude error is smaller. - Cost. RKMK4 needs four more exponential maps and four inverse Jacobians per step. Measured
with
cargo run --release -p mjk-cli -- validate integrators --timingon a shared 2.1 GHz Xeon virtual machine, RK4 took 220 to 320 ns per step and RKMK4 590 to 860 ns, 2.1 to 2.8 times as long.
At the default 1 kHz step both methods conserve energy and momentum to $10^{-12}$, far below any
modeling error, so the choice is about invariants and cost, not accuracy. RKMK4 is the method that
keeps the attitude a rotation by construction; RK4 with renormalization is cheaper and, for this
problem, as accurate.
Measuring the order
The order $p$ of a method is the slope of the error against the step size on logarithmic axes:
e(h) \approx C\,h^{p}
\quad\Longrightarrow\quad
\ln e = \ln C + p\,\ln h
\qquad\text{(INT-5)}
The tests fit $p$ by least squares over a geometric sequence of steps, small enough to be in the
asymptotic range and large enough that rounding does not dominate.
Validity range
All three methods are explicit, so the step must resolve the fastest dynamics: for RK4, stability
on an oscillator requires $h\,\omega < 2.8$, and accuracy needs much less. The default 1 kHz rate
resolves motor time constants of tens of milliseconds and every body mode with a wide margin
(ADR 0002). Stiff contact is handled after the step by the impulse solver, not by the integrator.
Implementation notes
- One trait, static dispatch.
Integrator::stepis generic over theSystem, so the compiler specializes each combination; no trait objects (Power of Ten rule 9) and no allocation. - Choosing a method at run time.
IntegratorKindnames each method (explicit-euler,semi-implicit-euler,rk4,rkmk4) for scenario files and dispatches with amatch, so a method chosen from a file still needs no trait object. It steps exactly like the method it names, to the bit. - Coordinates hold their own rates. The same type is used for $
\mathbf{y}$ and $\dot{\mathbf{y}}$. Its fields are named for the quantity (position,velocity,attitude,angular_velocity) without units, because the units differ between the two uses. - Semi-implicit Euler evaluates the rate twice: once for the velocities, then at the updated velocities for the positions.
- A degenerate attitude (a zero or non-finite quaternion) makes every rate NaN, so the failure shows in the state instead of being hidden by a fallback.
Validation
| Check | Result | Test |
|---|---|---|
Constant acceleration: each method against its own closed form (explicit Euler $h^2 a\,n(n-1)/2$, semi-implicit $h^2 a\,n(n+1)/2$, RK4 exact) | agree to $10^{-14}$ | each_method_has_its_own_closed_form_under_constant_acceleration |
| RK4 integrates a cubic rate exactly; Euler gives the Riemann sum | agree to $10^{-15}$ | rk4_integrates_a_cubic_rate_exactly |
Order on an oscillator, $x'' = -x$ to $t = 10$ s, $h = 0.1$ to $0.00625$ s | explicit 1.08, semi-implicit 1.07, RK4 3.99 | measured_order_on_an_oscillator |
Order on a tumbling asymmetric body with products of inertia, to $t = 2$ s, against RK4 at $h = 1/3200$ s | explicit 1.01, semi-implicit 1.00, RK4 4.00 | measured_order_on_a_tumbling_body |
Semi-implicit Euler energy over $10^6$ steps of $h = 0.01$ s (about 1600 periods) | bounded: at most 0.50 % | semi_implicit_euler_keeps_oscillator_energy_bounded |
Explicit Euler energy, which grows by exactly $1 + h^2$ per step | matches $(1 + h^2)^{n}$ to $10^{-8}$ | explicit_euler_gains_energy_on_an_oscillator |
| Unit attitude after 1000 steps of each method | $\lvert\lVert\mathbf{q}\rVert - 1\rvert < 10^{-15}$ | the_attitude_stays_a_unit_quaternion |
| RKMK4: exact under constant acceleration, like RK4 | agree to $10^{-14}$ | each_method_has_its_own_closed_form_under_constant_acceleration |
| RKMK4: steady spin about a principal axis (INT-8) | RKMK4 error below $10^{-13}$ rad; RK4 above $10^{-9}$ rad | rkmk4_is_exact_for_steady_spin_about_a_principal_axis |
| RKMK4: measured order on the oscillator and on the tumbling body | within $\pm 0.2$ of 4 | measured_order_on_an_oscillator, measured_order_on_a_tumbling_body |
RKMK4: unit norm over $10^5$ steps with no renormalization | $\lvert\lVert\mathbf{q}\rVert - 1\rvert < 10^{-12}$ | rkmk4_keeps_a_unit_quaternion_without_renormalizing |
| A method chosen at run time steps like the method itself; names round-trip | bit-identical after 50 steps, for all four | a_method_chosen_at_run_time_steps_exactly_like_the_method_itself |
| The published study table matches the code | identical | the_published_table_matches_the_code, validate_is_byte_identical_and_matches_the_book |
The acceptance tolerance for every measured order is $\pm 0.2$.
References
- H. Munthe-Kaas, “Runge–Kutta methods on Lie groups,” BIT Numerical Mathematics 38, 1998.
- A. Iserles, H. Z. Munthe-Kaas, S. P. Nørsett and A. Zanna, “Lie-group methods,” Acta Numerica 9, 2000.
- P. E. Crouch and R. Grossman, “Numerical integration of ordinary differential equations on manifolds,” Journal of Nonlinear Science 3, 1993.
- E. Hairer, C. Lubich and G. Wanner, Geometric Numerical Integration, 2nd ed., Springer, 2006, chapters I and VI.
- E. Hairer, S. P. Nørsett and G. Wanner, Solving Ordinary Differential Equations I: Nonstiff Problems, 2nd ed., Springer, 1993, section II.1.
- J. Solà, “Quaternion kinematics for the error-state Kalman filter,” arXiv:1711.02508, 2017.
Atmosphere and gravity
- Issue: #15
- Code:
mjk_env::{Atmosphere, Air, Gravity, NormalGravity, Environment},mjk_env::atmosphere,mjk_env::gravity::wgs84,mjk_env::reference,mjk_sim::validation::atmosphere - Equation prefix:
ATM
Summary
The air and gravity around the vehicle:
- Air: temperature, pressure, density, speed of sound and dynamic viscosity from the U.S. Standard Atmosphere, 1976, from −5 km to 20 km. Viscosity gives the Reynolds numbers the rotor models need.
- Temperature offset: shifts the whole profile for a hot or cold day (“ISA + 15”) while keeping the air in hydrostatic balance.
- Gravity: constant standard gravity, or WGS-84 normal gravity, which varies with latitude and altitude.
- Field elevation: places the world origin above mean sea level, so a position’s Down coordinate gives its altitude.
Every quantity matches the standard’s printed tables to four significant figures, and the
gravity model matches the exact field of the WGS-84 ellipsoid to $1.5\times10^{-6}$ m/s².
Assumptions
- One altitude for both models. Altitude is geometric height above mean sea level. Gravity
uses it as height above the WGS-84 ellipsoid: the two differ by the geoid height, at most
about 100 m, which changes gravity by about $
3\times10^{-5}$ of its value. - Air is a still, dry ideal gas of constant composition below 20 km, as the standard defines it. Humidity and weather are not modeled; wind arrives with #53.
- A temperature offset shifts every layer equally. Sea-level pressure stays 101 325 Pa, and pressure follows from hydrostatic balance with the warmer or colder air.
- Gravity points along $
+\mathbf{z}_W$, on the flat earth of the conventions: its direction changes by only 0.09° over 10 km.
Equations
Altitude comes from the field elevation $h_0$ and the Down coordinate $p_D$:
h = h_0 - p_D
\qquad\text{(ATM-1)}
The standard works in geopotential altitude $H$: the height in a uniform field of
$g_0 = 9.80665$ m/s² with the same potential energy. With its earth radius
$r_0 = 6\,356\,766$ m,
H = \frac{r_0\,h}{r_0 + h}
\qquad\text{(ATM-2)}
Below 20 km there are two layers: the troposphere, cooling at $L = -6.5$ K/km to the
tropopause at $H_{11} = 11$ km, and an isothermal layer above it. With a temperature offset
$\Delta T$ and sea-level temperature $T_0 = 288.15$ K,
T(H) = \begin{cases} T_0 + \Delta T + L\,H & H \le H_{11} \\ T_0 + \Delta T + L\,H_{11} & H > H_{11} \end{cases}
\qquad\text{(ATM-3)}
Hydrostatic balance, $dP = -\rho\,g_0\,dH$, with the gas law gives pressure in closed form,
starting from $P_0 = 101\,325$ Pa:
P = P_0 \left(\frac{T}{T_0 + \Delta T}\right)^{-g_0 M_0 / (R^* L)}, \quad H \le H_{11}
\qquad\text{(ATM-4)}
P = P_{11} \exp\!\left(-\frac{g_0 M_0 (H - H_{11})}{R^*\,T_{11}}\right), \quad H > H_{11}
\qquad\text{(ATM-5)}
where $T_{11}$ and $P_{11}$ are the values at the tropopause, $M_0 = 0.0289644$ kg/mol is
the mean molar mass of air, and $R^* = 8.31432$ J/(mol·K) is the gas constant as the 1976
standard defines it. The other quantities follow from $T$ and $P$:
\rho = \frac{P\,M_0}{R^*\,T}
\qquad\text{(ATM-6)}
a = \sqrt{\frac{\gamma\,R^*\,T}{M_0}}, \quad \gamma = 1.4
\qquad\text{(ATM-7)}
\mu = \frac{\beta\,T^{3/2}}{T + S}, \quad \beta = 1.458\times10^{-6}\ \text{kg/(m·s·K}^{1/2}),\ S = 110.4\ \text{K}
\qquad\text{(ATM-8)}
WGS-84 normal gravity at geodetic latitude $\varphi$ follows Somigliana’s closed form on the
ellipsoid,
\gamma(\varphi) = \gamma_e\,\frac{1 + k\sin^2\varphi}{\sqrt{1 - e^2\sin^2\varphi}}
\qquad\text{(ATM-9)}
and its second-order expansion in height above it, as NGA.STND.0036 gives them (eqs. 4-1 and 4-3),
\gamma_h = \gamma(\varphi)\left[1 - \frac{2}{a}\left(1 + f + m - 2f\sin^2\varphi\right)h + \frac{3h^2}{a^2}\right]
\qquad\text{(ATM-10)}
with semi-major axis $a$, flattening $f$, $m = \omega^2 a^2 b / GM$, equatorial gravity
$\gamma_e$, eccentricity $e$ and $k = b\gamma_p / (a\gamma_e) - 1$.
Validity range
| Range | Outside it | |
|---|---|---|
| Altitude | −5 km to 20 km geometric. 20 km lies inside the isothermal layer, which ends at 20 km geopotential (20 063 m geometric) | AltitudeOutOfRange: the model never extrapolates or clamps |
| Temperature offset | Any finite value that keeps the coldest layer above 0 K | InvalidTemperatureOffset |
| Latitude | ±90° | LatitudeOutOfRange |
| Normal gravity | −5 km to 20 km: the expansion’s error grows with height, to $1.5\times10^{-6}$ m/s² at 20 km | Usable higher, with a larger truncation error |
A non-finite input is an error, never a NaN in the results. A run that leaves the range finds out when a model asks for the air there; the world step has no error path yet, so the models that use the atmosphere (M2) will decide how such a run fails.
Parameters
| Symbol | Meaning | Unit | Value | Source |
|---|---|---|---|---|
$g_0$ | Standard gravity | m/s² | 9.80665 | USSA-1976 |
$R^*$ | Gas constant (1976 value, not CODATA’s 8.314 462 618) | J/(mol·K) | 8.31432 | USSA-1976 |
$M_0$ | Mean molar mass of air | kg/mol | 0.0289644 | USSA-1976 |
$r_0$ | Earth radius for geopotential altitude | m | 6 356 766 | USSA-1976 |
$a$, $1/f$ | WGS-84 semi-major axis, inverse flattening | m, — | 6 378 137, 298.257223563 | NGA.STND.0036 Table 3.1 |
$GM$, $\omega$ | Earth’s gravitational constant, angular velocity | m³/s², rad/s | $3.986004418\times10^{14}$, $7.292115\times10^{-5}$ | NGA.STND.0036 Table 3.1 |
$\gamma_e$, $\gamma_p$ | Normal gravity at the equator and the poles | m/s² | 9.780325335904, 9.832184937863 | Derived, below |
$k$, $e^2$, $m$ | Somigliana’s constant, eccentricity squared, gravity ratio | — | 0.001931852652458, 0.006694379990141, 0.003449786506841 | Derived, below |
The four WGS-84 defining parameters are those of NGA.STND.0036, Table 3.1. The derived constants are computed from them with the closed formulas of the level ellipsoid (Heiskanen and Moritz, 1967) at 40 significant digits, and agree with the standard’s printed values to the last digit:
| Constant | NGA.STND.0036 | Derived here |
|---|---|---|
$f$ (Table 3.5) | $3.3528106647475\times10^{-3}$ | $3.3528106647474805\times10^{-3}$ |
$b$ (Table 3.5) | 6 356 752.3142 m | 6 356 752.314245 m |
$e^2$ (Table 3.5) | $6.694379990141\times10^{-3}$ | $6.694379990141317\times10^{-3}$ |
$\gamma_e$ (Table 3.6) | 9.7803253359 m/s² | 9.78032533590389 m/s² |
$\gamma_p$ (Table 3.6) | 9.8321849379 m/s² | 9.83218493786340 m/s² |
$k$ (Table 3.6) | $1.931852652458\times10^{-3}$ | $1.931852652458274\times10^{-3}$ |
$m$ (Table 3.6) | $3.449786506841\times10^{-3}$ | $3.449786506840845\times10^{-3}$ |
Precision matters in the last digits. Computing $q_0$ directly in double precision loses about
$3\times10^{-13}$ of its value to cancellation, which gives $k = 1.93185265241\times10^{-3}$:
44 units off in the standard’s last printed digit. That value is quoted in some secondary
sources. The code stores the 40-digit constants, which match the standard, and a test fails if a
double-precision recomputation replaces them. The difference is about $10^{-10}$ m/s² in
gravity, so nothing physical depends on it; what depends on it is whether the constants can be
traced to the standard.
Implementation notes
- Closed forms, no tables. Each quantity is a handful of operations, with
libmfor the power, exponential and sine, so results are identical on every platform. Nothing allocates. - The tropopause pressure is computed once, when the atmosphere is built.
- Reference data from the standard’s tables lives in
mjk_env::reference, with the document’s page numbers, so the tests and the study compare against the same printed values.
Validation
How well the model agrees with the published tables, generated by mjk validate atmosphere:
| Z (m) | Source | T (K) | P (Pa) | ρ (kg/m³) | a (m/s) | μ (µPa·s) | Gap |
|---|---|---|---|---|---|---|---|
| 0 | Model | 288.150 | 101325 | 1.22500 | 340.294 | 17.8938 | 0.04 |
| 1976 | 288.150 | 101325 | 1.2250 | 340.29 | 17.894 | ||
| 1000 | Model | 281.651 | 89876.3 | 1.11166 | 336.435 | 17.5785 | 0.05 |
| 1976 | 281.651 | 89876 | 1.1117 | 336.43 | 17.579 | ||
| 2000 | Model | 275.154 | 79501.4 | 1.00655 | 332.532 | 17.2598 | 0.05 |
| 1976 | 275.154 | 79501 | 1.0066 | 332.53 | 17.260 | ||
| 5000 | Model | 255.676 | 54048.3 | 0.736428 | 320.546 | 16.2825 | 0.05 |
| 1976 | 255.676 | 54048 | 0.73643 | 320.55 | 16.282 | ||
| 11000 | Model | 216.774 | 22700.0 | 0.364802 | 295.154 | 14.2229 | 0.10 |
| 1976 | 216.774 | 22699 | 0.36480 | 295.15 | 14.223 | ||
| 20000 | Model | 216.650 | 5529.31 | 0.0889099 | 295.070 | 14.2161 | 0.01 |
| 1976 | 216.650 | 5529.3 | 0.088910 | 295.07 | 14.216 |
Each altitude has two rows: the model, then the 1976 table as printed. Gap is the largest difference at that altitude, in units of the table value’s fourth significant figure: four-figure agreement means at most 0.5. A test fails if this table no longer matches the code, and CI requires the WebAssembly build to print it byte for byte.
| Check | Criterion | Test |
|---|---|---|
| The 1976 tables at 0, 1, 2, 5, 11 and 20 km: T, P, ρ, a, μ | within half a unit of the fourth significant figure; in fact within $5\times10^{-5}$ relative | matches_the_1976_tables_to_four_significant_figures |
| Geopotential altitude against the tables’ H column | within 0.5 m | geopotential_altitude_matches_the_tables |
| Continuity at the tropopause | T and P continuous to $10^{-9}$ | temperature_and_pressure_are_continuous_at_the_tropopause |
Hydrostatic balance, $dP/dh = -\rho\,g_0\,(r_0/(r_0+h))^2$, with ΔT = 0, +15 and −20 K | within $10^{-6}$ relative | the_air_is_in_hydrostatic_balance_with_and_without_an_offset |
| A +15 K offset | T up 15 K everywhere; sea-level pressure unchanged; pressure higher at every altitude above sea level | an_offset_shifts_temperature_and_keeps_sea_level_pressure |
| The model’s range and invalid inputs | errors at −5 km − 1 mm and 20 km + 1 mm, and for non-finite values | the_model_covers_exactly_its_range, an_offset_that_is_not_physical_is_rejected |
| WGS-84 derived constants | recomputed from a, f, GM, ω | the_derived_constants_follow_from_the_defining_parameters |
| WGS-84 derived constants against NGA.STND.0036, Tables 3.5 and 3.6 | f, b, e², γe, γp, k and m within half a unit of the last printed digit; a double-precision derivation of k would miss by 44 units | the_derived_constants_agree_with_the_standard_to_the_last_printed_digit, a_double_precision_derivation_would_miss_the_published_k |
| Normal gravity against the exact field of the level ellipsoid, at 0°, 45° and 90° from −5 to 20 km | within $1.5\times10^{-6}$ m/s²; on the ellipsoid within $10^{-9}$ | normal_gravity_matches_the_exact_field_from_minus_5_to_20_km |
| Altitude from the field elevation, and air and gravity there | equal to evaluating the models directly | the_environment_measures_altitude_from_the_field |
A warm day does not simply thin the air. With ΔT = +15 K the air near the ground is thinner: 4 % less dense than standard at 2 km. But a warm column holds more air aloft, so pressure is higher at every altitude, and above about 9 km the air is denser than standard: 12 % at 20 km. A model that kept the standard pressure at each altitude and only raised the temperature would get the sign of that effect wrong up high.
References
- NOAA, NASA, USAF, U.S. Standard Atmosphere, 1976, NOAA-S/T 76-1562, 1976. NASA scan: NTRS 19770009539. Table I, pp. 53–61; Table III, pp. 101–109.
- NGA, Department of Defense World Geodetic System 1984: Its Definition and Relationships with Local Geodetic Systems, NGA.STND.0036_1.0.0_WGS84, version 1.0.0, 2014-07-08: Table 3.1 (p. 3-4), Table 3.5 (p. 3-9), Table 3.6 (p. 3-10), eqs. (4-1) and (4-3) (pp. 4-1, 4-3).
- NIMA, Department of Defense World Geodetic System 1984: Its Definition and Relationships with Local Geodetic Systems, TR8350.2, 3rd ed., Amendment 1, 2000: the standard’s predecessor.
- W. A. Heiskanen, H. Moritz, Physical Geodesy, W. H. Freeman, 1967: the normal gravity field of the level ellipsoid (ch. 2).
- Department of Defense, Performance Specification: World Magnetic Model (WMM),
MIL-PRF-89500B, 2019, Appendix A, eq. (8): the same $
a$ and $1/f$.
Motor and ESC
- Issue: #19
- Code:
mjk_aero::propulsion::{DcMotor, LagMotor, MotorModel, Esc, EscState, MotorSystem},mjk_sim::config::drive_train,mjk_sim::validation::motor - Equation prefix:
MOT
Summary
A brushless motor turns its rotor and propeller, and an electronic speed controller (ESC) sets the voltage it sees. The model has two tiers:
- DC-equivalent: the motor treated as a DC motor with speed constant $
K_v$, winding resistance $R$ and no-load current $i_0$. It gives speed, current, torque and power. - First-order lag: speed follows the command with one time constant, for airframes where only that is published.
The ESC turns a command from 0 to 1 into a duty cycle once per physics step, after a latency and through a slew limit. It saturates the command, limits the current, and either brakes actively or lets the motor coast.
Each motor’s only state is its rotor’s speed, which the integrators step like any other state. Coupling motor speeds to the rigid body waits for rotor forces (#21).
Assumptions
- Winding inductance is neglected, so the current follows the voltage at once. The
electrical time constant $
L/R$ is short next to the mechanical one, which is tens of milliseconds; the model’s speed response leads the real one by about $L/R$. - The ESC is lossless and commutation ideal. The motor sees the average voltage
$
d\,V_s$; switching ripple and commutation delay are not modeled. - Parameters are constant. $
K_v$, $R$ and $i_0$ do not change with temperature or load. Friction is the constant torque $i_0/K_v$ against the spin, not viscous drag. - A rotor turns one way. Its speed is a non-negative magnitude, and the airframe’s
spingives the direction. A rotor at rest is held there rather than driven backward. - The ESC updates once per physics step. Its latency is a whole number of steps, and its duty cycle is held for the step.
- The lag tier’s speed follows the duty cycle times a top speed, with one time constant that already includes its load and supply voltage.
Equations
With $V$ the average voltage at the motor and $\omega \ge 0$ the rotor’s speed, the free
current is
i = \frac{V - \omega/K_v}{R}
\qquad\text{(MOT-1)}
and the ESC holds it within its limits. With active braking it may reverse; without, it cannot:
i \leftarrow \min\!\left(\max\left(i,\ i_{\min}\right),\ i_{\max}\right), \qquad
i_{\min} = \begin{cases} -i_{\max} & \text{active braking} \\ 0 & \text{no braking} \end{cases}
\qquad\text{(MOT-2)}
In SI units the torque constant is $K_t = 1/K_v$, so the torque on the rotor, less friction, is
\tau_m = \frac{i - i_0}{K_v}
\qquad\text{(MOT-3)}
The rotor, of inertia $J$ (motor and propeller together), turns against its load
$\tau_L(\omega)$:
J\,\dot\omega = \tau_m - \tau_L(\omega), \qquad \dot\omega \ge 0 \ \text{when}\ \omega = 0
\qquad\text{(MOT-4)}
Steady speed, constant load. Setting $\dot\omega = 0$ with the current unsaturated:
\omega_{ss} = K_v\left(V - R\left(i_0 + K_v\,\tau_L\right)\right)
\qquad\text{(MOT-5)}
Small-signal time constant. Linearizing (MOT-4) about an operating point, back-EMF opposes a
change of speed with $1/(RK_v^2)$ N·m per rad/s, and the load adds its slope:
\tau = \frac{J}{1/(R K_v^2) + d\tau_L/d\omega}
\qquad\text{(MOT-6)}
Steady speed, propeller load $\tau_L = k\,\omega^2$. The positive root of
$k\omega^2 + a\omega - c = 0$, written without cancellation:
\omega_{ss} = \frac{2c}{a + \sqrt{a^2 + 4kc}}, \qquad a = \frac{1}{R K_v^2}, \qquad
c = \frac{V/R - i_0}{K_v}
\qquad\text{(MOT-7)}
Lag tier. With duty cycle $d$, top speed $\omega_{\max}$ and time constant $\tau_m$:
\tau_m\,\dot\omega = d\,\omega_{\max} - \omega
\qquad\text{(MOT-8)}
ESC.
- Saturation: the command $
u_k$ at tick $k$ is held to $[0, 1]$; a command that is not a number reads as 0. - Latency: delayed by $
L = \operatorname{round}(t_{\text{latency}}/h)$ ticks, halves rounded up. - Slew limit: moved toward by at most $
s\,h$ a tick, where $s$ is the slew rate in full scale per second.
d_k = \min\!\left(\max\left(u_{k-L},\ d_{k-1} - s\,h\right),\ d_{k-1} + s\,h\right), \qquad
V = d_k\,V_s
\qquad\text{(MOT-9)}
Power. Electrical power in, mechanical power out, and the current drawn from the supply through a lossless ESC; the difference is copper and friction loss:
P_e = V i, \qquad P_m = \tau_m\,\omega, \qquad i_s = d\,i, \qquad
V i = \tau_m\,\omega + i^2 R + i_0\,\omega/K_v
\qquad\text{(MOT-10)}
Saturation and braking
These closed forms follow from (MOT-2) to (MOT-4) under a constant load $\tau_L$:
-
Coasting without braking. When the voltage falls below the back-EMF $
\omega/K_v$, the current stops at zero instead of reversing. Only friction and the load slow the rotor, at a constant rate:\omega(t) = \omega_0 - \left(\frac{i_0}{K_v} + \tau_L\right)\frac{t}{J} \qquad\text{(MOT-11)} -
Active braking. At zero voltage the current reverses, $
i = -\omega/(RK_v)$, and the back-EMF brakes the rotor exponentially toward a negative speed it never reaches. It stops at zero:\omega(t) = (\omega_0 + b\tau)\,e^{-t/\tau} - b\tau, \qquad \tau = J R K_v^2, \qquad b = \frac{i_0/K_v + \tau_L}{J} \qquad\text{(MOT-12)} -
Current limit. While the free current exceeds the limit, the current is the limit, and the rotor accelerates at a constant rate:
\omega(t) = \omega_0 + \left(\frac{i_{\max} - i_0}{K_v} - \tau_L\right)\frac{t}{J} \qquad\text{(MOT-13)}
The duty cycle saturates at 0 and 1, so the voltage never exceeds the supply.
Validity range
- Speeds from rest up; the model does not turn a rotor backward.
- Step size: the physics step must resolve the mechanical time constant. RK4’s error per
step is about $
(h/\tau)^5/120$ of the change, below 10⁻¹¹ at 1 kHz for the 76 ms of the test motor. Time constants of a few milliseconds still integrate stably at 1 kHz, but less accurately. - Electrical tier: needs $
J > 0$. An airframe whose rotor has an electrical motor must give the motor’s inertia, the propeller’s, or both. - Latency must be a whole number of ticks that fits in 32 bits at the run’s physics rate. A longer one is refused when the drive train is built.
Parameters
| Symbol | Meaning | Unit | Airframe field | Source |
|---|---|---|---|---|
$K_v$ | Speed constant | rad/(s·V) | motors.<key>.kv (rpm/V) | Airframe file |
$R$ | Winding resistance | Ω | motors.<key>.resistance | Airframe file |
$i_0$ | No-load current | A | motors.<key>.no_load_current | Airframe file |
$J$ | Inertia turned | kg·m² | motors.<key>.inertia plus propellers.<key>.inertia | Airframe file |
$i_{\max}$ | Current limit | A | the smaller of motors.<key>.max_current and escs.<key>.max_current | Airframe file |
$\tau_m$ | Lag tier’s time constant | s | motors.<key>.time_constant | Airframe file |
$\omega_{\max}$ | Lag tier’s top speed | rad/s | motors.<key>.max_speed | Airframe file |
$L$ | ESC latency | ticks | escs.<key>.latency, rounded at the run’s rate | Airframe file |
$s$ | ESC slew rate | 1/s | escs.<key>.slew_rate | Airframe file |
| — | Braking | active or none | escs.<key>.braking | Airframe file |
$V_s$ | Supply voltage | V | from the battery (#20) | Battery model |
A rotor without an ESC gets an ideal one: no latency, no slew limit and active braking, limited
only by the motor’s own max_current.
Implementation notes
- The ESC is discrete.
EscState::updateruns before each step with the tick’s command, and its duty cycle is held for the step. That keeps the motor’s equations smooth inside the integrator’s stages, and real ESCs update discretely too.- Delay line: latency is a ring buffer sized when the ESC starts. A test makes 10⁵ updates under a counting allocator and finds no allocation.
- Slew limit: it clamps the target with
minandmax, so the duty cycle lands exactly on the target once it is within one step.
- The motor is a system.
MotorSystemimplementsSystemandLieSystem. The chart RKMK4 steps in is plain addition, so every integrator treats the motor alike.- Projection: after each step it holds the speed at zero or above.
- At rest: a rotor at rest under a net torque against its spin stays at rest.
- A NaN is never hidden. The current limit passes a NaN through instead of replacing it with a limit, and the speed’s projection does the same.
- Latency is converted without an
ascast, which the workspace forbids. The rounded number of ticks is decoded from the double’s bits.
Validation
mjk validate motor runs the models through the simulation loop and compares each with its
closed form. That means World with RKMK4 at 1 kHz, the ESC updated every tick.
- The test motor is an illustrative 2212-class outrunner: 920 rpm/V, 0.117 Ω and 0.4 A, turning 8.5 × 10⁻⁵ kg·m² from an 11.1 V supply.
- Each tolerance is ten times an error estimate computed before the run, rounded up to a power of ten, as in the analytic suite.
| # | Check | Closed form | Simulated | Error | Tolerance | Result |
|---|---|---|---|---|---|---|
| 1 | Steady speed, constant load 0 N·m | 1064.8893255 | 1064.8893255 | 1.0e-11 rad/s | 1e-8 rad/s | Pass |
| 2 | Steady speed, constant load 0.02 N·m | 1043.1698793 | 1043.1698793 | 1.0e-11 rad/s | 1e-8 rad/s | Pass |
| 3 | Steady speed, constant load 0.05 N·m | 1010.5907099 | 1010.5907099 | 8.2e-12 rad/s | 1e-8 rad/s | Pass |
| 4 | Steady speed, propeller load, 80 % duty | 767.7867127 | 767.7867127 | 4.2e-12 rad/s | 1e-8 rad/s | Pass |
| 5 | Small-signal time constant, 1 % step at 80 % duty | 0.0757383443 | 0.0757784664 | 5.3e-4 (relative) | 1e-2 | Pass |
| 6 | Lag tier time constant, step to half speed | 0.0300000000 | 0.0300000003 | 1.1e-8 (relative) | 1e-2 | Pass |
| 7 | ESC latency 2 ms at 1 kHz, in ticks | 2 | 2 | 0 ticks | 0 ticks | Pass |
| 8 | ESC latency 2.5 ms at 1 kHz, in ticks | 3 | 3 | 0 ticks | 0 ticks | Pass |
| 9 | ESC slew 40 /s, ticks from 0 to full duty | 25 | 25 | 0 ticks | 0 ticks | Pass |
| 10 | Coast-down without braking, 0.5 s | 857.9301878 | 857.9301878 | 2.0e-11 rad/s | 1e-8 rad/s | Pass |
| 11 | Active braking at zero duty, 0.1 s | 321.1143374 | 321.1143375 | 4.4e-8 rad/s | 1e-5 rad/s | Pass |
| 12 | Current-limited start at 15 A, 50 ms | 89.14304997 | 89.14304997 | 5.7e-14 rad/s | 1e-11 rad/s | Pass |
| 13 | Power balance at the steady 0.05 N·m point | 57.90990696 | 57.90990696 | 1.2e-16 (relative) | 1e-13 | Pass |
Why each tolerance:
- 1. The transient left after T = 3 s, ω·e^(−T/τ) = 8.2e-12 with τ = J·R·K_v² = 0.0923 s, plus rounding N·ε·ω = 7.1e-10 over N = 3000 steps: 7.2e-10 rad/s.
- 2. The transient left after T = 3 s, ω·e^(−T/τ) = 8.0e-12 with τ = J·R·K_v² = 0.0923 s, plus rounding N·ε·ω = 6.9e-10 over N = 3000 steps: 7.0e-10 rad/s.
- 3. The transient left after T = 3 s, ω·e^(−T/τ) = 7.8e-12 with τ = J·R·K_v² = 0.0923 s, plus rounding N·ε·ω = 6.7e-10 over N = 3000 steps: 6.8e-10 rad/s.
- 4. The transient left after T = 3 s with the linearized τ = 0.0759 s, Eq. (MOT-6), ω·e^(−T/τ) = 5.1e-15, plus rounding N·ε·ω = 5.1e-10: 5.1e-10 rad/s. The transient decays faster than e^(−T/τ) from below.
- 5. Relative: the quadratic load’s second-order term, k·Δω·τ/J = 8.1e-4 for a step of Δω = 7.03 rad/s, plus linear interpolation of the crossing, h²/(8τ²) = 2.2e-5: 8.4e-4.
- 6. Relative: linear interpolation of the crossing, h²/(8τ²) = 1.4e-4 with τ = 30 ms. RK4’s truncation of e^(−h/τ), (h/τ)⁴/120 = 1.0e-8, is four orders smaller and left out.
- 7–9. Exact: a latency is rounded to the nearest whole tick, halves up, and the delay line holds that many commands; a slew limit moves the duty cycle by at most slew/rate a tick and lands on the target.
- 10. With no braking the current stays at zero, so the deceleration is constant and RK4 integrates it exactly: only rounding, N·ε·ω₀ = 1.1e-10 rad/s.
- 11. RK4’s truncation of e^(−h/τ), N·(h/τ)⁵/120 of the 1026 rad/s decaying part: 1.3e-7 rad/s. Rounding, N·ε·ω₀ = 2.2e-11, is four orders smaller and left out.
- 12. The current stays at its limit, so the acceleration is constant and RK4 integrates it exactly: only rounding, N·ε·ω = 9.9e-13 rad/s.
- 13. Relative: V·i = τ·ω + i²R + i₀·ω/K_v holds exactly in real numbers; a few roundings, 10ε = 2.2e-15.
Generated by mjk validate motor. A test fails if this table no longer matches the code, and
CI requires the WebAssembly build to print the same bytes.
The acceptance criteria are rows 1–3 and 5.
- Steady speed under a constant load matches (MOT-5) to 10⁻¹¹ rad/s.
- A 1 % step at the propeller operating point settles with a time constant 5.3 × 10⁻⁴ from the linearized (MOT-6), relative. That difference is the quadratic load’s second-order term, which the estimate predicts at 8 × 10⁻⁴.
Every error is at or below its estimate. Rows 10 and 12 have a constant acceleration, so RK4 integrates them exactly and only rounding remains. The ESC’s timing is exact to the tick.
Unit tests in mjk-aero check each equation, both braking modes, the current limit and the ESC’s
rounding at every boundary. Mutation testing catches every viable mutant of the propulsion code.
Two are excluded as strictly equivalent, with their reasons in .cargo/mutants.toml.
Limitations
- No inductance: the current is quasi-static, as Assumption 1 says.
- No motor dynamics beyond the DC equivalent: no torque ripple, cogging, demagnetization or heating.
- No reverse rotation: reversing motors, as in 3D flight modes, are not modeled.
- The lag tier ignores supply voltage and load. Its time constant and top speed are what was measured for one propeller and one battery.
- The ESC’s latency is quantized to whole physics steps. At 1 kHz that is up to half a millisecond of difference.
References
- M. Drela, “First-Order DC Electric Motor Model,” MIT Aero & Astro, February 2007. The
$
K_v$, $R$, $i_0$ motor model this page uses.
Validation
Validation answers one question for each model: is the implementation computing what its page says it computes, to a stated tolerance? Checks fall into four levels.
| Level | Compares against | Examples |
|---|---|---|
| Analytic | Closed-form solutions | Free fall, projectile with linear drag, torque-free precession, the intermediate-axis flip, bounce height $e^2 h$, sliding on an incline |
| Numerical | Properties every correct method must have | Measured convergence order, energy and angular-momentum drift, unit-norm preservation on SO(3) |
| Published data and reference code | Measurements and independent implementations | UIUC propeller data, the Crazyflie identification, Aerosonde trim and eigenvalues from BYU’s reference code, the NTNU Skywalker X8 papers |
| Statistical | Spectra and noise statistics | Turbulence power spectra against the Dryden model, IMU noise recovered from Allan deviation |
Every check reports four things:
- Tolerance, and why it suits the step size and model.
- Result: the measured error.
- Pass or fail.
- Known limitations: what the check doesn’t cover.
The tables on this page are generated by mjk validate, so they always match the code that
produced them. The analytic checks below are the first; the full report is
#81.
Analytic checks
These checks run the whole simulation loop, World with RKMK4 at the default 1 kHz, and compare
it with closed-form solutions (#16). The
convergence-order checks run every integrator at four step sizes.
Each tolerance is fixed before the run from an error estimate: ten times the estimate, rounded up to a power of ten. The estimate is printed under the table, so a reader can check that the tolerance suits the step size. A test fails if any check fails, and CI requires the WebAssembly build to print the same table byte for byte.
Closed forms
Free fall from rest under standard gravity, Down positive:
z = \tfrac12 g_0 t^2, \qquad v = g_0 t
\qquad\text{(VAL-1)}
A projectile with linear drag $-c\,\mathbf{v}$, with time constant $\tau = m/c$ and
terminal velocity $\mathbf{v}_t = g_0\tau\,\mathbf{z}_W$, launched from the origin at
$\mathbf{v}_0$:
\mathbf{v}(t) = \mathbf{v}_t + (\mathbf{v}_0 - \mathbf{v}_t)\,e^{-t/\tau}
\qquad\text{(VAL-2)}
\mathbf{x}(t) = \mathbf{v}_t\,t + \tau\,(\mathbf{v}_0 - \mathbf{v}_t)\left(1 - e^{-t/\tau}\right)
\qquad\text{(VAL-3)}
A torque-free axisymmetric body, with transverse and axial moments $I_t$ and $I_a$:
the transverse angular velocity turns in body axes at
\Omega = \frac{(I_a - I_t)\,\omega_3}{I_t}
\qquad\text{(VAL-4)}
the symmetry axis turns around the fixed angular momentum $\mathbf{L}$ at
\dot\phi = \frac{\lvert\mathbf{L}\rvert}{I_t}
\qquad\text{(VAL-5)}
and the attitude, from $\mathbf{R}_0$, is a rotation about $\hat{\mathbf{L}}$ composed with one
about the body’s symmetry axis $\mathbf{e}_3$:
\mathbf{R}(t) = \mathrm{Rot}\!\left(\hat{\mathbf{L}},\ \frac{\lvert\mathbf{L}\rvert t}{I_t}\right)\mathbf{R}_0\,\mathrm{Rot}(\mathbf{e}_3,\ -\Omega t)
\qquad\text{(VAL-6)}
A torque-free body spinning near its intermediate axis, $I_1 < I_2 < I_3$, with angular
momentum $M$ and kinetic energy $E$ such that $M^2 > 2EI_2$. The intermediate-axis rate is
proportional to $\mathrm{sn}(\omega_p t, k)$ (Landau and Lifshitz, §37), so it changes sign, and
the body flips, every
\Delta t = \frac{2K(k)}{\omega_p}, \quad
\omega_p = \sqrt{\frac{(I_3 - I_2)(M^2 - 2EI_1)}{I_1 I_2 I_3}}, \quad
k^2 = \frac{(I_2 - I_1)(2EI_3 - M^2)}{(I_3 - I_2)(M^2 - 2EI_1)}
\qquad\text{(VAL-7)}
with the complete elliptic integral computed by the arithmetic–geometric mean:
K(k) = \frac{\pi}{2\,\mathrm{AGM}\!\left(1, \sqrt{1 - k^2}\right)}
\qquad\text{(VAL-8)}
Convergence order $p$ is the least-squares slope of $\ln e$ against $\ln h$ over
$h = 1/16$ to $1/128$ s, where $e$ is the error against Eq. (VAL-3) for translation and
Eq. (VAL-6) for rotation:
e \approx C\,h^{p}
\qquad\text{(VAL-9)}
Test bodies
| Check | Body | Start | Run |
|---|---|---|---|
| Free fall | 2 kg | at rest | 10 s |
| Linear drag | 2 kg, $c$ = 0.5 N·s/m ($\tau$ = 4 s) | $\mathbf{v}_0$ = (20, 0, −15) m/s | 5 s |
| Axisymmetric body | $I_t$ = 0.02, $I_a$ = 0.035 kg·m² | $\boldsymbol\omega$ = (1, 0, 12) rad/s | 10 s |
| Intermediate axis | $I$ = (0.010, 0.020, 0.030) kg·m² | $\boldsymbol\omega$ = (0.05, 3, 0.05) rad/s; $k'^2 = 5.6\times10^{-4}$ | 60 s |
| Order, translation | 2 kg, $c$ = 2 N·s/m ($\tau$ = 1 s) | $\mathbf{v}_0$ = (2, 0, −1) m/s | 4 s |
| Order, rotation | $I_t$ = 0.02, $I_a$ = 0.035 kg·m² | $\boldsymbol\omega$ = (0.3, 0, 1) rad/s | 4 s |
Results
| # | Check | Closed form | Simulated | Error | Tolerance | Result |
|---|---|---|---|---|---|---|
| 1 | Free fall: distance fallen in 10 s | 490.3325000 | 490.3325000 | 5.3e-11 m | 1e-7 m | Pass |
| 2 | Free fall: speed after 10 s | 98.06650000 | 98.06650000 | 1.3e-11 m/s | 1e-8 m/s | Pass |
| 3 | Linear drag: position after 5 s | 70.49587964 | 70.49587964 | 2.4e-13 m | 1e-9 m | Pass |
| 4 | Linear drag: velocity after 5 s | 24.37355023 | 24.37355023 | 1.4e-14 m/s | 1e-9 m/s | Pass |
| 5 | Axisymmetric body: precession rate in body axes | 9.000000000 | 9.000000000 | 4.9e-10 rad/s | 1e-8 rad/s | Pass |
| 6 | Axisymmetric body: precession rate in space | 21.02379604 | 21.02379604 | 4.9e-10 rad/s | 1e-7 rad/s | Pass |
| 7 | Axisymmetric body: attitude after 10 s | R(t), Eq. (VAL-6) | angle from it | 2.4e-10 rad | 1e-6 rad | Pass |
| 8 | Intermediate axis: time between flips | 5.926982582 | 5.926982582 | 7.1e-13 (relative) | 1e-6 | Pass |
| 9 | Intermediate axis: angular momentum over 60 s | constant | largest change | 3.4e-14 (relative) | 1e-8 | Pass |
| 10 | Intermediate axis: kinetic energy over 60 s | constant | largest change | 7.0e-14 (relative) | 1e-8 | Pass |
| 11 | Convergence order: explicit Euler, translation (linear drag) | 1 | 0.99 | 0.01 | 0.2 | Pass |
| 12 | Convergence order: explicit Euler, rotation (precession) | 1 | 0.99 | 0.01 | 0.2 | Pass |
| 13 | Convergence order: semi-implicit Euler, translation (linear drag) | 1 | 1.00 | 0.00 | 0.2 | Pass |
| 14 | Convergence order: semi-implicit Euler, rotation (precession) | 1 | 0.99 | 0.01 | 0.2 | Pass |
| 15 | Convergence order: RK4, translation (linear drag) | 4 | 4.02 | 0.02 | 0.2 | Pass |
| 16 | Convergence order: RK4, rotation (precession) | 4 | 4.00 | 0.00 | 0.2 | Pass |
| 17 | Convergence order: RKMK4, translation (linear drag) | 4 | 4.02 | 0.02 | 0.2 | Pass |
| 18 | Convergence order: RKMK4, rotation (precession) | 4 | 4.00 | 0.00 | 0.2 | Pass |
Vector checks show magnitudes; their error is the distance between the vectors.
Why each tolerance:
- 1. RKMK4 integrates translation as RK4 does, and RK4’s stages integrate a constant acceleration exactly, so only rounding remains: at most N·ε·z = 1.1e-9 over N = 10000 steps.
- 2. RKMK4 integrates translation as RK4 does, and RK4’s stages integrate a constant acceleration exactly, so only rounding remains: at most N·ε·v = 2.2e-10 over N = 10000 steps.
- 3–4. RKMK4 integrates translation as RK4 does. Its truncation, (T/τ)(h/τ)⁴/120 = 4e-17 of the 231 m transient, is far below rounding over N = 5000 steps, which sets both tolerances: N·ε·|x| = 7.8e-11 m and N·ε·|v| = 2.7e-11 m/s.
- 5. RK4-type phase error over the run, N·(h·ω)⁵/120 divided by T = 10 s, with ω = 9.00 rad/s: 4.9e-10 rad/s.
- 6. RK4-type phase error over the run, N·(h·ω)⁵/120 divided by T = 10 s, with ω = 12.04 rad/s: 2.2e-9 rad/s.
- 7. RK4-type phase error, N·(h·ω)⁵/120 with ω = 12.04 rad/s, plus rounding: 2.2e-8 rad.
- 8. Near the separatrix (k′² = 5.6e-4) an invariant error δ moves the interval by about δ/(2K·k′²) = 175δ; with δ = 1.3e-10, 2.4e-8.
- 9–10. RK4-type truncation N·(h·ω)⁵/120 plus rounding N·ε, with ω = 3.00 rad/s: 1.3e-10.
- 11–18. Slope of ln(error) against ln(h) over h = 1/16 to 1/128 s, for 2 kg with drag 2 N·s/m (τ = 1 s) launched at (2, 0, -1) m/s, and for a body with transverse and axial moments 0.02 and 0.035 kg·m² spinning at (0.3, 0, 1) rad/s. At the largest step h·ω = 0.11 and h/τ = 0.0625: the next term of the error expansion shifts the slope by about that much, and ±0.2 is about twice it.
Generated by mjk validate analytic. A test fails if this table no longer matches the code.
Every error is at or below its estimate. For the body-frame precession the estimate is not
only a bound but the error itself: RK4-type methods drop the $(h\omega)^5/120$ term of
$e^{ih\omega}$ each step, and over 10 000 steps at 9 rad/s that predicts $4.9\times10^{-10}$
rad/s, which is what the run shows. The flip-interval estimate is far above the measured
$7\times10^{-13}$ because it assumes the invariants drift as much as their own estimate allows;
they drift thousands of times less.
The checks have teeth. Tests rerun the physics checks with first-order methods: explicit Euler fails every group, and semi-implicit Euler fails the drag and precession groups. RK4 passes free fall, drag and precession, as a fourth-order method should.
Limitations
- One method at one step. The physics checks use RKMK4 at 1 kHz, the configuration a run uses; the convergence rows cover the other methods.
- The flip check compares the period, not the trajectory. Comparing $
\boldsymbol\omega(t)$ with the Jacobi elliptic functions sn, cn and dn throughout would be stronger. - No coupling between translation and rotation. Each check exercises one; the models that couple them, rotors and aerodynamics, arrive in M2 and M4 with their own validation.
- No contact. Bounce height and sliding on an incline need the contact solver and arrive with it (#55–#61).
Verified so far
The analytic checks above rest on foundations that are tested on their own, each property over hundreds of random inputs and each edge case deterministically:
| Component | What is checked |
|---|---|
| Frame-typed math (#8) | Rotations preserve norms; a quaternion times its inverse is the identity; quaternion composition matches the matrix product; transpose, determinant, inverse and symmetric eigen-decomposition identities; exact results of the elementary operators; eigen-decomposition accuracy independent of scale and of off-diagonal patterns |
| SO(3) maps (#9) | Log inverts Exp for angles from $10^{-12}$ rad to just under $\pi$; Exp inverts Log and takes the short way; Jacobian identities, and the right Jacobian linearizes Exp; plus and minus invert each other; slerp moves at constant rate; Euler angles round-trip, including at gimbal lock; matrix conversion round-trips and non-rotations are rejected; Jacobian coefficients agree with 40-digit references; the small-angle branches of Exp and Log are accurate to within 2 and 4 ulp |
| Rigid-body dynamics (#10) | Composite mass properties against a hand-computed tensor and the shape formulas; cutting a component in half or rotating every component leaves the result consistent; Euler’s equations against their principal-axis closed form; power balance and conservation of angular momentum hold for any state, inertia and loads |
| Integrators (#11, #12) | Each method against its closed form under constant acceleration; RK4 exact for cubic rates; RKMK4 exact for steady principal-axis spin; measured order 1, 1, 4 and 4 (within ±0.2) on an oscillator and on a tumbling body; semi-implicit Euler energy bounded over 10⁶ steps while explicit Euler’s grows as predicted; RKMK4 keeps a unit quaternion with no renormalization; the RK4-against-RKMK4 study table is generated by mjk validate and checked against the code |
| Motor and ESC (#19) | Steady speed under constant and propeller loads against the closed forms to 10⁻¹¹ rad/s; the small-signal time constant within 5.3 × 10⁻⁴ of the linearized one; the lag tier’s time constant; ESC latency and slew exact to the tick; coasting, active braking and a current-limited start against their closed forms; the power balance; every equation, braking mode and limit unit-tested; an ESC update allocates nothing; the table is generated by mjk validate motor |
| Atmosphere and gravity (#15) | Temperature, pressure, density, speed of sound and viscosity match the 1976 standard’s printed tables at 0, 1, 2, 5, 11 and 20 km to four significant figures (largest gap 0.10 of a unit in the fourth figure), in a table generated by mjk validate atmosphere; the air is continuous at the tropopause and in hydrostatic balance with any temperature offset; WGS-84 normal gravity matches the exact field of the level ellipsoid to $1.5\times10^{-6}$ m/s² from −5 to 20 km, and its derived constants, computed from the four defining parameters, match the printed tables of the WGS-84 standard (NGA.STND.0036) to the last digit |
| World loop (#13) | Every subsystem runs exactly at its rate over 10 s (500, 250, 50 and 10 Hz at 1 kHz); sensors run before controllers within a tick; commands are held between controller updates; time is exact at tick 123 456 789; the real-time accumulator carries remainders and drops a backlog it cannot catch up on; two runs are identical to the bit; a step allocates nothing |
| Determinism and replay (#14) | SplitMix64, xoshiro256** and FNV-1a match their published reference algorithms; adding a random stream leaves the others unchanged; no two seed-and-name pairs share a stream, no state word is shared within a run, and streams start with different draws and are uncorrelated (weekly, PractRand on interleaved streams to 32 GB); uniform and normal samples have the right values and moments; two runs of the reference scenario are identical at every checkpoint; replaying its recorded inputs reproduces the final hash; changing one input changes every hash from its tick on; a WebAssembly build prints the same tables as the native build, byte for byte; recording and replay allocate nothing |
| Analytic suite (#16) | Free fall, linear drag, torque-free precession and the intermediate-axis flip through the whole simulation loop, each within a tolerance fixed beforehand from an error estimate; measured order 1, 1, 4 and 4 (within ±0.2) for every integrator on drag and precession; first-order methods fail the physics checks; the table is generated by mjk validate analytic |
| Inertia consistency (#7) | Non-finite, asymmetric, indefinite and triangle-inequality-violating tensors are rejected, with each principal minor and its tolerance pinned by a case only it can detect (Engineering standards) |
| Configuration files (#7, #18) | Each of 23 malformed sample files produces an error naming the exact field at fault, among them a number without a unit, a unit of the wrong quantity, a source not in the bibliography, too little thrust and overlapping rotor disks; a number without a source loads with a warning; every unit symbol converts by its definition; each airframe’s generated page matches its file, natively and in WebAssembly |
These are unit and property tests, and their tolerances are stated in the tests. The generated report (#81) will tabulate model checks in the format above.
How the tests are checked
Two gates in CI measure the tests themselves. Engine line coverage must stay at or above 90 %. Mutation testing changes the code in small ways and fails if any change goes unnoticed by every test; no mutant of the engine survives. Both are described on the Engineering standards page.
Airframes
Four aircraft are modeled, chosen for the quality of their public data. Each airframe file gives
every parameter a unit, a source and, where known, an uncertainty
(format). Each airframe’s page is generated from its
file by mjk airframe, and a test fails if the two disagree, so the book can never disagree with
what the simulator loads (#18).
The example quadrotor shows the format and its generated page. Its values are illustrative, and its only source says so.
| Airframe | Class | Primary sources | Issue |
|---|---|---|---|
| Bitcraze Crazyflie 2.x | Nano quadrotor | Förster (2015); Eschmann, Albani & Loianno (2024) | #29 |
| Holybro X500 V2 | 500 mm quadrotor | PX4 Gazebo x500 model; Holybro specifications | #30 |
| Aerosonde | Small fixed-wing | Beard & McLain (2012); BYU mavsim_public | #50 |
| Skywalker X8 | Flying wing | Gryte et al. (2018); Reinhardt et al. (2022); Løw-Hansen et al. (2025) | #51 |
Where sources disagree, the airframe page lists every value with its source, and states which one the simulator uses and why.
Example quadrotor
Generated by mjk airframe from the airframe’s file. A test fails if this page no longer matches the file.
| Quantity | Value |
|---|---|
| Mass | 1.108 kg |
| Center of mass | [0, 0, 0.00517148] m |
| Inertia, diagonal | [0.00887531, 0.00938791, 0.0170679] kg·m² |
| Rotors | 4 |
| Thrust-to-weight | 3.61011 |
Rotors
Spin is seen from the side the thrust points to.
| # | Name | Hub | Thrust axis | Spin | Propeller | Motor | ESC |
|---|---|---|---|---|---|---|---|
| 0 | front right | [0.1591, 0.1591, -0.035] m | [0, 0, -1] | ccw | 10x4.5 | 2212-920 | 20a |
| 1 | rear left | [-0.1591, -0.1591, -0.035] m | [0, 0, -1] | ccw | 10x4.5 | 2212-920 | 20a |
| 2 | front left | [0.1591, -0.1591, -0.035] m | [0, 0, -1] | cw | 10x4.5 | 2212-920 | 20a |
| 3 | rear right | [-0.1591, 0.1591, -0.035] m | [0, 0, -1] | cw | 10x4.5 | 2212-920 | 20a |
Parts
The mass properties are built up from these parts: mass.components[#] below.
| # | Part | Shape |
|---|---|---|
| 0 | center plates | box |
| 1 | battery | box |
| 2 | flight controller and receiver | point |
| 3 | front right arm | box |
| 4 | rear left arm | box |
| 5 | front left arm | box |
| 6 | rear right arm | box |
| 7 | front right motor and propeller | cylinder |
| 8 | rear left motor and propeller | cylinder |
| 9 | front left motor and propeller | cylinder |
| 10 | rear right motor and propeller | cylinder |
Parameters
| Parameter | Value | Unit | SI | Uncertainty | Source |
|---|---|---|---|---|---|
mass.components[0].mass | 250 | g | 0.25 kg | — | illustrative |
mass.components[0].position | [0, 0, 0] | mm | [0, 0, 0] m | — | illustrative |
mass.components[0].size | [120, 120, 30] | mm | [0.12, 0.12, 0.03] m | — | illustrative |
mass.components[1].mass | 350 | g | 0.35 kg | ±5 | illustrative |
mass.components[1].position | [0, 0, 35] | mm | [0, 0, 0.035] m | — | illustrative |
mass.components[1].size | [140, 45, 35] | mm | [0.14, 0.045, 0.035] m | — | illustrative |
mass.components[2].mass | 100 | g | 0.1 kg | — | illustrative |
mass.components[2].position | [0, 0, -25] | mm | [0, 0, -0.025] m | — | illustrative |
mass.components[3].mass | 35 | g | 0.035 kg | — | illustrative |
mass.components[3].position | [79.55, 79.55, 0] | mm | [0.07955, 0.07955, 0] m | — | illustrative |
mass.components[3].size | [200, 20, 10] | mm | [0.2, 0.02, 0.01] m | — | illustrative |
mass.components[3].orientation | [0, 0, 45] | deg | [0, 0, 0.785398] rad | — | illustrative |
mass.components[4].mass | 35 | g | 0.035 kg | — | illustrative |
mass.components[4].position | [-79.55, -79.55, 0] | mm | [-0.07955, -0.07955, 0] m | — | illustrative |
mass.components[4].size | [200, 20, 10] | mm | [0.2, 0.02, 0.01] m | — | illustrative |
mass.components[4].orientation | [0, 0, -135] | deg | [0, 0, -2.35619] rad | — | illustrative |
mass.components[5].mass | 35 | g | 0.035 kg | — | illustrative |
mass.components[5].position | [79.55, -79.55, 0] | mm | [0.07955, -0.07955, 0] m | — | illustrative |
mass.components[5].size | [200, 20, 10] | mm | [0.2, 0.02, 0.01] m | — | illustrative |
mass.components[5].orientation | [0, 0, -45] | deg | [0, 0, -0.785398] rad | — | illustrative |
mass.components[6].mass | 35 | g | 0.035 kg | — | illustrative |
mass.components[6].position | [-79.55, 79.55, 0] | mm | [-0.07955, 0.07955, 0] m | — | illustrative |
mass.components[6].size | [200, 20, 10] | mm | [0.2, 0.02, 0.01] m | — | illustrative |
mass.components[6].orientation | [0, 0, 135] | deg | [0, 0, 2.35619] rad | — | illustrative |
mass.components[7].mass | 67 | g | 0.067 kg | — | illustrative |
mass.components[7].position | [159.1, 159.1, -15] | mm | [0.1591, 0.1591, -0.015] m | — | illustrative |
mass.components[7].radius | 14 | mm | 0.014 m | — | illustrative |
mass.components[7].length | 30 | mm | 0.03 m | — | illustrative |
mass.components[8].mass | 67 | g | 0.067 kg | — | illustrative |
mass.components[8].position | [-159.1, -159.1, -15] | mm | [-0.1591, -0.1591, -0.015] m | — | illustrative |
mass.components[8].radius | 14 | mm | 0.014 m | — | illustrative |
mass.components[8].length | 30 | mm | 0.03 m | — | illustrative |
mass.components[9].mass | 67 | g | 0.067 kg | — | illustrative |
mass.components[9].position | [159.1, -159.1, -15] | mm | [0.1591, -0.1591, -0.015] m | — | illustrative |
mass.components[9].radius | 14 | mm | 0.014 m | — | illustrative |
mass.components[9].length | 30 | mm | 0.03 m | — | illustrative |
mass.components[10].mass | 67 | g | 0.067 kg | — | illustrative |
mass.components[10].position | [-159.1, 159.1, -15] | mm | [-0.1591, 0.1591, -0.015] m | — | illustrative |
mass.components[10].radius | 14 | mm | 0.014 m | — | illustrative |
mass.components[10].length | 30 | mm | 0.03 m | — | illustrative |
rotors[0].position | [159.1, 159.1, -35] | mm | [0.1591, 0.1591, -0.035] m | — | illustrative |
rotors[0].axis | [0, 0, -1] | 1 | [0, 0, -1] | — | illustrative |
rotors[1].position | [-159.1, -159.1, -35] | mm | [-0.1591, -0.1591, -0.035] m | — | illustrative |
rotors[1].axis | [0, 0, -1] | 1 | [0, 0, -1] | — | illustrative |
rotors[2].position | [159.1, -159.1, -35] | mm | [0.1591, -0.1591, -0.035] m | — | illustrative |
rotors[2].axis | [0, 0, -1] | 1 | [0, 0, -1] | — | illustrative |
rotors[3].position | [-159.1, 159.1, -35] | mm | [-0.1591, 0.1591, -0.035] m | — | illustrative |
rotors[3].axis | [0, 0, -1] | 1 | [0, 0, -1] | — | illustrative |
propellers."10x4.5".diameter | 10 | in | 0.254 m | — | illustrative |
propellers."10x4.5".pitch | 4.5 | in | 0.1143 m | — | illustrative |
propellers."10x4.5".blades | 2 | 1 | 2 | — | illustrative |
propellers."10x4.5".max_thrust | 1000 | gf | 9.80665 N | ±50 | illustrative |
propellers."10x4.5".mass | 12 | g | 0.012 kg | — | illustrative |
propellers."10x4.5".inertia | 645 | g cm^2 | 6.45e-5 kg·m² | — | illustrative |
motors.2212-920.kv | 920 | rpm/V | 96.3422 rad/(s·V) | — | illustrative |
motors.2212-920.resistance | 117 | mohm | 0.117 Ω | — | illustrative |
motors.2212-920.no_load_current | 0.4 | A | 0.4 A | — | illustrative |
motors.2212-920.max_current | 15 | A | 15 A | — | illustrative |
motors.2212-920.inertia | 200 | g cm^2 | 2e-5 kg·m² | — | illustrative |
motors.2212-920.mass | 55 | g | 0.055 kg | — | illustrative |
escs.20a.latency | 2 | ms | 0.002 s | — | illustrative |
escs.20a.slew_rate | 40 | 1/s | 40 1/s | — | illustrative |
escs.20a.max_current | 20 | A | 20 A | — | illustrative |
battery.cells | 3 | 1 | 3 | — | illustrative |
battery.capacity | 3000 | mAh | 10800 A·s | — | illustrative |
battery.internal_resistance | 30 | mohm | 0.03 Ω | — | illustrative |
drag.area | [120, 120, 300] | cm^2 | [0.012, 0.012, 0.03] m² | — | illustrative |
controller.gains.attitude_p | 6.5 | 1/s | 6.5 s⁻¹ | — | illustrative |
controller.gains.roll_rate_p | 0.15 | N m s/rad | 0.15 kg·m²·s⁻¹·rad⁻¹ | — | illustrative |
controller.gains.velocity_p | 1.8 | 1/s | 1.8 s⁻¹ | — | illustrative |
visual.body_size | [120, 120, 40] | mm | [0.12, 0.12, 0.04] m | — | illustrative |
visual.arm_width | 20 | mm | 0.02 m | — | illustrative |
Sources
| Key | Source |
|---|---|
illustrative | Illustrative values for the airframe format’s documentation. Not a real aircraft. Real airframes, with every value cited, arrive with #29 and #30. |
Decision records
An architecture decision record (ADR) captures one significant design choice: the context, the decision, its consequences, and the alternatives that were considered and rejected. ADRs are never rewritten after acceptance. A changed decision gets a new ADR that supersedes the old one, so the history of the reasoning is kept.
Write an ADR when a choice is expensive to reverse, or when a reader would reasonably ask why it was done this way. Examples: adding an external dependency to an engine crate, choosing a numerical method, or changing a convention. Start from the template and number it sequentially.
| ADR | Decision | Status |
|---|---|---|
| 0001 | Hand-written, frame-typed math; no third-party math or physics crates in the engine | Accepted |
| 0002 | Fixed-step integration behind a trait, with RK4 and a Lie-group method for attitude | Accepted |
| 0003 | Sequential impulses with warm starting and soft constraints for contact | Accepted |
| 0004 | Rust physics compiled to WebAssembly, drawn by three.js with WebGPU | Accepted |
| 0005 | GitHub-native math syntax, rendered in the book by KaTeX | Accepted |
| 0006 | One engine error type in mjk-core; configuration parsed from TOML text with exact field paths | Accepted |
| 0007 | Operator-grade interface rules for the viewer and the book; the 3D scene and README hero are exempt | Accepted |
Status values: Proposed, Accepted, Superseded by ADR NNNN, Rejected. An accepted ADR may also say extended by ADR NNNN when a later record adds to it without changing what it decided; that note is the only edit an accepted ADR receives.
ADR 0001: Hand-written, frame-typed math
- Status: Accepted. The external-dependency allowlist is amended by ADR 0006.
- Date: 2026-11-26
- Issues: #8, #9, #2
Context
The engine needs 3-vectors, 3×3 matrices, unit quaternions and the SO(3) exponential and logarithm maps. It also needs small dense solvers later: eigen-decomposition of inertia tensors, and the eigenvalues used in modal analysis. The project’s purpose is to be checkable, and the most common simulator bugs are frame and convention errors: adding a body-frame vector to a world-frame one, or applying a quaternion in the wrong direction.
Decision
Engine crates use hand-written linear algebra in mjk-math, with no third-party math or physics
crates.
- Vectors carry their frame in their type:
Vec3<Body>,Vec3<World>. A rotation is typed by its source and target frames, soq_wb.rotate(v_b)returnsVec3<World>, and passing a world vector is a compile error. - All types are
Copy, sized at compile time, and never allocate. - Transcendental functions go through
libmso results are bit-identical on every platform. - The layering check allows only
libm,serdeandtomlas external engine dependencies.
Consequences
- Frame mistakes become compile errors instead of silent wrong answers.
- Every operation is short enough to read next to its equation in the conventions, and has property tests: rotations preserve norms, and composition matches matrix products.
- More code to write and test than importing a library. The surface is small, roughly what #8 and #9 list, so this is bounded.
- No SIMD-specialized kernels. At the engine’s scale (a handful of bodies, 1 kHz) this costs nothing measurable; the benchmarks (#82) will confirm it.
Alternatives considered
- nalgebra. Comprehensive and well tested, but it doesn’t tag vectors with frames, its
generic types slow compilation and obscure error messages, and it doesn’t route through
libmby default. - glam. Fast and simple, but
f32-first, without frame typing, and with its own precision and SIMD behavior that would complicate bit-exact determinism. - A units-of-measure crate (
uom). Compile-time units are attractive, but they add heavy generics throughout. Unit suffixes in names and frame types catch most errors at far lower cost. - An existing physics engine (Rapier, others). It would hide exactly the parts this project exists to show, and its conventions and integrators are not designed for flight dynamics.
ADR 0002: Fixed-step integration with a Lie-group method for attitude
Context
The state includes an attitude on SO(3), represented as a unit quaternion. Controllers and sensors run at fixed rates, as they do on real autopilots. Runs must be reproducible bit for bit, natively and in WebAssembly, so recorded flights replay exactly and native and browser results can be compared. Forces are dominated by aerodynamics and propulsion, which are dissipative, not conservative. Contact is the only stiff part of the system.
Decision
- Physics advances with a fixed step, 1 kHz by default. Controllers and sensors run at integer divisors of the physics rate, with sample-and-hold between their updates. Real-time front ends use an accumulator and interpolate between states for display.
- Integrators implement one trait and are generic over the force model, so they can be swapped and
compared. Four are provided:
- explicit Euler and semi-implicit Euler, as references;
- classical RK4, integrating the quaternion and renormalizing;
- Runge–Kutta–Munthe-Kaas (RKMK4) on SO(3) × ℝⁿ, which keeps the attitude on the rotation group by construction, with increments applied on the right as in (CONV-10).
- Contact is resolved by an impulse stage after integration, through operator splitting (ADR 0003), rather than inside the integrator.
- The validation suite measures convergence order, energy and angular-momentum drift, and unit-norm error for every integrator, and publishes the comparison.
Consequences
- Controllers see the same sample timing as on hardware, and runs are reproducible.
- The step size must resolve the fastest non-contact dynamics: motor time constants of tens of milliseconds and the fastest body modes. 1 kHz gives a wide margin and can be changed per scenario.
- Showing RK4 with renormalization next to RKMK4 makes the cost and benefit of geometric integration measurable, not just asserted.
Alternatives considered
- Adaptive step size (Dormand–Prince RK45 and similar). Efficient for smooth problems, but controller sampling becomes irregular and runs are no longer reproducible across platforms.
- Symplectic and variational integrators (for example RATTLE). Excellent long-term energy behavior for conservative systems, but the dominant forces here are dissipative, so the benefit is small.
- Implicit methods. Only contact is stiff, and the impulse solver handles it. Implicit integration of the whole state would add cost and nonlinear solves without a matching benefit.
- Euler angles as state. Singular at ±90° pitch; ruled out in the conventions.
ADR 0003: Sequential impulses for contact
Context
Aircraft touch the world when landing, taking off from slopes, launching, crashing, and towing slung payloads. The solver must:
- keep a landed vehicle at rest without jitter;
- handle Coulomb friction;
- support joints such as rope constraints for slung loads;
- be deterministic and allocation-free per step;
- couple cleanly with velocity-level rigid-body dynamics.
The scenes are small: a few bodies and tens of contacts.
Decision
Contacts and joints are velocity constraints solved by sequential impulses (projected Gauss–Seidel):
- warm starting from persistent contact manifolds;
- Coulomb friction with two tangent directions, bounded by the normal impulse;
- restitution above a velocity threshold;
- position error corrected with soft constraints, in the style of Box2D’s soft step, rather than raw Baumgarte stabilization;
- sleeping.
Collision detection uses GJK and EPA on convex shapes, with analytic fast paths, plus a dynamic AABB tree for the broadphase.
Consequences
- Cheap, robust, and well understood. Each impulse has a physical meaning that can be logged and plotted.
- Iterative: the residual depends on the iteration count, which is logged every step.
- Known limitations are documented and tested rather than hidden: slow convergence for large mass ratios, and Newton’s cradle (simultaneous impacts are resolved sequentially).
Alternatives considered
- Penalty springs. Simple, but stiff springs need tiny steps or they jitter and sink, and soft springs let bodies interpenetrate.
- Direct LCP solvers (Lemke, Dantzig). Exact for the linear complementarity problem, but more complex and costly, and their pivoting is harder to make deterministic, for little benefit at this scale.
- Position-based dynamics (XPBD). Very stable, but its corrections are less directly interpretable as physical impulses, and coupling it with force-based aerodynamics is less natural.
- Optimization-based soft contact (MuJoCo-style convex formulation). Elegant and accurate, but substantially more machinery than a few-body flight simulator needs.
ADR 0004: Rust physics in WebAssembly, rendered by three.js with WebGPU
Context
The project aims for modern game-engine visual quality and a live demo anyone can open from the README. The physics is the part that must be rigorous; the renderer must never be able to change a simulated result.
Decision
- The engine compiles to WebAssembly (
mjk-wasm) and runs in a Web Worker. It exchanges fixed-layout state snapshots and pilot inputs with the page as transferable buffers. GitHub Pages cannot send the headers thatSharedArrayBufferrequires. - The viewer is TypeScript with three.js, using the WebGPU renderer and falling back to WebGL2. Conversion from world coordinates happens in one module (CONV-4, CONV-5).
- The documentation and the live demo share one GitHub Pages site: the book at the root and the
demo under
/demo/.
Consequences
- Anyone can run the demo by opening a link.
- Physics and rendering are separated by a data interface, so either side can be tested alone. Native and WebAssembly results are compared bit for bit in CI.
- Two languages: rendering code follows the project’s TypeScript standard and gets its own lint, type checks and visual regression tests.
- Visual quality is bounded by what WebGPU and WebGL2 offer in browsers, and quality tiers handle weaker hardware.
Alternatives considered
- Bevy (all Rust). One language and a capable renderer, but large WebAssembly builds, breaking releases every few months, and heavy compile times. It would also pull the engine toward its ECS architecture.
- A custom wgpu renderer. The most impressive to graphics specialists, but the renderer would become the project.
- Unreal Engine or Unity. High fidelity, but not web-native, with licensing and tooling that don’t fit an open, reproducible research codebase.
ADR 0005: GitHub-native math syntax, rendered in the book by KaTeX
Context
Documentation pages are read in two places: on GitHub, and in the mdBook site. Writing the conventions page showed that GitHub’s renderer has four relevant quirks:
- It applies Markdown backslash escapes inside
$$blocks, so\;and\!appear as visible punctuation and mid-line\\row breaks are lost. - It rejects
\operatorname. \tagbreaks equation layout in Chromium.- In
$…$inline math, subscripts with underscores can be read as emphasis.
Decision
- Display equations are fenced code blocks with the language
math, and inline equations are written$`…`$, a code span wrapped in dollar signs. Markdown never processes code, so the TeX arrives intact on GitHub and in the book. - Equation IDs are written as a trailing
\qquad\text{(ID)}, not with\tag. - Use
\mathrm{…}instead of\operatorname{…}. - In the book,
docs/theme/math.jsrenders both forms with KaTeX 0.19.1. KaTeX is loaded from a CDN at a pinned version with subresource integrity. The script also gives each tagged display equation the anchoreq-ID.
Consequences
- A page renders correctly on GitHub and in the book from one source.
- Without JavaScript, the book shows readable TeX source in code blocks, so it degrades gracefully.
- Code comments can cite and link equations by stable ID.
cargo xtask equationschecks that IDs are unique and that every citation exists. - The book depends on the CDN at view time. If KaTeX fails to load, the TeX is shown as text.
Alternatives considered
$$and$delimiters with the mdbook-katex preprocessor. Server-side rendering is attractive, but pages written that way render incorrectly on GitHub.- mdBook’s built-in MathJax support. It needs
\\(and\\[delimiters, which GitHub doesn’t understand, and MathJax is heavier than KaTeX. - Vendoring KaTeX into the repository. It works offline, but adds fonts and minified JavaScript to the repository. A pinned CDN copy with integrity hashes gives the same guarantees about what code runs.
ADR 0006: One engine error type, and configuration parsed from TOML text
Context
Errors arise in every layer of the engine:
- configuration problems when airframes and scenarios are loaded;
- non-finite values in the dynamics;
- iterative solvers that fail to converge, such as rotor inflow and trim.
Callers, including the command-line tool, the browser bindings and the Python bindings, need one type to handle. They also need messages that point to the exact cause: for a configuration file, the exact field.
The architecture already says engine crates do no I/O (Architecture), and #7 asks for configuration in TOML with versioned headers, rejection of unknown fields, field-path messages and plausibility checks.
Decision
-
One error type,
EngineError, in a new bottom-layer cratemjk-core. Every engine crate may depend onmjk-core, and it depends on nothing. The enum is#[non_exhaustive]and has three variants:Config { document, path, reason };Numerical { sim_time_s, quantity, value }, wheresim_time_sisNoneoutside a running simulation, for example during trim or analysis;Convergence { solver, iterations, residual }.
The numerical and convergence variants use
&'static strnames, so creating them on the simulation path doesn’t allocate. -
No I/O variant. Engine loaders take the document’s text and a name for messages. Front ends read files and wrap their own I/O errors alongside
EngineError. -
TOML for human-written configuration, parsed with serde. Every document starts with
schema_versionandkind, which are checked before the rest of the document, so version problems are reported first. Configuration structs usedeny_unknown_fields. -
Exact field paths. Paths such as
mass.inertia_kg_m2[1][0]come fromserde_path_to_error, and syntax errors report line and column. Plausibility checks build paths withFieldPath. -
Physical checks live with the physics. For example, the inertia consistency check is
mjk_dynamics::mass::check_inertia. The configuration layer maps its result to a field path. -
Engine dependency allowlist:
libm,serde,serde_path_to_errorandtoml.serde_path_to_erroris added. serde’s derive becomes the one procedural macro allowed in engine crates.
Consequences
- Front ends handle one engine error type, and its messages read
document: field: reason. - Adding a variant is not a breaking change for callers, because the enum is non-exhaustive.
- Fixtures for every class of malformed file, with exact expected paths, are the acceptance tests
for the format (
crates/mjk-sim/tests/airframe_config.rs). - Loading parses the text twice, once for the header and once for the typed document. Documents are small and loaded once, so this costs nothing that matters.
Alternatives considered
- Per-crate error enums. More precise types, but callers would juggle many types, and the information they need (where and why) is the same everywhere.
thiserrororanyhow.thiserroradds another procedural macro for little benefit over a hand-writtenDisplay.anyhowerases the type, which the bindings need to inspect.- Putting
EngineErrorinmjk-math. It avoids a crate, but mixes unrelated concerns into the math layer. - YAML, JSON or RON for configuration. YAML’s implicit typing and significant indentation cause silent errors. JSON has no comments, and comments are where parameter provenance gets explained. RON is less familiar. TOML is explicit, supports comments, and is already familiar from Cargo.
- Recovering paths from TOML error spans by walking the parsed table. Possible without a dependency, but it means more code tied to TOML’s spanned-value API than a small, widely used crate written for exactly this job.
- Hand-written
Deserializeimplementations instead of serde’s derive. Far more code for each format change, with more room for error.
ADR 0007: Operator-grade interface rules for the viewer and the book
Context
ADR 0004 chose the renderer stack but said nothing about the interface around the scene: the on-screen display, telemetry plots, playback controls and debug overlays (#40, #41). The project follows an operator-grade interface standard: dense, token-driven layouts built for a named operator, with a list of banned generic styling (gradients, large radii, decorative color, emoji, slow motion).
Two parts of the project draw pixels without being interface chrome. The 3D scene renders physical light, and a physically based sky is a gradient by nature. The README hero is a marketing graphic. The book is a public site generated by mdBook, which already loads KaTeX from a CDN (ADR 0005).
Decision
- Scope. Interface chrome follows the standard: everything in
viewer/srcthat is not the rendered scene, including elements drawn over it, and the book’s own additions indocs/theme. The rendered scene (sky, lighting, materials, post-processing) is exempt from the surface bans. The README hero (assets/readme) is exempt as a marketing graphic. - Tokens. Every color, size and spacing value in interface code comes from one token file:
viewer/src/styles/tokens.cssfor the viewer (created with the shell in #34) anddocs/theme/tokens.cssfor the book. A color literal anywhere else is a defect. - Stack. The viewer is plain TypeScript and CSS around three.js, with no component library. Adopting one is a new decision record.
- Assets. The viewer self-hosts every asset it loads: fonts, environment maps, textures and the WebAssembly module. No request leaves the site’s origin, so a local build works offline. The book keeps KaTeX from jsDelivr, pinned by version and subresource-integrity hashes: it is only read online, and self-hosting would add about 1 MB of fonts to the repository.
- Enforcement.
npm run lint:uiscansviewer/srcanddocs/themefor the banned patterns on every pull request. Viewer changes also go through the visual loop at 1366×768, 1920×1080 and 2560×1440, which the visual regression suite (#42) automates.
Consequences
- The scan is mechanical, so a ban cannot be broken by accident; it can only be changed by editing the scan, which is reviewed.
- Interface work starts from an operator statement and a token file, which adds a step before the first panel is built.
- The exemption for the scene must be applied honestly: a gradient behind a HUD panel is chrome, not sky.
- The offline viewer needs its fonts and environment maps committed or fetched at build time, with their licenses recorded.
Alternatives considered
- Apply the surface bans to the scene too. This would forbid a physically based sky and tone-mapped lighting, which are the point of the renderer.
- Self-host KaTeX in the book. It only helps readers without network access, who cannot load the book from GitHub Pages anyway.
- A component library for the viewer. The interface is a few dense panels over a canvas; a library’s layout and theming would be overridden more than used.
Engineering standards
A flight dynamics engine is only as credible as the evidence that its code does what its pages say. This page describes the rules the code follows, how each one is enforced, and how the tests themselves are tested. CONTRIBUTING.md has the same rules as a checklist, with the commands to run them.
The rules come from the Power of Ten, NASA/JPL’s rules for safety-critical code, adapted to Rust, TypeScript and Python. The adaptation keeps their purpose: code whose control flow, memory use and failure modes can be checked by a tool rather than trusted.
When the checks run
| When | What runs |
|---|---|
Every pull request, before it can merge, and every push to main | Formatting, Clippy, tests, crate layering, the Power of Ten checks, cargo-deny, spelling, coverage, mutation testing of the changed lines, API docs, the WebAssembly build, the native-against-WebAssembly comparison, the viewer and script checks, the book build |
| Daily | The same suite, so a newly published advisory against a locked dependency fails within a day |
| Weekly | Tests on macOS and Windows; mutation testing of the whole engine; PractRand on interleaved random streams; Dependabot updates |
The pull-request checks are required, not advisory. main accepts a change only through a pull
request that has passed all fourteen, and no one can bypass the rule, admins included. The rule is
the versioned ruleset .github/rulesets/main.json, and cargo xtask standards fails if it and
the workflows disagree about which checks exist
(CONTRIBUTING).
Rust: the Power of Ten
| # | Rule | Enforced by |
|---|---|---|
| 1 | Simple control flow, no recursion | Clippy excessive_nesting; call-graph cycle check |
| 2 | Every loop has a fixed upper bound | // bound: comment on every loop and while; Clippy infinite_loop |
| 3 | No heap allocation after initialization | A counting global allocator proves a world step allocates nothing over 10⁵ steps |
| 4 | Functions of at most 50 lines | Clippy too_many_lines |
| 5 | Assertions state preconditions | Review, with assertion density reported per crate |
| 6 | Smallest possible scope | Compiler; Clippy shadow_unrelated |
| 7 | Check every return value | unused_must_use, let_underscore_must_use, let_underscore_untyped; no unwrap, expect or panic! |
| 8 | Limited preprocessor | No macro_rules!, no conditional compilation outside tests; serde’s derive is the only procedural macro in the engine |
| 9 | Restricted pointers | unsafe forbidden, except one audited test allocator; no dyn trait objects or function pointer types |
| 10 | All warnings on, analyzed daily | -D warnings, Clippy pedantic, the gates below, daily CI |
Rules 2, 8 and 9 and the assertion report come from cargo xtask standards, which parses every
crate’s source with syn. Test code is exempt from them.
Finding recursion in compiled code
A call graph built from source needs type inference to know which function a method call reaches,
and the compiler has already done that work. So the recursion check reads the compiler’s output:
it builds every workspace target unoptimized, with one codegen unit, as LLVM IR. In that IR every
direct call is explicit, including calls through generics (after monomorphization), trait methods
and closures. A breadth-first search from each of our functions looks for a path back to itself,
and the shortest such cycle is reported with demangled names, for example
mjk_dynamics::ping → mjk_dynamics::Pong::pong → mjk_dynamics::ping.
Cycles entirely inside the standard library, such as the recursion in its sort, are ignored. A cycle that leaves our code and comes back through a library callback is reported. Calls through trait objects or function pointers would be invisible in IR, which is one reason rule 9 bans them: the two rules close each other’s gaps.
The check was shown to catch direct recursion, mutual recursion through a method, and each of the other source rules, on a deliberately bad sample, before it was enabled.
The one exemption is xtask, the repository’s tooling. It walks syntax trees with syn’s
visitor, which recurses with the depth of the source’s own nesting.
Proving a step allocates nothing
Rule 3 is checked by running the world under a counting global allocator: a test binary built
without the test harness, so no other thread allocates while it measures, takes $10^5$ steps
with RK4 and with RKMK4 and fails if the allocation count moves. Planting a single Vec in a
500 Hz controller makes it report 55 050 allocations, one per controller run. The same test
records 1000 checkpoint hashes and 1000 inputs and replays them; a checkpoint record that skips
reserving its room reports 9 allocations as it grows.
Implementing GlobalAlloc is unsafe by definition, so that allocator is the repository’s only
unsafe code. It lives in a test-support crate, mjk-alloc-counter: every method forwards to the
system allocator unchanged, each unsafe block carries a SAFETY: comment that Clippy requires,
and the layering check lets crates use it only as a development dependency. Every other crate
forbids unsafe outright. Because Cargo cannot override one workspace lint, the crate repeats
the whole lint table, and cargo xtask standards fails if the copy differs from the workspace’s
in anything but unsafe_code and the SAFETY: comment rule.
Bit-exact arithmetic
Clippy’s disallowed-methods list rejects the standard library’s transcendental functions and
mul_add, for f64 and f32 and in tests too, so every target computes them with the same
libm code. The CI job Native and WebAssembly agree runs both validation studies natively and
as a WASI build under Node, and fails on any byte that differs from the other run or from the
book (Determinism and replay).
Nesting
Clippy’s excessive_nesting counts an impl block as a level. With the threshold at 4, a free
function may nest three levels deep and a method two. Deeper logic moves into a named helper.
Assertions
Engine functions that take physical quantities check their preconditions with debug_assert!:
a unit quaternion’s norm, the domain $\lVert\boldsymbol\theta\rVert < 2\pi$ of the SO(3)
Jacobians, a finite interpolation parameter, a symmetric matrix for the eigen-decomposition.
There is no per-function quota, because a quota produces assertions that check nothing. The
density is reported per crate so a drop shows up in review.
Testing the tests
Passing tests show that the code does what the tests check. Two gates measure how much that is.
- Coverage. Engine line coverage must stay at or above 90 %. Coverage shows which lines ran, not whether any test would notice if they were wrong.
- Mutation testing answers that.
cargo-mutantsmakes small changes to the code, one at a time:<to<=,+to-, a function body replaced by a default value. If every test still passes, the mutant has survived, and the tests do not pin that behavior. CI mutates the lines each change touches, and any survivor fails it. A weekly run mutates the whole engine.
What mutation testing found
When the gate was introduced, a full run made 1,369 mutants of the engine, and 144 survived, though line coverage was already above 90 %. The largest group, 65 survivors, was in the inertia-tensor check. Mutating its 2×2 and 3×3 principal minors, or the tolerance attached to each, changed nothing that any test observed.
The check accepts a symmetric tensor $J$ as the inertia of a rigid body when the second-moment
matrix $S = \tfrac12\,\mathrm{tr}(J)\,I - J$ is positive semidefinite. That is equivalent to the
triangle inequality on the principal moments. It tests all seven principal minors of $S$, each
against an allowance of the relative tolerance times the tensor’s largest entry to the power of
the minor’s order. The existing tests violated the triangle inequality so badly that the first
diagonal minor always caught it, so nothing tested the rest.
The new tests are built so that exactly one kind of minor can detect the violation:
- A diagonal minor. For a plate with largest moment $
L$ that violates the inequality by $\Delta$, $S$ has eigenvalues $(L/2,\ L/2,\ -\Delta/2)$. A diagonal entry crosses its allowance at $\Delta = 2\,\mathrm{tol}\,L$, a 2×2 minor at $4\,\mathrm{tol}\,L$, and the determinant at $8\,\mathrm{tol}\,L$. A plate with $\Delta = 3\,\mathrm{tol}\,L$ is rejected, by the diagonal alone, and one with $\Delta = \mathrm{tol}\,L$ is accepted. - A 2×2 minor. Give $
S$ eigenvalues $(-\delta,\ a,\ b)$ and mix the first two at 45° in one coordinate plane. The diagonal stays positive, and the determinant $-\delta a b$ stays inside its allowance. Only that plane’s minor, $-a\delta$, exceeds its own allowance. One case per plane covers all three minors. - The determinant. In a general orientation, with a violation small against the other
eigenvalues, every 2×2 minor is positive. Each equals $
\det S \cdot (S^{-1})_{kk}$, and both factors are negative. Only the determinant detects the violation.
Each case also sits within about a factor of ten of its allowance, at a realistic tensor scale of 0.01 kg·m², so a mutant that divides a tolerance by the tensor’s size instead of multiplying by it, or drops a power of it, is caught. After these and the other new tests (listed on the Validation page), no mutant of the engine survives.
Mutants no test can catch
Some mutants compute the same result as the original for every input. For example, < becomes
<= at the switch point between a series and its closed form, where both are exact to rounding.
These are excluded by name in .cargo/mutants.toml, each with a comment saying why no test can
tell the two versions apart. The list is kept short, and every entry carries its reason.
An exclusion can also expose code that does nothing measurable. Two mutants of the small-angle
logarithm survived because they replaced $q_0^2$ by 1 in the series
$(2/q_0)\,(1 - n^2/(3q_0^2))$. For a unit quaternion $q_0^2 = 1 - n^2$, so the factor
contributes only $O(n^4)$, under $10^{-24}$ where the series is used. The code now evaluates
$(2/q_0)(1 - n^2/3)$, which has the same truncation order and no equivalent mutants
(SO(3) maps).
Spelling
The project writes American English. typos, with its US locale, runs on every change and fails
on misspellings and on British spellings, in prose and inside identifiers: a British spelling in
the middle of a function name fails as readily as one in a sentence. Project terms such as NED and
SITL, and the name Shepperd, are allowed in typos.toml. A British spelling that is also an
American word passes: disc is American English for a compact disc, so the rotor disk is left
to review (below).
Supply chain
- Rust.
cargo-denyfails the build on any RustSec advisory (vulnerable, unmaintained or unsound crates), a yanked crate, a license outside MIT, Apache-2.0 and Unicode-3.0, two versions of one crate, a wildcard version, or a source other than crates.io. Engine crates may depend on only four external crates (libm,serde,serde_path_to_error,toml), enforced by the layering check. - npm. Versions are pinned exactly, and
npm auditmust report nothing. - Updates. Dependabot proposes a release only once it is 14 days old, so a compromised or broken release has time to be noticed. Security updates are not delayed.
- CI. Third-party actions are pinned to full commit SHAs, and checkouts don’t keep credentials. PractRand, the one tool built from source in CI, is checked against the SHA-256 of its archive before it is built.
TypeScript and JavaScript
The viewer, the README hero script and the book’s equation renderer share one ESLint policy,
built on typescript-eslint’s strict type-checked rules, and strict tsconfig settings. JavaScript
files are type-checked from their JSDoc annotations. Functions are limited to 50 lines and three
levels of nesting, with no any, non-null assertions, eval, shadowing or floating promises.
Inline eslint-disable comments are ignored and reported, so no file can switch a rule off.
ESLint cannot see call cycles, so recursion is a review item in TypeScript.
Interface
Interface code follows ADR 0007: one token file for every color, size and spacing value; no gradients, blur, radius above 4 px, shadows except on floating layers, decorative color, emoji or slow motion; and self-hosted assets. A scan for the banned patterns runs in CI over the viewer and this book’s theme. The rendered 3D scene is exempt, because a physically based sky is rendering, not decoration.
Python
Python arrives with the bindings (#78). It
will follow the same principles with ruff and mypy --strict, in CI from its first commit.
What review still covers
| Item | Why a tool doesn’t check it |
|---|---|
| Whether an assertion states a real precondition | Only a reader can judge what a precondition should be |
Units in names of physical quantities (mass_kg, omega_rad_s) | Names carry meaning a linter cannot infer |
| Recursion in TypeScript | ESLint has no call-graph rule |
@returns on JavaScript functions | ESLint’s return-type rules read TypeScript syntax only |
| Disk, not disc, for the rotor disk and disk loading | Disc is also American English, so typos accepts it |
Writing documentation
Pages are Markdown in docs/src/, built with mdBook 0.5.4. They must read correctly both on
GitHub and in the book (ADR 0005).
Math
-
Display equations are fenced blocks with the language
math, ending with the equation’s ID:```math \dot{\mathbf{q}}_{WB} = \tfrac{1}{2}\,\mathbf{q}_{WB}\otimes(0,\ \boldsymbol{\omega}^B) \qquad\text{(CONV-9)} ``` -
Inline math is a code span wrapped in dollar signs:
$`\alpha`$renders as $\alpha$. -
Not allowed:
$$blocks and plain$…$(GitHub mangles them),\tag(breaks layout), and\operatorname(rejected by GitHub; use\mathrm{…}). -
Use the symbols from the conventions. If a source uses different notation, give the mapping on the page.
Equation IDs and citations
- An ID is a page prefix from the models registry, a hyphen, and a number:
BEMT-4. IDs are never reused or renumbered once published. New equations take the next free number, even if that means the numbers on a page are out of order. - Each tagged equation has an anchor, so pages link to it as
conventions.md#eq-CONV-9. - Code cites equations in comments as
// Eq. (CONV-9). cargo xtask equationsfails if an ID is duplicated, malformed, or cited from code without existing in the docs. CI runs it on every pull request.
Style
- Plain, direct sentences. Define a term before using it.
- State assumptions and validity ranges with numbers.
- Cite sources in full at the end of the page. Link issues by URL so links work outside GitHub.
Building and previewing
cargo install mdbook --version 0.5.4 --locked
mdbook serve docs --open
CI builds the book on every pull request and publishes it to GitHub Pages from main.
Model page template
Every physical model gets a page in docs/src/models/, built from this template. Reserve an
equation prefix in the models registry in the same pull request.
# Model name
- **Issue:** #NN
- **Code:** `crate::module` (link to the source)
- **Equation prefix:** `ABC`
## Summary
What the model computes, what it is for, and which fidelity tier it belongs to.
## Assumptions
Numbered, specific and checkable, for example: "Inflow is uniform across the disk."
## Equations
Symbols follow the conventions page. Each display equation ends with its ID:
```math
T = C_{T,\text{prop}}\,\rho\,n^2 D^4 \qquad\text{(ABC-1)}
```
Inline math is written $`\rho`$. Derivations go here, or are cited when they are standard.
## Validity range
Where the model holds, with numbers, and what the engine does outside that range.
## Parameters
| Symbol | Meaning | Unit | Typical value | Source |
|---|---|---|---|---|
## Implementation notes
Numerical method, iteration bounds, guards, and how the code maps to the equations: cite
`// Eq. (ABC-1)` in the code.
## Validation
The tests that check this model, their tolerances and results, and known limitations.
## References
Full citations.
Decision record template
Copy this into docs/src/adr/NNNN-short-title.md, add it to SUMMARY.md and to the index in
Decision records.
# ADR NNNN: Decision in a few words
- **Status:** Proposed | Accepted | Superseded by ADR NNNN | Rejected
- **Date:** YYYY-MM-DD
- **Issues:** links to the issues this decision affects
## Context
The problem, the forces at play and the constraints. Facts, not advocacy.
## Decision
What was decided, stated so someone could check whether the code follows it.
## Consequences
What becomes easier, what becomes harder, and what must now be tested or monitored.
## Alternatives considered
- **Alternative.** Why it was not chosen, in one or two sentences.