Algorithm Search⌘K

Algorithmresearch

Geometric tracking control on SE(3)

Also called Lee-Leok-McClamroch controller.

Quadrotor position and attitude tracking with errors on SO(3); exponentially stable below 90 degrees of attitude error, almost globally attractive below 180.

Time
O(1) worst
Space
O(1) extra
Where
s = the size of the state, fixed at 18 numbers (position, velocity, rotation matrix, angular velocity); the bounds are for one control step
Properties
deterministicnot exactonlinenot randomized
Origin
Taeyoung Lee, Melvin Leok, N. Harris McClamroch, 2010

Geometric tracking control on SE(3) is a feedback law that makes a quadrotor follow a desired position xd(t)x_d(t) and a desired heading. It works with the rotation matrix RR directly and does not use Euler angles or quaternions, so it has no singularity of a chart and no double cover. The outer loop computes the force AA that the vehicle should produce; the thrust is the part of AA along the current body zz axis, and the desired attitude RdR_d turns the body zz axis toward AA. The inner loop drives the attitude error eR=12(RdTR−RTRd)∨e_R = \tfrac12(R_d^TR - R^TR_d)^\vee to zero with a proportional and derivative term on SO(3) plus a feedforward that cancels the gyroscopic term. Lee, Leok and McClamroch proved that the attitude loop is exponentially stable when the attitude error is less than 90 degrees, and that the full error converges exponentially from almost every attitude error less than 180 degrees. These are theorems for the continuous-time law with exact derivatives of RdR_d. The page uses a z-up world frame; the paper uses z down, and the page converts every sign.

In plain words

A quadrotor can only push along one direction, straight out of its top. To move sideways, it must first tilt. So the controller works in two layers. The outer layer says where the push should point and how hard it should be, from the position error and the speed error. The inner layer turns the body toward that direction, and the motors give the part of the push that the body can give in its current attitude.

The inner layer measures the attitude error on the set of all orientations itself, not in angles. This avoids the bad points that angle sets have. One problem remains: when the vehicle is exactly upside down from the wanted attitude, no single direction of turning is best. The law handles every other start, even one that is almost upside down.

The problem

The model. The vehicle is a rigid body with mass mm and body inertia JJ, with the world zz axis up and gravity −ge3-ge_3, g=9.81g = 9.81 m/s². The thrust ff acts along the third column of the rotation RR, and the moment MM acts in body coordinates:

x˙=v,mv˙=fRe3−mge3,R˙=RΩ^,JΩ˙=M−Ω×JΩ.\dot x = v,\quad m\dot v = fRe_3 - mge_3,\quad \dot R = R\hat\Omega,\quad J\dot\Omega = M - \Omega\times J\Omega.

Here Ω^\hat\Omega is the skew-symmetric matrix of the body angular velocity Ω\Omega. The four rotor forces map to (f,M)(f, M) through an invertible matrix, given on the quadrotor dynamics page. Arithmetic, square roots and trigonometric functions cost one step each, as in the real RAM.

Input. The state (x,v,R,Ω)(x, v, R, \Omega); the reference xd,x˙d,x¨dx_d, \dot x_d, \ddot x_d and a unit vector b1db_{1d} that gives the wanted heading; the gains kx,kv,kR,kΩ>0k_x, k_v, k_R, k_\Omega > 0; mm, JJ and the control period Δt\Delta t.

Output. The thrust ff in newtons and the moment MM in newton meters, held for one control period.

How it differs from close pages. A cascade of PID controllers on roll, pitch and yaw angles works near hover and fails near the singularity of the Euler angles. A law on unit quaternions must choose one of the two quaternions for each attitude, and a careless choice makes the vehicle turn the long way round. Feedback linearization needs local coordinates. Model predictive control handles rotor limits but costs much more per step. The differential flatness of the quadrotor gives the feedforward RdR_d, Ωd\Omega_d and Ω˙d\dot\Omega_d along a smooth trajectory, and this law is the usual feedback around it.

The algorithm

  1. GEOMETRIC-CONTROL(x, v, R, Ω; xd, vd, ad, b1d)
  2. 1ex ← x - xd; ev ← v - vd
  3. 2A ← -kx ex - kv ev + m g e3 + m ad
  4. 3f ← A · (R e3)
  5. 4b3d ← A / |A|; b2d ← b3d × b1d / |b3d × b1d|; Rd ← [b2d × b3d, b2d, b3d]
  6. 5Ωd, Ω̇d ← the angular velocity and acceleration of Rd, given or from differences of Rd
  7. 6eR ← (1/2) (Rd^T R - R^T Rd)^∨; eΩ ← Ω - R^T Rd Ωd
  8. 7M ← -kR eR - kΩ eΩ + Ω × JΩ - J (Ω̂ R^T Rd Ωd - R^T Rd Ω̇d)
  9. 8apply (f, M) for one control period; repeat from L1

Line L2 is the force that would make the position error obey the stable linear equation me¨x=−kxex−kve˙xm\ddot e_x = -k_xe_x - k_v\dot e_x if the body zz axis pointed along AA. Line L3 takes only the part of AA that the body can give now. Line L4 needs A≠0A \ne 0 and b1db_{1d} not parallel to AA; the code raises an error in these cases. The first column of RdR_d is the projection of b1db_{1d} onto the plane normal to b3db_{3d}, so the heading is followed as closely as the thrust direction allows. Version 1 of the paper on arXiv writes RdR_d without the normalization of b2db_{2d}; the normalized form here is a rotation for every valid input. Line L5 in the code uses Ωd=log⁡(Rd,k−1TRd,k)∨/Δt\Omega_d = \log(R_{d,k-1}^TR_{d,k})^\vee/\Delta t with the SO(3) logarithm and a backward difference of Ωd\Omega_d for Ω˙d\dot\Omega_d, when the caller does not give them. Line L8 integrates the model with the classical Runge-Kutta method, with (f,M)(f, M) held, and re-orthonormalizes RR.

Example

Take the vehicle of the paper: m=4.34m = 4.34 kg, J=diag⁡(0.0820,0.0845,0.1377)J = \operatorname{diag}(0.0820, 0.0845, 0.1377) kg m², kx=16mk_x = 16m, kv=5.6mk_v = 5.6m, kR=8.81k_R = 8.81, kΩ=2.54k_\Omega = 2.54. The vehicle hovers level (R=IR = I, v=0v = 0, Ω=0\Omega = 0) at x=(1,0,0)x = (1, 0, 0) m, and the target is the origin with b1d=(1,0,0)b_{1d} = (1, 0, 0).

Line L2 gives A=(−16⋅4.34,0,4.34⋅9.81)=(−69.44,0,42.575)A = (-16 \cdot 4.34, 0, 4.34 \cdot 9.81) = (-69.44, 0, 42.575) N. Line L3 gives f=42.575f = 42.575 N, which is mgmg: the body zz axis is still vertical. Line L4 gives ∣A∣=81.453|A| = 81.453 N and b3d=(−0.8525,0,0.5227)b_{3d} = (-0.8525, 0, 0.5227), a tilt of 58.5 degrees toward the target; b2d=(0,1,0)b_{2d} = (0, 1, 0) and b1db_{1d} becomes (0.5227,0,0.8525)(0.5227, 0, 0.8525). Line L6 gives Ψ=1−cos⁡58.5°=0.4773\Psi = 1 - \cos 58.5° = 0.4773 and eR=(0,0.8525,0)e_R = (0, 0.8525, 0), and line L7 gives M=(0,−7.511,0)M = (0, -7.511, 0) N m, a moment that tips the nose toward −x-x. Measured: in the simulation with Δt=10\Delta t = 10 ms, the position error stays below 1 cm after 1.81 s, and the attitude error never exceeds its first value. The large tilt shows that these gains are aggressive for a 1 m step; a real vehicle limits the tilt and the thrust.

The paper's two simulations, converted to z up:

Case Start Measured with this code (Δt=10\Delta t = 10 ms) Reported in the paper
I: elliptic helix xd=(0.4t,−0.4sin⁡πt,−0.6cos⁡πt)x_d = (0.4t, -0.4\sin\pi t, -0.6\cos\pi t), b1d=(cos⁡πt,−sin⁡πt,0)b_{1d} = (\cos\pi t, -\sin\pi t, 0) rest at the origin, level position error 5.3 mm at steady state; 2.6 mm at 5 ms, 1.1 mm at 2 ms the error converges
II: hover at the origin rotated 178 degrees about xx, Ψ(0)=1.9994\Psi(0) = 1.9994 Ψ<1\Psi < 1 after 1.29 s, Ψ<10−3\Psi < 10^{-3} after 2.2 s, position error below 1 cm after 3.45 s, largest excursion 1.0 m Ψ<1\Psi < 1 after 0.88 s

