Algorithm Search⌘K

Algorithmcore

Spherical quadrangle interpolation

Also called squad, Shoemake quaternion spline.

Interpolates a sequence of unit quaternions with a C1 curve made of three nested slerps per segment, the spherical form of a cubic curve built by the quadrangle construction.

Time
Θ(n) buildΘ(1) query
Space
Θ(n) extra
Where
n = the number of keys
Properties
deterministicnot exactofflineiterative

Spherical quadrangle interpolation, or squad, makes a smooth curve of unit quaternions through a sequence of key orientations q0,…,qn−1q_0, \dots, q_{n-1}. On the segment from qiq_i to qi+1q_{i+1} it nests three slerps:

squad⁡(qi,qi+1,si,si+1,t)=slerp⁡(slerp⁡(qi,qi+1,t), slerp⁡(si,si+1,t), 2t(1−t)),\operatorname{squad}(q_i, q_{i+1}, s_i, s_{i+1}, t) = \operatorname{slerp}\bigl(\operatorname{slerp}(q_i, q_{i+1}, t),\ \operatorname{slerp}(s_i, s_{i+1}, t),\ 2t(1 - t)\bigr),

with the inner control points si=qiexp⁡(−14(log⁡(qi−1qi+1)+log⁡(qi−1qi−1)))s_i = q_i \exp\bigl(-\tfrac14(\log(q_i^{-1} q_{i+1}) + \log(q_i^{-1} q_{i-1}))\bigr). The curve passes through the keys, and with these control points its first derivative is continuous at each key. Shoemake gave the method in his 1987 course notes, and it is a common way to interpolate orientation keys in animation systems.

In plain words

Slerp turns a body from one key orientation to the next at a steady rate about one fixed axis. If you chain slerps through many keys, the body changes its spin with a jerk at each key. Squad smooths these jerks. For each key it makes one extra helper orientation, which looks at the key before and the key after. Inside a segment it blends two slerps: one between the keys, and one between the helpers. At the two ends of the segment the blend uses only the keys, so the curve still goes through them. In the middle the helpers bend the path, so that the spin at each key is the same when you arrive and when you leave.

The problem

The input is a sequence of unit quaternions q0,…,qn−1q_0, \dots, q_{n-1}, n≥2n \ge 2, in the Hamilton convention with the scalar first, at the times 0,1,…,n−10, 1, \dots, n - 1. They stand for the key orientations of a body, as in keyframe interpolation. The output is a curve q(u)q(u) of unit quaternions, u∈[0,n−1]u \in [0, n - 1], with q(i)=qiq(i) = q_i for each key, and with a continuous first derivative q′(u)q'(u), so that the angular velocity of the body is continuous.

The quaternion logarithm of a unit quaternion (cos⁡φ,sin⁡φ u^)(\cos\varphi, \sin\varphi\,\hat u), φ∈[0,π]\varphi \in [0, \pi], is the pure quaternion (0,φ u^)(0, \varphi\,\hat u), and exp⁡\exp is its inverse. For unit quaternions q−1=q∗q^{-1} = q^*. On a unit quaternion the logarithm is the half of the rotation vector, so it is the SO(3) logarithm divided by 2. Write arc⁡(p,q,t)=pexp⁡(tlog⁡(p∗q))\operatorname{arc}(p, q, t) = p \exp(t \log(p^* q)). This is slerp from pp to qq without the sign test, and it is equal to slerp when p⋅q≥0p \cdot q \ge 0.

The algorithm

The build step makes the key signs consistent and computes the control points. The query step evaluates one segment at a local time t∈[0,1]t \in [0, 1]; for the global time uu, use i=⌊u⌋i = \lfloor u \rfloor and t=u−it = u - i.

  1. SQUAD(q₀, ..., qₙ₋₁; i, t) ▷ unit quaternions; returns the point at time i + t
  2. 1for k ← 1 to n - 1: if qₖ₋₁ · qₖ < 0 then
  3. 2qₖ ← -qₖ ▷ the same rotation, near the previous key
  4. 3s₀ ← q₀; sₙ₋₁ ← qₙ₋₁ ▷ the end keys are their own control points
  5. 4for k ← 1 to n - 2 do
  6. 5a ← log(qₖ* qₖ₊₁) ▷ half the rotation vector to the next key
  7. 6b ← log(qₖ* qₖ₋₁) ▷ half the rotation vector to the previous key
  8. 7sₖ ← qₖ exp(-(a + b) / 4)
  9. 8A ← arc(qᵢ, qᵢ₊₁, t) ▷ the slerp of the keys
  10. 9B ← arc(sᵢ, sᵢ₊₁, t) ▷ the slerp of the control points
  11. 10return arc(A, B, 2t(1 - t))

Lines L1 and L2 replace a key by its negative when it is far from the previous one on the unit sphere, so each step between keys is the short way. Lines L3 to L7 compute the control points; they run once for the whole sequence. Lines L8 to L10 are the query. The weight 2t(1−t)2t(1 - t) is 0 at both ends of the segment, so q(i)=qiq(i) = q_i, and it is at most 12\frac12 in the middle, so the curve never reaches the control points.

Example

Take three keys: q0=(1,0,0,0)q_0 = (1, 0, 0, 0), the identity; q1=(0.70711,0,0,0.70711)q_1 = (0.70711, 0, 0, 0.70711), the rotation by 90 degrees about zz; and q2=q1⋅(0.70711,0.70711,0,0)=(0.5,0.5,0.5,0.5)q_2 = q_1 \cdot (0.70711, 0.70711, 0, 0) = (0.5, 0.5, 0.5, 0.5), a further turn by 90 degrees about the xx axis of the body.

  • Lines L1 and L2: q0⋅q1=0.70711q_0 \cdot q_1 = 0.70711 and q1⋅q2=0.70711q_1 \cdot q_2 = 0.70711, so no key changes sign.
  • Line L3: s0=q0s_0 = q_0 and s2=q2s_2 = q_2.
  • Lines L5 and L6 at k=1k = 1: a=(0,0.7854,0,0)a = (0, 0.7854, 0, 0), half of the turn about xx, and b=(0,0,0,−0.7854)b = (0, 0, 0, -0.7854), half of the turn back about zz.
  • Line L7: −(a+b)/4=(0,−0.19635,0,0.19635)-(a + b)/4 = (0, -0.19635, 0, 0.19635), so s1=(0.54296,−0.13706,−0.13706,0.81708)s_1 = (0.54296, -0.13706, -0.13706, 0.81708).
  • Lines L8 to L10 at i=0i = 0, t=0.5t = 0.5: q(0.5)=(0.90349,−0.03911,−0.03911,0.42503)q(0.5) = (0.90349, -0.03911, -0.03911, 0.42503), a rotation by 0.88591 radians. Plain slerp gives (0.92388,0,0,0.38268)(0.92388, 0, 0, 0.38268), a rotation by π/4\pi/4 about zz.
  • At i=1i = 1, t=0.5t = 0.5: q(1.5)=(0.62514,0.23923,0.23923,0.70337)q(1.5) = (0.62514, 0.23923, 0.23923, 0.70337), a rotation by 1.79096 radians. Plain slerp gives (0.65328,0.27060,0.27060,0.65328)(0.65328, 0.27060, 0.27060, 0.65328).

