Algorithm Search⌘K

Algorithmadvanced

Double reflection method

Also called double reflection rotation minimizing frame.

Approximate a rotation minimizing frame along sampled curve points by two reflections per step, with fourth-order accuracy.

Time
Θ(N) worst
Space
Θ(1) extra
Where
N = the number of steps between sample points
Properties
deterministicnot exactonlineiterative

The double reflection method computes a rotation minimizing frame along a space curve from sample points and their unit tangents. Each step maps the frame at one point to the frame at the next point by two reflections in planes. The first reflection takes the point xix_i to xi+1x_{i+1}, and the second one takes the reflected tangent to the true tangent ti+1t_{i+1}. Wang, Jüttler, Zheng and Liu (2008) gave the method and showed that its global error is O(h4)O(h^4) for a step hh, at a much lower cost than a fourth-order Runge-Kutta integration of the defining equation. It is the standard way to frame sweep surfaces, tubes, camera paths and rods without the twist and the flips of the Frenet frame.

In plain words

To move a camera or to sweep a tube along a curved path, you need a direction "up" at each point of the path. That up direction must stay at a right angle to the path, and it must not spin about the path for no reason. The method finds it one step at a time. Put a mirror halfway between two neighbouring points, so that the mirror image of the first point is the second point. Mirror the current up direction and the current path direction in it. The mirrored path direction is usually a little off from the true one at the new point, so a second mirror moves it onto the true one. The second mirror moves the up direction too. Two mirrors together give a turn, and the turn is very close to the one that the ideal frame makes.

The problem

The input is a list of points x0,…,xNx_0, \dots, x_N on a regular space curve x(u)x(u), the unit tangents tit_i at these points, and a unit normal vector r0⊥t0r_0 \perp t_0. The output is a list of frames (ri,si,ti)(r_i, s_i, t_i), each a right-handed orthonormal basis with si=ti×ris_i = t_i \times r_i. The frames must approximate the rotation minimizing frame of the curve, the solution of r′=−(r⋅t′) tr' = -(r \cdot t')\,t with r(u0)=r0r(u_0) = r_0. The definition of the frame and its properties are on the page rotation minimizing frame.

The algorithm

For a nonzero vector vv with c=v⋅vc = v \cdot v, the map a↦a−2c(v⋅a) va \mapsto a - \frac{2}{c}(v \cdot a)\,v is the reflection in the plane through the origin that is perpendicular to vv.

  1. DOUBLE-REFLECTION(x₀..x_N, t₀..t_N, r₀) ▷ returns the frames (rᵢ, sᵢ, tᵢ)
  2. 1for i ← 0 to N - 1 do
  3. 2v₁ ← xᵢ₊₁ - xᵢ; c₁ ← v₁ · v₁
  4. 3r_L ← rᵢ - (2/c₁)(v₁ · rᵢ) v₁
  5. 4t_L ← tᵢ - (2/c₁)(v₁ · tᵢ) v₁
  6. 5v₂ ← tᵢ₊₁ - t_L; c₂ ← v₂ · v₂
  7. 6rᵢ₊₁ ← r_L - (2/c₂)(v₂ · r_L) v₂
  8. 7sᵢ₊₁ ← tᵢ₊₁ × rᵢ₊₁
  9. 8return the frames (rᵢ, sᵢ, tᵢ), with s₀ = t₀ × r₀

Lines L2 to L4 apply the reflection R1R_1 in the plane perpendicular to the chord v1v_1. This reflection maps the vector from any point on the perpendicular bisector plane of the chord to xix_i onto the vector from the same point to xi+1x_{i+1}. Line L5 sets up the second reflection R2R_2, whose plane is perpendicular to v2=ti+1−tLv_2 = t_{i+1} - t_L. Because tLt_L and ti+1t_{i+1} are unit vectors, R2R_2 maps tLt_L exactly to ti+1t_{i+1}. Line L6 applies R2R_2 to the reflected normal, and line L7 completes the frame. The product R2R1R_2R_1 is a rotation that maps tit_i to ti+1t_{i+1}, so each new frame is orthonormal and right-handed.

If c1=0c_1 = 0, the two points are the same. The implementation then uses v1=tiv_1 = t_i, the limit of the chord direction, and the step becomes the smallest rotation that takes tit_i to ti+1t_{i+1}; for ti+1=tit_{i+1} = t_i it leaves the frame unchanged. For small steps on a smooth curve, tLt_L is close to −ti+1-t_{i+1} and c2c_2 is close to 4. A c2c_2 near 0 means that the step is too coarse, and the implementation raises an error, because the direction of v2v_2 is then not determined. The implementation also projects r0r_0 onto the plane perpendicular to t0t_0 and normalizes it.

Example

