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
- Model
- Real RAM
- Properties
- deterministiciterative
- Evidence
- Proof sketchCode in 1 languages
- 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 , and the feed schedule says how fast the tool must move. In each period the tool must advance the arc length along the curve. The difficulty is that the parameter is not the arc length, so a fixed step in 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 as a function of arc length instead. The second-order step is
and the arc length that it really covers differs from by , a relative feed error of order . 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 that runs from start to end, but equal steps of 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 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 , , with the derivatives and , a feed and a period , find parameters such that the arc length from each to the next is , as closely as possible, with a fixed and small amount of work per period. The arc length has no closed form for most splines, so the exact answer, the inverse of at , 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
PARAMETRIC-INTERPOLATOR(C', C'', u_start, u_end, V, τ)- 1
L ← V τ ▷ the arc length per period - 2
u ← u_start; params ← [u] - 3
while u < u_end - 4
d₁ ← C'(u); d₂ ← C''(u); σ ← |d₁| - 5
Δu ← L/σ − L² (d₁ · d₂) / (2 σ⁴) ▷ Taylor expansion of u(s) to second order - 6
u ← min(u + Δu, u_end) - 7
append u to params ▷ the drives move to C(u) - 8
return params
Line L5 is the Taylor polynomial of degree 2 of . The derivatives of the inverse of are and . The first-order interpolator drops the second term. In a real controller changes from period to period, as the feed schedule says, and is computed in each pass.
Example
Take the PH cubic . Its speed is and its arc length is . Here , so line L5 gives
With and the start , the first steps are:
| first-order | second-order | first-order error | second-order error | ||
|---|---|---|---|---|---|
| 0 | 1.000000 | 0.050000 | 0.048750 | ||
| 1 | 1.048750 | 0.047622 | 0.046489 | ||
| 2 | 1.095239 | 0.045464 | 0.044435 | ||
| 3 | 1.139674 | 0.043500 | 0.042562 |
The errors are measured with the exact arc length. At the first-order error is exactly, and the second-order error is close to . Over the whole curve from to , the largest relative errors per step are:
| first order, PH cubic | second order, PH cubic | first order, parabola | second order, parabola | |
|---|---|---|---|---|
| 0.02 | ||||
| 0.01 | ||||
| 0.005 |
Halving halves the first-order error and divides the second-order error by four, as the theorem says. On the parabola , which is not a PH curve, the reference is the closed form .
Correctness
Theorem. Let be three times continuously differentiable and regular. Then each step of the second-order interpolator covers an arc length with
where bounds and bounds . So the relative feedrate error is . The first-order step has , a relative error .
The proof is in the proof file. Line L5 is the Taylor polynomial of , so the parameter misses the exact one by the remainder , and the arc length misses by at most times that. The orders are sharp: tends to , which for the PH cubic is . The tests check this limit, and the exact errors at and at , 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 be three times continuously differentiable and regular, on . Its arc length has , and is three times continuously differentiable, because is twice continuously differentiable where . So has an inverse on , also three times continuously differentiable. The feed is , the period is , and . Let
Lemma 1 (derivatives of the inverse). At ,
Proof. The first is the derivative of an inverse function, . For the second, write . Then , and by the chain rule .
So line L5 computes , the Taylor polynomial of degree 2 of , where . The first-order interpolator uses .
Theorem. Let be the arc length that a step of the second-order interpolator covers, and suppose that and are in . Then
For the first-order step, , a relative error of order .
Proof. By Taylor's theorem with the Lagrange remainder, there is between and with
The exact step ends at , where . So
By the mean value theorem, , and . This gives the first bound, and division by gives the second. For the first-order step the remainder is instead, and the same argument gives .
The orders are sharp. Write for some between the two end parameters. As , and , so
This limit is not zero where , so the error is of order exactly there. In the same way, the first-order error divided by tends to , which is not zero where the speed of the curve changes.
Exact check on a Pythagorean hodograph cubic. For , and , so . Then and , so
Also and , so the limit above is . At , and exactly. At , the first-order step is with the error exactly, and the second-order error is . The tests check these values in exact rational arithmetic.
The loop. Each pass of the loop moves forward by a positive step, and the code stops with an error if the step is not positive. On a regular curve, is at least once is small enough, so the loop ends after at most passes, and the last point is clipped to .
What is not covered. The theorem bounds the arc length of each step. The machine moves along the chord between and , which is shorter than the arc by for a curve of curvature , so the feed along the chords has a relative error of order as well, from this second source. The errors of all steps add up, so after steps the position along the curve may drift by up to , which is of order times the length of the path.
Complexity
Each period evaluates and once and does more arithmetic. For a NURBS curve of degree the derivatives cost with the de Boor recurrences, so periods take time and extra space. The work per period is fixed, which is what a real-time controller needs. The exact method, quadrature and Newton steps on , has no fixed bound on its work.
Properties
- Second order. The relative feed error per step is , against for the first-order step.
- Fixed work per period. Two derivative evaluations and a few operations.
- Accumulating error. The step errors add up. After steps the position along the curve can drift by times the step bound, which is of order 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 , so a separate feed limit is needed on tight curves.
- Exact on PH curves when solved exactly. For a PH curve, is a polynomial, and a few Newton steps on it give the exact parameter.
Variants and improvements
- First-order interpolator. only. It is simpler and has the relative error .
- 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 by Newton steps, with no truncation error in the feed.
- Adaptive feed with a chord limit. Yeh and Hsu lower where the chord error 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 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 , the step is not defined. Splines with repeated control points or cusps must be repaired before interpolation.
- Long periods on tight curves. If is not small compared with the radius of curvature and the scale on which 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 relative to .
- Feed changes. The expansion assumes a constant in the period. With acceleration, a term in is added, or 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.
# 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag QFCNX0 Edit this page History Report an error Markdown