The body angular velocity at the key q1q_1 shows the difference. With slerp per segment it jumps from (0,0,1.5708)(0, 0, 1.5708) before the key to (1.5708,0,0)(1.5708, 0, 0) after it. With squad it is (0.7854,0,0.7854)(0.7854, 0, 0.7854) from both sides, which is the vector part of a−ba - b.

Correctness

The weight 2t(1−t)2t(1 - t) vanishes at t=0t = 0 and t=1t = 1, and arc⁡(A,B,0)=A\operatorname{arc}(A, B, 0) = A, so the segment starts at qiq_i and ends at qi+1q_{i+1}. Each arc is a product of unit quaternions, so the result has length 1.

For the first derivative, use ∂∂warc⁡(A,B,w)=Alog⁡(A∗B)\frac{\partial}{\partial w}\operatorname{arc}(A, B, w) = A\log(A^* B) at w=0w = 0, where the derivative with respect to BB vanishes. At t=0t = 0 the weight has derivative 2 and A∗B=qi∗si=exp⁡(−(a+b)/4)A^* B = q_i^* s_i = \exp(-(a + b)/4), so

q′(i+)=qia+2qi⋅(−a+b4)=qi a−b2.q'(i^+) = q_i a + 2 q_i \cdot \left(-\tfrac{a + b}{4}\right) = q_i\,\frac{a - b}{2}.

At t=1t = 1 of the segment before, the inner slerp arrives with the derivative qilog⁡(qi−1∗qi)=−qibq_i \log(q_{i-1}^* q_i) = -q_i b, the weight has derivative −2-2, and again A∗B=qi∗siA^* B = q_i^* s_i, so q′(i−)=−qib+qia+b2=qia−b2q'(i^-) = -q_i b + q_i\frac{a + b}{2} = q_i\frac{a - b}{2}. The two sides agree, so the curve is C1C^1 at every inner key. In flat space the same construction gives the tangent 12(qi+1−qi−1)\frac12(q_{i+1} - q_{i-1}), which is the tangent of the Catmull-Rom spline. The proof gives the details.

Proof: Squad passes through the keys, stays on the unit sphere and has a continuous first derivativefull

We use the notation of the page. Quaternions are in the Hamilton convention, scalar first. For a unit quaternion p=(cos⁡φ,sin⁡φ u^)p = (\cos\varphi, \sin\varphi\,\hat u) with φ∈[0,π]\varphi \in [0, \pi], log⁡p=(0,φu^)\log p = (0, \varphi\hat u), and exp⁡(0,v)=(cos⁡∣v∣,sin⁡∣v∣ v/∣v∣)\exp(0, v) = (\cos|v|, \sin|v|\, v/|v|). So exp⁡\exp maps pure quaternions to unit quaternions, and exp⁡(log⁡p)=p\exp(\log p) = p. We write arc⁡(p,q,w)=pexp⁡(wlog⁡(p∗q))\operatorname{arc}(p, q, w) = p\exp(w\log(p^* q)). The keys are at the times 0,1,…,n−10, 1, \dots, n - 1.

Interpolation and unit length

Lemma 1. For unit quaternions pp and qq, arc⁡(p,q,w)\operatorname{arc}(p, q, w) is a unit quaternion, arc⁡(p,q,0)=p\operatorname{arc}(p, q, 0) = p and arc⁡(p,q,1)=q\operatorname{arc}(p, q, 1) = q.

Proof. exp⁡\exp of a pure quaternion has length 1, and a product of unit quaternions has length 1. At w=0w = 0 the factor is exp⁡(0)=1\exp(0) = 1. At w=1w = 1 it is exp⁡(log⁡(p∗q))=p∗q\exp(\log(p^* q)) = p^* q, and pp∗q=qp p^* q = q. □\square

Lemma 2. Segment ii of squad starts at qiq_i and ends at qi+1q_{i+1}, and every point has length 1.

Proof. By Lemma 1, line L8 gives A=qiA = q_i at t=0t = 0 and A=qi+1A = q_{i+1} at t=1t = 1. The weight 2t(1−t)2t(1 - t) of line L10 is 0 at both ends, so by Lemma 1 the result is AA there. All three arcs are unit quaternions by Lemma 1. □\square

Lines L1 and L2 replace qkq_k by −qk-q_k only, which is the same rotation, so the curve passes through the key rotations.

The derivative of an arc

Lemma 3. Let A(t)A(t) and B(t)B(t) be differentiable curves of unit quaternions and w(t)w(t) a differentiable weight with w(t0)=0w(t_0) = 0. Then f(t)=arc⁡(A(t),B(t),w(t))f(t) = \operatorname{arc}(A(t), B(t), w(t)) has f′(t0)=A′(t0)+w′(t0) A(t0)log⁡(A(t0)∗B(t0))f'(t_0) = A'(t_0) + w'(t_0)\, A(t_0)\log(A(t_0)^* B(t_0)), if A(t0)∗B(t0)≠−1A(t_0)^* B(t_0) \ne -1.

Proof. Write L(t)=log⁡(A(t)∗B(t))L(t) = \log(A(t)^* B(t)), which is differentiable near t0t_0 because log⁡\log is smooth away from −1-1. Then f=Aexp⁡(wL)f = A\exp(wL) and f′=A′exp⁡(wL)+A ddtexp⁡(wL)f' = A'\exp(wL) + A\,\frac{d}{dt}\exp(wL). At t0t_0, exp⁡(wL)=1\exp(wL) = 1. The derivative of exp⁡\exp at 0 is the identity on pure quaternions, so ddtexp⁡(wL)=(wL)′=w′L+wL′=w′L\frac{d}{dt}\exp(wL) = (wL)' = w'L + wL' = w'L at t0t_0. □\square

Lemma 4. For a pure quaternion cc with ∣c∣<π|c| < \pi and A(t)=pexp⁡(tc)A(t) = p\exp(tc), A′(t)=A(t) cA'(t) = A(t)\,c.

Proof. The pure quaternions tctc for different tt commute, so exp⁡((t+h)c)=exp⁡(tc)exp⁡(hc)\exp((t + h)c) = \exp(tc)\exp(hc), and ddhexp⁡(hc)=c\frac{d}{dh}\exp(hc) = c at h=0h = 0. □\square

Continuity of the first derivative

Fix an inner key ii, 1≤i≤n−21 \le i \le n - 2, and let a=log⁡(qi∗qi+1)a = \log(q_i^* q_{i+1}), b=log⁡(qi∗qi−1)b = \log(q_i^* q_{i-1}) and e=−(a+b)/4e = -(a + b)/4, as in lines L5 to L7, so that si=qiexp⁡(e)s_i = q_i\exp(e). Assume that adjacent keys are not opposite rotations by a half turn, so that the logarithms are smooth where we use them.

Lemma 5. The right derivative at key ii is qia−b2q_i\frac{a - b}{2}.