Take the helix x(u)=(cos⁡u,sin⁡u,u/2)x(u) = (\cos u, \sin u, u/2) on one turn, u∈[0,2π]u \in [0, 2\pi], with the step h=π/2h = \pi/2, so N=4N = 4. Its speed is w=5/2w = \sqrt{5}/2, and the start frame is r0=(−1,0,0)r_0 = (-1, 0, 0), the principal normal, with t0=(0,0.89443,0.44721)t_0 = (0, 0.89443, 0.44721).

  • Line L2 gives v1=(−1,1,0.78540)v_1 = (-1, 1, 0.78540) and c1=2.61685c_1 = 2.61685.
  • Lines L3 and L4 give rL=(−0.23572,−0.76428,−0.60026)r_L = (-0.23572, -0.76428, -0.60026) and tL=(0.95204,−0.05761,−0.30051)t_L = (0.95204, -0.05761, -0.30051).
  • The true tangent is t1=(−0.89443,0,0.44721)t_1 = (-0.89443, 0, 0.44721), so line L5 gives v2=(−1.84646,0.05761,0.74773)v_2 = (-1.84646, 0.05761, 0.74773) and c2=3.97184c_2 = 3.97184.
  • Line L6 gives r1=(−0.28929,−0.76261,−0.57857)r_1 = (-0.28929, -0.76261, -0.57857).

The exact rotation minimizing normal at u=π/2u = \pi/2 is (−0.28895,−0.76324,−0.57790)(-0.28895, -0.76324, -0.57790), so the error after one quarter turn is 9.8⋅10−49.8 \cdot 10^{-4}. The exact frame is known in closed form for a helix: it is the Frenet frame turned about the tangent by the angle −∫τ ds-\int\tau\,ds, which is 2π⋅1/2w=2.8102\pi \cdot \frac{1/2}{w} = 2.810 radians, or 161 degrees, per turn.

The largest error of rir_i over the turn, for N=4,8,16,32,64N = 4, 8, 16, 32, 64, is shown with the projection method, which projects rir_i onto the normal plane at xi+1x_{i+1} and normalizes it.

NN double reflection projection
4 3.9⋅10−33.9 \cdot 10^{-3} 0.840.84
8 2.4⋅10−42.4 \cdot 10^{-4} 0.340.34
16 1.5⋅10−51.5 \cdot 10^{-5} 0.170.17
32 9.3⋅10−79.3 \cdot 10^{-7} 0.0860.086
64 5.8⋅10−85.8 \cdot 10^{-8} 0.0430.043

Each halving of the step divides the error of the double reflection method by about 16, and that of the projection method by 2.

Correctness

Each frame is orthonormal and right-handed, because R2R1R_2R_1 is a product of two reflections, which is a rotation, and it maps tit_i to ti+1t_{i+1}. So the frames never drift away from orthonormality, even after many steps, which is not true of a general integrator applied to the defining equation.

On a curve that lies in a plane with the normal nn, both v1v_1 and v2v_2 are in the plane, so R1R_1 and R2R_2 fix nn. The rotation R2R1R_2R_1 then turns the plane by the angle from tit_i to ti+1t_{i+1}, which is what the exact frame does. On a curve on a sphere with the center pp, R1R_1 maps xi−px_i - p to xi+1−px_{i+1} - p, and R2R_2 fixes the new radial direction, because tLt_L and ti+1t_{i+1} are both perpendicular to it. So the radial unit vector, which is the exact rotation minimizing normal of a curve on a sphere, is reproduced at every point. This is Theorem 4.3 of Wang et al.

Running the method backward along the reversed points, from the last frame, returns every earlier frame exactly, because the backward step uses the reflection R1R_1 and the reflection R1R2R1R_1R_2R_1, whose product is (R2R1)−1(R_2R_1)^{-1}.

For a smooth curve with ui=u0+ihu_i = u_0 + ih, Wang et al. show that the error of one step is K720h5+O(h6)\frac{K}{720}h^5 + O(h^6), where KK depends on the curvature, the torsion and their derivatives, and that the global error is O(h4)O(h^4) (Theorems 4.4 and 4.5). The proof gives the exact properties in detail.

Proof: The double reflection method gives orthonormal frames that are exact on planes and spheres and symmetric under reversalfull

We use the notation of the page. For a nonzero vector vv, let Hva=a−2v⋅v(v⋅a) vH_v a = a - \frac{2}{v \cdot v}(v \cdot a)\,v. Line L3 is rL=Hv1rir_L = H_{v_1}r_i, line L4 is tL=Hv1tit_L = H_{v_1}t_i, and line L6 is ri+1=Hv2rLr_{i+1} = H_{v_2}r_L. If c1=0c_1 = 0, the implementation sets v1=tiv_1 = t_i. If c2c_2 is below a small threshold, it stops with an error, so in every completed step v1≠0v_1 \ne 0 and v2≠0v_2 \ne 0. Write Mi=Hv2Hv1M_i = H_{v_2}H_{v_1} for the map of step ii. The tangents tit_i are unit vectors and r0r_0 is a unit vector perpendicular to t0t_0.

Reflections

Lemma 1. HvH_v is linear, orthogonal, symmetric, of determinant −1-1, and Hv2=IH_v^2 = I. It fixes every vector perpendicular to vv, and Hλv=HvH_{\lambda v} = H_v for λ≠0\lambda \ne 0.

