Algorithm Search⌘K

Algorithmadvanced

PH quintic Hermite interpolation

Also called Farouki-Neff PH interpolation.

Farouki and Neff's construction of planar PH quintics with given end points and end derivatives by complex arithmetic. It gives four solutions, of which one is usually fair.

Time
Θ(N) worst · best
Space
Θ(1) extra
Where
N = the number of samples used to compare the four solutions
Properties
deterministicofflineiterative
Origin
Rida T. Farouki, C. Andrew Neff, 1995

PH quintic Hermite interpolation builds a quintic Pythagorean hodograph curve with given end points and given end derivatives. Farouki and Neff wrote the curve in the complex plane as r′=w2r' = w^2 for a complex quadratic ww, which turns the problem into three quadratic equations that can be solved one after the other with square roots. There are four solutions. One of them is usually a fair curve, and the other three turn too much or turn back and forth, so the algorithm ends with a measured choice among the four. The result has a polynomial speed, an exact arc length and rational offsets, which is what tool path and motion planning code needs.

The model is the real RAM, with exact complex arithmetic and exact square roots. The implementation uses Python complex numbers in floating point.

In plain words

You know where a path starts and ends, in which direction it leaves and arrives, and how fast. You want a smooth curve with these ends whose length you can compute exactly, so that a machine can move along it at a steady speed without approximations. Pythagorean hodograph curves have this property, and the simplest ones that can match all these end conditions have degree five. Their shape is fixed by three complex numbers. The start condition fixes the first, the end condition fixes the third up to a sign, and the end point fixes the middle one up to a second sign. Two signs give four curves through the same ends. Usually one of them is a calm arc, and the others swing out or wiggle. The method computes all four and keeps the calmest.

The problem

Points and vectors of the plane are complex numbers x+iyx + iy. The input is two end points p0,p5p_0, p_5 and two nonzero end derivatives d0,d1d_0, d_1. A PH quintic here is a polynomial curve r:[0,1]→Cr : [0, 1] \to \mathbb{C} with

r′(t)=w(t)2,w(t)=w0(1−t)2+w1 2(1−t)t+w2t2,r'(t) = w(t)^2, \qquad w(t) = w_0 (1 - t)^2 + w_1\, 2 (1 - t) t + w_2 t^2,

for complex w0,w1,w2w_0, w_1, w_2. By the characterization on the PH curve page, with w=u+ivw = u + iv this is x′=u2−v2x' = u^2 - v^2, y′=2uvy' = 2uv, so the speed σ=∣r′∣=∣w∣2=u2+v2\sigma = |r'| = |w|^2 = u^2 + v^2 is a polynomial. The output is the PH quintics with

r(0)=p0,r(1)=p5,r′(0)=d0,r′(1)=d1.r(0) = p_0, \quad r(1) = p_5, \quad r'(0) = d_0, \quad r'(1) = d_1.