The steady error of Case I is proportional to Δt\Delta t, so it comes from the zero-order hold and from the differences of line L5, not from the law. In Case I the first attitude error is Ψ(0)=0.366\Psi(0) = 0.366 here; the paper reports a value below 0.15, and the time of 0.88 s in Case II also differs. The paper does not give every detail of its setup, so these numbers are not expected to match.

Correctness

The proof has four parts. Lemma 1: with RdTR=exp⁡(ξ^)R_d^TR = \exp(\hat\xi) and θ=∣ξ∣\theta = |\xi|, the error function is Ψ=1−cos⁡θ\Psi = 1 - \cos\theta and eR=(sin⁡θ/θ)ξe_R = (\sin\theta/\theta)\xi; so eRe_R is zero both at the target and at every rotation error of 180 degrees. Lemma 2: the moment of line L7 gives the attitude error dynamics Je˙Ω=−kReR−kΩeΩJ\dot e_\Omega = -k_Re_R - k_\Omega e_\Omega. Theorem 1 uses the Lyapunov function 12eΩ⋅JeΩ+kRΨ\tfrac12 e_\Omega\cdot Je_\Omega + k_R\Psi, whose derivative is −kΩ∣eΩ∣2-k_\Omega|e_\Omega|^2, to show that the attitude stays away from the 180 degree set when it starts away from it with a small enough angular velocity. Theorem 2 adds a cross term and gives exponential stability of the attitude. Theorem 3 quotes Propositions 2 and 3 of the paper for the full loop: exponential stability when Ψ(0)<1\Psi(0) < 1 (less than 90 degrees) and the gains meet the inequalities of the paper, and almost global exponential attractiveness for 1≤Ψ(0)<21 \le \Psi(0) < 2. Because of the topology of SO(3), no continuous feedback can stabilize one attitude from every start, so a continuous law cannot remove the 180 degree set.

Proof: The attitude loop of the geometric controller is stable, and the position loop converges near the desired pathfull

Line numbers refer to the pseudocode on the geometric tracking control on SE(3) page. The frame convention is z up, as on the page: mv˙=fRe3−mge3m\dot v = fRe_3 - mge_3. Lee, Leok and McClamroch write the same equations with z down; the attitude equations are the same in both conventions, and the position equations differ only by the signs of gg and ff (see Lemma 3). This proof covers the continuous-time law with exact Ωd\Omega_d and Ω˙d\dot\Omega_d. The implementation holds the command for one control period and estimates Ωd\Omega_d by backward differences, so its results are measurements; the tests check them.

Notation: a^\hat a is the skew-symmetric matrix of a∈R3a \in \mathbb{R}^3, with a^b=a×b\hat a b = a \times b, and (⋅)∨(\cdot)^\vee is its inverse. Ψ=12tr⁡(I−RdTR)\Psi = \tfrac12\operatorname{tr}(I - R_d^TR), eR=12(RdTR−RTRd)∨e_R = \tfrac12(R_d^TR - R^TR_d)^\vee, eΩ=Ω−RTRdΩde_\Omega = \Omega - R^TR_d\Omega_d.

Lemma 1 (the errors in terms of the angle). Let RdTR=exp⁡(ξ^)R_d^TR = \exp(\hat\xi) with θ=∥ξ∥∈[0,π]\theta = \|\xi\| \in [0, \pi]. Then Ψ=1−cos⁡θ\Psi = 1 - \cos\theta and eR=(sin⁡θ/θ) ξe_R = (\sin\theta/\theta)\,\xi (with eR=ξ=0e_R = \xi = 0 at θ=0\theta = 0). So Ψ∈[0,2]\Psi \in [0, 2], Ψ=0\Psi = 0 only at R=RdR = R_d, Ψ=2\Psi = 2 exactly when the rotation error is π\pi, and there eR=0e_R = 0.

Proof. By Rodrigues' formula, exp⁡(ξ^)=I+sin⁡θ u^+(1−cos⁡θ)u^2\exp(\hat\xi) = I + \sin\theta\,\hat u + (1 - \cos\theta)\hat u^2 with u=ξ/θu = \xi/\theta. The trace of u^\hat u is 0 and the trace of u^2\hat u^2 is −2-2, so the trace of exp⁡(ξ^)\exp(\hat\xi) is 1+2cos⁡θ1 + 2\cos\theta and Ψ=12(3−1−2cos⁡θ)=1−cos⁡θ\Psi = \tfrac12(3 - 1 - 2\cos\theta) = 1 - \cos\theta. The skew part of exp⁡(ξ^)\exp(\hat\xi) is sin⁡θ u^\sin\theta\,\hat u, so eR=sin⁡θ ue_R = \sin\theta\,u. □\square

The test test_errors_match_the_logarithm checks both formulas on 300 random cases to 10−1210^{-12}, and test_upside_down_is_a_critical_point checks eR=0e_R = 0 at θ=π\theta = \pi.

Lemma 2 (error dynamics of the attitude). Let Rd(t)R_d(t) be smooth with R˙d=RdΩ^d\dot R_d = R_d\hat\Omega_d. Along the closed loop of lines L6 and L7,

Ψ˙=eR⋅eΩ,e˙R=C(RdTR) eΩ with ∥C∥≤1,Je˙Ω=−kReR−kΩeΩ.\dot\Psi = e_R\cdot e_\Omega,\qquad \dot e_R = C(R_d^TR)\,e_\Omega \text{ with } \|C\| \le 1,\qquad J\dot e_\Omega = -k_Re_R - k_\Omega e_\Omega.

Proof. Let Q=RdTRQ = R_d^TR. Then Q˙=−Ω^dQ+QΩ^=Q(Ω−QTΩd)∧=Qe^Ω\dot Q = -\hat\Omega_dQ + Q\hat\Omega = Q(\Omega - Q^T\Omega_d)^\wedge = Q\hat e_\Omega, using QTa^Q=(QTa)∧Q^T\hat aQ = (Q^Ta)^\wedge. So Ψ˙=−12tr⁡(Qe^Ω)\dot\Psi = -\tfrac12\operatorname{tr}(Q\hat e_\Omega). For any matrix QQ and vector ee, tr⁡(Qe^)=tr⁡(12(Q−QT)e^)=−2 (12(Q−QT))∨⋅e\operatorname{tr}(Q\hat e) = \operatorname{tr}(\tfrac12(Q - Q^T)\hat e) = -2\,\big(\tfrac12(Q - Q^T)\big)^\vee\cdot e, because the symmetric part of QQ is orthogonal to e^\hat e in the trace inner product and tr⁡(a^e^)=−2a⋅e\operatorname{tr}(\hat a\hat e) = -2a\cdot e. Hence Ψ˙=eR⋅eΩ\dot\Psi = e_R\cdot e_\Omega. Next, e˙R=12(Qe^Ω+e^ΩQT)∨\dot e_R = \tfrac12(Q\hat e_\Omega + \hat e_\Omega Q^T)^\vee, and the identity (x^A+ATx^)∨=(tr⁡(A)I−A)x(\hat xA + A^T\hat x)^\vee = (\operatorname{tr}(A)I - A)x gives e˙R=12(tr⁡(QT)I−QT)eΩ=CeΩ\dot e_R = \tfrac12(\operatorname{tr}(Q^T)I - Q^T)e_\Omega = C e_\Omega. With Q=exp⁡(ξ^)Q = \exp(\hat\xi), the eigenvalues of the symmetric part of CC are at most 1 in absolute value; Lee, Leok and McClamroch prove ∥C∥2≤1\|C\|_2 \le 1 in the appendix of their paper. Last, e˙Ω=Ω˙+Ω^QTΩd−QTΩ˙d\dot e_\Omega = \dot\Omega + \hat\Omega Q^T\Omega_d - Q^T\dot\Omega_d, because ddtQT=−e^ΩQT\tfrac{d}{dt}Q^T = -\hat e_\Omega Q^T and e^ΩQTΩd=Ω^QTΩd−(QTΩd)×(QTΩd)=Ω^QTΩd\hat e_\Omega Q^T\Omega_d = \hat\Omega Q^T\Omega_d - (Q^T\Omega_d)\times(Q^T\Omega_d) = \hat\Omega Q^T\Omega_d. Multiply by JJ and put in JΩ˙=M−Ω×JΩJ\dot\Omega = M - \Omega\times J\Omega with MM from line L7: the terms Ω×JΩ\Omega\times J\Omega and J(Ω^QTΩd−QTΩ˙d)J(\hat\Omega Q^T\Omega_d - Q^T\dot\Omega_d) cancel, and Je˙Ω=−kReR−kΩeΩJ\dot e_\Omega = -k_Re_R - k_\Omega e_\Omega remains. □\square