Proof. Hv=I−2v^v^TH_v = I - 2\hat v\hat v^{\mathsf T} with v^=v/∣v∣\hat v = v/|v|, which depends only on the line of vv. It is symmetric, and Hv2=I−4v^v^T+4v^(v^Tv^)v^T=IH_v^2 = I - 4\hat v\hat v^{\mathsf T} + 4\hat v(\hat v^{\mathsf T}\hat v)\hat v^{\mathsf T} = I, so it is orthogonal. It maps v^\hat v to −v^-\hat v and fixes the plane v^⊥\hat v^\perp, so its determinant is −1-1. □\square

Lemma 2. If ∣a∣=∣b∣|a| = |b| and a≠ba \ne b, then Hb−a a=bH_{b - a}\,a = b.

Proof. Let v=b−av = b - a. Then v⋅v=∣a∣2−2a⋅b+∣b∣2=2(∣a∣2−a⋅b)=−2 v⋅av \cdot v = |a|^2 - 2a\cdot b + |b|^2 = 2(|a|^2 - a \cdot b) = -2\,v \cdot a. So Hva=a−2(v⋅a)v⋅vv=a+v=bH_v a = a - \frac{2(v \cdot a)}{v \cdot v}v = a + v = b. □\square

Orthonormal frames

Lemma 3. Miti=ti+1M_i t_i = t_{i+1}, and MiM_i is a rotation.

Proof. tL=Hv1tit_L = H_{v_1}t_i is a unit vector by Lemma 1, and tL≠ti+1t_L \ne t_{i+1} because v2≠0v_2 \ne 0. Lemma 2 with a=tLa = t_L and b=ti+1b = t_{i+1} gives Hv2tL=ti+1H_{v_2}t_L = t_{i+1}. MiM_i is a product of two orthogonal maps of determinant −1-1, so it is orthogonal with determinant +1+1. □\square

Lemma 4. If xi+1=xix_{i+1} = x_i, MiM_i is the smallest rotation that takes tit_i to ti+1t_{i+1}, the rotation about ti×ti+1t_i \times t_{i+1} by the angle between the two tangents. In particular Mi=IM_i = I if ti+1=tit_{i+1} = t_i.

Proof. Here v1=tiv_1 = t_i, so tL=−tit_L = -t_i and v2=ti+1+tiv_2 = t_{i+1} + t_i, which is not zero. Both tit_i and ti+ti+1t_i + t_{i+1} are perpendicular to k=ti×ti+1k = t_i \times t_{i+1}, so both reflections fix kk, and MiM_i is a rotation about kk (or the identity if k=0k = 0). The product of the reflections in two planes that meet at the angle β\beta along a line is the rotation about that line by 2β2\beta. The normals tit_i and ti+ti+1t_i + t_{i+1} make the angle θ/2\theta/2, where θ\theta is the angle from tit_i to ti+1t_{i+1}, so the rotation angle is θ\theta, and by Lemma 3 its sense takes tit_i to ti+1t_{i+1}. □\square

Theorem 1. Every frame (ri,si,ti)(r_i, s_i, t_i) of line L8 is a right-handed orthonormal basis.

Proof. By induction on ii. For i=0i = 0, r0⊥t0r_0 \perp t_0 are unit vectors and s0=t0×r0s_0 = t_0 \times r_0. If ri⊥tir_i \perp t_i are unit vectors, then ri+1=Mirir_{i+1} = M_ir_i and ti+1=Mitit_{i+1} = M_it_i (Lemma 3) are unit vectors with ri+1⋅ti+1=ri⋅ti=0r_{i+1}\cdot t_{i+1} = r_i \cdot t_i = 0, because MiM_i is orthogonal. With si+1=ti+1×ri+1s_{i+1} = t_{i+1} \times r_{i+1} from line L7, ri+1×si+1=ri+1×(ti+1×ri+1)=ti+1(ri+1⋅ri+1)−ri+1(ri+1⋅ti+1)=ti+1r_{i+1} \times s_{i+1} = r_{i+1} \times (t_{i+1} \times r_{i+1}) = t_{i+1}(r_{i+1} \cdot r_{i+1}) - r_{i+1}(r_{i+1}\cdot t_{i+1}) = t_{i+1}, so the basis (ri+1,si+1,ti+1)(r_{i+1}, s_{i+1}, t_{i+1}) is orthonormal and right-handed. □\square

Exact cases

