Algorithm Search⌘K

Algorithmadvanced

Parametric curve interpolator for CNC

Also called NURBS interpolator, real-time parametric interpolation.

Computes the next curve parameter each servo period by a Taylor expansion in arc length, so the tool follows a spline at the planned feed, after Shpitalni, Koren and Lo.

Time
O(n p^2) worst
Space
O(1) extra
Where
n = number of interpolation periods; p = degree of the curve
Properties
deterministiciterative
Origin
Moshe Shpitalni, Yoram Koren, C. C. Lo, 1994

A parametric curve interpolator is the part of a CNC controller that turns a curved toolpath into the positions that the drives must reach at each tick of the servo clock. The path is a spline, such as a NURBS curve C(u)C(u), and the feed schedule says how fast the tool must move. In each period τ\tau the tool must advance the arc length L=VτL = V\tau along the curve. The difficulty is that the parameter uu is not the arc length, so a fixed step in uu gives an uneven speed, and the exact parameter for a given arc length needs the inverse of an integral. The interpolator of Shpitalni, Koren and Lo uses a Taylor expansion of uu as a function of arc length instead. The second-order step is

Δu=L∣C′∣−L2 (C′⋅C′′)2∣C′∣4,\Delta u = \frac{L}{|C'|} - \frac{L^2\, (C' \cdot C'')}{2|C'|^4},

and the arc length that it really covers differs from LL by O(L3)O(L^3), a relative feed error of order (Vτ)2(V\tau)^2. For a Pythagorean hodograph curve the arc length is a polynomial, so the step can be checked, or computed, exactly.

In plain words

A machine controller wakes up many times a second, and each time it must say where the tool should be next. On a straight line this is easy. On a smooth curve the curve is drawn by a number uu that runs from start to end, but equal steps of uu do not give equal steps along the curve. The tool would speed up and slow down.

The interpolator asks how fast the curve moves when uu changes, and divides the wanted distance by that speed. This first guess is a little off where the curve speeds up or slows down, so a second term corrects for that change. With the correction, the error of each step is tiny, and halving the step makes it eight times smaller, so the error relative to the step length becomes four times smaller.

The problem

Given a regular parametric curve C(u)C(u), u∈[u0,u1]u \in [u_0, u_1], with the derivatives C′C' and C′′C'', a feed VV and a period τ\tau, find parameters u0<u1′<u2′<…u_0 < u_1' < u_2' < \dots such that the arc length from each to the next is L=VτL = V\tau, as closely as possible, with a fixed and small amount of work per period. The arc length s(u)=∫∣C′∣s(u) = \int |C'| has no closed form for most splines, so the exact answer, the inverse of ss at s(uk)+Ls(u_k) + L, is too slow to compute by quadrature and root finding in each period of a millisecond or less. This is the inverse problem of arc length parametrization, solved approximately and in real time.

The algorithm

  1. PARAMETRIC-INTERPOLATOR(C', C'', u_start, u_end, V, τ)
  2. 1L ← V τ ▷ the arc length per period
  3. 2u ← u_start; params ← [u]
  4. 3while u < u_end
  5. 4d₁ ← C'(u); d₂ ← C''(u); σ ← |d₁|
  6. 5Δu ← L/σ − L² (d₁ · d₂) / (2 σ⁴) ▷ Taylor expansion of u(s) to second order
  7. 6u ← min(u + Δu, u_end)
  8. 7append u to params ▷ the drives move to C(u)
  9. 8return params

Line L5 is the Taylor polynomial of degree 2 of u(s+L)−u(s)u(s + L) - u(s). The derivatives of the inverse of s(u)s(u) are du/ds=1/∣C′∣du/ds = 1/|C'| and d2u/ds2=−(C′⋅C′′)/∣C′∣4d^2u/ds^2 = -(C' \cdot C'')/|C'|^4. The first-order interpolator drops the second term. In a real controller VV changes from period to period, as the feed schedule says, and LL is computed in each pass.

Example

Take the PH cubic C(t)=(t−t3/3, t2)C(t) = (t - t^3/3,\ t^2). Its speed is ∣C′∣=1+t2|C'| = 1 + t^2 and its arc length is s(t)=t+t3/3s(t) = t + t^3/3. Here C′⋅C′′=2t(1+t2)C' \cdot C'' = 2t(1 + t^2), so line L5 gives

Δu=L1+t2−L2 t(1+t2)3.\Delta u = \frac{L}{1 + t^2} - \frac{L^2\, t}{(1 + t^2)^3}.

With L=0.1L = 0.1 and the start t=1t = 1, the first steps are:

kk uku_k first-order Δu\Delta u second-order Δu\Delta u first-order error ΔS−L\Delta S - L second-order error ΔS−L\Delta S - L
0 1.000000 0.050000 0.048750 +2.54×10−3+2.54 \times 10^{-3} −8.48×10−5-8.48 \times 10^{-5}
1 1.048750 0.047622 0.046489 +2.41×10−3+2.41 \times 10^{-3} −7.83×10−5-7.83 \times 10^{-5}
2 1.095239 0.045464 0.044435 +2.30×10−3+2.30 \times 10^{-3} −7.21×10−5-7.21 \times 10^{-5}
3 1.139674 0.043500 0.042562 +2.18×10−3+2.18 \times 10^{-3} −6.63×10−5-6.63 \times 10^{-5}

The errors are measured with the exact arc length. At t=1t = 1 the first-order error is L2/4+L3/24L^2/4 + L^3/24 exactly, and the second-order error is close to −L3/12=−8.33×10−5-L^3/12 = -8.33 \times 10^{-5}. Over the whole curve from t=0t = 0 to t=2t = 2, the largest relative errors per step are:

LL first order, PH cubic second order, PH cubic first order, parabola second order, parabola
0.02 6.55×10−36.55 \times 10^{-3} 1.33×10−41.33 \times 10^{-4} 7.78×10−37.78 \times 10^{-3} 2.67×10−42.67 \times 10^{-4}
0.01 3.26×10−33.26 \times 10^{-3} 3.33×10−53.33 \times 10^{-5} 3.87×10−33.87 \times 10^{-3} 6.67×10−56.67 \times 10^{-5}
0.005 1.63×10−31.63 \times 10^{-3} 8.33×10−68.33 \times 10^{-6} 1.93×10−31.93 \times 10^{-3} 1.67×10−51.67 \times 10^{-5}

Halving LL halves the first-order error and divides the second-order error by four, as the theorem says. On the parabola (t,t2)(t, t^2), which is not a PH curve, the reference is the closed form s(t)=12t1+4t2+14asinh⁡(2t)s(t) = \tfrac12 t\sqrt{1 + 4t^2} + \tfrac14 \operatorname{asinh}(2t).

Correctness

Theorem. Let CC be three times continuously differentiable and regular. Then each step of the second-order interpolator covers an arc length ΔS\Delta S with

∣ΔS−L∣≤M1M36L3,|\Delta S - L| \le \frac{M_1 M_3}{6} L^3,

where M1M_1 bounds ∣C′∣|C'| and M3M_3 bounds ∣d3u/ds3∣|d^3u/ds^3|. So the relative feedrate error is O((Vτ)2)O((V\tau)^2). The first-order step has ∣ΔS−L∣≤12M1M2L2|\Delta S - L| \le \tfrac12 M_1 M_2 L^2, a relative error O(Vτ)O(V\tau).

The proof is in the proof file. Line L5 is the Taylor polynomial of u(sk+L)−u(sk)u(s_k + L) - u(s_k), so the parameter misses the exact one by the remainder 16L3u′′′(ξ)\tfrac16 L^3 u'''(\xi), and the arc length misses LL by at most M1M_1 times that. The orders are sharp: (ΔS−L)/L3(\Delta S - L)/L^3 tends to −∣C′∣u′′′/6-|C'| u'''/6, which for the PH cubic is (1−5t2)/(3(1+t2)4)(1 - 5t^2)/(3(1 + t^2)^4). The tests check this limit, and the exact errors L3/3L^3/3 at t=0t = 0 and L2/4+L3/24L^2/4 + L^3/24 at t=1t = 1, in rational arithmetic. They check the orders and the bound on the parabola against the exact arc length, and they compare the parameters with a reference that inverts the exact arc length by bisection.

Proof: The second-order Taylor interpolator moves the arc length L per period up to an error of order L cubed, so its relative feedrate error is of order (V tau) squaredfull

Setting. Let C:[a,b]→RdC : [a, b] \to \mathbb{R}^d be three times continuously differentiable and regular, ∣C′(u)∣>0|C'(u)| > 0 on [a,b][a, b]. Its arc length s(u)=∫au∣C′(w)∣ dws(u) = \int_a^u |C'(w)|\, dw has s′=∣C′∣>0s' = |C'| > 0, and ss is three times continuously differentiable, because ∣C′∣=C′⋅C′|C'| = \sqrt{C' \cdot C'} is twice continuously differentiable where C′≠0C' \ne 0. So ss has an inverse u(s)u(s) on [0,s(b)][0, s(b)], also three times continuously differentiable. The feed is VV, the period is τ\tau, and L=VτL = V\tau. Let

M1=max⁡[a,b]∣C′∣,M2=max⁡∣d2uds2∣,M3=max⁡∣d3uds3∣.M_1 = \max_{[a,b]} |C'|, \qquad M_2 = \max \Big|\frac{d^2u}{ds^2}\Big|, \qquad M_3 = \max \Big|\frac{d^3u}{ds^3}\Big|.

Lemma 1 (derivatives of the inverse). At u=u(s)u = u(s),

duds=1∣C′∣,d2uds2=−C′⋅C′′∣C′∣4.\frac{du}{ds} = \frac{1}{|C'|}, \qquad \frac{d^2u}{ds^2} = -\frac{C' \cdot C''}{|C'|^4}.

Proof. The first is the derivative of an inverse function, 1/s′(u)1/s'(u). For the second, write g(u)=∣C′(u)∣−1=(C′⋅C′)−1/2g(u) = |C'(u)|^{-1} = (C' \cdot C')^{-1/2}. Then g′(u)=−(C′⋅C′)−3/2(C′⋅C′′)g'(u) = -(C' \cdot C')^{-3/2} (C' \cdot C''), and by the chain rule d2u/ds2=g′(u) du/ds=g′(u)g(u)=−(C′⋅C′′)/∣C′∣4d^2u/ds^2 = g'(u)\, du/ds = g'(u) g(u) = -(C' \cdot C'')/|C'|^4. □\square

So line L5 computes Δu2=L u′(sk)+12L2u′′(sk)\Delta u_2 = L\, u'(s_k) + \tfrac12 L^2 u''(s_k), the Taylor polynomial of degree 2 of u(sk+L)−u(sk)u(s_k + L) - u(s_k), where sk=s(uk)s_k = s(u_k). The first-order interpolator uses Δu1=L u′(sk)\Delta u_1 = L\, u'(s_k).

Theorem. Let ΔSk=s(uk+Δu2)−s(uk)\Delta S_k = s(u_k + \Delta u_2) - s(u_k) be the arc length that a step of the second-order interpolator covers, and suppose that uk+Δu2u_k + \Delta u_2 and u(sk+L)u(s_k + L) are in [a,b][a, b]. Then

∣ΔSk−L∣≤M1M36L3,so∣ΔSkL−1∣≤M1M36(Vτ)2.|\Delta S_k - L| \le \frac{M_1 M_3}{6} L^3, \qquad \text{so} \qquad \Big|\frac{\Delta S_k}{L} - 1\Big| \le \frac{M_1 M_3}{6} (V\tau)^2 .

For the first-order step, ∣ΔSk−L∣≤12M1M2L2|\Delta S_k - L| \le \tfrac12 M_1 M_2 L^2, a relative error of order VτV\tau.

Proof. By Taylor's theorem with the Lagrange remainder, there is ξ\xi between sks_k and sk+Ls_k + L with

u(sk+L)=uk+Lu′(sk)+12L2u′′(sk)+16L3u′′′(ξ)=uk+Δu2+16L3u′′′(ξ).u(s_k + L) = u_k + L u'(s_k) + \tfrac12 L^2 u''(s_k) + \tfrac16 L^3 u'''(\xi) = u_k + \Delta u_2 + \tfrac16 L^3 u'''(\xi).

The exact step ends at u∗=u(sk+L)u^\ast = u(s_k + L), where s(u∗)−s(uk)=Ls(u^\ast) - s(u_k) = L. So

ΔSk−L=s(uk+Δu2)−s(u∗).\Delta S_k - L = s(u_k + \Delta u_2) - s(u^\ast).

By the mean value theorem, ∣s(x)−s(y)∣≤M1∣x−y∣|s(x) - s(y)| \le M_1 |x - y|, and ∣uk+Δu2−u∗∣=16L3∣u′′′(ξ)∣≤16M3L3|u_k + \Delta u_2 - u^\ast| = \tfrac16 L^3 |u'''(\xi)| \le \tfrac16 M_3 L^3. This gives the first bound, and division by LL gives the second. For the first-order step the remainder is 12L2u′′(ξ)\tfrac12 L^2 u''(\xi) instead, and the same argument gives 12M1M2L2\tfrac12 M_1 M_2 L^2. □\square

The orders are sharp. Write ΔSk−L=s′(η)(uk+Δu2−u∗)\Delta S_k - L = s'(\eta)\big(u_k + \Delta u_2 - u^\ast\big) for some η\eta between the two end parameters. As L→0L \to 0, η→uk\eta \to u_k and ξ→sk\xi \to s_k, so

ΔSk−LL3→−∣C′(uk)∣ u′′′(sk)6.\frac{\Delta S_k - L}{L^3} \to -\frac{|C'(u_k)|\, u'''(s_k)}{6}.

This limit is not zero where u′′′≠0u''' \ne 0, so the error is of order exactly L3L^3 there. In the same way, the first-order error divided by L2L^2 tends to −∣C′∣u′′/2=(C′⋅C′′)/(2∣C′∣3)-|C'| u''/2 = (C' \cdot C'')/(2|C'|^3), which is not zero where the speed of the curve changes.

Exact check on a Pythagorean hodograph cubic. For C(t)=(t−t3/3, t2)C(t) = (t - t^3/3,\ t^2), C′=(1−t2,2t)C' = (1 - t^2, 2t) and ∣C′∣=1+t2|C'| = 1 + t^2, so s(t)=t+t3/3s(t) = t + t^3/3. Then C′′=(−2t,2)C'' = (-2t, 2) and C′⋅C′′=2t(1+t2)C' \cdot C'' = 2t(1 + t^2), so

Δu2=L1+t2−L2t(1+t2)3.\Delta u_2 = \frac{L}{1 + t^2} - \frac{L^2 t}{(1 + t^2)^3}.

Also u′′(s)=−2t/(1+t2)3u''(s) = -2t/(1+t^2)^3 and u′′′(s)=(10t2−2)/(1+t2)5u'''(s) = (10t^2 - 2)/(1 + t^2)^5, so the limit above is (1−5t2)/(3(1+t2)4)(1 - 5t^2)/(3(1 + t^2)^4). At t=0t = 0, Δu2=L\Delta u_2 = L and ΔS−L=L3/3\Delta S - L = L^3/3 exactly. At t=1t = 1, the first-order step is L/2L/2 with the error L2/4+L3/24L^2/4 + L^3/24 exactly, and the second-order error is −L3/12+O(L4)-L^3/12 + O(L^4). The tests check these values in exact rational arithmetic.

The loop. Each pass of the loop moves uu forward by a positive step, and the code stops with an error if the step is not positive. On a regular curve, Δu2=L/∣C′∣+O(L2)\Delta u_2 = L/|C'| + O(L^2) is at least L/(2M1)L/(2M_1) once LL is small enough, so the loop ends after at most 2M1(b−a)/L+12M_1(b - a)/L + 1 passes, and the last point is clipped to uendu_{\text{end}}.

What is not covered. The theorem bounds the arc length of each step. The machine moves along the chord between C(uk)C(u_k) and C(uk+1)C(u_{k+1}), which is shorter than the arc by κ2ΔS3/24+O(ΔS4)\kappa^2 \Delta S^3/24 + O(\Delta S^4) for a curve of curvature κ\kappa, so the feed along the chords has a relative error of order L2L^2 as well, from this second source. The errors of all steps add up, so after nn steps the position along the curve may drift by up to nM1M3L3/6n M_1 M_3 L^3 / 6, which is of order L2L^2 times the length of the path.

Complexity

Each period evaluates C′C' and C′′C'' once and does O(1)O(1) more arithmetic. For a NURBS curve of degree pp the derivatives cost O(p2)O(p^2) with the de Boor recurrences, so nn periods take O(np2)O(n p^2) time and O(1)O(1) extra space. The work per period is fixed, which is what a real-time controller needs. The exact method, quadrature and Newton steps on s(u)s(u), has no fixed bound on its work.

Properties

  • Second order. The relative feed error per step is O((Vτ)2)O((V\tau)^2), against O(Vτ)O(V\tau) for the first-order step.
  • Fixed work per period. Two derivative evaluations and a few operations.
  • Accumulating error. The step errors add up. After nn steps the position along the curve can drift by nn times the step bound, which is of order L2L^2 times the path length.
  • No chord control. The tool moves along chords between the computed points, and the chord is shorter than the arc by about κ2L3/24\kappa^2 L^3/24, so a separate feed limit is needed on tight curves.
  • Exact on PH curves when solved exactly. For a PH curve, s(u)s(u) is a polynomial, and a few Newton steps on it give the exact parameter.

Variants and improvements

  • First-order interpolator. Δu=L/∣C′∣\Delta u = L/|C'| only. It is simpler and has the relative error O(Vτ)O(V\tau).
  • Higher order and predictor-corrector. More Taylor terms, or one Newton correction on an approximate arc length, reduce the feed error further.
  • PH curve interpolators. Farouki and Shah used the polynomial arc length of PH curves to solve s(u)=s(uk)+Ls(u) = s(u_k) + L by Newton steps, with no truncation error in the feed.
  • Adaptive feed with a chord limit. Yeh and Hsu lower VV where the chord error ρ−ρ2−L2/4\rho - \sqrt{\rho^2 - L^2/4} on the circle of curvature would exceed a tolerance. This is one of the speed limits of feedrate scheduling.
  • Feed correction polynomials. Some interpolators fit a polynomial to u(s)u(s) before the run, from the exact arc length, and evaluate it in real time.

When to use it

Use a parametric interpolator when the CAM system can send splines to the controller, as in high-speed milling of molds, dies and aircraft parts. It replaces many short lines, which give a jerky motion and large programs, by a smooth curve followed at the planned feed. The second-order step is the usual choice. Use the exact PH method when the path is a PH curve.

Pitfalls

  • Singular points. Where C′=0C' = 0, the step is not defined. Splines with repeated control points or cusps must be repaired before interpolation.
  • Long periods on tight curves. If LL is not small compared with the radius of curvature and the scale on which ∣C′∣|C'| changes, the second term can be larger than the first, and the step can even be negative. The implementation stops with an error then.
  • Drift. The small step errors add up over a long path. Controllers that must end exactly at a point correct the last steps.
  • The feed is along the chords. The interpolator controls the arc length of each step, but the drives follow straight chords. Both errors are of order L2L^2 relative to LL.
  • Feed changes. The expansion assumes a constant VV in the period. With acceleration, a term in V˙\dot V is added, or VV is taken at the middle of the period.

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.

parametric_cnc_interpolator.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/parametric-cnc-interpolator/. The authors are listed in prov/QFCNX0.jsonl.

"""A parametric curve interpolator for CNC, after Shpitalni, Koren and Lo.

The tool follows a parametric curve C(u). In each interpolation period tau
it should move the arc length L = V tau along the curve. The interpolator
computes the next parameter by the Taylor expansion of u as a function of
the arc length s:

    du/ds   = 1 / |C'|
    d2u/ds2 = -(C' . C'') / |C'|^4

so the second order step is

    du = L / |C'| - L^2 (C' . C'') / (2 |C'|^4)

and the first order step keeps only the first term. The arc length that
the step really covers differs from L by O(L^3) for the second order step
and by O(L^2) for the first order step.

Curves are given by their derivative functions d1(u) = C'(u) and
d2(u) = C''(u), which return tuples. The speed |C'(u)| is computed with
math.sqrt unless a function `speed` is given. For a Pythagorean hodograph
curve the speed is a polynomial, and with Fractions the whole step is exact.
"""

import math


def dot(a, b):
    return sum(x * y for x, y in zip(a, b))


def taylor_step(d1, d2, u, L, order=2, speed=None):
    """The parameter increment for the arc length L at the parameter u."""
    a = d1(u)
    sigma = speed(u) if speed is not None else math.sqrt(dot(a, a))
    if sigma == 0:
        raise ValueError("the curve is singular: C'(u) = 0")
    du = L / sigma
    if order == 2:
        b = d2(u)
        du -= L * L * dot(a, b) / (2 * sigma ** 4)
    elif order != 1:
        raise ValueError("order must be 1 or 2")
    return du


def interpolate(d1, d2, u_start, u_end, V, tau, order=2, speed=None):
    """The list of parameters at the ends of the periods, from u_start to u_end."""
    if V <= 0 or tau <= 0:
        raise ValueError("the feed and the period must be positive")
    L = V * tau  # @line L1
    u = u_start  # @line L2
    params = [u]
    if order not in (1, 2):
        raise ValueError("order must be 1 or 2")
    while u < u_end:  # @line L3
        a, b = d1(u), d2(u)  # @line L4
        sigma = speed(u) if speed is not None else math.sqrt(dot(a, a))
        if sigma == 0:
            raise ValueError("the curve is singular: C'(u) = 0")
        du = L / sigma - (L * L * dot(a, b) / (2 * sigma ** 4) if order == 2 else 0)  # @line L5
        if du <= 0:
            raise ValueError("the step is not positive; the period is too long for this curve")
        u = min(u + du, u_end)  # @line L6
        params.append(u)  # @line L7
    return params  # @line L8


def exact_parameters(s, s_inverse, u_start, u_end, V, tau):
    """Reference method: the parameters at arc length steps of exactly V tau,
    from the arc length function s(u) and its inverse."""
    L = V * tau
    s0, s1 = s(u_start), s(u_end)
    params = [u_start]
    k = 1
    while s0 + k * L < s1:
        params.append(s_inverse(s0 + k * L))
        k += 1
    params.append(u_end)
    return params


def feed_errors(params, s, L):
    """The relative error (arc length of the step - L) / L of each full step."""
    out = []
    for a, b in zip(params, params[1:-1]):
        out.append((s(b) - s(a) - L) / L)
    return out
test_parametric_cnc_interpolator.py 154 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/parametric-cnc-interpolator/. The authors are listed in prov/QFCNX0.jsonl.

import math
import random
from fractions import Fraction as F

import pytest

from parametric_cnc_interpolator import exact_parameters, feed_errors, interpolate, taylor_step

# The Pythagorean hodograph cubic C(t) = (t - t^3/3, t^2): |C'(t)| = 1 + t^2,
# so its arc length s(t) = t + t^3/3 is a polynomial and exact with Fractions.


def ph_d1(t):
    return (1 - t * t, 2 * t)


def ph_d2(t):
    return (-2 * t, 2)


def ph_speed(t):
    return 1 + t * t


def ph_s(t):
    return t + t ** 3 / 3


def ph_leading(t):
    """The limit of (step arc length - L) / L^3 at t, from -|C'| u'''(s) / 6."""
    return (1 - 5 * t * t) / (3 * (1 + t * t) ** 4)


# The parabola C(t) = (t, t^2) is not a PH curve; its arc length has a closed form.


def pa_d1(t):
    return (1.0, 2.0 * t)


def pa_d2(t):
    return (0.0, 2.0)


def pa_s(t):
    return t * math.sqrt(1 + 4 * t * t) / 2 + math.asinh(2 * t) / 4


def pa_s_inverse(S):
    lo, hi = 0.0, 10.0
    for _ in range(200):
        mid = (lo + hi) / 2
        if pa_s(mid) < S:
            lo = mid
        else:
            hi = mid
    return (lo + hi) / 2


def step_error(u, L, order):
    du = taylor_step(ph_d1, ph_d2, u, L, order, speed=ph_speed)
    return ph_s(u + du) - ph_s(u) - L


def test_step_at_zero_is_exact_to_the_cubic_term():
    for L in [F(1, 10), F(1, 100), F(3, 1000)]:
        assert taylor_step(ph_d1, ph_d2, F(0), L, 2, ph_speed) == L
        assert step_error(F(0), L, 2) == L ** 3 / 3


def test_step_at_one_closed_forms():
    for L in [F(1, 10), F(1, 100), F(1, 1000)]:
        # first order: du = L/2, the error is L^2/4 + L^3/24 exactly
        assert step_error(F(1), L, 1) == L ** 2 / 4 + L ** 3 / 24
        # second order: du = L/2 - L^2/8, the error is -L^3/12 + O(L^4)
        e = step_error(F(1), L, 2)
        assert abs(e / L ** 3 + F(1, 12)) <= L


def test_leading_term_exact_on_random_parameters():
    rng = random.Random(11)
    L = F(1, 2000)
    for _ in range(40):
        u = F(rng.randint(0, 300), 100)
        e = step_error(u, L, 2)
        assert abs(e / L ** 3 - ph_leading(u)) <= 4 * L
        # the first order step is wrong already at L^2
        e1 = step_error(u, L, 1)
        c1 = u / (1 + u * u) ** 2  # -|C'| u''(s) / 2 = (C'.C'') / (2 |C'|^3)
        assert abs(e1 / L ** 2 - c1) <= 4 * L


def max_rel_error(order, L, curve):
    if curve == "ph":
        params = interpolate(ph_d1, ph_d2, 0.0, 2.0, L, 1.0, order, speed=ph_speed)
        errs = feed_errors(params, ph_s, L)
    else:
        params = interpolate(pa_d1, pa_d2, 0.0, 2.0, L, 1.0, order)
        errs = feed_errors(params, pa_s, L)
    return max(abs(e) for e in errs), params


@pytest.mark.parametrize("curve", ["ph", "parabola"])
def test_feed_error_orders_against_exact_arc_length(curve):
    e2 = [max_rel_error(2, L, curve)[0] for L in (0.02, 0.01, 0.005)]
    e1 = [max_rel_error(1, L, curve)[0] for L in (0.02, 0.01, 0.005)]
    for a, b in zip(e2, e2[1:]):
        assert 3.5 <= a / b <= 4.5  # relative error O(L^2)
    for a, b in zip(e1, e1[1:]):
        assert 1.8 <= a / b <= 2.2  # relative error O(L)
    assert e2[-1] < e1[-1] / 50


def test_parabola_bound():
    # |relative error| <= max|C'| max|u'''(s)| L^2 / 6; on the parabola over [0, 2],
    # u'(s) = (1 + 4t^2)^(-1/2), and u''' is largest in size at t = 0, where it is -4.
    # max |C'| = sqrt(17).
    for L in (0.02, 0.01, 0.005):
        e2, _ = max_rel_error(2, L, "parabola")
        assert e2 <= math.sqrt(17) * 4 * L * L / 6


def test_matches_the_exact_arc_length_reference():
    L = 0.01
    _, params = max_rel_error(2, L, "parabola")
    ref = exact_parameters(pa_s, pa_s_inverse, 0.0, 2.0, L, 1.0)
    assert abs(len(params) - len(ref)) <= 1
    n = min(len(params), len(ref)) - 1
    # the arc length positions drift by at most the sum of the step errors
    drift = max(abs(pa_s(params[k]) - pa_s(ref[k])) for k in range(n))
    assert drift <= n * (math.sqrt(17) * 4 * L ** 3 / 6)


def test_chord_is_shorter_by_the_curvature_term():
    # chord = arc - kappa^2 arc^3 / 24 + O(arc^4); check at t = 0 on the parabola, kappa = 2
    for L in (0.02, 0.01):
        du = taylor_step(pa_d1, pa_d2, 0.0, L, 2)
        arc = pa_s(du)
        chord = math.hypot(du, du * du)
        assert abs((arc - chord) / arc ** 3 - 4 / 24) <= 2 * L


def test_errors():
    with pytest.raises(ValueError):
        interpolate(ph_d1, ph_d2, 0.0, 1.0, 0.0, 1.0)
    with pytest.raises(ValueError):
        interpolate(lambda t: (0.0, 0.0), ph_d2, 0.0, 1.0, 1.0, 0.01)
    with pytest.raises(ValueError):
        interpolate(ph_d1, ph_d2, 0.0, 1.0, 1.0, 0.01, order=3)
    with pytest.raises(ValueError):
        taylor_step(ph_d1, ph_d2, 0.0, 0.1, order=3)

History

Early CNC controllers could only follow lines and circular arcs, and CAM systems broke curves into many short lines. Shpitalni, Koren and Lo (1994) showed how a controller can follow a parametric curve directly, with the parameter step in each period from the first and second derivatives of the curve. Farouki and Shah (1996) gave interpolators for Pythagorean hodograph curves, whose arc length is a polynomial, and Yeh and Hsu (2002) added a feed limit from the chord error. Commercial controllers added NURBS interpolation in the late 1990s and the 2000s.

References

  1. M. Shpitalni, Y. Koren and C. C. Lo, Realtime curve interpolators, Computer-Aided Design 26(11), 832-838, 1994, the interpolation of parametric curves in real time, with the parameter step from the first and second derivatives of the curve
  2. Rida T. Farouki and Sagar Shah, Real-time CNC interpolators for Pythagorean-hodograph curves, Computer Aided Geometric Design 13(7), 583-600, 1996, the exact arc length of PH curves and the interpolator that solves the polynomial arc length equation in each period
  3. Syh-Shiuh Yeh and Pau-Lo Hsu, Adaptive-feedrate interpolation for parametric curves with a confined chord error, Computer-Aided Design 34(3), 229-237, 2002, the feed limit from the chord error and its use in the Taylor interpolator

About this page

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

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