Theorem 1 (the attitude stays away from the upside down set). Let kR,kΩ>0k_R, k_\Omega > 0 and let λM\lambda_M be the largest eigenvalue of JJ. If Ψ(0)<2\Psi(0) < 2 and 12λM∥eΩ(0)∥2<kR(2−Ψ(0))\tfrac12\lambda_M\|e_\Omega(0)\|^2 < k_R(2 - \Psi(0)), then V0=12eΩ⋅JeΩ+kRΨV_0 = \tfrac12 e_\Omega\cdot Je_\Omega + k_R\Psi does not increase, and Ψ(t)≤ψ2<2\Psi(t) \le \psi_2 < 2 for all t≥0t \ge 0 with ψ2=V0(0)/kR\psi_2 = V_0(0)/k_R.

Proof. By Lemma 2, V˙0=eΩ⋅(−kReR−kΩeΩ)+kReR⋅eΩ=−kΩ∥eΩ∥2≤0\dot V_0 = e_\Omega\cdot(-k_Re_R - k_\Omega e_\Omega) + k_Re_R\cdot e_\Omega = -k_\Omega\|e_\Omega\|^2 \le 0. So kRΨ(t)≤V0(t)≤V0(0)≤12λM∥eΩ(0)∥2+kRΨ(0)<2kRk_R\Psi(t) \le V_0(t) \le V_0(0) \le \tfrac12\lambda_M\|e_\Omega(0)\|^2 + k_R\Psi(0) < 2k_R. □\square

This is the step that uses the hypothesis Ψ(0)<2\Psi(0) < 2: the sublevel set {Ψ≤ψ2}\{\Psi \le \psi_2\} with ψ2<2\psi_2 < 2 does not contain the rotation errors of angle π\pi, where Lemma 1 gives eR=0e_R = 0. Version 1 of the paper on arXiv states the bound on ∥eΩ(0)∥\|e_\Omega(0)\| with the smallest eigenvalue of JJ; the argument above needs the largest one, which gives a smaller, safe bound. The test test_attitude_lyapunov_function_does_not_increase integrates the attitude loop with the moment evaluated at every Runge-Kutta stage and checks that V0V_0 does not increase by more than 10−910^{-9} per step, from 4 random starts.

Theorem 2 (exponential stability of the attitude; Proposition 1 of the paper). Under the hypotheses of Theorem 1, the equilibrium eR=eΩ=0e_R = e_\Omega = 0 is exponentially stable: ∥eR∥\|e_R\| and ∥eΩ∥\|e_\Omega\| decay as e−βte^{-\beta t} for some β>0\beta > 0.

Proof. On {Ψ≤ψ2}\{\Psi \le \psi_2\}, Lemma 1 gives 12∥eR∥2≤Ψ≤∥eR∥2/(2−ψ2)\tfrac12\|e_R\|^2 \le \Psi \le \|e_R\|^2/(2 - \psi_2), because ∥eR∥2=sin⁡2θ=Ψ(2−Ψ)\|e_R\|^2 = \sin^2\theta = \Psi(2 - \Psi). Take V2=V0+c2 eR⋅eΩV_2 = V_0 + c_2\,e_R\cdot e_\Omega with a small c2>0c_2 > 0. By Lemma 2, V˙2=−kΩ∥eΩ∥2−c2kR eR⋅J−1eR+c2 CeΩ⋅eΩ−c2kΩ eR⋅J−1eΩ\dot V_2 = -k_\Omega\|e_\Omega\|^2 - c_2k_R\,e_R\cdot J^{-1}e_R + c_2\,Ce_\Omega\cdot e_\Omega - c_2k_\Omega\,e_R\cdot J^{-1}e_\Omega. With ∥C∥≤1\|C\| \le 1 and z=(∥eR∥,∥eΩ∥)z = (\|e_R\|, \|e_\Omega\|), this is at most −zTW2z-z^TW_2z with W2=(c2kR/λM−c2kΩ/(2λm)−c2kΩ/(2λm)kΩ−c2)W_2 = \begin{pmatrix} c_2k_R/\lambda_M & -c_2k_\Omega/(2\lambda_m) \\ -c_2k_\Omega/(2\lambda_m) & k_\Omega - c_2\end{pmatrix}, where λm\lambda_m is the smallest eigenvalue of JJ. For c2c_2 small enough, W2W_2 is positive definite, and V2V_2 lies between two positive definite quadratic forms in zz. Then V˙2≤−β′V2\dot V_2 \le -\beta' V_2 for some β′>0\beta' > 0, and the decay follows. □\square

Theorem 3 (the position loop; Proposition 2 of the paper, quoted). Assume the commanded force AA of line L2 is never zero, b1db_{1d} is never parallel to AA, and ∥mge3+mx¨d∥<B\|mge_3 + m\ddot x_d\| < B for a known BB. If Ψ(0)<1\Psi(0) < 1 and the gains satisfy the inequalities of Proposition 2 of Lee, Leok and McClamroch, then the zero equilibrium of (ex,ev,eR,eΩ)(e_x, e_v, e_R, e_\Omega) is exponentially stable. If 1≤Ψ(0)<21 \le \Psi(0) < 2, the attitude first enters {Ψ<1}\{\Psi < 1\} in finite time by Theorems 1 and 2, and from there the full error converges exponentially; the paper calls this almost global exponential attractiveness (Proposition 3).

Proof sketch. The thrust of line L3 is f=A⋅Re3f = A\cdot Re_3, so fRe3=A+XfRe_3 = A + X with X=(A⋅Re3)Re3−AX = (A\cdot Re_3)Re_3 - A. When R=RdR = R_d, Re3=A/∥A∥Re_3 = A/\|A\| and X=0X = 0. In general ∥X∥=∥A∥sin⁡ϕ\|X\| = \|A\|\sin\phi, where ϕ\phi is the angle between Re3Re_3 and Rde3R_de_3. A rotation by θ\theta turns no unit vector by more than θ\theta, so ϕ≤θ\phi \le \theta. On {Ψ<1}\{\Psi < 1\} the angle θ\theta is less than π/2\pi/2, so sin⁡ϕ≤sin⁡θ=∥eR∥\sin\phi \le \sin\theta = \|e_R\| by Lemma 1, and ∥X∥≤∥A∥ ∥eR∥≤(kx∥ex∥+kv∥ev∥+B)∥eR∥\|X\| \le \|A\|\,\|e_R\| \le (k_x\|e_x\| + k_v\|e_v\| + B)\|e_R\|. The position error then obeys me˙v=−kxex−kvev+Xm\dot e_v = -k_xe_x - k_ve_v + X, a stable linear system with a perturbation that decays with the attitude error. A Lyapunov function that is the sum of a quadratic form in (ex,ev)(e_x, e_v) and V2V_2, with cross terms, has a negative definite derivative under the gain conditions. The full argument is in the appendix of the paper. □\square

Lemma 3 (the change of frame). Let P=diag⁡(1,−1,−1)P = \operatorname{diag}(1, -1, -1), the rotation by π\pi about xx. If (x,v,R)(x, v, R) is a state in the z-up frame, then (Px,Pv,PRP)(Px, Pv, PRP) is the same physical state in the z-down frame of the paper, with the body axes also turned by PP, and the paper's thrust f=−(−kxex−kvev−mge3+mx¨d)⋅Re3f = -(-k_xe_x - k_ve_v - mge_3 + m\ddot x_d)\cdot Re_3 equals the thrust A⋅Re3A\cdot Re_3 of line L3.