A unit normal field r(u)⊥t(u)r(u) \perp t(u) along a regular curve is rotation minimizing if and only if r′r' is parallel to tt, which is the equation r′=−(r⋅t′) tr' = -(r \cdot t')\,t after the product rule on r⋅t=0r \cdot t = 0.

Theorem 2 (plane curves). If all the points lie in a plane with the unit normal nn, all the tangents are parallel to that plane, and r0=cos⁡α n+sin⁡α (n×t0)r_0 = \cos\alpha\,n + \sin\alpha\,(n \times t_0), then ri=cos⁡α n+sin⁡α (n×ti)r_i = \cos\alpha\,n + \sin\alpha\,(n \times t_i) for every ii, and this is the rotation minimizing frame at xix_i.

Proof. The vectors v1v_1 and v2v_2 are parallel to the plane, so Hv1H_{v_1} and Hv2H_{v_2} fix nn by Lemma 1, and so does MiM_i. A rotation that fixes nn commutes with a↦n×aa \mapsto n \times a, so Mi(n×ti)=n×Miti=n×ti+1M_i(n \times t_i) = n \times M_it_i = n \times t_{i+1} by Lemma 3. By linearity ri+1=Miri=cos⁡α n+sin⁡α (n×ti+1)r_{i+1} = M_ir_i = \cos\alpha\,n + \sin\alpha\,(n \times t_{i+1}). For the continuous field r(u)=cos⁡α n+sin⁡α (n×t(u))r(u) = \cos\alpha\,n + \sin\alpha\,(n \times t(u)), r′=sin⁡α (n×t′)r' = \sin\alpha\,(n \times t'), and t′⊥tt' \perp t lies in the plane, so n×t′n \times t' is parallel to tt, and rr is rotation minimizing. □\square

Theorem 3 (spherical curves). If all the points lie on a sphere with the center pp and the radius ρ>0\rho > 0, each tit_i is perpendicular to xi−px_i - p, the points are distinct, and r0=(x0−p)/ρr_0 = (x_0 - p)/\rho, then ri=(xi−p)/ρr_i = (x_i - p)/\rho for every ii, and this is the rotation minimizing frame at xix_i.

Proof. Assume ri=(xi−p)/ρr_i = (x_i - p)/\rho. The vectors a=xi−pa = x_i - p and b=xi+1−pb = x_{i+1} - p have the length ρ\rho and b−a=v1b - a = v_1, so Lemma 2 gives Hv1a=bH_{v_1}a = b and rL=(xi+1−p)/ρr_L = (x_{i+1} - p)/\rho. By Lemma 1, tL⋅rL=ti⋅ri=0t_L \cdot r_L = t_i \cdot r_i = 0, and ti+1⋅rL=0t_{i+1}\cdot r_L = 0 by the assumption on the tangents. So v2=ti+1−tLv_2 = t_{i+1} - t_L is perpendicular to rLr_L, and Hv2H_{v_2} fixes rLr_L. So ri+1=rLr_{i+1} = r_L. For the continuous field r(u)=(x(u)−p)/ρr(u) = (x(u) - p)/\rho on a curve on the sphere, r′=x′/ρr' = x'/\rho is parallel to tt, and r⊥tr \perp t because (x−p)⋅(x−p)=ρ2(x - p)\cdot(x - p) = \rho^2 has the derivative 2(x−p)⋅x′=02(x - p)\cdot x' = 0. □\square

Theorem 4 (straight lines). If ti=ti+1t_i = t_{i+1} and v1v_1 is a positive multiple of tit_i, then ri+1=rir_{i+1} = r_i.

Proof. By Lemma 1, Hv1ti=−tiH_{v_1}t_i = -t_i, so v2=2ti+1v_2 = 2t_{i+1} and Hv2=Hv1H_{v_2} = H_{v_1}. So Mi=Hv12=IM_i = H_{v_1}^2 = I. □\square

Symmetry

Theorem 5. Run the method on the reversed points xN,…,x0x_N, \dots, x_0 with the reversed tangents −tN,…,−t0-t_N, \dots, -t_0, starting from rNr_N. If the points xix_i are distinct, the backward step from xi+1x_{i+1} to xix_i is Mi−1M_i^{-1}, so the backward run gives rN,…,r0r_N, \dots, r_0.

Proof. The backward chord is −v1-v_1, so its first reflection is H−v1=Hv1H_{-v_1} = H_{v_1} by Lemma 1. The backward reflected tangent is Hv1(−ti+1)=−Hv1ti+1H_{v_1}(-t_{i+1}) = -H_{v_1}t_{i+1}, so the backward second vector is v2′=−ti+Hv1ti+1v_2' = -t_i + H_{v_1}t_{i+1}. Since Hv12=IH_{v_1}^2 = I, v2′=Hv1(ti+1−Hv1ti)=Hv1v2v_2' = H_{v_1}(t_{i+1} - H_{v_1}t_i) = H_{v_1}v_2. For an orthogonal QQ, HQv=QHvQTH_{Qv} = QH_vQ^{\mathsf T}, so Hv2′=Hv1Hv2Hv1H_{v_2'} = H_{v_1}H_{v_2}H_{v_1}. The backward step is Hv2′Hv1=Hv1Hv2Hv1Hv1=Hv1Hv2=(Hv2Hv1)−1=Mi−1H_{v_2'}H_{v_1} = H_{v_1}H_{v_2}H_{v_1}H_{v_1} = H_{v_1}H_{v_2} = (H_{v_2}H_{v_1})^{-1} = M_i^{-1}. □\square

