Algorithmadvanced
Fairing by knot removal and reinsertion
Also called Farin-Sapidis fairing.
Farin, Rein, Sapidis and Worsey's fairing that removes and reinserts the knot where the curvature plot jumps most, step by step, until the curve is fair.
- Time
- O(R n^3) worst
- Space
- Θ(n) extra
- Where
- R = the number of rounds; n = the number of control points minus one
- Model
- Real RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Gerald Farin, Gerhard Rein, Nickolas Sapidis, Andrew Worsey, 1987
Fairing by knot removal and reinsertion smooths the curvature of a planar cubic B-spline curve, one knot at a time. At a simple knot a cubic spline is , so its curvature is continuous, but the derivative of the curvature can jump. A large jump shows in the curvature plot as a kink, and the eye sees it as a flat spot or a bump in the curve. The method finds the knot with the largest jump, removes that knot as if the curve were there, and inserts it again. The knot vector does not change, one control point moves, and after the step the curvature derivative is continuous at that knot. Farin, Rein, Sapidis and Worsey gave the method in 1987, and Sapidis and Farin made it automatic in 1990. A tolerance keeps the curve near the original.
In plain words
A designer looks at a curve, for example a section of a car body, and sees a small dent. The dent is hard to see in the curve but easy to see in a plot of how sharply the curve bends: the plot has kinks and dips. The curve is made of cubic pieces that meet at knots. At each knot the method asks how much the bending rate jumps. It takes the knot with the largest jump and pretends that the two pieces there are really one cubic. It computes that single cubic from the control points on both sides, which do not see the dent, and splits it again at the same knot. This moves one control point, and the kink at that knot is gone. Then it looks again for the worst knot, until no step helps or the curve would move too far.
The problem
Input. A planar cubic B-spline curve on a clamped knot vector , with simple inner knots. A tolerance and a number of rounds.
Output. New control points on the same knots with for all , and a curve that is fairer by the measure below.
Measure. Write . The signed curvature is , and its derivative is
At a simple knot only jumps, so jumps by . The measure is over the inner knots. Fairness has no single definition. The measure , the number of sign changes of the curvature and the energies of the other fairing methods are design criteria, not theorems: a curve that is better by one of them can look worse, and can be worse by another.
The algorithm
The step at an inner knot , , uses the three ratios of Boehm insertion of into the knot vector without :
Insertion makes , and from four points of the curve without . Removal inverts the first equation from the left and the last one from the right:
Reinsertion gives back and unchanged and replaces the middle point by .
FAIR(t_0..t_{n+4}, d_0..d_n, ε, rounds)- 1
d⁰ ← d; E ← Σ_r Δ_r² over the inner knots - 2
repeat at most rounds times - 3
order the inner knots t_r by decreasing Δ_r² - 4
for each t_r in this order with Δ_r ≠ 0 - 5
d̂ ← d with d_{r-2} replaced by (1 − α_{r-2}) L + α_{r-2} R - 6
if |d̂_i − d⁰_i| ≤ ε for every i and E(d̂) < E then - 7
d ← d̂; E ← E(d̂); go to the next round - 8
if no knot was accepted then stop - 9
return d
Lines L3 and L4 are the choice of Sapidis and Farin: try the worst knot first. Line L6 has two tests. The first keeps every control point within of its first position, which keeps the curve within . The second is the rule of this implementation: a step is taken only if it lowers , since fairing one knot changes the jumps at the four knots around it, and without the rule the loop can go round in a circle.
Example
Take the uniform knots and the nine control points , a convex curve shaped like a parabola. Dent it by moving from to . The point of the curve at moves from to , and the bottom of the curve becomes a shallow W: on the function is , so the curvature changes sign at and, by symmetry, at .
- L1. The squared jumps at the knots are about . At , and jumps from to , so .
- L3 to L5. The worst knot is , so . The ratios are , , . From and , . From and , . So .
- L6, L7. With the move is allowed, and falls from about to about . The curve is the undented curve again, with no sign change of curvature, and the point at has moved by .
- Next round. The remaining jumps sit at the knots near the clamped ends, where the B-spline basis is not uniform. No step there lowers within the tolerance, so the loop stops.
The step restores the dent exactly because and depend only on , , and , which lie on the undented curve, and the undented curve is at . With the point cannot move back. The method then takes four smaller steps, at the knots , , and in this order, which move , and by less than each. The result has no inflection either, but its measure is about , and the bottom of the curve stays a little flatter than the parabola.
Correctness
Three facts make the method sound. First, the step at is a real knot removal followed by insertion: and , with the other points unchanged, are the control points of a cubic spline on the knots without , and Boehm insertion of into it gives exactly the new points, with and unchanged by the choice of and . That spline is one cubic polynomial on , so after the step the curve is at and . Second, the curve on fixed knots depends on the control points through with , so the curve moves by at most , which line L6 checks. Third, every accepted step lowers strictly, and the number of rounds is bounded, so the loop ends. The method does not promise fewer inflections, since the measure is a design criterion: the tests contain a dent on a steep part of a curve where falls and both inflections stay. The proofs, with the count of sign changes, are in the proof file.
Proof: The fairing step makes the curve C3 at the knot, moves one control point, and keeps the curve within the tolerancefull
We use the notation of the page. The curve is , a planar cubic B-spline on the clamped knots with simple inner knots . Let , and let be the knot vector without , so for and for .
Lemma 1 (the step is removal and reinsertion)
Let for , , and for , a cubic spline with control points on . Boehm insertion of into gives exactly the control points of the step: for , and .
Proof. The knot lies in the span of , since . Boehm's rule for inserting into a cubic on with span index keeps for , shifts to place for , and for sets the new point to with . With and this is , and in the same way and . The denominators are positive, and and because the inner knots are simple, so and are defined. Now:
- for the new point is , by the definition of ;
- for it is , by the definition of ;
- for it is ;
- all other points are .
Theorem 1 (the step removes the jump)
After the step at the curve is a single cubic polynomial on . Hence is continuous at , and, if , the jump of the curvature derivative at is . Only the control point changes.
Proof. By Lemma 1, equals after knot insertion, and knot insertion does not change a curve, so . The knot vector has no knot in , so is one polynomial of degree there. Its derivatives of every order are continuous at . The curvature derivative is the formula of the page in , and , which is continuous wherever . The last claim is part of Lemma 1.
Lemma 2 (the jump of the curvature derivative)
At a simple inner knot a cubic spline is . If , then jumps at by .
Proof. Differentiate . Since and ,
At the values and are the same from both sides, so the second term has no jump and the first jumps by the stated amount.
The implementation returns with the jump of , which is a rational number when the input is rational.
Theorem 2 (the curve stays within the tolerance)
Let be the first control points and the control points at any time. Then for all .
Proof. The knots never change, so . The B-spline basis functions are non negative and sum to on the parameter interval, so this is a convex combination of the vectors , and its length is at most the largest of their lengths. Line L6 accepts a step only if every , so the bound holds after every accepted step, and it holds at the start.
Theorem 3 (termination)
The loop ends after at most the given number of rounds, and the measure falls strictly with every accepted step.
Proof. Each round either accepts one step, in line L7, or stops, in line L8. Line L6 accepts a step only if .
Lemma 3 (the count of curvature sign changes)
On a knot interval the function is a polynomial of degree at most , and the signs of , of at its vertex if the vertex lies in , and of , with zeros dropped, have exactly as many sign changes as has on .
Proof. On the interval is a cubic polynomial, with vectors . Then and , and the coefficient of in is . So has degree at most . A polynomial of degree at most is monotone on , or monotone on each side of its vertex . On a monotone piece changes sign at most once, and it does so exactly when the signs at the ends of the piece differ, zeros dropped. The pieces are and , or alone, so the sequence of signs at , and sees every change. Since and are continuous at simple knots, the sequences of consecutive intervals join without new changes at the knots. The curvature has the sign of where . The implementation finds from its values at , and , which determine a polynomial of degree at most .
What is not claimed
The method does not guarantee that the number of curvature sign changes falls. A lower is a design criterion for fairness, not a theorem about inflections. The test file has a parabola with a dent on its steep side: the step accepted at the worst knot lowers , but both inflections remain, and no further step lowers .
Complexity
Let be the number of control points and the number of rounds. The implementation computes the derivative curves for each jump, in , so the measure costs . In a round it may try all knots and compute for each, so a round costs and the whole run . A step changes one control point, which changes the jumps at most at the five knots . An implementation that keeps the jumps in a priority queue and updates only these five costs per step after set up. The extra space is the copy of the first control points, .
Properties
- Local. A step moves one control point, so the curve changes only on the four knot intervals of , .
- Same representation. The knot vector and the number of control points stay the same, so the faired curve can replace the original in a model without changes to the data structure.
- Bounded change. The curve never moves farther than the tolerance from the original.
- Exact. With rational input every step is rational, and the implementation is exact, including the count of curvature sign changes.
- Fixed points. A curve that is at a knot is not changed by the step there. A single cubic polynomial, written on any knots, is not changed at all.
- Not invariant under reparametrization. The step depends on the knots, so the same point set on other knots gives another result.
Variants and improvements
- Several knots at a time. Removing two or more neighbouring knots and reinserting them changes more control points and smooths over a longer stretch.
- Other removal steps. The step here takes the left estimate for one side and the right estimate for the other. Sapidis and Farin give a new knot removal algorithm for this use, and the general knot removal of Lyche and Mørken removes knots within a tolerance in a norm.
- Fairing to a target curvature. Later methods move the control points so that the curvature plot approaches a smooth target plot.
- Local energy fairing. Eck and Hadenfeld, motivated by this method, change the curve locally to lower an energy, which is a local form of energy-based fairing for curves.
- Surfaces. The same idea, applied to the iso-parameter curves of a tensor product surface, fairs surfaces row by row, but the rows interact, and global energy methods are more usual.
- Space curves. For a curve in space the jump of the curvature derivative uses and needs a square root, but the step itself is the same.
When to use it
Use the method to remove small local defects from a cubic B-spline curve that is already close to the wanted shape, such as a curve interpolated through measured points with noise, when the curve must keep its knots and stay within a tolerance. It is cheap, local and easy to control. It does not fix the global shape: for that, a smoothing spline or an energy minimization over all control points is better. For curves with large wiggles the tolerance stops it before it can help.
Pitfalls
- Measure is not shape. A lower does not mean fewer inflections, and fewer inflections is not always the aim. Check the result with a curvature comb or reflection lines.
- End knots. Near a clamped end the basis is not uniform, and even a fair curve has jumps there. The rule that must fall stops the loop from wasting the tolerance on them.
- Cycles. Without a rule that the measure must fall, fairing one knot can undo another, and the loop runs to its limit of rounds.
- Weighting. The jump is divided by , so knots where the parameter speed is high count less. A defect on a fast part of the curve may never be chosen.
- Multiple knots. At a double knot the curve is only , and the step above does not apply. The implementation rejects such curves.
- Tolerance used up. The tolerance is measured from the original points, so many small steps can use it up and block a later, more useful step.
Implementations
The Python file in this folder has fair_by_knot_removal(knots, ctrl, tol, rounds), which returns the new control points and the list of faired knots, remove_and_reinsert for one step, kappa_jump for the squared jump of the curvature derivative, fairness for the measure , and curvature_sign_changes, which counts the sign changes of the curvature exactly: on each knot interval of a cubic, is a polynomial of degree at most , and its signs at the ends and at its vertex give every change. The shared helper si3spline.py holds the evaluation and the derivative curves. The tests check the worked example, that one step changes one control point and makes the third derivative continuous at the knot, that dents near the bottom of a parabola lose their inflections, that the curve never moves more than the tolerance at random points, that the measure never rises, the sign change counter against dense sampling, and the steep dent where the measure falls but the inflections stay.
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/knot-removal-fairing/. The authors are listed in prov/GM71P6.jsonl.
"""Fairing a planar cubic B-spline curve by knot removal and reinsertion.
This is the method of Farin, Rein, Sapidis and Worsey (1987) and Farin and
Sapidis (1989). At each step it finds the inner knot where the derivative of
the curvature jumps most, removes that knot as if the curve were C3 there,
and inserts it again. The knot vector does not change, and exactly one
control point moves. After the step the curve is C3 at that knot, so the
curvature derivative is continuous there. A global tolerance bounds how far
any control point may move from its first position, which bounds how far
the curve moves.
The curve is a clamped cubic B-spline in the plane with simple inner knots.
With int or Fraction input every step is exact.
"""
from fractions import Fraction
from si3spline import check_curve, curve_point, derivative_curve, lincomb, sub
P = 3
def _check(knots, ctrl):
check_curve(knots, P, ctrl)
if len(ctrl[0]) != 2:
raise ValueError("the curve must be planar")
if knots[:P + 1] != [knots[0]] * (P + 1) or knots[-P - 1:] != [knots[-1]] * (P + 1):
raise ValueError("the knot vector must be clamped")
inner = knots[P + 1:len(ctrl)]
if len(set(inner)) != len(inner) or knots[0] in inner or knots[-1] in inner:
raise ValueError("the inner knots must be simple")
def _derivatives(knots, ctrl):
"""The first, second and third derivative curves."""
d1 = derivative_curve(knots, P, ctrl)
d2 = derivative_curve(*d1)
d3 = derivative_curve(*d2)
return d1, d2, d3
def _cross(a, b):
return a[0] * b[1] - a[1] * b[0]
def _dot(a, b):
return a[0] * b[0] + a[1] * b[1]
def kappa_jump(knots, ctrl, r):
"""The square of the jump of the curvature derivative at the inner knot knots[r].
The curve is C2 at a simple knot, so only the third derivative jumps, by
D, and the curvature derivative jumps by (c' x D) / |c'|^3. The square is
returned, which is exact. None if c' = 0 there.
"""
t = knots[r]
d1, _, d3 = _derivatives(knots, ctrl)
v = curve_point(*d1, t)
s = _dot(v, v)
if s == 0:
return None
left = curve_point(*d3, (knots[r - 1] + t) / Fraction(2))
right = curve_point(*d3, (t + knots[r + 1]) / Fraction(2))
j = _cross(v, sub(right, left))
return Fraction(j * j) / (s * s * s)
def remove_and_reinsert(knots, ctrl, r):
"""Remove the inner knot knots[r] and insert it again; return the new control points.
Boehm insertion of t into the curve without t, of span k = r - 1, keeps
the points up to k - 3 and from k + 1 on, and makes the points k - 2, k - 1
and k from the old points k - 3, ..., k. Solving its first equation from
the left and its last equation from the right gives the two inner points
of the curve without t; reinsertion then changes only point k - 1.
"""
t = knots[r]
k = r - 1
K = knots[:r] + knots[r + 1:] # the knot vector without t
def alpha(i):
return (t - K[i]) / Fraction(K[i + P] - K[i])
a0, a1, a2 = alpha(k - 2), alpha(k - 1), alpha(k)
left = tuple((x - (1 - a0) * y) / a0 for x, y in zip(ctrl[k - 2], ctrl[k - 3]))
right = tuple((x - a2 * y) / (1 - a2) for x, y in zip(ctrl[k], ctrl[k + 1]))
new = list(ctrl)
new[k - 1] = lincomb([1 - a1, a1], [left, right])
return new
def curvature_sign_changes(knots, ctrl):
"""The exact number of sign changes of the curvature along the curve.
On each knot interval of a cubic, f = x'y'' - y'x'' is a polynomial of
degree at most 2 (the cubic terms cancel). Its signs at the ends of each
interval and at its vertex, if the vertex is inside, give every sign
change, because a quadratic is monotone on each side of its vertex.
"""
_check(knots, ctrl)
d1, d2, _ = _derivatives(knots, ctrl)
def f(t):
return _cross(curve_point(*d1, t), curve_point(*d2, t))
signs = []
breaks = sorted(set(knots))
for a, b in zip(breaks, breaks[1:]):
f0, fm, f1 = f(a), f((a + b) / Fraction(2)), f(b)
A = 2 * f0 + 2 * f1 - 4 * fm # f = A s^2 + B s + f0 on s in [0, 1]
B = f1 - f0 - A
vals = [f0]
if A != 0 and 0 < -B / Fraction(2 * A) < 1:
vals.append(f0 - Fraction(B * B) / (4 * A))
vals.append(f1)
signs += [1 if x > 0 else -1 for x in vals if x != 0]
return sum(1 for x, y in zip(signs, signs[1:]) if x != y)
def max_move_squared(ctrl0, ctrl1):
"""The largest squared distance between matching control points.
On one knot vector, the curves differ by sum N_i(t) (ctrl1[i] - ctrl0[i]),
and the N_i are non negative with sum 1, so every point of the curve moves
by at most the square root of this number.
"""
return max(_dot(sub(a, b), sub(a, b)) for a, b in zip(ctrl0, ctrl1))
def jumps(knots, ctrl):
"""The pairs (squared jump, r) for every inner knot index r where c' is not zero."""
out = []
for r in range(P + 1, len(ctrl)):
J = kappa_jump(knots, ctrl, r)
if J is not None:
out.append((J, r))
return out
def fairness(knots, ctrl):
"""The fairness measure: the sum of the squared jumps of the curvature derivative."""
return sum((J for J, _ in jumps(knots, ctrl)), Fraction(0))
def fair_by_knot_removal(knots, ctrl, tol, rounds=50):
"""Fair the curve; return (new control points, the list of the faired knot indices).
Each round tries the knots in the order of decreasing jump of the
curvature derivative, and fairs the first one whose remove-and-reinsert
step keeps every control point within tol of its first position and
lowers the fairness measure. The loop stops when no knot qualifies or
after the given number of rounds.
"""
_check(knots, ctrl)
tol2 = Fraction(tol) ** 2
start = list(ctrl) # @line L1
E = fairness(knots, ctrl) # @line L1
done = []
for _ in range(rounds): # @line L2
order = sorted(jumps(knots, ctrl), key=lambda x: (-x[0], x[1])) # @line L3
for J, r in order: # @line L4
if J == 0:
continue
new = remove_and_reinsert(knots, ctrl, r) # @line L5
if max_move_squared(start, new) > tol2: # @line L6
continue
E_new = fairness(knots, new) # @line L6
if E_new < E:
ctrl, E = new, E_new # @line L7
done.append(r)
break
else:
break # @line L8
return ctrl, done # @line L9
si3spline.py 225 lines
# SPDX-License-Identifier: MIT
# Shared helper of the si3 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small B-spline tools for the si3 pages.
A point is a tuple of numbers of any fixed length. A B-spline curve of degree
p is a knot vector (a list of n + p + 2 non-decreasing numbers, clamped, that
is with p + 1 equal knots at each end) and a list of n + 1 control points.
Entries may be int or Fraction, and then every result here is exact. No
function here is the algorithm of a page: the basis functions, de Boor
evaluation, knot insertion and global interpolation are the standard tools of
the pages b-spline, de-boor-algorithm, boehm-knot-insertion and
curve-interpolation.
"""
from fractions import Fraction
# ---- points ----------------------------------------------------------------
def add(a, b):
return tuple(x + y for x, y in zip(a, b))
def sub(a, b):
return tuple(x - y for x, y in zip(a, b))
def scale(s, a):
return tuple(s * x for x in a)
def lincomb(ws, ps):
"""Return the sum of ws[i] * ps[i]; ps is not empty."""
out = [0] * len(ps[0])
for w, p in zip(ws, ps):
if w:
for d in range(len(out)):
out[d] += w * p[d]
return tuple(out)
# ---- basis and evaluation --------------------------------------------------
def check_curve(knots, p, ctrl):
if p < 0 or len(knots) != len(ctrl) + p + 1:
raise ValueError("a curve of degree p with n + 1 control points needs n + p + 2 knots")
if any(knots[i] > knots[i + 1] for i in range(len(knots) - 1)):
raise ValueError("knots must not decrease")
if knots[p] >= knots[len(ctrl)]:
raise ValueError("the parameter interval is empty")
def find_span(knots, p, t):
"""The index k with knots[k] <= t < knots[k + 1], in p..n, and n at the right end."""
n = len(knots) - p - 2
if t >= knots[n + 1]:
return n
if t <= knots[p]:
return p
k = p
while knots[k + 1] <= t:
k += 1
return k
def basis_funs(knots, p, k, t):
"""The values N_{k-p,p}(t), ..., N_{k,p}(t), by the Cox-de Boor recursion."""
N = [Fraction(1)] + [Fraction(0)] * p
left = [0] * (p + 1)
right = [0] * (p + 1)
for j in range(1, p + 1):
left[j] = t - knots[k + 1 - j]
right[j] = knots[k + j] - t
saved = Fraction(0)
for r in range(j):
tmp = N[r] / (right[r + 1] + left[j - r])
N[r] = saved + right[r + 1] * tmp
saved = left[j - r] * tmp
N[j] = saved
return N
def basis_row(knots, p, t):
"""All n + 1 basis values at t, as one list."""
n = len(knots) - p - 2
k = find_span(knots, p, t)
row = [Fraction(0)] * (n + 1)
for r, val in enumerate(basis_funs(knots, p, k, t)):
row[k - p + r] = val
return row
def curve_point(knots, p, ctrl, t):
"""The point of the curve at t, as the basis combination of the control points."""
k = find_span(knots, p, t)
N = basis_funs(knots, p, k, t)
return lincomb(N, ctrl[k - p:k + 1])
def derivative_curve(knots, p, ctrl):
"""The derivative as a B-spline of degree p - 1 on the knots without their ends."""
if p == 0:
raise ValueError("the degree must be positive")
Q = []
for i in range(len(ctrl) - 1):
h = knots[i + p + 1] - knots[i + 1]
Q.append(scale(Fraction(p) / h, sub(ctrl[i + 1], ctrl[i])) if h else
tuple(0 for _ in ctrl[0]))
return knots[1:-1], p - 1, Q
# ---- knot insertion --------------------------------------------------------
def insert_knot(knots, p, ctrl, t):
"""Insert the inner knot t once (Boehm). The curve does not change."""
if not knots[p] < t < knots[len(ctrl)]:
raise ValueError("only inner knots can be inserted")
if knots.count(t) + 1 > p:
raise ValueError("an inner knot can have multiplicity at most p")
k = find_span(knots, p, t)
new = []
for i in range(len(ctrl) + 1):
if i <= k - p:
new.append(ctrl[i])
elif i > k:
new.append(ctrl[i - 1])
else:
a = (t - knots[i]) / Fraction(knots[i + p] - knots[i])
new.append(add(scale(1 - a, ctrl[i - 1]), scale(a, ctrl[i])))
return knots[:k + 1] + [t] + knots[k + 1:], new
def missing_knots(knots, target):
"""The multiset target minus the multiset knots; raises if knots is not a part of target."""
out = []
for t in sorted(set(target)):
d = target.count(t) - knots.count(t)
if d < 0:
raise ValueError("the target knot vector must contain the old one")
out += [t] * d
return out
def refine(knots, p, ctrl, target):
"""Insert knots until the knot vector equals target. The curve does not change."""
for t in missing_knots(knots, target):
knots, ctrl = insert_knot(knots, p, ctrl, t)
return knots, ctrl
def merge_knots(vectors):
"""The least knot vector that contains each vector, as multisets."""
vals = sorted(set(t for v in vectors for t in v))
out = []
for t in vals:
out += [t] * max(v.count(t) for v in vectors)
return out
# ---- tensor product surfaces -----------------------------------------------
# A surface is (U, V, p, q, P): degree p on the knots U in u, degree q on the
# knots V in v, and the control net P[k][l], k along u and l along v.
def surface_point(U, V, p, q, P, u, v):
k = find_span(U, p, u)
N = basis_funs(U, p, k, u)
return lincomb(N, [curve_point(V, q, P[k - p + r], v) for r in range(p + 1)])
def iso_curve_u(U, p, P, u):
"""Control points over V of the curve v -> S(u, v) for a fixed u."""
k = find_span(U, p, u)
N = basis_funs(U, p, k, u)
return [lincomb(N, [P[k - p + r][l] for r in range(p + 1)]) for l in range(len(P[0]))]
def iso_curve_v(V, q, P, v):
"""Control points over U of the curve u -> S(u, v) for a fixed v."""
return [curve_point(V, q, row, v) for row in P]
def refine_surface(U, V, p, q, P, U2, V2):
"""The same surface on the finer knot vectors U2 and V2."""
cols = [refine(U, p, [row[l] for row in P], U2)[1] for l in range(len(P[0]))]
P = [[cols[l][k] for l in range(len(cols))] for k in range(len(cols[0]))]
return [refine(V, q, row, V2)[1] for row in P]
# ---- interpolation ---------------------------------------------------------
def solve(A, B):
"""Solve A X = B by Gauss-Jordan elimination with exact pivots. B is a list of points."""
n = len(A)
M = [[Fraction(x) for x in A[i]] + [Fraction(x) for x in B[i]] for i in range(n)]
w = len(M[0])
for c in range(n):
r = next((r for r in range(c, n) if M[r][c] != 0), None)
if r is None:
raise ValueError("singular system")
M[c], M[r] = M[r], M[c]
piv = M[c][c]
M[c] = [x / piv for x in M[c]]
for r in range(n):
if r != c and M[r][c] != 0:
f = M[r][c]
M[r] = [x - f * y for x, y in zip(M[r], M[c])]
return [tuple(M[i][n:w]) for i in range(n)]
def averaging_knots(params, p):
"""Clamped knots whose inner knots are means of p consecutive parameters."""
n = len(params) - 1
inner = [sum(params[j:j + p], Fraction(0)) / p for j in range(1, n - p + 1)]
return [params[0]] * (p + 1) + inner + [params[-1]] * (p + 1)
def interpolate(params, points, p):
"""The B-spline of degree p through points[k] at params[k], with averaging knots."""
if len(params) != len(points) or len(points) < p + 1:
raise ValueError("need at least p + 1 points, one parameter each")
if any(params[k] >= params[k + 1] for k in range(len(params) - 1)):
raise ValueError("the parameters must increase")
knots = averaging_knots(params, p)
A = [basis_row(knots, p, t) for t in params]
return knots, solve(A, points)
test_knot_removal_fairing.py 162 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/knot-removal-fairing/. The authors are listed in prov/GM71P6.jsonl.
import random
import unittest
from fractions import Fraction as Fr
from knot_removal_fairing import (curvature_sign_changes, fair_by_knot_removal, fairness,
kappa_jump, max_move_squared, remove_and_reinsert)
from si3spline import curve_point, derivative_curve, sub
UNIFORM = [0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 6, 6, 6]
PARABOLA = [(i, Fr((i - 4) ** 2, 4)) for i in range(9)]
def dented():
c = list(PARABOLA)
c[4] = (4, Fr(1, 2))
return c
def third_derivative_sides(knots, ctrl, r):
d = derivative_curve(*derivative_curve(*derivative_curve(knots, 3, ctrl)))
t = knots[r]
return (curve_point(*d, (knots[r - 1] + t) / 2), curve_point(*d, (t + knots[r + 1]) / 2))
def random_curve(rng, uniform):
n = rng.randint(6, 10)
m = n - 2
if uniform:
inner = list(range(1, m))
else:
inner = [Fr(x, 4) for x in sorted(rng.sample(range(1, 4 * m), m - 1))]
knots = [0] * 4 + inner + [m] * 4
ctrl = [(Fr(i), Fr((2 * i - n) ** 2, 8)) for i in range(n + 1)]
return knots, ctrl
def dist2(a, b):
d = sub(a, b)
return d[0] * d[0] + d[1] * d[1]
class TestKnotRemovalFairing(unittest.TestCase):
def test_example(self):
c = dented()
self.assertEqual(curvature_sign_changes(UNIFORM, PARABOLA), 0)
self.assertEqual(curvature_sign_changes(UNIFORM, c), 2)
self.assertEqual(kappa_jump(UNIFORM, c, 6), 9)
self.assertEqual(kappa_jump(UNIFORM, PARABOLA, 6), 0)
new, done = fair_by_knot_removal(UNIFORM, c, tol=1)
self.assertEqual(done, [6])
self.assertEqual(new, PARABOLA)
self.assertEqual(curvature_sign_changes(UNIFORM, new), 0)
self.assertLess(fairness(UNIFORM, new), fairness(UNIFORM, c))
self.assertEqual(curve_point(UNIFORM, 3, c, 3), (4, Fr(5, 12)))
self.assertEqual(curve_point(UNIFORM, 3, new, 3), (4, Fr(1, 12)))
self.assertEqual(max_move_squared(c, new), Fr(1, 4))
def test_tight_tolerance_stops_early(self):
c = dented()
new, done = fair_by_knot_removal(UNIFORM, c, tol=Fr(1, 4))
self.assertEqual(done, [5, 7, 6, 5])
self.assertNotIn(new, (c, PARABOLA))
self.assertEqual(curvature_sign_changes(UNIFORM, new), 0)
self.assertLess(fairness(UNIFORM, PARABOLA), fairness(UNIFORM, new))
self.assertLessEqual(max_move_squared(c, new), Fr(1, 16))
new0, done0 = fair_by_knot_removal(UNIFORM, c, tol=0)
self.assertEqual((new0, done0), (c, []))
def test_one_step_makes_the_knot_removable(self):
rng = random.Random(3)
for _ in range(40):
knots, ctrl = random_curve(rng, uniform=False)
ctrl = [(x + Fr(rng.randint(-4, 4), 8), y + Fr(rng.randint(-4, 4), 8)) for x, y in ctrl]
r = rng.randint(4, len(ctrl) - 1)
new = remove_and_reinsert(knots, ctrl, r)
changed = [i for i in range(len(ctrl)) if new[i] != ctrl[i]]
self.assertLessEqual(len(changed), 1)
if changed:
self.assertEqual(changed, [r - 2])
left, right = third_derivative_sides(knots, new, r)
self.assertEqual(left, right)
self.assertIn(kappa_jump(knots, new, r), (0, None))
def test_dents_lose_inflections(self):
# a dent near the bottom of the parabola, where the curve is flat
rng = random.Random(7)
cases = 0
for _ in range(60):
knots, ctrl = random_curve(rng, uniform=True)
n = len(ctrl) - 1
j = rng.randint(max(3, (n - 2) // 2), min(n - 3, (n + 3) // 2))
ctrl[j] = (ctrl[j][0], ctrl[j][1] + Fr(rng.randint(2, 6), 8))
before = curvature_sign_changes(knots, ctrl)
if before == 0:
continue
cases += 1
new, _ = fair_by_knot_removal(knots, ctrl, tol=1, rounds=12)
self.assertLess(curvature_sign_changes(knots, new), before)
self.assertLessEqual(max_move_squared(ctrl, new), 1)
self.assertGreaterEqual(cases, 10)
def test_lower_measure_is_not_fewer_inflections(self):
# a dent on the steep side: the measure drops, the two inflections stay
knots = [0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 8, 8]
ctrl = [(Fr(i), Fr((2 * i - 10) ** 2, 8)) for i in range(11)]
ctrl[3] = (3, Fr(2) + Fr(3, 4))
new, done = fair_by_knot_removal(knots, ctrl, tol=2)
self.assertEqual(done, [7])
self.assertLess(fairness(knots, new), fairness(knots, ctrl))
self.assertEqual(curvature_sign_changes(knots, ctrl), 2)
self.assertEqual(curvature_sign_changes(knots, new), 2)
def test_curve_moves_less_than_the_tolerance(self):
rng = random.Random(11)
for _ in range(25):
knots, ctrl = random_curve(rng, uniform=rng.random() < 0.5)
ctrl = [(x + Fr(rng.randint(-6, 6), 8), y + Fr(rng.randint(-6, 6), 8)) for x, y in ctrl]
tol = Fr(rng.randint(1, 8), 8)
new, done = fair_by_knot_removal(knots, ctrl, tol=tol, rounds=8)
self.assertEqual(len(new), len(ctrl))
self.assertLessEqual(max_move_squared(ctrl, new), tol * tol)
self.assertLessEqual(fairness(knots, new), fairness(knots, ctrl))
for _ in range(10):
t = Fr(rng.randint(0, 1000), 1000) * knots[-1]
self.assertLessEqual(dist2(curve_point(knots, 3, new, t), curve_point(knots, 3, ctrl, t)), tol * tol)
def test_sign_change_counter(self):
bezier = [0, 0, 0, 0, 1, 1, 1, 1]
self.assertEqual(curvature_sign_changes(bezier, [(0, 0), (1, 1), (2, -1), (3, 0)]), 1)
self.assertEqual(curvature_sign_changes(bezier, [(0, 0), (1, 1), (2, 1), (3, 0)]), 0)
# random curves: a dense sample never sees more sign changes than the exact count
rng = random.Random(5)
for _ in range(30):
knots, ctrl = random_curve(rng, uniform=False)
ctrl = [(x, y + Fr(rng.randint(-8, 8), 4)) for x, y in ctrl]
exact = curvature_sign_changes(knots, ctrl)
d1 = derivative_curve(knots, 3, ctrl)
d2 = derivative_curve(*d1)
signs = []
for s in range(0, 801):
t = Fr(s, 800) * knots[-1]
a, b = curve_point(*d1, t), curve_point(*d2, t)
f = a[0] * b[1] - a[1] * b[0]
if f:
signs.append(f > 0)
sampled = sum(1 for x, y in zip(signs, signs[1:]) if x != y)
self.assertLessEqual(sampled, exact)
self.assertEqual(exact % 2, (signs[0] != signs[-1]) % 2)
def test_rejections(self):
with self.assertRaises(ValueError):
fair_by_knot_removal(UNIFORM, [(x, y, 0) for x, y in PARABOLA], 1)
double = [0, 0, 0, 0, 1, 2, 2, 4, 5, 6, 6, 6, 6]
with self.assertRaises(ValueError):
fair_by_knot_removal(double, PARABOLA, 1)
if __name__ == "__main__":
unittest.main()
History
Fairing by hand, with splines and weights on the loft floor, is old, and the curvature plot became the tool for judging fairness in CAD in the 1980s. Farin, Rein, Sapidis and Worsey published fairing of cubic B-spline curves by inverting knot insertion in 1987, and in the same year Sapidis wrote a master's thesis on local fairing at the University of Utah. Farin and Sapidis described the curvature plot as the measure of fairness in 1989, and in 1990 Sapidis and Farin gave the automatic algorithm that picks the knots by the fairness criterion and repeats.
References
- Farin, Rein, Sapidis and Worsey 1987, local fairing of cubic B-spline curves by inversion of knot insertion, judged by the curvature plot
- Nickolas Sapidis and Gerald Farin, Automatic fairing algorithm for B-spline curves, Computer-Aided Design 22(2), 121 to 129, 1990, repeated removal and reinsertion of knots chosen automatically by a fairness criterion
- Gerald Farin and Nickolas Sapidis, Curvature and the fairness of curves and surfaces, IEEE Computer Graphics and Applications 9(2), 52 to 57, 1989, the curvature plot as the measure of fairness, and few monotone pieces of curvature as the aim
- Gerald Farin, Curves and Surfaces for CAGD, A Practical Guide, fifth edition, Morgan Kaufmann, 2002, the treatment of curve fairing and of knot removal
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 GM71P6 Edit this page History Report an error Markdown