Proof. The z-down force is A′=P(−kxex−kvev+mx¨d)−mge3A' = P(-k_xe_x - k_ve_v + m\ddot x_d) - mge_3, and −mge3=P(mge3)-mge_3 = P(mge_3), so A′=PAA' = PA. The paper's body zz axis is PRPe3=−PRe3PRPe_3 = -PRe_3. Then −A′⋅(−PRe3)=PA⋅PRe3=A⋅Re3-A'\cdot(-PRe_3) = PA\cdot PRe_3 = A\cdot Re_3, because PP is orthogonal. □\square

The test test_thrust_matches_the_z_down_form_of_the_paper checks Lemma 3 on 100 random states to 10−910^{-9}.

What the implementation adds. Line L5 estimates Ωd\Omega_d by log⁡(Rd,k−1TRd,k)∨/Δt\log(R_{d,k-1}^TR_{d,k})^\vee/\Delta t and Ω˙d\dot\Omega_d by a backward difference of that. This lags the true values by about half a period, so the hypotheses of Lemma 2 hold only approximately, and a small steady error remains on a moving reference. The test test_tracks_an_elliptic_helix measures it: below 5 mm after 5 s with Δt=5\Delta t = 5 ms. The tests test_hover_from_an_offset and test_recovery_from_almost_upside_down check convergence to the set point from an offset and from a rotation error of 178 degrees.

Complexity

  • Time per step. A fixed number of 3×33 \times 3 matrix products, cross products, one square root for each normalization and, in line L5, one logarithm on SO(3): O(1)O(1). Measured: one call of the command function takes about 150 microseconds in CPython on a laptop.
  • Space. O(1)O(1): the previous RdR_d and Ωd\Omega_d for the differences of line L5.

Properties

  • Coordinate-free. The law uses RR only through matrix products, so it has no gimbal lock and no sign ambiguity of a quaternion.
  • Thrust along the body axis. The thrust of line L3 is never more than ∣A∣|A|, and it is negative when the body zz axis points away from AA. Most rotors cannot reverse, so a real vehicle clamps it at zero.
  • Gains in physical units. The position gains scale with the mass in the paper's example; the attitude gains act on eRe_R, which has no unit.
  • Not exact in discrete time. With a zero-order hold and differences for Ωd\Omega_d, the measured tracking error is proportional to the control period.
  • Almost global, not global. At a rotation error of exactly 180 degrees with zero angular velocity, eR=0e_R = 0 and the attitude loop exerts no moment.

Variants and improvements

  • Given feedforward. Along a trajectory from minimum snap optimization, the flatness map gives Ωd\Omega_d and Ω˙d\dot\Omega_d exactly from the jerk and the snap, and line L5 needs no differences. Mellinger and Kumar used this combination in 2011.
  • Attitude tracking alone. Lines L6 and L7 alone, with RdR_d given by a pilot or a planner, are an attitude controller for any rigid body; Proposition 1 of the paper covers this case.
  • Hybrid control for global results. A switching law with a second error function removes the 180 degree critical set at the cost of a discontinuity; later papers by Lee and others use this.
  • Integral terms and robust terms. Later work adds an integral of the errors or a term for a bounded disturbance, to cancel a constant wind or a wrong mass.
  • Rotor limits. The law does not know the rotor limits. Practical code clamps the tilt in line L4 and the thrust in line L3, which removes the proof.

When to use it

Use it for a quadrotor or another vehicle with one thrust direction that must make large attitude changes: aggressive flight, recovery from a flip, or tracking of fast trajectories. Near hover with small angles, a cascade of PID loops on Euler angles is simpler and works as well. When the rotor limits or obstacles matter, use model predictive control and keep this law as the inner loop or as a fallback.

Pitfalls

  • Frame conventions. The paper uses z down, and the signs of gg and ff differ from code with z up. A wrong sign in line L2 makes the vehicle push itself into the ground.
  • The singular cases of line L4. A=0A = 0 happens when the commanded acceleration equals −ge3-ge_3, for example in a commanded free fall. b1db_{1d} parallel to AA happens when the vehicle must point its thrust along the heading direction. Both make RdR_d undefined; a robust implementation keeps the previous RdR_d or picks another heading vector.
  • Noisy differences. The backward differences of line L5 amplify the noise of RdR_d, which itself depends on the measured position and velocity. Filter them, or use the flatness map.
  • Version of the paper. The bound on the first angular velocity in Proposition 1 of version 1 on arXiv uses the smallest eigenvalue of JJ; the Lyapunov argument needs the largest one. Use the conservative form.
  • Large position errors. With the gains of the example, a 1 m error gives a tilt of 58 degrees and a large thrust. Saturate the position error or plan a feasible trajectory first.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

geometric_tracking_control_se3.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/geometric-tracking-control-se3/. The authors are listed in prov/R3QEN8.jsonl.

"""Geometric tracking control of a quadrotor on SE(3) (Lee, Leok and McClamroch 2010).

Frames and signs. The world frame {s} has its z axis up and gravity is -g e3 with
g = 9.81 m/s^2. The body frame {b} has its z axis along the thrust. The paper uses a
z axis that points down; this file converts every equation to z up (the signs of the
gravity and thrust terms change, the attitude part does not).

Model (rigid body, thrust along the body z axis, moment M in body coordinates):
    x' = v,  m v' = f R e3 - m g e3,  R' = R [W],  J W' = M - W x J W.

Controller, for a desired position xd(t) with its first two derivatives and a desired
heading direction b1d(t):
    ex = x - xd, ev = v - vd
    A  = -kx ex - kv ev + m g e3 + m ad          (the force the body should produce)
    f  = A . (R e3)
    b3d = A / |A|,  b2d = b3d x b1d / |b3d x b1d|,  Rd = [b2d x b3d, b2d, b3d]
    eR = (1/2) vee(Rd^T R - R^T Rd),  eW = W - R^T Rd Wd
    M  = -kR eR - kW eW + W x J W - J ([W] R^T Rd Wd - R^T Rd Wd')
Wd and Wd' are the angular velocity and acceleration of Rd. The caller may give them;
otherwise they are estimated by backward differences of Rd between control steps.
"""

import math

import rbm

E3 = [0.0, 0.0, 1.0]


def psi(r, rd):
    """The attitude error function Psi = (1/2) trace(I - Rd^T R), in [0, 2]."""
    return 0.5 * (3.0 - sum(rd[i][j] * r[i][j] for i in range(3) for j in range(3)))


def attitude_errors(r, w, rd, wd):
    """eR = (1/2) vee(Rd^T R - R^T Rd) and eW = W - R^T Rd Wd."""
    rdt_r = rbm.mul(rbm.transpose(rd), r)
    er = rbm.scale(rbm.vee3(rbm.sub(rdt_r, rbm.transpose(rdt_r))), 0.5)
    rt_rd = rbm.transpose(rdt_r)
    ew = rbm.sub(w, rbm.matvec(rt_rd, wd))
    return er, ew, rt_rd


def attitude_moment(r, w, rd, wd, dwd, J, kr, kw):
    """The moment of the attitude loop, lines L6 and L7 of the page."""
    er, ew, rt_rd = attitude_errors(r, w, rd, wd)  # @line L6
    jw = rbm.matvec(J, w)
    a = rbm.matvec(rt_rd, wd)
    b = rbm.matvec(rt_rd, dwd)
    ff = rbm.matvec(J, rbm.sub(rbm.cross(w, a), b))
    m = [-kr * er[i] - kw * ew[i] + rbm.cross(w, jw)[i] - ff[i] for i in range(3)]  # @line L7
    return m, er, ew


def desired_rotation(a, b1d):
    """Rd = [b2d x b3d, b2d, b3d] with b3d = a / |a|. Needs a != 0 and b1d not parallel to a."""
    na = rbm.norm(a)
    if na == 0.0:
        raise ValueError("the commanded force is zero; the thrust direction is undefined")
    b3 = [x / na for x in a]
    c = rbm.cross(b3, b1d)
    nc = rbm.norm(c)
    if nc < 1e-9:
        raise ValueError("b1d is parallel to the thrust direction")
    b2 = [x / nc for x in c]
    b1 = rbm.cross(b2, b3)
    return [[b1[i], b2[i], b3[i]] for i in range(3)]