The same argument with the tangents tN,…,t0t_N, \dots, t_0 not negated gives v2′=−Hv1v2v_2' = -H_{v_1}v_2, which defines the same reflection, so the orientation of the tangents does not matter for the symmetry.

Accuracy

The order of accuracy is not proved here. Wang, Jüttler, Zheng and Liu (2008, Theorems 4.4 and 4.5) show that, for a smooth curve with ui=u0+ihu_i = u_0 + ih and exact tangents, one step has the error K720h5+O(h6)\frac{K}{720}h^5 + O(h^6), with K=2κ12τ0+κ02τ03+κ1κ0τ1−κ2κ0τ0K = 2\kappa_1^2\tau_0 + \kappa_0^2\tau_0^3 + \kappa_1\kappa_0\tau_1 - \kappa_2\kappa_0\tau_0 in terms of the curvature, the torsion and their derivatives at the start of the step, and that the global error on a fixed interval is O(h4)O(h^4). The tests check this rate on a helix against its closed form and on the twisted cubic against a fine Runge-Kutta integration.

Complexity

Each step does a fixed number of dot products, scalings and one cross product, so NN steps take Θ(N)\Theta(N) time. Wang et al. count 28 additions, 32 multiplications and 2 divisions per frame. The method needs Θ(1)\Theta(1) memory besides the output, since each frame depends only on the one before it. A fourth-order Runge-Kutta integration of the defining equation reaches the same order, but it needs the second derivative of the curve and several evaluations per step.

Properties

  • Fourth order. The global error is O(h4)O(h^4) for equally spaced parameters, as the table of the example shows.
  • Exact on planes and spheres. For curves in a plane or on a sphere, the frames equal the exact rotation minimizing frames at the sample points.
  • Orthonormal by construction. Every frame is an exact rotation of the first one, up to roundoff, with no normalization step.
  • Symmetric. The backward run from the last frame gives back the earlier frames.
  • Only points and tangents. The method needs no second derivative and no curvature, so it also works on a curve that is given by samples and tangent estimates.
  • Defined where the curvature is zero. On a straight piece, R1R_1 and R2R_2 both reverse the tangent, and the frame does not change.

Variants and improvements

  • Closed curves. On a closed curve, the last frame differs from the first by a rotation about the tangent by some angle α\alpha. Adding the twist −α i/N-\alpha\,i/N to frame ii spreads the error evenly and closes the frame. The angle is a property of the curve, not an error of the method.
  • Projection method. Projecting rir_i onto the plane normal to ti+1t_{i+1} and normalizing it is simpler, but it is only of the first order globally, as the example shows.
  • Rotation method. Rotating the frame by the smallest rotation that takes tit_i to ti+1t_{i+1}, about the axis ti×ti+1t_i \times t_{i+1}, ignores the positions of the points. On the helix of the example its error falls only by 4 when the step is halved, from 0.120.12 at N=8N = 8 to 1.8⋅10−31.8 \cdot 10^{-3} at N=64N = 64.
  • Runge-Kutta integration. A Runge-Kutta method on r′=−(r⋅t′)tr' = -(r \cdot t')t gives any order, but it needs the derivatives of the tangent and a final normalization.
  • Rational frames. For some polynomial curves, such as Pythagorean hodograph curves, a rotation minimizing frame with rational coefficients exists, and it can be computed exactly.

When to use it

Use the double reflection method to frame sweep surfaces, tubes, ribbons, roads, roller coasters and camera paths, where the frame must follow the curve without twist. For a polyline that is the curve itself, as in discrete elastic rods, the frame is moved from edge to edge by the rotation method instead, which is exact for that discrete curve. If the frame must point a given direction, as for a camera that keeps the horizon level, a rotation minimizing frame is the wrong frame, and an up vector or a keyframed orientation is the better tool.

Pitfalls

  • Large steps. The method assumes that neighbouring tangents are close. If a step is so large that R1tiR_1t_i is close to ti+1t_{i+1}, then c2c_2 is small and the direction of v2v_2 is badly determined. Sample more points where the curve turns quickly.
  • Bad tangents. The method uses the given tangents as exact. Tangents from finite differences of the points lower the accuracy to that of the difference formula.
  • Uneven samples. The fourth-order result is for equally spaced parameters. With very uneven spacing, the error constant grows.
  • The start normal. r0r_0 must be perpendicular to t0t_0. A start vector parallel to t0t_0 has no valid projection.
  • Closed curves do not close. Expect a twist between the last frame and the first frame on a closed curve, and correct it as in the variants.

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
double_reflection_method.py 74 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/double-reflection-method/. The authors are listed in prov/EA23M6.jsonl.
"""Double reflection method for a rotation minimizing frame (Wang, Juttler, Zheng and Liu 2008).

The input is a list of points x_0, ..., x_N on a space curve, the unit
tangents t_0, ..., t_N at these points, and a unit normal r_0 at x_0. Each
step maps the frame at x_i to the frame at x_(i+1) by two reflections:

    R1 is the reflection in the plane through the midpoint of x_i x_(i+1)
       that is perpendicular to v1 = x_(i+1) - x_i,
    R2 is the reflection that takes R1 t_i to t_(i+1), with v2 = t_(i+1) - R1 t_i,

and r_(i+1) = R2 R1 r_i, s_(i+1) = t_(i+1) x r_(i+1). The product R2 R1 is a
rotation that takes t_i to t_(i+1), so every frame (r_i, s_i, t_i) is a right
handed orthonormal frame. For points u_i = a + i h on a smooth curve, the
global error is O(h^4) (Theorem 4.5 of the paper).

If v1 = 0 (a repeated point), this implementation uses v1 = t_i, the limit
of the chord direction; then the step is the smallest rotation from t_i to
t_(i+1). For small steps on a smooth curve, R1 t_i is close to -t_(i+1) and
v2 . v2 is close to 4. If v2 . v2 < C2_MIN, the direction of v2 is not
determined and ValueError is raised: the step is too coarse.
"""