Proof. On segment ii, A(t)=arc⁡(qi,qi+1,t)=qiexp⁡(ta)A(t) = \operatorname{arc}(q_i, q_{i+1}, t) = q_i\exp(ta), so A(0)=qiA(0) = q_i and by Lemma 4 A′(0)=qiaA'(0) = q_i a. B(0)=siB(0) = s_i by Lemma 1, w(t)=2t(1−t)w(t) = 2t(1 - t), w(0)=0w(0) = 0 and w′(0)=2w'(0) = 2. A(0)∗B(0)=qi∗qiexp⁡(e)=exp⁡(e)A(0)^* B(0) = q_i^* q_i\exp(e) = \exp(e), and since ∣e∣≤(∣a∣+∣b∣)/4≤π/2|e| \le (|a| + |b|)/4 \le \pi/2, log⁡exp⁡(e)=e\log\exp(e) = e. By Lemma 3, q′(i+)=qia+2qie=qi(a−a+b2)=qia−b2q'(i^+) = q_i a + 2q_i e = q_i(a - \frac{a + b}{2}) = q_i\frac{a - b}{2}. □\square

Lemma 6. The left derivative at key ii is qia−b2q_i\frac{a - b}{2}.

Proof. On segment i−1i - 1, A(t)=qi−1exp⁡(tc)A(t) = q_{i-1}\exp(tc) with c=log⁡(qi−1∗qi)c = \log(q_{i-1}^* q_i). Since qi∗qi−1=(qi−1∗qi)∗q_i^* q_{i-1} = (q_{i-1}^* q_i)^* and log⁡(p∗)=−log⁡p\log(p^*) = -\log p for a unit pp, c=−bc = -b. By Lemma 4, A′(1)=A(1)c=−qibA'(1) = A(1)c = -q_i b. B(1)=siB(1) = s_i by Lemma 1, w(1)=0w(1) = 0 and w′(1)=−2w'(1) = -2. As in Lemma 5, log⁡(A(1)∗B(1))=e\log(A(1)^* B(1)) = e. By Lemma 3, q′(i−)=−qib−2qie=qi(−b+a+b2)=qia−b2q'(i^-) = -q_i b - 2q_i e = q_i(-b + \frac{a + b}{2}) = q_i\frac{a - b}{2}. □\square

Theorem. With keys at equal time steps, squad is continuous with a continuous first derivative on [0,n−1][0, n - 1].

Proof. Inside each segment the curve is a composition of smooth maps. At an inner key the two segments meet at qiq_i by Lemma 2, and their derivatives agree by Lemmas 5 and 6. □\square