This is first order Hermite interpolation in the class of PH quintics. A cubic Hermite interpolant always exists and is unique, but it is a PH curve only for special data. The PH quintic has the same number of real degrees of freedom, three complex coefficients for ww and one for p0p_0, but they enter quadratically. This page uses the left unit normal N=ir′/∣r′∣N = i r'/|r'| and the signed curvature κ=Im⁡(rˉ′r′′)/∣r′∣3\kappa = \operatorname{Im}(\bar r' r'')/|r'|^3, positive where the curve turns toward NN; the mean curvature HH of surfaces does not appear.

The algorithm

The square roots are principal square roots of complex numbers.

  1. PH-QUINTIC-HERMITE(p_0, p_5, d_0, d_1)
  2. 1Δ ← p_5 − p_0
  3. 2w_0 ← √d_0 ▷ fixes the sign of w, which r' = w² does not see
  4. 3for ε in (+1, −1) do
  5. 4w_2 ← ε √d_1
  6. 5c ← 120 Δ − 15 (d_0 + d_1) + 10 w_0 w_2
  7. 6for η in (+1, −1) do
  8. 7w_1 ← (−3 (w_0 + w_2) + η √c) / 4
  9. 8p_1, ..., p_5' ← p_0 + w_0²/5, p_1 + w_0 w_1/5, p_2 + (2 w_1² + w_0 w_2)/15, p_3 + w_1 w_2/5, p_4 + w_2²/5
  10. 9add the curve with control points p_0, p_1, p_2, p_3, p_4, p_5' to S
  11. 10return S

The equations come from the end data. At the ends, r′(0)=w02r'(0) = w_0^2 and r′(1)=w22r'(1) = w_2^2, which gives lines L2 and L4. The squares of the quadratic Bernstein polynomials are quartic Bernstein polynomials, so w2w^2 has the quartic Bernstein coefficients w02w_0^2, w0w1w_0 w_1, (2w12+w0w2)/3(2 w_1^2 + w_0 w_2)/3, w1w2w_1 w_2, w22w_2^2. Integrating gives the control points of line L8, and the end point condition r(1)=p5r(1) = p_5 becomes, after completing the square in w1w_1,

(4w1+3(w0+w2))2=120Δ−15(d0+d1)+10w0w2,\left(4 w_1 + 3 (w_0 + w_2)\right)^2 = 120 \Delta - 15 (d_0 + d_1) + 10 w_0 w_2,

which line L7 solves. The last control point p5′p_5' equals p5p_5 up to rounding.

Choosing one. Among the four curves, choose the one with the least absolute rotation index Rabs=12π∫∣κ∣ dsR_{\text{abs}} = \frac{1}{2\pi} \int |\kappa|\, ds, the total turning of the tangent. Since the tangent angle of r′=w2r' = w^2 is 2arg⁡w2 \arg w, this is 1π∫01∣darg⁡w(t)∣\frac{1}{\pi} \int_0^1 |d \arg w(t)|. The implementation measures it by summing the changes of arg⁡w\arg w over NN equal steps. The choice is a heuristic, supported by measurement and not by a theorem: it rejects curves whose tangent makes extra turns or turns back and forth, and Moon, Farouki and Choi use this measure to compare the four. Bending energy ∫κ2 ds\int \kappa^2\, ds is another criterion and usually agrees.

The speed and the arc length. The speed σ=∣w∣2\sigma = |w|^2 has the quartic Bernstein coefficients

σ0=∣w0∣2,σ1=Re⁡(w0wˉ1),σ2=13(2∣w1∣2+Re⁡(w0wˉ2)),σ3=Re⁡(w1wˉ2),σ4=∣w2∣2,\sigma_0 = |w_0|^2, \quad \sigma_1 = \operatorname{Re}(w_0 \bar w_1), \quad \sigma_2 = \tfrac{1}{3}\left(2 |w_1|^2 + \operatorname{Re}(w_0 \bar w_2)\right), \quad \sigma_3 = \operatorname{Re}(w_1 \bar w_2), \quad \sigma_4 = |w_2|^2,

and the arc length is S=(σ0+σ1+σ2+σ3+σ4)/5S = (\sigma_0 + \sigma_1 + \sigma_2 + \sigma_3 + \sigma_4)/5. The arc length function s(t)s(t) is the quintic with Bernstein coefficients 0,σ0/5,(σ0+σ1)/5,…,S0, \sigma_0/5, (\sigma_0 + \sigma_1)/5, \dots, S.

Example

Take p0=0p_0 = 0, p5=1p_5 = 1, d0=3id_0 = 3i and d1=−3id_1 = -3i: start at the origin going straight up, end at (1,0)(1, 0) going straight down, with speed 33 at both ends. Then Δ=1\Delta = 1, d0+d1=0d_0 + d_1 = 0, and with a=3/2a = \sqrt{3/2},

w0=3i=a(1+i),w2=ε a(1−i),w0w2=3ε,c=120+30ε.w_0 = \sqrt{3i} = a (1 + i), \qquad w_2 = \varepsilon\, a (1 - i), \qquad w_0 w_2 = 3 \varepsilon, \qquad c = 120 + 30 \varepsilon.
ε\varepsilon, η\eta cc w1w_1 p2p_2 p3p_3 arc length SS RabsR_{\text{abs}}
+1+1, +1+1 150150 a≈1.22474a \approx 1.22474 (0.3,0.9)(0.3, 0.9) (0.7,0.9)(0.7, 0.9) 22 0.50.5
+1+1, −1-1 150150 −26≈−4.89898-2\sqrt 6 \approx -4.89898 (−1.2,−0.6)(-1.2, -0.6) (2.2,−0.6)(2.2, -0.6) 22 1.51.5
−1-1, +1+1 9090 (310−36 i)/4(3\sqrt{10} - 3\sqrt 6\, i)/4 (1.03095,0.73095)(1.03095, 0.73095) (1.13095,−0.43095)(1.13095, -0.43095) 1.51.5 ≈1.173\approx 1.173
−1-1, −1-1 9090 (−310−36 i)/4(-3\sqrt{10} - 3\sqrt 6\, i)/4 (−0.13095,−0.43095)(-0.13095, -0.43095) (−0.03095,0.73095)(-0.03095, 0.73095) 1.51.5 ≈1.173\approx 1.173

All four have p1=0.6i=(0,0.6)p_1 = 0.6i = (0, 0.6) and p4=1+0.6i=(1,0.6)p_4 = 1 + 0.6i = (1, 0.6), because these depend only on the end derivatives.

The first solution is an arch. Its w1=aw_1 = a is real, and its control points (0,0)(0, 0), (0,0.6)(0, 0.6), (0.3,0.9)(0.3, 0.9), (0.7,0.9)(0.7, 0.9), (1,0.6)(1, 0.6), (1,0)(1, 0) are symmetric about x=1/2x = 1/2. Its speed has the Bernstein coefficients 3,32,1,32,33, \tfrac{3}{2}, 1, \tfrac{3}{2}, 3, so its arc length is 10/5=210/5 = 2. At t=1/2t = 1/2 it is at the top point (0.5,0.75)(0.5, 0.75), with w=aw = a, w′=w2−w0=−2aiw' = w_2 - w_0 = -2ai, speed 3/23/2 and curvature κ=2Im⁡(wˉw′)/∣w∣4=−8/3\kappa = 2 \operatorname{Im}(\bar w w')/|w|^4 = -8/3. Its tangent turns clockwise by half a turn and never back, so Rabs=1/2R_{\text{abs}} = 1/2, the least possible for these end directions. The second solution has the same length, but its tangent makes a full extra turn: the curve swings out to the left, passes below the chord down to y=−0.1875y = -0.1875, and comes back up on the right, so Rabs=3/2R_{\text{abs}} = 3/2. The third and fourth are mirror images of each other in the line x=1/2x = 1/2 and have inflections. The rule of least RabsR_{\text{abs}} picks the arch.