class GeometricController:
    """The tracking controller. Gains kx, kv in N/m and N s/m, kR, kW in N m and N m s."""

    def __init__(self, m, J, kx, kv, kr, kw, dt, g=9.81):
        self.m, self.J, self.g, self.dt = m, J, g, dt
        self.kx, self.kv, self.kr, self.kw = kx, kv, kr, kw
        self.rd_prev = None
        self.wd_prev = None
        self.last = {}

    def command(self, state, ref, wd=None, dwd=None):
        """Return (f, M) for state (x, v, R, W) and ref (xd, vd, ad, b1d)."""
        x, v, r, w = state
        xd, vd, ad, b1d = ref
        ex = rbm.sub(x, xd)  # @line L1
        ev = rbm.sub(v, vd)  # @line L1
        a = [-self.kx * ex[i] - self.kv * ev[i] + self.m * self.g * E3[i] + self.m * ad[i] for i in range(3)]  # @line L2
        re3 = [r[0][2], r[1][2], r[2][2]]
        f = rbm.dot(a, re3)  # @line L3
        rd = desired_rotation(a, b1d)  # @line L4
        if wd is None:  # @line L5
            if self.rd_prev is None:
                wd = [0.0, 0.0, 0.0]
            else:
                wd = rbm.scale(rbm.so3_log(rbm.mul(rbm.transpose(self.rd_prev), rd)), 1.0 / self.dt)
            dwd = [0.0] * 3 if self.wd_prev is None else rbm.scale(rbm.sub(wd, self.wd_prev), 1.0 / self.dt)
            self.rd_prev, self.wd_prev = rd, wd
        elif dwd is None:
            dwd = [0.0, 0.0, 0.0]
        m, er, ew = attitude_moment(r, w, rd, wd, dwd, self.J, self.kr, self.kw)  # @line L6
        self.last = {"ex": ex, "ev": ev, "eR": er, "eW": ew, "Rd": rd, "psi": psi(r, rd)}
        return f, m


def dynamics(state, f, moment, m, J, Jinv, g=9.81):
    """Time derivative of (x, v, R, W) with z up."""
    x, v, r, w = state
    re3 = [r[0][2], r[1][2], r[2][2]]
    acc = [f * re3[i] / m - g * E3[i] for i in range(3)]
    rdot = rbm.mul(r, rbm.hat3(w))
    jw = rbm.matvec(J, w)
    wdot = rbm.matvec(Jinv, rbm.sub(moment, rbm.cross(w, jw)))
    return v, acc, rdot, wdot


def _axpy(state, k, h):
    x, v, r, w = state
    dx, dv, dr, dw = k
    return (
        [x[i] + h * dx[i] for i in range(3)],
        [v[i] + h * dv[i] for i in range(3)],
        [[r[i][j] + h * dr[i][j] for j in range(3)] for i in range(3)],
        [w[i] + h * dw[i] for i in range(3)],
    )


def orthonormalize(r):
    """Gram-Schmidt on the columns of r, to remove the drift of the integrator."""
    c0 = [r[i][0] for i in range(3)]
    c1 = [r[i][1] for i in range(3)]
    n0 = rbm.norm(c0)
    c0 = [x / n0 for x in c0]
    d = rbm.dot(c0, c1)
    c1 = [c1[i] - d * c0[i] for i in range(3)]
    n1 = rbm.norm(c1)
    c1 = [x / n1 for x in c1]
    c2 = rbm.cross(c0, c1)
    return [[c0[i], c1[i], c2[i]] for i in range(3)]


def rk4_step(state, f, moment, dt, m, J, Jinv, g=9.81):
    """One classical Runge-Kutta step with f and M held (zero-order hold), then re-orthonormalize R."""
    k1 = dynamics(state, f, moment, m, J, Jinv, g)
    k2 = dynamics(_axpy(state, k1, dt / 2), f, moment, m, J, Jinv, g)
    k3 = dynamics(_axpy(state, k2, dt / 2), f, moment, m, J, Jinv, g)
    k4 = dynamics(_axpy(state, k3, dt), f, moment, m, J, Jinv, g)
    x, v, r, w = state
    out = []
    for idx in range(4):
        a, b, c, d = k1[idx], k2[idx], k3[idx], k4[idx]
        if idx == 2:
            out.append([[r[i][j] + dt / 6 * (a[i][j] + 2 * b[i][j] + 2 * c[i][j] + d[i][j]) for j in range(3)] for i in range(3)])
        else:
            base = state[idx]
            out.append([base[i] + dt / 6 * (a[i] + 2 * b[i] + 2 * c[i] + d[i]) for i in range(3)])
    out[2] = orthonormalize(out[2])
    return tuple(out)


def simulate(ctrl, state, ref_fn, t_end, record=None):
    """Run the closed loop with control period ctrl.dt. ref_fn(t) returns (xd, vd, ad, b1d).

    record(t, state, ctrl) is called after each command, if given. Returns the final state.
    """
    Jinv = rbm.inv(ctrl.J)
    steps = int(round(t_end / ctrl.dt))
    for k in range(steps):
        t = k * ctrl.dt
        f, moment = ctrl.command(state, ref_fn(t))
        if record is not None:
            record(t, state, ctrl)
        state = rk4_step(state, f, moment, ctrl.dt, ctrl.m, ctrl.J, Jinv, ctrl.g)  # @line L8
    return state


def lee_quadrotor(dt):
    """The vehicle and the gains of the numerical example of Lee, Leok and McClamroch (2010)."""
    m = 4.34
    J = [[0.0820, 0.0, 0.0], [0.0, 0.0845, 0.0], [0.0, 0.0, 0.1377]]
    return GeometricController(m, J, 16.0 * m, 5.6 * m, 8.81, 2.54, dt)
rbm.py 482 lines
# SPDX-License-Identifier: MIT
# Shared helper of the robotics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small linear algebra, rotations, poses and quaternions for the robotics pages.

Conventions (Lynch and Park, Modern Robotics, 2017):
- A matrix is a list of rows. A vector is a flat list.
- hat3(w) is the skew-symmetric matrix [w], so that [w] x = w x x.
- A twist or screw is a 6-vector (omega, v), angular part first.
  hat6(V) is the 4x4 matrix [[[omega], v], [0, 0]].
- A pose T is the 4x4 matrix [[R, p], [0, 1]].
- so3_exp and so3_log use exponential coordinates w = omega_hat * theta,
  with theta = |w| in [0, pi] for so3_log.
- se3_exp and se3_log use 6-vectors (w, v) = S * theta.
- Quaternions are Hamilton, scalar first: q = (w, x, y, z), with i j = k.
- Angles are in radians.

The helper holds no algorithm of a robotics page except the four maps
so3_exp, so3_log, se3_exp and se3_log. The pages so3-logarithm-map and
se3-exponential-map hold their own complete versions with comments.
"""

import math

# Below this angle, the coefficient functions of the exponential and the
# logarithm are evaluated by their Taylor series. The first omitted term
# of each series is of order theta^6 and is below 3e-16 for theta < 1e-2;
# it also multiplies [w] or [w]^2, which are small. Above the threshold,
# the closed forms such as (1 - cos(theta)) / theta^2 lose at most about
# 1e-16 / theta^2 to cancellation, which [w] or [w]^2 brings to 1e-14.
SERIES_THETA = 1e-2

# Above pi - NEAR_PI, so3_log takes the axis from the symmetric part of R
# (which is (R + I) / 2 at theta = pi) and not from the skew part.
NEAR_PI = 1e-2

# A pivot whose magnitude is at most PIVOT_TOL times the largest entry of
# the matrix makes solve, inv and pinv_right raise ValueError.
PIVOT_TOL = 1e-12


# ---------------------------------------------------------------- matrices


def zeros(n, m):
    """Return the n by m zero matrix."""
    return [[0.0] * m for _ in range(n)]


def eye(n):
    """Return the n by n identity matrix."""
    return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]


def _is_matrix(a):
    return len(a) > 0 and isinstance(a[0], list)


def add(a, b):
    """Return a + b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x + y for x, y in zip(a, b)]