The body angular velocity is ω=2 vec(q∗q′)\omega = 2\,\mathrm{vec}(q^* q'), so at key ii it is the vector part of a−ba - b from both sides.

Independence of frames

Lemma 7. For unit quaternions cc and dd, the keys c qk dc\,q_k\,d give the control points c sk dc\,s_k\,d and the curve c q(u) dc\,q(u)\,d.

Proof. (cqkd)∗(cqk+1d)=d∗(qk∗qk+1)d(c q_k d)^*(c q_{k+1} d) = d^*(q_k^* q_{k+1})d. Conjugation by dd is a rotation of the pure quaternions and preserves the angle, so log⁡(d∗p d)=d∗log⁡(p) d\log(d^* p\, d) = d^*\log(p)\, d and exp⁡(d∗v d)=d∗exp⁡(v) d\exp(d^* v\, d) = d^*\exp(v)\, d. Then the control point is cqkd d∗exp⁡(e)d=c sk dc q_k d\, d^*\exp(e)d = c\, s_k\, d. The same identity gives arc⁡(cpd,cqd,w)=carc⁡(p,q,w)d\operatorname{arc}(cpd, cqd, w) = c\operatorname{arc}(p, q, w)d, and the three arcs of the query carry the factors through. The dot products of line L1 do not change, since multiplication by unit quaternions is an isometry of R4\mathbb{R}^4. □\square

Complexity

The build step, lines L1 to L7, takes Θ(n)\Theta(n) time: two logarithms, one exponential and three quaternion products per inner key. It stores the nn control points, Θ(n)\Theta(n) extra space. One query takes Θ(1)\Theta(1) time: three arcs, each with one logarithm, one exponential and two products. If the keys are at uneven times, finding the segment of a time uu takes O(log⁡n)O(\log n) by binary search.

Properties

  • Interpolation. The curve passes through every key, q(i)=qiq(i) = q_i, up to the sign that line L2 chooses.
  • First derivative continuous. With keys at equal time steps, the curve is C1C^1 and the body angular velocity at key ii is the vector part of a−ba - b from both sides.
  • Not C2C^2. The second derivative jumps at the keys in general. In the example the one-sided second differences at q1q_1 differ in each component.
  • Two keys give slerp. For n=2n = 2, s0=q0s_0 = q_0 and s1=q1s_1 = q_1, so lines L8 and L9 give the same point and the curve is the slerp.
  • Keys about one axis. If all keys are rotations about one fixed axis with equal angle steps, then a+b=0a + b = 0, sk=qks_k = q_k, and the curve is slerp at constant speed.
  • Independence of frames. For unit quaternions cc and dd, the keys c qk dc\,q_k\,d give the curve c q(u) dc\,q(u)\,d. So the curve does not depend on the world frame or the body frame.
  • Local control. The control point sks_k depends on the keys k−1k - 1, kk and k+1k + 1, so moving one key changes at most four segments.
  • Not the shortest path. Between keys the curve bends away from the great arc, as the example shows. It does not minimize any energy, and the angular speed is not constant.

Variants and improvements

  • Spherical Bezier curves. Shoemake (1985) built cubic Bezier curves on the sphere with the de Casteljau algorithm, with slerp in place of linear interpolation. It needs six slerps per point. Squad uses three, and in flat space its quadrangle form is the cubic Bezier curve with the control points qiq_i, 13(2si+qi+1)\frac13(2s_i + q_{i+1}), 13(2si+1+qi)\frac13(2s_{i+1} + q_i) and qi+1q_{i+1}.
  • Uneven key times. If segment ii has the duration hih_i, the time derivative of the curve is qia−b2hiq_i\frac{a - b}{2h_i} on the right of key ii and qia−b2hi−1q_i\frac{a - b}{2h_{i-1}} on the left. The axis of the angular velocity stays continuous, but its size jumps. To remove the jump, use e=−(hi−1a+hib)/(2(hi−1+hi))e = -(h_{i-1} a + h_i b) / (2(h_{i-1} + h_i)) in line L7. Then both sides have the derivative qi(a−b)/(hi−1+hi)q_i (a - b)/(h_{i-1} + h_i), by the computation of the Correctness section.
  • Tension, continuity and bias. The control point can use the Kochanek-Bartels weights on aa and bb, as in the scalar case.
  • Cumulative B-spline curves. The cumulative B-spline quaternion curve of Kim, Kim and Shin is C2C^2 and has simple closed forms for its derivatives, but it does not pass through the keys.
  • Rigid motions. For a rotation with a translation, interpolate the translation with a scalar spline, or use dual quaternions, as in dual quaternion skinning for blends of joint transforms.

When to use it

Use squad for camera and joint orientations in keyframe animation when the keys must be hit exactly and the turning must have no jerk at the keys. It is cheap to evaluate, so it suits games and real-time playback. If the keys are only guides and a smoother angular acceleration matters more, use the cumulative B-spline curve. For two keys only, use slerp.

Pitfalls

  • Inconsistent signs. Without lines L1 and L2, the logarithms in lines L5 and L6 measure the long way between two keys, and the body turns by nearly a full turn.
  • Sign tests inside the query. Lines L8 to L10 must not flip the sign of BB when A⋅B<0A \cdot B < 0. A flip changes the result, and the curve then jumps at the time where A⋅BA \cdot B crosses 0.
  • Euler angles. Splines on Euler angles per channel depend on the angle order and fail near gimbal lock. Squad works on the rotations themselves.
  • Speed. The parameter is not the angle. The angular speed varies inside a segment, so a constant speed needs a reparametrization.
  • Logarithm near the angle π\pi. If two adjacent keys differ by a half turn, their logarithm has no unique axis, and a small change of a key switches the path.

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.

anim.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the graphics-and-signals animation and simulation pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small vectors, matrices, polar decomposition, quaternions and transforms.

This file is copied byte for byte into each impl/python folder that needs it.
It holds no method of a page: no curve, no skinning, no integrator step, no
collision test and no solver of a page. The method of each page lives in its
slug file.

Conventions (prompts/graphics-ext.md, "Mathematical conventions"):
- Vectors are tuples. Functions accept lists too and return tuples.
- Matrices are lists of rows, and a matrix acts on a column vector on the
  left: x' = M x.
- Quaternions use the Hamilton convention, scalar first, q = (w, x, y, z)
  with i j = k. A unit quaternion q rotates v by v' = q (0, v) q*.
- The log of a unit quaternion (cos phi, sin phi u) is (0, phi u), and the
  rotation angle is 2 phi. q_exp is the inverse map.
- Angles are in radians.
"""

import math

# Below this angle on the sphere of R^4, slerp uses normalized linear
# interpolation (nlerp), which avoids the division by sin(W).
SLERP_SMALL_ANGLE = 1e-6


# ---------------------------------------------------------------- vectors


def add(a, b):
    """Return a + b."""
    return tuple(x + y for x, y in zip(a, b))


def sub(a, b):
    """Return a - b."""
    return tuple(x - y for x, y in zip(a, b))


def scale(a, s):
    """Return s a for a number s."""
    return tuple(s * x for x in a)


def dot(a, b):
    """Return the dot product of a and b."""
    return sum(x * y for x, y in zip(a, b))


def cross(a, b):
    """Return the cross product of two 3D 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 cross2(a, b):
    """Return the scalar 2D cross product a_x b_y - a_y b_x."""
    return a[0] * b[1] - a[1] * b[0]


def norm(a):
    """Return the Euclidean length of a."""
    return math.sqrt(sum(x * x for x in a))


def normalize(a):
    """Return a / |a|. Raise ValueError for the zero vector."""
    n = norm(a)
    if n == 0.0:
        raise ValueError("cannot normalize the zero vector")
    return tuple(x / n for x in a)


def lerp(a, b, t):
    """Return (1 - t) a + t b."""
    return tuple((1 - t) * x + t * y for x, y in zip(a, b))


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


def zeros(n, m=None):
    """Return the n by m zero matrix (n by n if m is None)."""
    if m is None:
        m = n
    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 mul(a, b):
    """Return the matrix product a b."""
    bt = list(zip(*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 vector a x as a tuple."""
    return tuple(sum(p * q for p, q in zip(row, x)) for row in a)


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


def _lu(a):
    """Gaussian elimination with partial pivoting on a copy of a square a.

    Return (lu, perm, sign), or None if a pivot is exactly zero.
    """
    n = len(a)
    lu = [list(map(float, row)) for row in a]
    perm = list(range(n))
    sign = 1.0
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(lu[i][k]))
        if lu[p][k] == 0.0:
            return None
        if p != k:
            lu[k], lu[p] = lu[p], lu[k]
            perm[k], perm[p] = perm[p], perm[k]
            sign = -sign
        piv = lu[k][k]
        for i in range(k + 1, n):
            f = lu[i][k] / piv
            lu[i][k] = f
            if f != 0.0:
                rk = lu[k]
                ri = lu[i]
                for j in range(k + 1, n):
                    ri[j] -= f * rk[j]
    return lu, perm, sign


def det(a):
    """Return the determinant of a square matrix."""
    n = len(a)
    if n == 1:
        return a[0][0]
    if n == 2:
        return a[0][0] * a[1][1] - a[0][1] * a[1][0]
    if n == 3:
        return (
            a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
            - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
            + a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0])
        )
    r = _lu(a)
    if r is None:
        return 0.0
    lu, _, sign = r
    d = sign
    for i in range(n):
        d *= lu[i][i]
    return d


def _lu_solve(lu, perm, b):
    n = len(lu)
    y = [float(b[perm[i]]) for i in range(n)]
    for i in range(n):
        s = y[i]
        row = lu[i]
        for j in range(i):
            s -= row[j] * y[j]
        y[i] = s
    for i in range(n - 1, -1, -1):
        s = y[i]
        row = lu[i]
        for j in range(i + 1, n):
            s -= row[j] * y[j]
        y[i] = s / row[i]
    return y


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

    b is a vector (returns a list) or a matrix given as a list of rows
    (returns a list of rows, one column of x per column of b).
    Raise ValueError if a is singular.
    """
    r = _lu(a)
    if r is None:
        raise ValueError("singular matrix")
    lu, perm, _ = r
    if len(b) > 0 and isinstance(b[0], (list, tuple)):
        cols = [_lu_solve(lu, perm, col) for col in zip(*b)]
        return [list(row) for row in zip(*cols)]
    return _lu_solve(lu, perm, b)


def inv(a):
    """Return the inverse of a square matrix. Raise ValueError if singular."""
    return solve(a, eye(len(a)))


# ---------------------------------------------------------------- polar decomposition


def rot2(theta):
    """Return the 2 by 2 rotation matrix by the angle theta."""
    c, s = math.cos(theta), math.sin(theta)
    return [[c, -s], [s, c]]


def _frob(a):
    return math.sqrt(sum(x * x for row in a for x in row))


def _sym_eig3(s):
    """Eigenvalues and eigenvectors of a symmetric 3 by 3 matrix (cyclic Jacobi).

    Return (values, vectors), where vectors[k] is the unit eigenvector of
    values[k].
    """
    a = [list(map(float, row)) for row in s]
    v = eye(3)
    for _ in range(50):
        off = a[0][1] ** 2 + a[0][2] ** 2 + a[1][2] ** 2
        if off <= 1e-30 * (sum(a[i][i] ** 2 for i in range(3)) + 1e-300):
            break
        for p, q in ((0, 1), (0, 2), (1, 2)):
            if a[p][q] == 0.0:
                continue
            theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
            t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
            c = 1.0 / math.sqrt(t * t + 1.0)
            sn = t * c
            for k in range(3):
                akp, akq = a[k][p], a[k][q]
                a[k][p] = c * akp - sn * akq
                a[k][q] = sn * akp + c * akq
            for k in range(3):
                apk, aqk = a[p][k], a[q][k]
                a[p][k] = c * apk - sn * aqk
                a[q][k] = sn * apk + c * aqk
            for k in range(3):
                vkp, vkq = v[k][p], v[k][q]
                v[k][p] = c * vkp - sn * vkq
                v[k][q] = sn * vkp + c * vkq
    values = [a[i][i] for i in range(3)]
    vectors = [tuple(v[k][i] for k in range(3)) for i in range(3)]
    return values, vectors


def polar(f, tol=1e-14, max_iter=100):
    """Return (R, S) with F = R S, det R = +1 and S symmetric.

    2 by 2: closed form. R = rot2(theta) with theta = atan2(f10 - f01, f00 + f11),
    the rotation that maximizes trace(R^T F), and S = R^T F.
    3 by 3: the Newton iteration X <- (X + X^(-T)) / 2 of Higham (1986), with
    the scaling gamma = (|X^(-1)|_F / |X|_F)^(1/2) while the relative change
    is above 1e-2. It stops when the relative change in the Frobenius norm is
    at most tol, or after max_iter steps. The iteration gives the orthogonal
    polar factor U. If det U < 0 (det F < 0), R = U (I - 2 v v^T) for the unit
    eigenvector v of the smallest eigenvalue of U^T F, so that det R = +1.
    If det F > 0, S is symmetric positive definite. If det F < 0, S is
    symmetric with one negative eigenvalue. Raise ValueError for a singular
    3 by 3 F.
    """
    n = len(f)
    if n == 2:
        theta = math.atan2(f[1][0] - f[0][1], f[0][0] + f[1][1])
        r = rot2(theta)
        s = mul(transpose(r), f)
        s01 = 0.5 * (s[0][1] + s[1][0])
        s[0][1] = s[1][0] = s01
        return r, s
    if n != 3:
        raise ValueError("polar supports 2 by 2 and 3 by 3 matrices")
    x = [list(map(float, row)) for row in f]
    change = float("inf")
    for _ in range(max_iter):
        xi = inv(x)
        if change > 1e-2:
            g = math.sqrt(_frob(xi) / _frob(x))
        else:
            g = 1.0
        xit = transpose(xi)
        y = [[0.5 * (g * x[i][j] + xit[i][j] / g) for j in range(3)] for i in range(3)]
        change = _frob([[y[i][j] - x[i][j] for j in range(3)] for i in range(3)]) / _frob(y)
        x = y
        if change <= tol:
            break
    u = x
    s = mul(transpose(u), f)
    s = [[0.5 * (s[i][j] + s[j][i]) for j in range(3)] for i in range(3)]
    if det(u) < 0.0:
        values, vectors = _sym_eig3(s)
        k = min(range(3), key=lambda i: values[i])
        v = vectors[k]
        h = [[(1.0 if i == j else 0.0) - 2.0 * v[i] * v[j] for j in range(3)] for i in range(3)]
        u = mul(u, h)
        s = mul(h, s)
        s = [[0.5 * (s[i][j] + s[j][i]) for j in range(3)] for i in range(3)]
    return u, s


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


def q_mul(p, q):
    """Return the Hamilton product p q."""
    a1, b1, c1, d1 = p
    a2, b2, c2, d2 = q
    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 q_conj(q):
    """Return the conjugate (w, -x, -y, -z)."""
    return (q[0], -q[1], -q[2], -q[3])


def q_dot(p, q):
    """Return the dot product of p and q as vectors of R^4."""
    return p[0] * q[0] + p[1] * q[1] + p[2] * q[2] + p[3] * q[3]


def q_normalize(q):
    """Return q / |q|."""
    n = math.sqrt(q_dot(q, q))
    if n == 0.0:
        raise ValueError("cannot normalize the zero quaternion")
    return (q[0] / n, q[1] / n, q[2] / n, q[3] / n)


def q_from_axis_angle(axis, angle):
    """Return the unit quaternion of the rotation by angle about axis (any length)."""
    u = normalize(axis)
    s = math.sin(0.5 * angle)
    return (math.cos(0.5 * angle), s * u[0], s * u[1], s * u[2])


def q_to_mat3(q):
    """Return the 3 by 3 rotation matrix of a unit quaternion."""
    w, x, y, z = q
    return [
        [1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
        [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
        [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)],
    ]


def q_rotate(q, v):
    """Return the vector part of q (0, v) q* for a unit quaternion q."""
    r = q_mul(q_mul(q, (0.0, v[0], v[1], v[2])), q_conj(q))
    return (r[1], r[2], r[3])


def q_log(q):
    """Return the log of a nonzero quaternion as a 4-tuple (ln|q|, phi u).

    For a unit quaternion (cos phi, sin phi u) this is (0, phi u), with
    phi = atan2(|v|, w) in [0, pi]. For a real q the vector part is zero.
    """
    n = math.sqrt(q_dot(q, q))
    if n == 0.0:
        raise ValueError("log of the zero quaternion")
    vn = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3])
    lw = math.log(n)
    if vn == 0.0:
        return (lw, 0.0, 0.0, 0.0)
    phi = math.atan2(vn, q[0])
    f = phi / vn
    return (lw, f * q[1], f * q[2], f * q[3])


def q_exp(q):
    """Return exp(q) = e^w (cos|v|, sin|v| v / |v|) for q = (w, v)."""
    vn = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3])
    ew = math.exp(q[0])
    if vn == 0.0:
        return (ew, 0.0, 0.0, 0.0)
    f = ew * math.sin(vn) / vn
    return (ew * math.cos(vn), f * q[1], f * q[2], f * q[3])