As a check that is independent of the formula for σ\sigma, the tests compute ∣r′(t)∣|r'(t)| from the control points by differencing and the de Casteljau algorithm, and integrate it by composite Gaussian quadrature. The values agree with SS to about 10−1510^{-15}, here and on random data.

Correctness

The proof file below proves the following, using only the product rule of Bernstein polynomials and the fact that C[t]\mathbb{C}[t] has no zero divisors.

  1. Each of the four curves is a PH quintic with the given end points and end derivatives. The control points of line L8 integrate w2w^2, and the three end conditions are equivalent to w02=d0w_0^2 = d_0, w22=d1w_2^2 = d_1 and the squared equation of line L7.
  2. Every PH quintic with the given end data is one of the four. If r′=v2r' = v^2, then vv or −v-v has v(0)=d0v(0) = \sqrt{d_0}, and the equations then fix v(1)v(1) up to the sign ε\varepsilon and v1v_1 up to the sign η\eta.
  3. The four are pairwise different when both radicands c+1c_{+1} and c−1c_{-1} are nonzero. Two quadratics with w2=v2w^2 = v^2 satisfy w=±vw = \pm v, and with the same nonzero w(0)w(0) this forces w=vw = v. If cε=0c_\varepsilon = 0, the two solutions with this ε\varepsilon coincide.

The speed formula and S=15∑σkS = \frac{1}{5} \sum \sigma_k follow from ∣w∣2=wwˉ|w|^2 = w \bar w by the same product rule. The choice among the four is a measured heuristic and is not part of the proof.

Proof: The construction gives PH quintics with the given end data, there are exactly four when the radicands are nonzero, and there are no othersfull

We use the pseudocode of the page. Points and vectors of the plane are complex numbers. The data are p0,p5∈Cp_0, p_5 \in \mathbb{C} and d0,d1∈C∖{0}d_0, d_1 \in \mathbb{C} \setminus \{0\}, and Δ=p5−p0\Delta = p_5 - p_0. Write Bkn(t)=(nk)(1−t)n−ktkB_k^n(t) = \binom{n}{k} (1 - t)^{n-k} t^k. A PH quintic in the sense of this page is a polynomial curve r(t)r(t) with r′(t)=w(t)2r'(t) = w(t)^2 for a complex polynomial ww of degree at most 22, written w=w0B02+w1B12+w2B22w = w_0 B_0^2 + w_1 B_1^2 + w_2 B_2^2.

Lemma 1 (the square of ww). w2=w02B04+w0w1B14+13(2w12+w0w2)B24+w1w2B34+w22B44w^2 = w_0^2 B_0^4 + w_0 w_1 B_1^4 + \tfrac{1}{3}(2 w_1^2 + w_0 w_2) B_2^4 + w_1 w_2 B_3^4 + w_2^2 B_4^4.

Proof. Bi2Bj2=(2i)(2j)(4i+j)−1Bi+j4B_i^2 B_j^2 = \binom{2}{i}\binom{2}{j} \binom{4}{i+j}^{-1} B_{i+j}^4, since both sides equal (2i)(2j)(1−t)4−i−jti+j\binom{2}{i}\binom{2}{j}(1 - t)^{4-i-j} t^{i+j}. Collect the terms with i+j=ki + j = k. For k=1k = 1 the coefficient is 2w0w1⋅2/4=w0w12 w_0 w_1 \cdot 2/4 = w_0 w_1. For k=2k = 2 it is w12⋅4/6+2w0w2⋅1/6=(2w12+w0w2)/3w_1^2 \cdot 4/6 + 2 w_0 w_2 \cdot 1/6 = (2 w_1^2 + w_0 w_2)/3. The cases k=0,3,4k = 0, 3, 4 are the same. □\square

Lemma 2 (control points). Let h0,…,h4h_0, \dots, h_4 be the coefficients of Lemma 1, and let p0′=p0p_0' = p_0 and pk+1′=pk′+hk/5p_{k+1}' = p_k' + h_k/5. Then the quintic Bézier curve rr with control points p0′,…,p5′p_0', \dots, p_5' satisfies r(0)=p0r(0) = p_0 and r′=w2r' = w^2. These are the points of line L8.

Proof. The derivative of a quintic Bézier curve is r′=5∑k=04(pk+1′−pk′)Bk4=∑khkBk4=w2r' = 5 \sum_{k=0}^4 (p_{k+1}' - p_k') B_k^4 = \sum_k h_k B_k^4 = w^2, and r(0)=p0′r(0) = p_0'. Line L8 computes exactly pk+1′=pk′+hk/5p_{k+1}' = p_k' + h_k/5. □\square

Lemma 3 (the end conditions as equations). A PH quintic rr with r(0)=p0r(0) = p_0 satisfies r(1)=p5r(1) = p_5, r′(0)=d0r'(0) = d_0 and r′(1)=d1r'(1) = d_1 if and only if

w02=d0,w22=d1,(4w1+3(w0+w2))2=120Δ−15(d0+d1)+10w0w2.(1)w_0^2 = d_0, \qquad w_2^2 = d_1, \qquad \left(4 w_1 + 3 (w_0 + w_2)\right)^2 = 120 \Delta - 15 (d_0 + d_1) + 10 w_0 w_2. \tag{1}