from anim import cross, dot, normalize, scale, sub

C2_MIN = 1e-16


def reflect(a, v, c):
    """Return the reflection a - (2 / c) (v . a) v of a in the plane normal to v, with c = v . v."""
    return sub(a, scale(v, 2.0 * dot(v, a) / c))


def double_reflection(points, tangents, r0):
    """Return the frames [(r_i, s_i, t_i)] of the double reflection method.

    points and tangents have the same length N + 1 >= 1. The tangents are
    normalized here. r0 is projected onto the plane normal to t_0 and
    normalized, so any vector that is not parallel to t_0 is accepted.
    """
    if len(points) != len(tangents) or len(points) == 0:
        raise ValueError("points and tangents must be nonempty lists of the same length")
    ts = [normalize(t) for t in tangents]
    t0 = ts[0]
    r = normalize(sub(r0, scale(t0, dot(r0, t0))))
    frames = [(r, cross(t0, r), t0)]
    for i in range(len(points) - 1):  # @line L1
        v1 = sub(points[i + 1], points[i])  # @line L2
        c1 = dot(v1, v1)
        if c1 == 0.0:
            # A repeated point: use the limit direction of the chord, the tangent.
            v1, c1 = ts[i], 1.0
        r_l = reflect(r, v1, c1)  # @line L3
        t_l = reflect(ts[i], v1, c1)  # @line L4
        v2 = sub(ts[i + 1], t_l)  # @line L5
        c2 = dot(v2, v2)
        if c2 < C2_MIN:
            raise ValueError("step %d is too coarse: the reflected tangent equals the next tangent" % i)
        r = reflect(r_l, v2, c2)  # @line L6
        frames.append((r, cross(ts[i + 1], r), ts[i + 1]))  # @line L7
    return frames  # @line L8


def sample_curve(c, dc, a, b, n):
    """Return the points c(u_i) and the unit tangents of dc(u_i) for u_i = a + i (b - a) / n."""
    us = [a + (b - a) * i / n for i in range(n + 1)]
    return [tuple(c(u)) for u in us], [normalize(dc(u)) for u in us]


def rotation_minimizing_frames(c, dc, a, b, n, r0):
    """Return the frames of the double reflection method at n + 1 equally spaced parameters of c."""
    points, tangents = sample_curve(c, dc, a, b, n)
    return double_reflection(points, tangents, r0)
test_double_reflection_method.py 209 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/double-reflection-method/. The authors are listed in prov/EA23M6.jsonl.
import math
import random

import pytest

import anim
from double_reflection_method import double_reflection, rotation_minimizing_frames, sample_curve


def helix(a, b):
    w = math.hypot(a, b)

    def c(u):
        return (a * math.cos(u), a * math.sin(u), b * u)

    def dc(u):
        return (-a * math.sin(u), a * math.cos(u), b)

    def exact_r(u, theta0):
        # The rotation minimizing normal: theta(u) = theta0 - (b / w) u from the Frenet normal.
        n = (-math.cos(u), -math.sin(u), 0.0)
        bn = (b * math.sin(u) / w, -b * math.cos(u) / w, a / w)
        th = theta0 - b * u / w
        return anim.add(anim.scale(n, math.cos(th)), anim.scale(bn, math.sin(th)))

    return c, dc, exact_r


def twisted_cubic():
    def c(u):
        return (u, u * u, u**3)

    def dc(u):
        return (1.0, 2 * u, 3 * u * u)

    def ddc(u):
        return (0.0, 2.0, 6 * u)

    return c, dc, ddc


def rk4_rmf(dc, ddc, a, b, steps, r0):
    # Reference: RK4 on the defining equation r' = -(r . t') t, with t' = (x'' - (t . x'') t) / |x'|.
    def f(u, r):
        d1, d2 = dc(u), ddc(u)
        sp = anim.norm(d1)
        t = anim.scale(d1, 1.0 / sp)
        dt = anim.scale(anim.sub(d2, anim.scale(t, anim.dot(t, d2))), 1.0 / sp)
        return anim.scale(t, -anim.dot(r, dt))

    h = (b - a) / steps
    r = r0
    for k in range(steps):
        u = a + k * h
        k1 = f(u, r)
        k2 = f(u + h / 2, anim.add(r, anim.scale(k1, h / 2)))
        k3 = f(u + h / 2, anim.add(r, anim.scale(k2, h / 2)))
        k4 = f(u + h, anim.add(r, anim.scale(k3, h)))
        r = anim.add(r, anim.scale(anim.add(anim.add(k1, k4), anim.scale(anim.add(k2, k3), 2.0)), h / 6))
    return r