def slerp(q0, q1, t):
    """Spherical linear interpolation of unit quaternions on the short arc.

    If q0 . q1 < 0, q1 is replaced by -q1 (the same rotation). The angle W
    comes from atan2(|q1 - q0|, |q1 + q0|). Below SLERP_SMALL_ANGLE the
    normalized linear interpolation is returned. See
    robotics/rigid-body-motion/spherical-linear-interpolation.
    """
    if q_dot(q0, q1) < 0.0:
        q1 = (-q1[0], -q1[1], -q1[2], -q1[3])
    a = math.sqrt(sum((y - x) ** 2 for x, y in zip(q0, q1)))
    b = math.sqrt(sum((y + x) ** 2 for x, y in zip(q0, q1)))
    w = 2.0 * math.atan2(a, b)
    if w < SLERP_SMALL_ANGLE:
        return q_normalize(tuple((1 - t) * x + t * y for x, y in zip(q0, q1)))
    s = math.sin(w)
    c0 = math.sin((1 - t) * w) / s
    c1 = math.sin(t * w) / s
    return tuple(c0 * x + c1 * y for x, y in zip(q0, q1))


def q_from_mat3(r):
    """Return the unit quaternion, with w >= 0, of a 3 by 3 rotation matrix.

    Shepperd's method: take the largest of the trace, r00, r11 and r22, and
    divide by the component that it gives. See
    robotics/rigid-body-motion/shepperd-method.
    """
    t = r[0][0] + r[1][1] + r[2][2]
    k = max(range(4), key=lambda i: (t, r[0][0], r[1][1], r[2][2])[i])
    if k == 0:
        w = math.sqrt(1.0 + t) / 2.0
        f = 4.0 * w
        q = (w, (r[2][1] - r[1][2]) / f, (r[0][2] - r[2][0]) / f, (r[1][0] - r[0][1]) / f)
    elif k == 1:
        x = math.sqrt(max(0.0, 1.0 + 2.0 * r[0][0] - t)) / 2.0
        f = 4.0 * x
        q = ((r[2][1] - r[1][2]) / f, x, (r[1][0] + r[0][1]) / f, (r[0][2] + r[2][0]) / f)
    elif k == 2:
        y = math.sqrt(max(0.0, 1.0 + 2.0 * r[1][1] - t)) / 2.0
        f = 4.0 * y
        q = ((r[0][2] - r[2][0]) / f, (r[1][0] + r[0][1]) / f, y, (r[2][1] + r[1][2]) / f)
    else:
        z = math.sqrt(max(0.0, 1.0 + 2.0 * r[2][2] - t)) / 2.0
        f = 4.0 * z
        q = ((r[1][0] - r[0][1]) / f, (r[0][2] + r[2][0]) / f, (r[2][1] + r[1][2]) / f, z)
    if q[0] < 0.0:
        q = (-q[0], -q[1], -q[2], -q[3])
    return q