Proof. r′(0)=w(0)2=w02r'(0) = w(0)^2 = w_0^2 and r′(1)=w22r'(1) = w_2^2, which gives the first two equations. Since ∫01Bk4 dt=1/5\int_0^1 B_k^4\, dt = 1/5, Lemma 1 gives r(1)−r(0)=15∑khkr(1) - r(0) = \frac{1}{5} \sum_k h_k, so r(1)=p5r(1) = p_5 if and only if

15Δ=3w02+3w0w1+2w12+w0w2+3w1w2+3w22.15 \Delta = 3 w_0^2 + 3 w_0 w_1 + 2 w_1^2 + w_0 w_2 + 3 w_1 w_2 + 3 w_2^2.

Multiply by 88 and subtract (4w1+3(w0+w2))2=16w12+24w0w1+24w1w2+9w02+18w0w2+9w22(4 w_1 + 3(w_0 + w_2))^2 = 16 w_1^2 + 24 w_0 w_1 + 24 w_1 w_2 + 9 w_0^2 + 18 w_0 w_2 + 9 w_2^2. The terms in w1w_1 cancel and

120Δ−(4w1+3(w0+w2))2=15w02+15w22−10w0w2.120 \Delta - (4 w_1 + 3(w_0 + w_2))^2 = 15 w_0^2 + 15 w_2^2 - 10 w_0 w_2.

Given the first two equations, 15w02+15w22=15(d0+d1)15 w_0^2 + 15 w_2^2 = 15(d_0 + d_1), and the last equation of (1) follows. Each step can be reversed. □\square

Lemma 4 (square roots in C[t]\mathbb{C}[t]). If w,v∈C[t]w, v \in \mathbb{C}[t] and w2=v2w^2 = v^2, then w=vw = v or w=−vw = -v.

Proof. (w−v)(w+v)=0(w - v)(w + v) = 0, and C[t]\mathbb{C}[t] has no zero divisors. □\square

Theorem. Let d0,d1≠0d_0, d_1 \ne 0, and for ε=±1\varepsilon = \pm 1 let cε=120Δ−15(d0+d1)+10d0 εd1c_\varepsilon = 120 \Delta - 15 (d_0 + d_1) + 10 \sqrt{d_0}\, \varepsilon \sqrt{d_1}, with the principal square roots.

  1. Each of the curves returned in line L10 is a PH quintic with r(0)=p0r(0) = p_0, r(1)=p5r(1) = p_5, r′(0)=d0r'(0) = d_0, r′(1)=d1r'(1) = d_1.
  2. Every PH quintic with these end data is one of them.
  3. If c+1≠0c_{+1} \ne 0 and c−1≠0c_{-1} \ne 0, the four curves are pairwise different. If cε=0c_\varepsilon = 0, the two curves with this ε\varepsilon coincide.

Proof. (1) Lines L2, L4 and L7 choose w0=d0w_0 = \sqrt{d_0}, w2=εd1w_2 = \varepsilon \sqrt{d_1} and w1=(−3(w0+w2)+ηcε)/4w_1 = (-3(w_0 + w_2) + \eta \sqrt{c_\varepsilon})/4, and line L5 computes c=cεc = c_\varepsilon. So w02=d0w_0^2 = d_0, w22=d1w_2^2 = d_1, and (4w1+3(w0+w2))2=(ηcε)2=cε(4 w_1 + 3(w_0 + w_2))^2 = (\eta \sqrt{c_\varepsilon})^2 = c_\varepsilon, which is (1). By Lemma 2 the curve of line L8 is a PH quintic with r(0)=p0r(0) = p_0, and by Lemma 3 it has the end data.

(2) Let rr be a PH quintic with the end data, r′=v2r' = v^2. By Lemma 3, v(0)2=d0v(0)^2 = d_0, so v(0)=±d0v(0) = \pm \sqrt{d_0}. Replacing vv by −v-v does not change r′r', so we may assume v(0)=d0=w0v(0) = \sqrt{d_0} = w_0. By Lemma 3 again, v(1)=±d1v(1) = \pm \sqrt{d_1}, which is w2w_2 for one ε\varepsilon, and 4v1+3(w0+w2)4 v_1 + 3(w_0 + w_2) is one of the two square roots ±cε\pm \sqrt{c_\varepsilon} of cεc_\varepsilon, which fixes v1v_1 as the w1w_1 of one η\eta. So vv has the coefficients of one of the four triples, and rr is its curve, since r(0)=p0r(0) = p_0 and r′=v2r' = v^2.

(3) Let two of the triples have quadratics ww and vv with w2=v2w^2 = v^2. By Lemma 4, w=±vw = \pm v. Both have w(0)=v(0)=d0≠0w(0) = v(0) = \sqrt{d_0} \ne 0, so w=vw = v, and the triples are equal. Triples with different ε\varepsilon differ in w2w_2, because d1≠−d1\sqrt{d_1} \ne -\sqrt{d_1}. Triples with the same ε\varepsilon and different η\eta differ in w1w_1 by cε/2\sqrt{c_\varepsilon}/2, which is nonzero exactly when cε≠0c_\varepsilon \ne 0. Different triples give different r′r', and so different curves, since all curves start at p0p_0. □\square

Lemma 5 (speed and arc length). For a PH quintic, ∣r′(t)∣=σ(t)=∣w(t)∣2|r'(t)| = \sigma(t) = |w(t)|^2, a polynomial of degree at most 44 with Bernstein coefficients