def test_frames_are_right_handed_and_orthonormal(rng=random.Random(1)):
    coef = [[rng.uniform(-2, 2) for _ in range(4)] for _ in range(3)]

    def c(u):
        return tuple(sum(row[k] * u**k for k in range(4)) for row in coef)

    def dc(u):
        return tuple(sum(k * row[k] * u ** (k - 1) for k in range(1, 4)) for row in coef)

    frames = rotation_minimizing_frames(c, dc, 0.0, 1.0, 50, (rng.gauss(0, 1), rng.gauss(0, 1), rng.gauss(0, 1)))
    for r, s, t in frames:
        for x in (r, s, t):
            assert abs(anim.dot(x, x) - 1.0) < 1e-12
        assert abs(anim.dot(r, s)) < 1e-12 and abs(anim.dot(r, t)) < 1e-12 and abs(anim.dot(s, t)) < 1e-12
        assert anim.norm(anim.sub(anim.cross(r, s), t)) < 1e-12


def test_helix_against_the_closed_form():
    c, dc, exact_r = helix(1.0, 0.5)
    t0 = anim.normalize(dc(0.0))
    r0 = exact_r(0.0, 0.3)
    assert abs(anim.dot(r0, t0)) < 1e-15
    errors = []
    for n in (16, 32, 64):
        frames = rotation_minimizing_frames(c, dc, 0.0, 2 * math.pi, n, r0)
        errors.append(max(anim.norm(anim.sub(fr[0], exact_r(2 * math.pi * i / n, 0.3))) for i, fr in enumerate(frames)))
    assert errors[-1] < 1e-5
    # Fourth order: halving the step divides the error by about 16.
    for e1, e2 in zip(errors, errors[1:]):
        assert 13.0 < e1 / e2 < 19.0


def test_twisted_cubic_against_rk4():
    c, dc, ddc = twisted_cubic()
    r0 = (0.0, 0.0, 1.0)
    ref = rk4_rmf(dc, ddc, 0.0, 1.0, 2000, r0)
    errors = []
    for n in (10, 20, 40, 80):
        r_end = rotation_minimizing_frames(c, dc, 0.0, 1.0, n, r0)[-1][0]
        errors.append(anim.norm(anim.sub(r_end, ref)))
    assert errors[-1] < 1e-6
    for e1, e2 in zip(errors[1:], errors[2:]):
        assert 12.0 < e1 / e2 < 20.0


def test_exact_on_a_plane_curve(rng=random.Random(2)):
    q = anim.q_normalize(tuple(rng.gauss(0, 1) for _ in range(4)))
    n_plane = anim.q_rotate(q, (0.0, 0.0, 1.0))

    def c(u):
        return anim.q_rotate(q, (math.cos(u), math.sin(2 * u), 0.0))

    def dc(u):
        return anim.q_rotate(q, (-math.sin(u), 2 * math.cos(2 * u), 0.0))

    alpha = 0.7
    t0 = anim.normalize(dc(0.0))
    r0 = anim.add(anim.scale(n_plane, math.cos(alpha)), anim.scale(anim.cross(n_plane, t0), math.sin(alpha)))
    frames = rotation_minimizing_frames(c, dc, 0.0, 3.0, 7, r0)
    for r, _, t in frames:
        exact = anim.add(anim.scale(n_plane, math.cos(alpha)), anim.scale(anim.cross(n_plane, t), math.sin(alpha)))
        assert anim.norm(anim.sub(r, exact)) < 1e-12


def test_exact_on_a_sphere():
    center, rho = (0.3, -1.0, 2.0), 1.7

    def angles(u):
        return 0.5 * math.sin(2 * u), u + 0.3 * u * u, math.cos(2 * u), 1 + 0.6 * u

    def c(u):
        ph, th, _, _ = angles(u)
        return anim.add(center, anim.scale((math.cos(ph) * math.cos(th), math.cos(ph) * math.sin(th), math.sin(ph)), rho))

    def dc(u):
        ph, th, dph, dth = angles(u)
        return anim.scale(
            (
                -math.sin(ph) * dph * math.cos(th) - math.cos(ph) * math.sin(th) * dth,
                -math.sin(ph) * dph * math.sin(th) + math.cos(ph) * math.cos(th) * dth,
                math.cos(ph) * dph,
            ),
            rho,
        )

    r0 = anim.scale(anim.sub(c(0.0), center), 1.0 / rho)
    frames = rotation_minimizing_frames(c, dc, 0.0, 2.5, 6, r0)
    points, _ = sample_curve(c, dc, 0.0, 2.5, 6)
    for (r, _, _), x in zip(frames, points):
        assert anim.norm(anim.sub(r, anim.scale(anim.sub(x, center), 1.0 / rho))) < 1e-12