# ---------------------------------------------------------------- transforms


def make_T(r, t):
    """Return the homogeneous (d + 1) by (d + 1) matrix [[R, t], [0, 1]] for d = len(t)."""
    d = len(t)
    m = [[float(r[i][j]) for j in range(d)] + [float(t[i])] for i in range(d)]
    m.append([0.0] * d + [1.0])
    return m


def T_mul(a, b):
    """Return the product a b of two homogeneous transforms."""
    return mul(a, b)


def T_inv(m):
    """Return the inverse of an affine homogeneous transform [[A, t], [0, 1]].

    The result is [[A^(-1), -A^(-1) t], [0, 1]]; A may hold a scale.
    """
    d = len(m) - 1
    a = [row[:d] for row in m[:d]]
    t = [m[i][d] for i in range(d)]
    ai = inv(a)
    ti = matvec(ai, t)
    return make_T(ai, tuple(-x for x in ti))


def T_apply(m, p):
    """Apply a homogeneous transform to a point p and return a tuple."""
    d = len(m) - 1
    return tuple(sum(m[i][j] * p[j] for j in range(d)) + m[i][d] for i in range(d))


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


def num_grad(f, x, h=1e-6):
    """Return the gradient of a scalar f at x by central differences of step h."""
    x = list(x)
    g = []
    for i in range(len(x)):
        xi = x[i]
        x[i] = xi + h
        fp = f(x)
        x[i] = xi - h
        fm = f(x)
        x[i] = xi
        g.append((fp - fm) / (2.0 * h))
    return g
squad.py 90 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/squad/. The authors are listed in prov/5MKSXN.jsonl.
"""Spherical quadrangle interpolation (squad) of unit quaternion keys.

Keys q_0, ..., q_(n-1) are unit quaternions (Hamilton, scalar first) at the
times 0, 1, ..., n - 1. The curve on segment i, for t in [0, 1], is

    squad(q_i, q_(i+1), s_i, s_(i+1), t)
        = arc(arc(q_i, q_(i+1), t), arc(s_i, s_(i+1), t), 2 t (1 - t)),

where arc(p, q, t) = p exp(t log(p* q)) is slerp without a sign flip, and

    s_i = q_i exp(-(log(q_i* q_(i+1)) + log(q_i* q_(i-1))) / 4)

for the inner keys. The end keys use s_0 = q_0 and s_(n-1) = q_(n-1).
Before this, the keys are made sign consistent: q_i is replaced by -q_i if
q_(i-1) . q_i < 0. The curve passes through the keys and has a continuous
first derivative at each inner key (Shoemake 1987; Dam, Koch and Lillholm
1998).
"""

import math

from anim import q_conj, q_dot, q_exp, q_log, q_mul


def arc(p, q, t):
    """Return p (p* q)^t, the point at the fraction t of the arc from p to q.

    No sign flip is done. For p . q >= 0 this is slerp on the short arc.
    """
    lg = q_log(q_mul(q_conj(p), q))
    return q_mul(p, q_exp((0.0, t * lg[1], t * lg[2], t * lg[3])))


def align_signs(keys):
    """Return the keys with q_i replaced by -q_i where q_(i-1) . q_i < 0."""
    out = [tuple(keys[0])]
    for q in keys[1:]:
        q = tuple(q)
        if q_dot(out[-1], q) < 0.0:  # @line L1
            q = (-q[0], -q[1], -q[2], -q[3])  # @line L2
        out.append(q)
    return out


def control_points(keys):
    """Return the inner control quaternions s_0, ..., s_(n-1) of aligned keys."""
    n = len(keys)
    s = [keys[0]] + [None] * (n - 2) + [keys[-1]] if n > 1 else [keys[0]]  # @line L3
    for i in range(1, n - 1):  # @line L4
        qi_c = q_conj(keys[i])
        a = q_log(q_mul(qi_c, keys[i + 1]))  # @line L5
        b = q_log(q_mul(qi_c, keys[i - 1]))  # @line L6
        e = (0.0, -(a[1] + b[1]) / 4.0, -(a[2] + b[2]) / 4.0, -(a[3] + b[3]) / 4.0)
        s[i] = q_mul(keys[i], q_exp(e))  # @line L7
    return s


def squad_segment(qi, qj, si, sj, t):
    """Return squad(q_i, q_(i+1), s_i, s_(i+1), t) for t in [0, 1]."""
    a = arc(qi, qj, t)  # @line L8
    b = arc(si, sj, t)  # @line L9
    return arc(a, b, 2.0 * t * (1.0 - t))  # @line L10


class Squad:
    """A squad curve through keys at the times 0, 1, ..., n - 1."""

    def __init__(self, keys):
        if len(keys) < 2:
            raise ValueError("squad needs at least two keys")
        self.keys = align_signs(keys)
        self.ctrl = control_points(self.keys)

    def __call__(self, u):
        """Return the unit quaternion at the time u in [0, n - 1]."""
        n = len(self.keys)
        if u <= 0.0:
            i, t = 0, 0.0
        elif u >= n - 1:
            i, t = n - 2, 1.0
        else:
            i = int(math.floor(u))
            t = u - i
        return squad_segment(self.keys[i], self.keys[i + 1], self.ctrl[i], self.ctrl[i + 1], t)

    def segment(self, i, t):
        """Return the point at the local time t in [0, 1] of segment i."""
        return squad_segment(self.keys[i], self.keys[i + 1], self.ctrl[i], self.ctrl[i + 1], t)
test_squad.py 277 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/squad/. The authors are listed in prov/5MKSXN.jsonl.
"""Tests of squad and of the shared helper anim.py.

The squad tests check the round trip through the keys, the unit norm, the
continuity of the first derivative at the inner keys (one sided differences
against the closed form tangent q_i (a - b) / 2 of the proof), the reduction
to slerp for two keys and for keys on one great circle at equal steps, and
the invariance under a change of the world frame.
"""

import math
import random

import anim
from squad import Squad, align_signs, arc, control_points