def sub(a, b):
    """Return a - b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x - y for x, y in zip(a, b)]


def scale(a, s):
    """Return s * a for a vector or a matrix a and a number s."""
    if _is_matrix(a):
        return [[s * x for x in row] for row in a]
    return [s * x for x in a]


def transpose(a):
    """Return the transpose of the matrix a."""
    return [list(col) for col in zip(*a)]


def mul(a, b):
    """Return the matrix product a b."""
    bt = transpose(b)
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """Return the product of the matrix a and the vector x."""
    return [sum(p * q for p, q in zip(row, x)) for row in a]


def dot(x, y):
    """Return the dot product of two vectors."""
    return sum(p * q for p, q in zip(x, y))


def norm(x):
    """Return the Euclidean norm of a vector."""
    return math.sqrt(dot(x, x))


def cross(a, b):
    """Return the cross product a x b of two 3-vectors."""
    return [
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0],
    ]


def _max_abs(a):
    return max((abs(x) for row in a for x in row), default=0.0)


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    a is a square matrix. b is a vector or a matrix with one column per
    right-hand side; the result has the same shape as b. Raise ValueError
    if a pivot is at most PIVOT_TOL times the largest entry of a.
    """
    n = len(a)
    vec = not _is_matrix(b)
    rhs = [[x] for x in b] if vec else [list(row) for row in b]
    m = [list(map(float, row)) + list(map(float, r)) for row, r in zip(a, rhs)]
    k = len(rhs[0]) if rhs else 0
    tol = PIVOT_TOL * _max_abs(a)
    for c in range(n):
        piv = max(range(c, n), key=lambda r: abs(m[r][c]))
        if abs(m[piv][c]) <= tol or m[piv][c] == 0.0:
            raise ValueError("matrix is singular to working precision")
        m[c], m[piv] = m[piv], m[c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            if f != 0.0:
                row_r, row_c = m[r], m[c]
                for j in range(c, n + k):
                    row_r[j] -= f * row_c[j]
    x = [[0.0] * k for _ in range(n)]
    for r in range(n - 1, -1, -1):
        for j in range(k):
            s = m[r][n + j] - sum(m[r][i] * x[i][j] for i in range(r + 1, n))
            x[r][j] = s / m[r][r]
    return [row[0] for row in x] if vec else x


def inv(a):
    """Return the inverse of the square matrix a (see solve for errors)."""
    return solve(a, eye(len(a)))


def det(a):
    """Return the determinant of the square matrix a by elimination."""
    n = len(a)
    m = [list(map(float, row)) for row in a]
    d = 1.0
    for c in range(n):
        piv = max(range(c, n), key=lambda r: abs(m[r][c]))
        if m[piv][c] == 0.0:
            return 0.0
        if piv != c:
            m[c], m[piv] = m[piv], m[c]
            d = -d
        d *= m[c][c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            for j in range(c, n):
                m[r][j] -= f * m[c][j]
    return d


def cholesky(a):
    """Return the lower triangular L with a = L L^T.

    a must be symmetric positive definite. Raise ValueError if a diagonal
    entry of the factor is not positive.
    """
    n = len(a)
    low = zeros(n, n)
    for i in range(n):
        for j in range(i + 1):
            s = a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))
            if i == j:
                if s <= 0.0:
                    raise ValueError("matrix is not positive definite")
                low[i][i] = math.sqrt(s)
            else:
                low[i][j] = s / low[j][j]
    return low


def pinv_right(j):
    """Return the right pseudoinverse J^T (J J^T)^(-1) of a J with full row rank."""
    jt = transpose(j)
    return mul(jt, inv(mul(j, jt)))


# ---------------------------------------------------------------- hat and vee


def hat3(w):
    """Return the 3x3 skew-symmetric matrix [w] of a 3-vector w."""
    return [
        [0.0, -w[2], w[1]],
        [w[2], 0.0, -w[0]],
        [-w[1], w[0], 0.0],
    ]


def vee3(m):
    """Return the 3-vector w of a skew-symmetric matrix m = [w]."""
    return [m[2][1], m[0][2], m[1][0]]


def hat6(v):
    """Return the 4x4 matrix [V] = [[[omega], v], [0, 0]] of V = (omega, v)."""
    w = hat3(v[:3])
    return [
        [w[0][0], w[0][1], w[0][2], v[3]],
        [w[1][0], w[1][1], w[1][2], v[4]],
        [w[2][0], w[2][1], w[2][2], v[5]],
        [0.0, 0.0, 0.0, 0.0],
    ]


def vee6(m):
    """Return the 6-vector (omega, v) of a 4x4 matrix [V]."""
    return [m[2][1], m[0][2], m[1][0], m[0][3], m[1][3], m[2][3]]


# ---------------------------------------------------------------- rotations


def rot_x(a):
    """Return the rotation by a radians about the x axis."""
    c, s = math.cos(a), math.sin(a)
    return [[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]


def rot_y(a):
    """Return the rotation by a radians about the y axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]


def rot_z(a):
    """Return the rotation by a radians about the z axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]


def rpy(roll, pitch, yaw):
    """Return R = Rz(yaw) Ry(pitch) Rx(roll)."""
    return mul(rot_z(yaw), mul(rot_y(pitch), rot_x(roll)))


def so3_exp(w):
    """Return exp([w]) for exponential coordinates w = omega_hat * theta.

    Rodrigues' formula in the form I + A [w] + B [w]^2 with
    A = sin(theta) / theta and B = (1 - cos(theta)) / theta^2.
    """
    t = norm(w)
    if t < SERIES_THETA:
        t2 = t * t
        a = 1.0 - t2 / 6.0 + t2 * t2 / 120.0
        b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
    else:
        a = math.sin(t) / t
        b = (1.0 - math.cos(t)) / (t * t)
    k = hat3(w)
    k2 = mul(k, k)
    return [[(1.0 if i == j else 0.0) + a * k[i][j] + b * k2[i][j] for j in range(3)] for i in range(3)]


def so3_log(r):
    """Return w = omega_hat * theta with exp([w]) = r and theta in [0, pi].

    theta = atan2(|s|, c), where c = (trace(r) - 1) / 2 = cos(theta) and
    s = vee(r - r^T) / 2 = sin(theta) omega_hat. For theta below
    SERIES_THETA, w = s (1 + theta^2 / 6 + 7 theta^4 / 360). For theta
    above pi - NEAR_PI, the axis comes from the symmetric part
    ((r + r^T) / 2 - c I) / (1 - c) = omega_hat omega_hat^T, and its sign
    from s. At theta = pi both signs are valid; the sign is then chosen so
    that the largest component of the axis is positive.
    """
    c = (r[0][0] + r[1][1] + r[2][2] - 1.0) / 2.0
    c = max(-1.0, min(1.0, c))
    s = [(r[2][1] - r[1][2]) / 2.0, (r[0][2] - r[2][0]) / 2.0, (r[1][0] - r[0][1]) / 2.0]
    sn = norm(s)
    t = math.atan2(sn, c)
    if t < SERIES_THETA:
        t2 = t * t
        f = 1.0 + t2 / 6.0 + 7.0 * t2 * t2 / 360.0
        return [f * x for x in s]
    if t <= math.pi - NEAR_PI:
        return [t / sn * x for x in s]
    b = [[(r[i][j] + r[j][i]) / 2.0 - (c if i == j else 0.0) for j in range(3)] for i in range(3)]
    # b = (1 - c) omega_hat omega_hat^T. Its column k with the largest
    # diagonal entry is (1 - c) omega_k omega_hat, with omega_k^2 >= 1/3.
    k = max(range(3), key=lambda i: b[i][i])
    col = [b[i][k] for i in range(3)]
    axis = [x / norm(col) for x in col]
    if dot(axis, s) < 0.0 or (dot(axis, s) == 0.0 and axis[k] < 0.0):
        axis = [-x for x in axis]
    return [t * x for x in axis]


# ---------------------------------------------------------------- poses


def make_T(r, p):
    """Return the 4x4 pose [[r, p], [0, 1]]."""
    return [
        [r[0][0], r[0][1], r[0][2], p[0]],
        [r[1][0], r[1][1], r[1][2], p[1]],
        [r[2][0], r[2][1], r[2][2], p[2]],
        [0.0, 0.0, 0.0, 1.0],
    ]


def _rp(t):
    return [row[:3] for row in t[:3]], [t[0][3], t[1][3], t[2][3]]


def T_inv(t):
    """Return the inverse [[R^T, -R^T p], [0, 1]] of a pose t."""
    r, p = _rp(t)
    rt = transpose(r)
    return make_T(rt, [-x for x in matvec(rt, p)])


def T_apply(t, x):
    """Return R x + p, the image of the point x under the pose t."""
    r, p = _rp(t)
    return add(matvec(r, x), p)