σ0=∣w0∣2,σ1=Re⁡(w0wˉ1),σ2=13(2∣w1∣2+Re⁡(w0wˉ2)),σ3=Re⁡(w1wˉ2),σ4=∣w2∣2,\sigma_0 = |w_0|^2, \quad \sigma_1 = \operatorname{Re}(w_0 \bar w_1), \quad \sigma_2 = \tfrac{1}{3}\left(2 |w_1|^2 + \operatorname{Re}(w_0 \bar w_2)\right), \quad \sigma_3 = \operatorname{Re}(w_1 \bar w_2), \quad \sigma_4 = |w_2|^2,

and the arc length is S=15(σ0+⋯+σ4)S = \frac{1}{5}(\sigma_0 + \dots + \sigma_4).

Proof. ∣r′∣=∣w2∣=∣w∣2=wwˉ|r'| = |w^2| = |w|^2 = w \bar w, where wˉ=wˉ0B02+wˉ1B12+wˉ2B22\bar w = \bar w_0 B_0^2 + \bar w_1 B_1^2 + \bar w_2 B_2^2 for real tt. The product rule of Lemma 1 gives the coefficients w0wˉ0w_0 \bar w_0, 12(w0wˉ1+w1wˉ0)\frac{1}{2}(w_0 \bar w_1 + w_1 \bar w_0), 16(4w1wˉ1+w0wˉ2+w2wˉ0)\frac{1}{6}(4 w_1 \bar w_1 + w_0 \bar w_2 + w_2 \bar w_0), 12(w1wˉ2+w2wˉ1)\frac{1}{2}(w_1 \bar w_2 + w_2 \bar w_1) and w2wˉ2w_2 \bar w_2, which are the real numbers above. The integral of each Bk4B_k^4 over [0,1][0, 1] is 1/51/5. □\square

Complexity