def rand_unit(rng, n=4):
    while True:
        v = [rng.gauss(0.0, 1.0) for _ in range(n)]
        s = math.sqrt(sum(x * x for x in v))
        if s > 1e-3:
            return tuple(x / s for x in v)


def rand_rot(rng):
    return anim.q_to_mat3(rand_unit(rng))


def qclose(p, q, tol):
    d1 = max(abs(a - b) for a, b in zip(p, q))
    d2 = max(abs(a + b) for a, b in zip(p, q))
    return min(d1, d2) <= tol


def mclose(a, b, tol):
    return all(abs(a[i][j] - b[i][j]) <= tol for i in range(len(a)) for j in range(len(a[0])))


def rot_angle(q):
    q = anim.q_normalize(q)
    return 2.0 * math.atan2(math.sqrt(q[1] ** 2 + q[2] ** 2 + q[3] ** 2), abs(q[0]))


# ---------------------------------------------------------------- anim.py


def test_vectors():
    a, b = (1.0, 2.0, 3.0), (4.0, -5.0, 6.0)
    assert anim.add(a, b) == (5.0, -3.0, 9.0)
    assert anim.sub(a, b) == (-3.0, 7.0, -3.0)
    assert anim.scale(a, 2.0) == (2.0, 4.0, 6.0)
    assert anim.dot(a, b) == 12.0
    c = anim.cross(a, b)
    assert abs(anim.dot(c, a)) < 1e-12 and abs(anim.dot(c, b)) < 1e-12
    assert c == (27.0, 6.0, -13.0)
    assert anim.cross2((1.0, 0.0), (0.0, 1.0)) == 1.0
    assert abs(anim.norm(anim.normalize(b)) - 1.0) < 1e-15
    assert anim.lerp(a, b, 0.5) == (2.5, -1.5, 4.5)


def test_matrices():
    rng = random.Random(1)
    for n in (2, 3, 4, 5):
        a = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
        ai = anim.inv(a)
        assert mclose(anim.mul(a, ai), anim.eye(n), 1e-10)
        x = [rng.uniform(-1, 1) for _ in range(n)]
        b = anim.matvec(a, x)
        y = anim.solve(a, b)
        assert max(abs(p - q) for p, q in zip(x, y)) < 1e-10
        # det by the Leibniz formula for small n, by the product rule otherwise
        bm = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
        assert abs(anim.det(anim.mul(a, bm)) - anim.det(a) * anim.det(bm)) < 1e-10
        assert abs(anim.det(anim.transpose(a)) - anim.det(a)) < 1e-12
    assert anim.det([[1.0, 2.0, 3.0, 4.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 2.0, 0.0], [0.0, 0.0, 0.0, 3.0]]) == 6.0
    try:
        anim.solve([[1.0, 2.0], [2.0, 4.0]], [1.0, 2.0])
        raise AssertionError("singular matrix was not detected")
    except ValueError:
        pass


def test_slerp_check_values():
    q0 = (1.0, 0.0, 0.0, 0.0)
    q1 = (math.sqrt(0.5), 0.0, 0.0, math.sqrt(0.5))
    h = anim.slerp(q0, q1, 0.5)
    assert max(abs(a - b) for a, b in zip(h, (0.92388, 0.0, 0.0, 0.38268))) < 1e-5
    nl = anim.q_normalize(anim.lerp(q0, q1, 0.5))
    assert qclose(h, nl, 1e-12)
    q = anim.slerp(q0, q1, 0.25)
    assert max(abs(a - b) for a, b in zip(q, (0.98079, 0.0, 0.0, 0.19509))) < 1e-5
    assert abs(rot_angle(q) - math.pi / 8) < 1e-12
    assert abs(rot_angle(q) - 0.392699) < 1e-6
    nl = anim.q_normalize(anim.lerp(q0, q1, 0.25))
    assert abs(rot_angle(nl) - 0.376959) < 1e-6
    # the sign flip: -q1 gives the same result
    assert qclose(anim.slerp(q0, tuple(-x for x in q1), 0.25), q, 1e-12)
    # the end points and the small angle branch
    rng = random.Random(2)
    for _ in range(50):
        a, b = rand_unit(rng), rand_unit(rng)
        assert qclose(anim.slerp(a, b, 0.0), a, 1e-12)
        assert qclose(anim.slerp(a, b, 1.0), b, 1e-12)
        assert abs(anim.norm(anim.slerp(a, b, rng.random())) - 1.0) < 1e-12
    a = rand_unit(rng)
    b = anim.q_normalize(anim.add(a, (1e-9, 0.0, 0.0, 0.0)))
    assert abs(anim.norm(anim.slerp(a, b, 0.3)) - 1.0) < 1e-12


def test_quaternions():
    rng = random.Random(3)
    for _ in range(100):
        q = rand_unit(rng)
        v = tuple(rng.uniform(-1, 1) for _ in range(3))
        r = anim.q_to_mat3(q)
        assert max(abs(a - b) for a, b in zip(anim.q_rotate(q, v), anim.matvec(r, v))) < 1e-12
        assert mclose(anim.mul(r, anim.transpose(r)), anim.eye(3), 1e-12)
        assert abs(anim.det(r) - 1.0) < 1e-12
        assert qclose(anim.q_from_mat3(r), q, 1e-12)
        assert qclose(anim.q_exp(anim.q_log(q)), q, 1e-12)
        p = rand_unit(rng)
        assert mclose(anim.q_to_mat3(anim.q_mul(p, q)), anim.mul(anim.q_to_mat3(p), r), 1e-12)
    # i j = k (Hamilton)
    assert anim.q_mul((0, 1, 0, 0), (0, 0, 1, 0)) == (0, 0, 0, 1)
    # rotation by pi about x: q = (0, 1, 0, 0), through the matrix and back
    q = anim.q_from_axis_angle((2.0, 0.0, 0.0), math.pi)
    r = anim.q_to_mat3(q)
    assert mclose(r, [[1, 0, 0], [0, -1, 0], [0, 0, -1]], 1e-15)
    qb = anim.q_from_mat3(r)
    assert qclose(qb, (0.0, 1.0, 0.0, 0.0), 1e-15)
    assert mclose(anim.q_to_mat3(qb), r, 1e-15)
    # the log of (cos phi, sin phi u) is (0, phi u)
    lg = anim.q_log(anim.q_from_axis_angle((0, 0, 1), 1.2))
    assert max(abs(a - b) for a, b in zip(lg, (0.0, 0.0, 0.0, 0.6))) < 1e-15