def se3_exp(xi):
    """Return exp([xi]) for a 6-vector xi = (w, v) = S * theta.

    The rotation is so3_exp(w). The translation is G v with
    G = I + B [w] + C [w]^2, B = (1 - cos(theta)) / theta^2 and
    C = (theta - sin(theta)) / theta^3, theta = |w|. For w = 0 this is a
    translation by v.
    """
    w, v = xi[:3], xi[3:]
    t = norm(w)
    if t < SERIES_THETA:
        t2 = t * t
        b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
        c = 1.0 / 6.0 - t2 / 120.0 + t2 * t2 / 5040.0
    else:
        b = (1.0 - math.cos(t)) / (t * t)
        c = (t - math.sin(t)) / (t * t * t)
    k = hat3(w)
    k2 = mul(k, k)
    g = [[(1.0 if i == j else 0.0) + b * k[i][j] + c * k2[i][j] for j in range(3)] for i in range(3)]
    return make_T(so3_exp(w), matvec(g, v))


def se3_log(t):
    """Return the 6-vector xi = (w, v) with se3_exp(xi) = t and |w| in [0, pi].

    w = so3_log(R) and v = G^(-1) p with
    G^(-1) = I - [w] / 2 + D [w]^2, D = (1 - (theta / 2) cot(theta / 2)) / theta^2.
    """
    r, p = _rp(t)
    w = so3_log(r)
    th = norm(w)
    if th < SERIES_THETA:
        t2 = th * th
        d = 1.0 / 12.0 + t2 / 720.0 + t2 * t2 / 30240.0
    else:
        half = th / 2.0
        d = (1.0 - half * math.cos(half) / math.sin(half)) / (th * th)
    k = hat3(w)
    k2 = mul(k, k)
    gi = [[(1.0 if i == j else 0.0) - 0.5 * k[i][j] + d * k2[i][j] for j in range(3)] for i in range(3)]
    return w + matvec(gi, p)


def adjoint(t):
    """Return the 6x6 adjoint [[R, 0], [[p] R, R]] of a pose t."""
    r, p = _rp(t)
    pr = mul(hat3(p), r)
    out = zeros(6, 6)
    for i in range(3):
        for j in range(3):
            out[i][j] = r[i][j]
            out[i + 3][j + 3] = r[i][j]
            out[i + 3][j] = pr[i][j]
    return out


# ---------------------------------------------------------------- quaternions


def quat_mul(q, r):
    """Return the Hamilton product q r of quaternions (w, x, y, z)."""
    a1, b1, c1, d1 = q
    a2, b2, c2, d2 = r
    return [
        a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
        a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
        a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
        a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2,
    ]


def quat_conj(q):
    """Return the conjugate (w, -x, -y, -z)."""
    return [q[0], -q[1], -q[2], -q[3]]


def quat_to_rot(q):
    """Return the rotation matrix of the quaternion q, so that (0, R v) = q (0, v) q*.

    q need not be of unit length; the result is the rotation of q / |q|.
    """
    w, x, y, z = q
    n = w * w + x * x + y * y + z * z
    s = 2.0 / n
    return [
        [1.0 - s * (y * y + z * z), s * (x * y - w * z), s * (x * z + w * y)],
        [s * (x * y + w * z), 1.0 - s * (x * x + z * z), s * (y * z - w * x)],
        [s * (x * z - w * y), s * (y * z + w * x), 1.0 - s * (x * x + y * y)],
    ]


def quat_from_axis_angle(axis, angle):
    """Return (cos(angle / 2), sin(angle / 2) axis / |axis|).

    A zero axis is allowed only with angle 0 (the identity); otherwise
    raise ValueError.
    """
    n = norm(axis)
    if n == 0.0:
        if angle == 0.0:
            return [1.0, 0.0, 0.0, 0.0]
        raise ValueError("zero axis with a nonzero angle")
    s = math.sin(angle / 2.0) / n
    return [math.cos(angle / 2.0), s * axis[0], s * axis[1], s * axis[2]]


# ---------------------------------------------------------------- derivatives


def num_jacobian(f, x, h=1e-6):
    """Return the Jacobian of f at x by central differences with step h.

    f maps a list of n numbers to a list of m numbers; the result is m by n.
    """
    cols = []
    for i in range(len(x)):
        xp = list(x)
        xm = list(x)
        xp[i] += h
        xm[i] -= h
        fp, fm = f(xp), f(xm)
        cols.append([(a - b) / (2.0 * h) for a, b in zip(fp, fm)])
    return transpose(cols)


# ---------------------------------------------------------------- self-test