Lines L1 to L10 use three complex square roots and a fixed number of complex additions and multiplications, so the four curves cost Θ(1)\Theta(1) operations. The arc length costs Θ(1)\Theta(1) more. The measured absolute rotation index costs Θ(N)\Theta(N) for NN samples per curve, which dominates. A version that splits [0,1][0, 1] at the inflections, the zeros of the quadratic Im⁡(wˉw′)\operatorname{Im}(\bar w w'), and adds the exact changes of arg⁡w\arg w on the pieces costs Θ(1)\Theta(1). Extra space is Θ(1)\Theta(1).

Properties

  • Exact arc length. The speed is a quartic polynomial and the arc length a quintic, with no quadrature. This is what real-time CNC interpolators use to move at a given feed rate along the curve.
  • Rational offsets. As for every PH curve, the offset at distance dd is r+dNr + d N with N=iw2/∣w∣2N = i w^2/|w|^2, a rational curve of degree 99 in the parameter; see offset curve.
  • Invariant under similarities. If all data are mapped by z↦az+bz \mapsto a z + b with a≠0a \ne 0, the set of four solutions is mapped in the same way, and the lengths scale by ∣a∣|a|. The individual labels (ε,η)(\varepsilon, \eta) can change, because the principal square root is not multiplicative. General affine maps do not preserve the PH property, so the method is not affine invariant.
  • Not linear in the data. Doubling the end derivatives does not give a combination of earlier solutions. The shape depends on the magnitudes ∣d0∣|d_0|, ∣d1∣|d_1|, and not only on the directions.
  • Polynomial degree. Five is the least degree for which PH curves can match general first order Hermite data. A PH cubic has a hodograph w2w^2 with ww linear, two complex coefficients, and cannot match two end points and two arbitrary end derivatives.

Variants and improvements

  • Free tangent magnitudes. If only the end directions are given, the magnitudes ∣d0∣|d_0| and ∣d1∣|d_1| are free parameters. Choosing them, for example to make the curve close to a given curve or to minimize bending energy, gives G1G^1 interpolation.
  • PH quintic splines. For C2C^2 interpolation of many points by PH quintics, the coefficients of neighbouring pieces are coupled by quadratic equations that no longer decouple. They are solved by Newton's method for systems from the cubic spline as a starting guess, and among exponentially many formal solutions the one near the cubic spline is kept.
  • Spatial PH quintics. In space the hodograph is written with quaternions, r′=AiA∗r' = \mathcal{A} \mathbf{i} \mathcal{A}^* for a quaternion quadratic A\mathcal{A}, see unit quaternion rotation. The Hermite problem then has a two parameter family of solutions instead of four.
  • Higher order Hermite data. Matching curvature at the ends as well needs PH curves of degree seven.

When to use it

Use it to build tool paths, robot paths or motion curves that a controller will follow at a given speed, when the path is given by points and tangents: each span becomes a PH quintic, and the controller computes the parameter for each arc length exactly. Use it also to convert a free form curve into a chain of PH quintics, sampling points and derivatives and interpolating each span. For curves that are only drawn or intersected, an ordinary cubic Hermite or B-spline curve is simpler, and the arc length can be computed by quadrature when needed.

Pitfalls

  • Taking any one of the four. A fixed choice of the signs, such as ε=η=+1\varepsilon = \eta = +1, gives the good curve for the example above, but not in general. Compute all four and compare.
  • Branches of the square root. The set of four does not depend on which square roots are taken, but the labels do. Code that remembers a solution by its labels can switch to a different curve after a small change of the data that crosses the branch cut of the principal root.
  • Zero end derivatives. For d0=0d_0 = 0, the normalization w0=d0w_0 = \sqrt{d_0} fixes nothing, and the curve has a cusp at the start. The construction requires d0,d1≠0d_0, d_1 \ne 0.
  • Merging solutions. When cεc_\varepsilon is near zero, two solutions are close to each other and sensitive to the data, through the square root.
  • Magnitudes matter. End derivatives that are much longer or shorter than the chord can give a curve with a lot of turning even for the best choice of signs. Scale them in proportion to ∣p5−p0∣|p_5 - p_0|, for example to ∣p5−p0∣|p_5 - p_0| or a small multiple of it.
  • Rounding of the end point. In floating point, the last control point differs from p5p_5 by rounding. Code that needs exact continuity between spans should copy p5p_5 into it.

Implementations

The Python file in this folder has ph_quintic_hermite(p0, p5, d0, d1), which returns the four solutions with their coefficients and control points, and helpers for the speed, the arc length, the measured absolute rotation index and the choice of the fairest solution. The tests check the end data, the hodograph against the control points, the polynomial speed and arc length against composite Gauss-Legendre quadrature of ∣r′∣|r'|, the distinctness of the four solutions, the solutions against Newton's method on the raw equations from random starts, and the worked example.

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.

ph_quintic_hermite_interpolation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ph-quintic-hermite-interpolation/. The authors are listed in prov/XD0FDH.jsonl.

"""Farouki and Neff's PH quintic Hermite interpolation in the complex plane.

Points and vectors of the plane are Python complex numbers x + iy. A PH
quintic is r(t) with r'(t) = w(t)^2, where w is the complex quadratic
w(t) = w0 (1 - t)^2 + w1 2 (1 - t) t + w2 t^2. Given the end points p0, p5
and the end derivatives d0, d1, there are four such quintics, found with
two complex square roots each. The speed |r'(t)| = |w(t)|^2 is a polynomial,
so the arc length is a finite sum.
"""

import cmath
from typing import NamedTuple


class PHQuintic(NamedTuple):
    eps: int  # sign of w2 relative to the principal root of d1
    eta: int  # sign of the square root in w1
    w: tuple  # (w0, w1, w2), Bernstein coefficients of the quadratic w(t)
    points: tuple  # the six control points p0, ..., p5 of the quintic


def control_points(p0: complex, w: tuple) -> tuple:
    """Return the Bezier control points of p0 + integral of w(t)^2."""
    w0, w1, w2 = w
    p1 = p0 + w0 * w0 / 5
    p2 = p1 + w0 * w1 / 5
    p3 = p2 + (2 * w1 * w1 + w0 * w2) / 15
    p4 = p3 + w1 * w2 / 5
    p5 = p4 + w2 * w2 / 5
    return (p0, p1, p2, p3, p4, p5)


def ph_quintic_hermite(p0: complex, p5: complex, d0: complex, d1: complex) -> list:
    """Return the four PH quintics with r(0) = p0, r(1) = p5, r'(0) = d0, r'(1) = d1.

    The end derivatives must be nonzero. The list has the order
    (eps, eta) = (+1, +1), (+1, -1), (-1, +1), (-1, -1). Two entries
    coincide only when the radicand c of their eps is zero.
    """
    p0, p5, d0, d1 = complex(p0), complex(p5), complex(d0), complex(d1)
    if d0 == 0 or d1 == 0:
        raise ValueError("the end derivatives must be nonzero")
    delta = p5 - p0  # @line L1
    w0 = cmath.sqrt(d0)  # @line L2
    out = []
    for eps in (1, -1):  # @line L3
        w2 = eps * cmath.sqrt(d1)  # @line L4
        c = 120 * delta - 15 * (d0 + d1) + 10 * w0 * w2  # @line L5
        root = cmath.sqrt(c)
        for eta in (1, -1):  # @line L6
            w1 = (-3 * (w0 + w2) + eta * root) / 4  # @line L7
            pts = control_points(p0, (w0, w1, w2))  # @line L8
            out.append(PHQuintic(eps, eta, (w0, w1, w2), pts))  # @line L9
    return out  # @line L10


def evaluate(points, t: float) -> complex:
    """Point of the Bezier curve with complex control points, by de Casteljau."""
    b = list(points)
    for r in range(1, len(b)):
        for i in range(len(b) - r):
            b[i] = (1 - t) * b[i] + t * b[i + 1]
    return b[0]


def hodograph(w: tuple, t: float) -> complex:
    """Return w(t)^2, the derivative r'(t)."""
    w0, w1, w2 = w
    s = 1 - t
    wt = w0 * s * s + 2 * w1 * s * t + w2 * t * t
    return wt * wt


def speed_coefficients(w: tuple) -> tuple:
    """Bernstein coefficients of the degree 4 polynomial sigma(t) = |w(t)|^2."""
    w0, w1, w2 = w
    return (
        abs(w0) ** 2,
        (w0 * w1.conjugate()).real,
        (2 * abs(w1) ** 2 + (w0 * w2.conjugate()).real) / 3,
        (w1 * w2.conjugate()).real,
        abs(w2) ** 2,
    )


def speed(w: tuple, t: float) -> float:
    """Return sigma(t) = |r'(t)| from its Bernstein coefficients."""
    s = speed_coefficients(w)
    u = 1 - t
    basis = (u**4, 4 * u**3 * t, 6 * u * u * t * t, 4 * u * t**3, t**4)
    return sum(a * b for a, b in zip(s, basis))


def arc_length(w: tuple, t: float = 1.0) -> float:
    """Arc length from r(0) to r(t), the integral of sigma, in closed form."""
    s = speed_coefficients(w)
    cum = [0.0]
    for a in s:
        cum.append(cum[-1] + a / 5)
    return evaluate([complex(c) for c in cum], t).real


def absolute_rotation_index(w: tuple, samples: int = 1024) -> float:
    """Measured total turning of the tangent, divided by 2 pi.

    The tangent angle is 2 arg w(t). The sum of |change of 2 arg w| over
    `samples` equal steps converges to the absolute rotation index as the
    steps shrink, provided w has no zero on [0, 1].
    """
    w0, w1, w2 = w
    total = 0.0
    prev = w0
    for k in range(1, samples + 1):
        t = k / samples
        s = 1 - t
        cur = w0 * s * s + 2 * w1 * s * t + w2 * t * t
        total += abs(cmath.phase(cur / prev))
        prev = cur
    return total / cmath.pi


def fairest(solutions: list) -> PHQuintic:
    """The solution with the least absolute rotation index."""
    return min(solutions, key=lambda q: absolute_rotation_index(q.w))
test_ph_quintic_hermite_interpolation.py 213 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ph-quintic-hermite-interpolation/. The authors are listed in prov/XD0FDH.jsonl.

import cmath
import math
import random

from ph_quintic_hermite_interpolation import (
    absolute_rotation_index,
    arc_length,
    evaluate,
    fairest,
    hodograph,
    ph_quintic_hermite,
    speed,
)


def legendre_nodes(n):
    """Gauss-Legendre nodes and weights on [-1, 1], by Newton's method on P_n."""
    nodes, weights = [], []
    for i in range(1, n + 1):
        x = math.cos(math.pi * (i - 0.25) / (n + 0.5))
        for _ in range(100):
            p0, p1 = 1.0, x
            for k in range(2, n + 1):
                p0, p1 = p1, ((2 * k - 1) * x * p1 - (k - 1) * p0) / k
            dp = n * (x * p1 - p0) / (x * x - 1)
            dx = p1 / dp
            x -= dx
            if abs(dx) < 1e-16:
                break
        p0, p1 = 1.0, x
        for k in range(2, n + 1):
            p0, p1 = p1, ((2 * k - 1) * x * p1 - (k - 1) * p0) / k
        dp = n * (x * p1 - p0) / (x * x - 1)
        nodes.append(x)
        weights.append(2 / ((1 - x * x) * dp * dp))
    return nodes, weights


NODES, WEIGHTS = legendre_nodes(12)


def gauss(f, a, b, panels=16):
    """Composite Gauss-Legendre quadrature of f on [a, b]."""
    h = (b - a) / panels
    total = 0.0
    for j in range(panels):
        lo = a + j * h
        for x, wt in zip(NODES, WEIGHTS):
            total += wt * f(lo + (x + 1) * h / 2) * h / 2
    return total


def bezier_derivative(points, t):
    """r'(t) from the control points alone: 5 times the Bezier curve of the differences."""
    diffs = [5 * (points[i + 1] - points[i]) for i in range(5)]
    return evaluate(diffs, t)


def random_data(rng):
    def z():
        return complex(rng.uniform(-2, 2), rng.uniform(-2, 2))

    d0, d1 = z(), z()
    while abs(d0) < 0.2:
        d0 = z()
    while abs(d1) < 0.2:
        d1 = z()
    return z(), z(), d0, d1


def close(a, b, tol=1e-10):
    return abs(a - b) <= tol * (1 + abs(a) + abs(b))


def test_gauss_legendre_rule():
    assert close(gauss(lambda t: t**7, 0, 1, panels=1), 1 / 8, 1e-14)
    assert close(gauss(math.exp, 0, 1), math.e - 1, 1e-14)


def test_end_data():
    rng = random.Random(20260101)
    for _ in range(300):
        p0, p5, d0, d1 = random_data(rng)
        sols = ph_quintic_hermite(p0, p5, d0, d1)
        assert len(sols) == 4
        for q in sols:
            pts = q.points
            assert close(pts[0], p0) and close(pts[5], p5)
            assert close(5 * (pts[1] - pts[0]), d0)
            assert close(5 * (pts[5] - pts[4]), d1)
            assert close(evaluate(pts, 0.0), p0) and close(evaluate(pts, 1.0), p5)


def test_hodograph_is_square_of_w():
    rng = random.Random(7)
    for _ in range(100):
        sols = ph_quintic_hermite(*random_data(rng))
        for q in sols:
            for k in range(11):
                t = k / 10
                assert close(bezier_derivative(q.points, t), hodograph(q.w, t))


def test_speed_is_polynomial_and_matches_numerical_arc_length():
    rng = random.Random(31337)
    for _ in range(60):
        sols = ph_quintic_hermite(*random_data(rng))
        for q in sols:
            for k in range(21):
                t = k / 20
                assert close(speed(q.w, t), abs(bezier_derivative(q.points, t)))
            # Arc length by Gauss-Legendre on |r'(t)| computed from the control points.
            numeric = gauss(lambda t: abs(bezier_derivative(q.points, t)), 0.0, 1.0)
            assert close(arc_length(q.w), numeric, 1e-9)
            numeric_half = gauss(lambda t: abs(bezier_derivative(q.points, t)), 0.0, 0.37)
            assert close(arc_length(q.w, 0.37), numeric_half, 1e-9)


def test_four_distinct_solutions():
    rng = random.Random(99)
    for _ in range(200):
        sols = ph_quintic_hermite(*random_data(rng))
        for i in range(4):
            for j in range(i + 1, 4):
                assert sols[i].w != sols[j].w
                # Different w with the same w0 give different curves somewhere.
                diff = max(abs(evaluate(sols[i].points, k / 8) - evaluate(sols[j].points, k / 8)) for k in range(9))
                assert diff > 1e-9


def newton_reference(p0, p5, d0, d1, start):
    """Solve w2^2 = d1 and integral of w^2 = p5 - p0 for (w1, w2) by complex Newton."""
    w0 = cmath.sqrt(d0)
    w1, w2 = start
    delta = p5 - p0
    for _ in range(100):
        f1 = w2 * w2 - d1
        f2 = (w0 * w0 + w0 * w1 + (2 * w1 * w1 + w0 * w2) / 3 + w1 * w2 + w2 * w2) / 5 - delta
        a, b = 0, 2 * w2
        c, d = (w0 + 4 * w1 / 3 + w2) / 5, (w0 / 3 + w1 + 2 * w2) / 5
        det = a * d - b * c
        if det == 0:
            return None
        s1 = (d * f1 - b * f2) / det
        s2 = (a * f2 - c * f1) / det
        w1, w2 = w1 - s1, w2 - s2
        if abs(s1) + abs(s2) < 1e-14:
            return w1, w2
    return None


def test_against_newton_on_the_raw_equations():
    rng = random.Random(4242)
    for _ in range(25):
        data = random_data(rng)
        sols = ph_quintic_hermite(*data)
        found = set()
        for _ in range(60):
            start = (complex(rng.uniform(-4, 4), rng.uniform(-4, 4)), complex(rng.uniform(-4, 4), rng.uniform(-4, 4)))
            r = newton_reference(*data, start)
            if r is None:
                continue
            # Every root of the raw system is one of the four solutions.
            matches = [i for i, q in enumerate(sols) if abs(q.w[1] - r[0]) < 1e-8 and abs(q.w[2] - r[1]) < 1e-8]
            assert len(matches) == 1
            found.add(matches[0])
        assert found == {0, 1, 2, 3}


def test_worked_example():
    sols = ph_quintic_hermite(0, 1, 3j, -3j)
    good = sols[0]
    expected = (0, 0.6j, 0.3 + 0.9j, 0.7 + 0.9j, 1 + 0.6j, 1)
    assert all(close(a, b, 1e-14) for a, b in zip(good.points, expected))
    assert close(arc_length(good.w), 2.0, 1e-14)
    loop = sols[1]
    assert close(loop.w[1], -2 * math.sqrt(6), 1e-14)
    assert all(close(a, b, 1e-14) for a, b in zip(loop.points, (0, 0.6j, -1.2 - 0.6j, 2.2 - 0.6j, 1 + 0.6j, 1)))
    assert close(arc_length(loop.w), 2.0, 1e-14)
    assert close(arc_length(sols[2].w), 1.5, 1e-14) and close(arc_length(sols[3].w), 1.5, 1e-14)
    assert abs(absolute_rotation_index(good.w) - 0.5) < 1e-9
    assert abs(absolute_rotation_index(loop.w) - 1.5) < 1e-9
    assert fairest(sols) is good


def test_straight_line_data():
    sols = ph_quintic_hermite(0, 1, 1, 1)
    line = fairest(sols)
    assert all(close(line.w[i], 1, 1e-14) for i in range(3))
    for k in range(11):
        assert close(evaluate(line.points, k / 10), k / 10, 1e-14)


def test_invariance_under_similarity():
    rng = random.Random(5)
    for _ in range(50):
        p0, p5, d0, d1 = random_data(rng)
        a = complex(rng.uniform(-2, 2), rng.uniform(-2, 2))
        b = complex(rng.uniform(-2, 2), rng.uniform(-2, 2))
        base = {round(arc_length(q.w), 9) for q in ph_quintic_hermite(p0, p5, d0, d1)}
        moved = {round(arc_length(q.w) / abs(a), 9) for q in ph_quintic_hermite(a * p0 + b, a * p5 + b, a * d0, a * d1)}
        assert base == moved


def test_zero_derivative_rejected():
    try:
        ph_quintic_hermite(0, 1, 0, 1)
    except ValueError:
        return
    raise AssertionError("expected ValueError")

History

Farouki and Sakkalis introduced PH curves in 1990 and gave the PH cubics, which are too stiff for general Hermite data. In 1995 Farouki and Neff solved the first order Hermite problem for PH quintics. In the complex form the equations decouple into square roots, and they showed that there are four solutions, of which typically only one has a reasonable shape. Later work by Moon, Farouki and Choi analysed the shape of the four interpolants, and the method became the base of PH quintic splines and of CNC interpolators for PH tool paths, collected in Farouki's book of 2008.

References

  1. Rida T. Farouki and C. Andrew Neff, Hermite interpolation by Pythagorean hodograph quintics, Mathematics of Computation 64(212), 1995, pp. 1589 to 1609 (the complex form of the problem, the four solutions, and the choice of the good one)
  2. Rida T. Farouki, Pythagorean-Hodograph Curves, Algebra and Geometry Inseparable, Springer, 2008, Chapter 25, planar PH quintic Hermite interpolants (pages 523 to 541), and the chapter on real-time CNC interpolators
  3. Moon, Farouki and Choi 2001, the shape of the four interpolants and their comparison by the absolute rotation index

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.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example