def test_polar():
    rng = random.Random(4)
    for _ in range(40):
        r = rand_rot(rng)
        m = [[rng.uniform(-1, 1) for _ in range(3)] for _ in range(3)]
        s = anim.mul(anim.transpose(m), m)
        for i in range(3):
            s[i][i] += 0.1
        f = anim.mul(r, s)
        r2, s2 = anim.polar(f)
        assert mclose(r2, r, 1e-9) and mclose(s2, s, 1e-9)
        assert abs(anim.det(r2) - 1.0) < 1e-12
        # det F < 0: R stays a rotation, R S = F, and S is symmetric
        g = [row[:] for row in f]
        g[0] = [-x for x in g[0]]
        r3, s3 = anim.polar(g)
        assert abs(anim.det(r3) - 1.0) < 1e-10
        assert mclose(anim.mul(r3, s3), g, 1e-10)
        assert mclose(s3, anim.transpose(s3), 1e-12)
    for _ in range(40):
        th = rng.uniform(-math.pi, math.pi)
        a = rng.uniform(0.2, 2.0)
        c = rng.uniform(0.2, 2.0)
        b = rng.uniform(-1, 1) * 0.9 * math.sqrt(a * c)
        s = [[a, b], [b, c]]
        r2, s2 = anim.polar(anim.mul(anim.rot2(th), s))
        assert mclose(r2, anim.rot2(th), 1e-12) and mclose(s2, s, 1e-12)


def test_transforms_and_num_grad():
    rng = random.Random(5)
    r = rand_rot(rng)
    rs = anim.mul(r, [[2.0, 0, 0], [0, 0.5, 0], [0, 0, 1.5]])
    m = anim.make_T(rs, (1.0, -2.0, 3.0))
    p = (0.3, 0.4, -0.5)
    assert max(abs(a - b) for a, b in zip(anim.T_apply(anim.T_inv(m), anim.T_apply(m, p)), p)) < 1e-12
    assert mclose(anim.T_mul(m, anim.T_inv(m)), anim.eye(4), 1e-12)

    def f(x):
        return x[0] ** 3 + 2.0 * x[0] * x[1] + math.sin(x[1])

    g = anim.num_grad(f, [0.7, -0.4], 1e-6)
    exact = [3 * 0.49 + 2 * -0.4, 2 * 0.7 + math.cos(-0.4)]
    assert max(abs(a - b) for a, b in zip(g, exact)) < 1e-8


# ---------------------------------------------------------------- squad


def random_keys(rng, n, step=1.0):
    keys = [rand_unit(rng)]
    for _ in range(n - 1):
        axis = rand_unit(rng, 3)
        keys.append(anim.q_mul(keys[-1], anim.q_from_axis_angle(axis, rng.uniform(0.2, step))))
    # random signs, which align_signs must undo
    return [q if rng.random() < 0.5 else tuple(-x for x in q) for q in keys]


def test_passes_through_keys_and_unit_norm():
    rng = random.Random(6)
    keys = random_keys(rng, 7, 1.5)
    c = Squad(keys)
    for i, q in enumerate(keys):
        assert qclose(c(float(i)), q, 1e-12)
    for k in range(0, 601):
        u = 6.0 * k / 600
        assert abs(anim.norm(c(u)) - 1.0) < 1e-12


def test_first_derivative_is_continuous():
    rng = random.Random(7)
    keys = random_keys(rng, 6, 1.5)
    c = Squad(keys)
    q = c.keys
    h = 1e-6
    for i in range(1, len(q) - 1):
        left = tuple((x - y) / h for x, y in zip(c.segment(i - 1, 1.0), c.segment(i - 1, 1.0 - h)))
        right = tuple((y - x) / h for x, y in zip(c.segment(i, 0.0), c.segment(i, h)))
        qc = anim.q_conj(q[i])
        a = anim.q_log(anim.q_mul(qc, q[i + 1]))
        b = anim.q_log(anim.q_mul(qc, q[i - 1]))
        tangent = anim.q_mul(q[i], tuple((x - y) / 2.0 for x, y in zip(a, b)))
        assert max(abs(x - y) for x, y in zip(left, tangent)) < 1e-4
        assert max(abs(x - y) for x, y in zip(right, tangent)) < 1e-4
    # slerp keyed piecewise has a jump in the derivative at the same keys
    i = 2
    l2 = tuple((x - y) / h for x, y in zip(arc(q[i - 1], q[i], 1.0), arc(q[i - 1], q[i], 1.0 - h)))
    r2 = tuple((y - x) / h for x, y in zip(arc(q[i], q[i + 1], 0.0), arc(q[i], q[i + 1], h)))
    assert max(abs(x - y) for x, y in zip(l2, r2)) > 1e-2


def test_two_keys_is_slerp():
    rng = random.Random(8)
    for _ in range(20):
        a, b = rand_unit(rng), rand_unit(rng)
        c = Squad([a, b])
        for k in range(11):
            t = k / 10
            assert qclose(c(t), anim.slerp(a, b, t), 1e-12)


def test_equal_steps_on_one_axis_is_constant_speed_slerp():
    keys = [anim.q_from_axis_angle((0.0, 0.0, 1.0), 0.7 * i) for i in range(5)]
    c = Squad(keys)
    for i in range(1, 4):
        assert qclose(c.ctrl[i], keys[i], 1e-15)
    for k in range(41):
        u = 4.0 * k / 40
        assert qclose(c(u), anim.q_from_axis_angle((0.0, 0.0, 1.0), 0.7 * u), 1e-12)


def test_arc_equals_slerp_on_short_arcs():
    rng = random.Random(9)
    for _ in range(50):
        a, b = rand_unit(rng), rand_unit(rng)
        if anim.q_dot(a, b) < 0:
            b = tuple(-x for x in b)
        t = rng.random()
        assert qclose(arc(a, b, t), anim.slerp(a, b, t), 1e-12)


def test_world_frame_invariance():
    rng = random.Random(10)
    keys = random_keys(rng, 5, 1.2)
    g = rand_unit(rng)
    c1 = Squad(keys)
    c2 = Squad([anim.q_mul(g, q) for q in keys])
    for k in range(41):
        u = 4.0 * k / 40
        assert qclose(c2(u), anim.q_mul(g, c1(u)), 1e-12)


def test_controls_of_aligned_keys():
    rng = random.Random(11)
    keys = align_signs(random_keys(rng, 5, 1.0))
    for p, q in zip(keys, keys[1:]):
        assert anim.q_dot(p, q) >= 0.0
    s = control_points(keys)
    assert s[0] == keys[0] and s[-1] == keys[-1]

History

Shoemake (1985) brought quaternions and slerp to computer animation and built spherical Bezier curves through keys. He gave squad in the course notes "Quaternion calculus and fast animation" of SIGGRAPH 1987, as a cheaper form of the same idea. Dam, Koch and Lillholm (1998) wrote out the construction, proved that squad is C1C^1, and noted that the first published proof was flawed. Parent (2012) describes squad and other orientation curves in his textbook on computer animation.

References

  1. Ken Shoemake, Animating rotation with quaternion curves, Computer Graphics (Proceedings of SIGGRAPH 1985) 19(3), 245-254, 1985, the whole paper (slerp, and spherical Bezier curves through quaternion keys built from slerp)
  2. Erik B. Dam, Martin Koch and Martin Lillholm, Quaternions, interpolation and animation, Technical Report DIKU-TR-98/5, University of Copenhagen, 1998, Section 6.2.1 (Squad, Definition 17, equations 6.14 and 6.15) and Proposition 30 (Squad is C1)
  3. Rick Parent, Computer Animation, Algorithms and Techniques, 3rd edition, Morgan Kaufmann, 2012, Chapter 3, Section 3.3 (interpolation of orientations)

Where this leads

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.build
  • a full proof of time.query
  • 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
  • History with a source
  • a scene preset for the example