def self_test():
    """Check the area check values; return True or raise AssertionError."""
    r = so3_exp([2.0 * math.pi / 3.0 / math.sqrt(3.0)] * 3)
    want = [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
    assert max(abs(r[i][j] - want[i][j]) for i in range(3) for j in range(3)) < 1e-12
    w = so3_log(want)
    assert abs(norm(w) - 2.0943951) < 1e-7
    assert max(abs(x - 2.0 * math.pi / 3.0 / math.sqrt(3.0)) for x in w) < 1e-12
    t = se3_exp([0.0, 0.0, math.pi / 2.0, math.pi / 2.0, 0.0, 0.0])
    want_t = make_T(rot_z(math.pi / 2.0), [1.0, 1.0, 0.0])
    assert max(abs(t[i][j] - want_t[i][j]) for i in range(4) for j in range(4)) < 1e-12
    return True
test_geometric_tracking_control_se3.py 192 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/geometric-tracking-control-se3/. The authors are listed in prov/R3QEN8.jsonl.

import math
import random

import rbm
from geometric_tracking_control_se3 import (
    GeometricController,
    attitude_errors,
    attitude_moment,
    desired_rotation,
    lee_quadrotor,
    orthonormalize,
    psi,
    simulate,
)

ZERO = [0.0, 0.0, 0.0]


def rand_rot(rng, max_angle=math.pi):
    axis = [rng.gauss(0.0, 1.0) for _ in range(3)]
    n = rbm.norm(axis)
    ang = rng.uniform(0.0, max_angle)
    return rbm.so3_exp([ang * a / n for a in axis])


def is_rotation(r, tol=1e-12):
    rtr = rbm.mul(rbm.transpose(r), r)
    ok = all(abs(rtr[i][j] - (1.0 if i == j else 0.0)) < tol for i in range(3) for j in range(3))
    return ok and abs(rbm.det(r) - 1.0) < tol


def test_rbm_helper_self_test():
    assert rbm.self_test()


def test_errors_match_the_logarithm():
    # With Rd^T R = exp([xi]) and theta = |xi| < pi: eR = sin(theta) xi / theta and Psi = 1 - cos(theta).
    rng = random.Random(1)
    for _ in range(300):
        rd = rand_rot(rng)
        xi = [rng.uniform(-1.0, 1.0) for _ in range(3)]
        th = rbm.norm(xi)
        if th > 3.0 or th < 1e-6:
            continue
        r = rbm.mul(rd, rbm.so3_exp(xi))
        er, ew, _ = attitude_errors(r, ZERO, rd, ZERO)
        want = [math.sin(th) / th * x for x in xi]
        assert max(abs(a - b) for a, b in zip(er, want)) < 1e-12
        assert abs(psi(r, rd) - (1.0 - math.cos(th))) < 1e-12
        assert max(abs(x) for x in ew) == 0.0


def test_upside_down_is_a_critical_point():
    # At a rotation error of pi, eR = 0: the attitude loop exerts no moment there.
    r = rbm.rot_x(math.pi)
    er, _, _ = attitude_errors(r, ZERO, rbm.eye(3), ZERO)
    assert max(abs(x) for x in er) < 1e-15
    assert abs(psi(r, rbm.eye(3)) - 2.0) < 1e-15


def test_desired_rotation_is_a_rotation_with_the_thrust_axis():
    rng = random.Random(2)
    for _ in range(300):
        a = [rng.uniform(-5, 5), rng.uniform(-5, 5), rng.uniform(1, 50)]
        b1d = [math.cos(rng.uniform(0, 6.3)), math.sin(rng.uniform(0, 6.3)), 0.0]
        rd = desired_rotation(a, b1d)
        assert is_rotation(rd)
        b3 = [rd[i][2] for i in range(3)]
        b2 = [rd[i][1] for i in range(3)]
        na = rbm.norm(a)
        assert max(abs(b3[i] - a[i] / na) for i in range(3)) < 1e-12
        assert abs(rbm.dot(b2, b1d)) < 1e-12


def test_zero_force_is_rejected():
    try:
        desired_rotation([0.0, 0.0, 0.0], [1.0, 0.0, 0.0])
    except ValueError:
        return
    raise AssertionError("expected ValueError")


def test_thrust_matches_the_z_down_form_of_the_paper():
    # Lee et al. write the law with z down: f = -(-kx ex - kv ev - m g e3 + m ad) . R e3.
    # Map a z-up state with P = diag(1, -1, -1): x -> P x, R -> P R P.
    rng = random.Random(3)
    c = lee_quadrotor(0.01)
    p = [1.0, -1.0, -1.0]
    for _ in range(100):
        x = [rng.uniform(-2, 2) for _ in range(3)]
        v = [rng.uniform(-2, 2) for _ in range(3)]
        r = rand_rot(rng, 1.5)
        xd, vd, ad = ([rng.uniform(-2, 2) for _ in range(3)] for _ in range(3))
        f_up, _ = c.command((x, v, r, ZERO), (xd, vd, ad, [1.0, 0.0, 0.0]), ZERO, ZERO)
        rp = [[p[i] * r[i][j] * p[j] for j in range(3)] for i in range(3)]
        exd = [p[i] * (x[i] - xd[i]) for i in range(3)]
        evd = [p[i] * (v[i] - vd[i]) for i in range(3)]
        add = [p[i] * ad[i] for i in range(3)]
        e3 = [0.0, 0.0, 1.0]
        a_dn = [-c.kx * exd[i] - c.kv * evd[i] - c.m * c.g * e3[i] + c.m * add[i] for i in range(3)]
        f_dn = -rbm.dot(a_dn, [rp[0][2], rp[1][2], rp[2][2]])
        assert abs(f_up - f_dn) < 1e-9


def attitude_only(rd, r, w, J, kr, kw, dt, steps):
    """RK4 on (R, W) with the moment evaluated at every stage (continuous feedback), Wd = 0."""
    Jinv = rbm.inv(J)

    def deriv(r, w):
        m, _, _ = attitude_moment(r, w, rd, ZERO, ZERO, J, kr, kw)
        jw = rbm.matvec(J, w)
        return rbm.mul(r, rbm.hat3(w)), rbm.matvec(Jinv, rbm.sub(m, rbm.cross(w, jw)))

    def lyap(r, w):
        return 0.5 * rbm.dot(w, rbm.matvec(J, w)) + kr * psi(r, rd)

    out = [lyap(r, w)]
    for _ in range(steps):
        k1 = deriv(r, w)
        k2 = deriv(rbm.add(r, rbm.scale(k1[0], dt / 2)), rbm.add(w, rbm.scale(k1[1], dt / 2)))
        k3 = deriv(rbm.add(r, rbm.scale(k2[0], dt / 2)), rbm.add(w, rbm.scale(k2[1], dt / 2)))
        k4 = deriv(rbm.add(r, rbm.scale(k3[0], dt)), rbm.add(w, rbm.scale(k3[1], dt)))
        r = orthonormalize([[r[i][j] + dt / 6 * (k1[0][i][j] + 2 * k2[0][i][j] + 2 * k3[0][i][j] + k4[0][i][j]) for j in range(3)] for i in range(3)])
        w = [w[i] + dt / 6 * (k1[1][i] + 2 * k2[1][i] + 2 * k3[1][i] + k4[1][i]) for i in range(3)]
        out.append(lyap(r, w))
    return r, w, out


def test_attitude_lyapunov_function_does_not_increase():
    # With Rd constant and Wd = 0, V = (1/2) W.J W + kR Psi has V' = -kW |W|^2 <= 0.
    rng = random.Random(4)
    c = lee_quadrotor(0.01)
    for _ in range(4):
        rd = rand_rot(rng)
        r = rbm.mul(rd, rand_rot(rng, 3.0))
        w = [rng.uniform(-2, 2) for _ in range(3)]
        r, w, vals = attitude_only(rd, r, w, c.J, c.kr, c.kw, 0.01, 600)
        assert all(b <= a + 1e-9 for a, b in zip(vals, vals[1:]))
        assert vals[-1] < 1e-3 * vals[0]


def test_hover_from_an_offset():
    c = lee_quadrotor(0.01)
    state = ([1.0, -1.0, 0.5], ZERO, rbm.rpy(0.3, -0.2, 1.0), [0.5, 0.0, -0.5])
    fin = simulate(c, state, lambda t: (ZERO, ZERO, ZERO, [1.0, 0.0, 0.0]), 6.0)
    assert rbm.norm(fin[0]) < 1e-3
    assert rbm.norm(fin[1]) < 1e-3
    assert is_rotation(fin[2], 1e-9)


def test_recovery_from_almost_upside_down():
    # Case II of Lee et al., converted to z up: start 178 degrees from the desired attitude.
    c = lee_quadrotor(0.01)
    log = []
    state = (ZERO, ZERO, rbm.rot_x(math.radians(178.0)), ZERO)
    fin = simulate(c, state, lambda t: (ZERO, ZERO, ZERO, [1.0, 0.0, 0.0]), 6.0,
                   record=lambda t, s, cc: log.append((t, cc.last["psi"])))
    assert log[0][1] > 1.999
    assert any(p < 1.0 for t, p in log if t < 2.0)
    assert log[-1][1] < 1e-9
    assert rbm.norm(fin[0]) < 1e-3


def test_tracks_an_elliptic_helix():
    # Case I of Lee et al., converted to z up. The steady error comes from the zero-order
    # hold and the backward differences for Wd, and shrinks with the control period.
    w = math.pi

    def helix(t):
        xd = [0.4 * t, -0.4 * math.sin(w * t), -0.6 * math.cos(w * t)]
        vd = [0.4, -0.4 * w * math.cos(w * t), 0.6 * w * math.sin(w * t)]
        ad = [0.0, 0.4 * w * w * math.sin(w * t), 0.6 * w * w * math.cos(w * t)]
        return xd, vd, ad, [math.cos(w * t), -math.sin(w * t), 0.0]

    c = lee_quadrotor(0.005)
    errs = []
    simulate(c, (ZERO, ZERO, rbm.eye(3), ZERO), helix, 8.0,
             record=lambda t, s, cc: errs.append((t, rbm.norm(cc.last["ex"]))))
    assert errs[0][1] > 0.5
    assert max(e for t, e in errs if t >= 5.0) < 5e-3


def test_gains_do_not_need_the_paper_values():
    # A light vehicle with other gains also hovers; the law has no hidden constants.
    J = [[0.002, 0.0, 0.0], [0.0, 0.002, 0.0], [0.0, 0.0, 0.004]]
    c = GeometricController(0.5, J, 4.0, 2.0, 0.2, 0.03, 0.005)
    fin = simulate(c, ([0.3, 0.2, -0.4], ZERO, rbm.rot_y(1.2), ZERO),
                   lambda t: (ZERO, ZERO, ZERO, [0.0, 1.0, 0.0]), 8.0)
    assert rbm.norm(fin[0]) < 1e-3

History

Attitude control on SO(3) without coordinates goes back to the study of rigid spacecraft. Bhat and Bernstein showed in 2000 that no continuous feedback stabilizes one attitude globally on SO(3), because of its topology. Lee, Leok and McClamroch combined an attitude law on SO(3) with a position loop for a quadrotor and proved the stability results in their paper at the IEEE Conference on Decision and Control in 2010. Mellinger and Kumar used the same attitude error with flat trajectories in 2011, and their demonstrations of aggressive flight made the law common in research code for multirotors.

References

  1. Geometric tracking control of a quadrotor UAV on SE(3), Section II (the model, z down), Section III (the controller, Propositions 1 to 3), Section IV (the numerical example: mass, inertia, gains, Cases I and II) and the Appendix (the proofs); also arXiv:1003.2005
  2. Minimum snap trajectory generation and control for quadrotors, the sections on differential flatness and on the controller (the attitude error on SO(3))
  3. Multirotor aerial vehicles: modeling, estimation, and control of quadrotor, the sections on the dynamic model and on attitude and position control
  4. Modern Robotics: Mechanics, Planning, and Control, Chapter 3 (rotation matrices, the exponential and logarithm on SO(3))

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example