def test_reversal_returns_the_first_frame():
    c, dc, _ = twisted_cubic()
    points, tangents = sample_curve(c, dc, 0.0, 1.0, 9)
    forward = double_reflection(points, tangents, (0.0, 0.0, 1.0))
    back = double_reflection(points[::-1], [anim.scale(t, -1.0) for t in tangents[::-1]], forward[-1][0])
    for (r, _, _), (rb, _, _) in zip(forward, back[::-1]):
        assert anim.norm(anim.sub(r, rb)) < 1e-12


def test_straight_line_keeps_the_frame():
    points = [(1.0 + k, 2.0 + 2 * k, -k) for k in range(5)]
    tangents = [(1.0, 2.0, -1.0)] * 5
    frames = double_reflection(points, tangents, (2.0, -1.0, 0.0))
    for r, s, t in frames:
        assert anim.norm(anim.sub(r, frames[0][0])) < 1e-15
        assert anim.norm(anim.sub(s, frames[0][1])) < 1e-15


def test_repeated_point_keeps_the_frame():
    c, dc, _ = twisted_cubic()
    points, tangents = sample_curve(c, dc, 0.0, 1.0, 6)
    base = double_reflection(points, tangents, (0.0, 0.0, 1.0))
    dup = double_reflection(points[:3] + points[2:], tangents[:3] + tangents[2:], (0.0, 0.0, 1.0))
    assert anim.norm(anim.sub(dup[2][0], dup[3][0])) < 1e-15
    for a, b in zip(base, dup[:3] + dup[4:]):
        assert anim.norm(anim.sub(a[0], b[0])) < 1e-14


def test_corner_at_a_repeated_point_is_the_smallest_rotation(rng=random.Random(3)):
    t0 = anim.normalize((rng.gauss(0, 1), rng.gauss(0, 1), rng.gauss(0, 1)))
    t1 = anim.normalize((rng.gauss(0, 1), rng.gauss(0, 1), rng.gauss(0, 1)))
    r0 = (1.0, 0.0, 0.0)
    frames = double_reflection([(0.0, 0.0, 0.0)] * 2, [t0, t1], r0)
    axis = anim.cross(t0, t1)
    angle = math.atan2(anim.norm(axis), anim.dot(t0, t1))
    q = anim.q_from_axis_angle(axis, angle)
    assert anim.norm(anim.sub(anim.q_rotate(q, t0), t1)) < 1e-12
    assert anim.norm(anim.sub(frames[1][0], anim.q_rotate(q, frames[0][0]))) < 1e-12


def test_too_coarse_step_raises():
    # The chord is along x, and the next tangent is the mirror image of t_0 in the plane x = 1/2.
    t0 = anim.normalize((1.0, 1.0, 0.0))
    t1 = anim.normalize((-1.0, 1.0, 0.0))
    with pytest.raises(ValueError):
        double_reflection([(0.0, 0.0, 0.0), (1.0, 0.0, 0.0)], [t0, t1], (0.0, 0.0, 1.0))


def test_initial_normal_is_projected():
    frames = double_reflection([(0.0, 0.0, 0.0)], [(0.0, 0.0, 2.0)], (1.0, 0.0, 5.0))
    assert frames[0][0] == pytest.approx((1.0, 0.0, 0.0))
    with pytest.raises(ValueError):
        double_reflection([], [], (1.0, 0.0, 0.0))

History

Bishop (1975) described the relatively parallel frame, a frame along a curve whose normal vectors do not turn about the tangent and which, unlike the Frenet frame, exists where the curvature is zero. Klok (1986) called it the rotation minimizing frame, studied it as the solution of a differential equation for sweeping, and gave a simple projection scheme to compute it. Other early schemes rotated the frame from one tangent to the next. Wang, Jüttler, Zheng and Liu (2008) introduced the double reflection method, proved its exactness on spheres and planes and its fourth-order accuracy, and showed that it is faster than the earlier methods of the same accuracy.

References

  1. Wenping Wang, Bert Jüttler, Dayue Zheng and Yang Liu, Computation of rotation minimizing frames, ACM Transactions on Graphics 27(1), Article 2, 2008, Section 4.1 and Table I (the algorithm), Theorem 4.3 (exact on spheres and planes), Section 4.4 (degenerate cases and symmetry), Theorems 4.4 and 4.5 (local error O(h^5) and global error O(h^4))
  2. Richard L. Bishop, There is more than one way to frame a curve, The American Mathematical Monthly 82(3), 246-251, 1975, the relatively parallel frame, the continuous form of the frame that the method approximates
  3. Fopke Klok, Two moving coordinate frames for sweeping along a 3D trajectory, Computer Aided Geometric Design 3(3), 217-229, 1986, the rotation minimizing frame as the solution of a differential equation, and the projection method that the double reflection method improves

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
  • History with a source
  • a scene preset for the example