Algorithm Search⌘K

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
Properties
deterministicofflineiterative
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 C2C^2, 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 C3C^3 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 c(t)=∑i=0nNi(t)dic(t) = \sum_{i=0}^{n} N_i(t) d_i on a clamped knot vector t0=⋯=t3<t4<⋯<tn<tn+1=⋯=tn+4t_0 = \dots = t_3 < t_4 < \dots < t_n < t_{n+1} = \dots = t_{n+4}, with simple inner knots. A tolerance ε≥0\varepsilon \ge 0 and a number of rounds.

Output. New control points d^0,…,d^n\hat d_0, \dots, \hat d_n on the same knots with ∣d^i−di∣≤ε|\hat d_i - d_i| \le \varepsilon for all ii, and a curve that is fairer by the measure below.

Measure. Write c′×c′′=x′y′′−y′x′′c' \times c'' = x' y'' - y' x''. The signed curvature is κ=(c′×c′′)/∣c′∣3\kappa = (c' \times c'') / |c'|^3, and its derivative is

κ′=c′×c′′′∣c′∣3−3(c′×c′′)(c′⋅c′′)∣c′∣5.\kappa' = \frac{c' \times c'''}{|c'|^3} - 3 \frac{(c' \times c'')(c' \cdot c'')}{|c'|^5}.

At a simple knot trt_r only c′′′c''' jumps, so κ′\kappa' jumps by Δr=c′(tr)×(c′′′(tr+)−c′′′(tr−))/∣c′(tr)∣3\Delta_r = c'(t_r) \times (c'''(t_r^+) - c'''(t_r^-)) / |c'(t_r)|^3. The measure is E=∑rΔr2E = \sum_r \Delta_r^2 over the inner knots. Fairness has no single definition. The measure EE, 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 trt_r, 4≤r≤n4 \le r \le n, uses the three ratios of Boehm insertion of trt_r into the knot vector without trt_r:

αr−3=tr−tr−3tr+1−tr−3,αr−2=tr−tr−2tr+2−tr−2,αr−1=tr−tr−1tr+3−tr−1.\alpha_{r-3} = \frac{t_r - t_{r-3}}{t_{r+1} - t_{r-3}}, \qquad \alpha_{r-2} = \frac{t_r - t_{r-2}}{t_{r+2} - t_{r-2}}, \qquad \alpha_{r-1} = \frac{t_r - t_{r-1}}{t_{r+3} - t_{r-1}}.

Insertion makes dr−3d_{r-3}, dr−2d_{r-2} and dr−1d_{r-1} from four points of the curve without trt_r. Removal inverts the first equation from the left and the last one from the right:

L=dr−3−(1−αr−3)dr−4αr−3,R=dr−1−αr−1dr1−αr−1.L = \frac{d_{r-3} - (1 - \alpha_{r-3}) d_{r-4}}{\alpha_{r-3}}, \qquad R = \frac{d_{r-1} - \alpha_{r-1} d_r}{1 - \alpha_{r-1}}.

Reinsertion gives back dr−3d_{r-3} and dr−1d_{r-1} unchanged and replaces the middle point by d^r−2=(1−αr−2)L+αr−2R\hat d_{r-2} = (1 - \alpha_{r-2}) L + \alpha_{r-2} R.

  1. FAIR(t_0..t_{n+4}, d_0..d_n, ε, rounds)
  2. 1d⁰ ← d; E ← Σ_r Δ_r² over the inner knots
  3. 2repeat at most rounds times
  4. 3order the inner knots t_r by decreasing Δ_r²
  5. 4for each t_r in this order with Δ_r ≠ 0
  6. 5d̂ ← d with d_{r-2} replaced by (1 − α_{r-2}) L + α_{r-2} R
  7. 6if |d̂_i − d⁰_i| ≤ ε for every i and E(d̂) < E then
  8. 7d ← d̂; E ← E(d̂); go to the next round
  9. 8if no knot was accepted then stop
  10. 9return 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 ε\varepsilon of its first position, which keeps the curve within ε\varepsilon. The second is the rule of this implementation: a step is taken only if it lowers EE, 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 (0,0,0,0,1,2,3,4,5,6,6,6,6)(0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 6, 6, 6) and the nine control points di=(i,(i−4)24)d_i = (i, \frac{(i - 4)^2}{4}), a convex curve shaped like a parabola. Dent it by moving d4d_4 from (4,0)(4, 0) to (4,12)(4, \frac12). The point of the curve at t=3t = 3 moves from (4,112)(4, \frac1{12}) to (4,512)(4, \frac{5}{12}), and the bottom of the curve becomes a shallow W: on [2,3][2, 3] the function c′×c′′c' \times c'' is 1−32(t−2)1 - \frac32 (t - 2), so the curvature changes sign at t=83t = \frac83 and, by symmetry, at t=103t = \frac{10}{3}.

  • L1. The squared jumps at the knots 1,2,3,4,51, 2, 3, 4, 5 are about 0.51,1.88,9,1.88,0.510.51, 1.88, 9, 1.88, 0.51. At t=3t = 3, c′=(1,0)c' = (1, 0) and c′′′c''' jumps from (0,−32)(0, -\frac32) to (0,32)(0, \frac32), so Δ=3\Delta = 3.
  • L3 to L5. The worst knot is t6=3t_6 = 3, so r=6r = 6. The ratios are α3=34\alpha_3 = \frac34, α4=12\alpha_4 = \frac12, α5=14\alpha_5 = \frac14. From d2=(2,1)d_2 = (2, 1) and d3=(3,14)d_3 = (3, \frac14), L=(103,0)L = (\frac{10}{3}, 0). From d5=(5,14)d_5 = (5, \frac14) and d6=(6,1)d_6 = (6, 1), R=(143,0)R = (\frac{14}{3}, 0). So d^4=12L+12R=(4,0)\hat d_4 = \frac12 L + \frac12 R = (4, 0).
  • L6, L7. With ε=1\varepsilon = 1 the move 12\frac12 is allowed, and EE falls from about 13.7713.77 to about 0.8850.885. The curve is the undented curve again, with no sign change of curvature, and the point at t=3t = 3 has moved by 13\frac13.
  • 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 EE within the tolerance, so the loop stops.

The step restores the dent exactly because LL and RR depend only on d2d_2, d3d_3, d5d_5 and d6d_6, which lie on the undented curve, and the undented curve is C3C^3 at t=3t = 3. With ε=14\varepsilon = \frac14 the point d4d_4 cannot move back. The method then takes four smaller steps, at the knots 22, 44, 33 and 22 in this order, which move d3d_3, d4d_4 and d5d_5 by less than 14\frac14 each. The result has no inflection either, but its measure EE is about 1.681.68, and the bottom of the curve stays a little flatter than the parabola.

Correctness

Three facts make the method sound. First, the step at trt_r is a real knot removal followed by insertion: LL and RR, with the other points unchanged, are the control points of a cubic spline on the knots without trt_r, and Boehm insertion of trt_r into it gives exactly the new points, with dr−3d_{r-3} and dr−1d_{r-1} unchanged by the choice of LL and RR. That spline is one cubic polynomial on (tr−1,tr+1)(t_{r-1}, t_{r+1}), so after the step the curve is C3C^3 at trt_r and Δr=0\Delta_r = 0. Second, the curve on fixed knots depends on the control points through Ni≥0N_i \ge 0 with ∑iNi=1\sum_i N_i = 1, so the curve moves by at most max⁡i∣d^i−di0∣≤ε\max_i |\hat d_i - d^0_i| \le \varepsilon, which line L6 checks. Third, every accepted step lowers EE 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 EE 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 c(t)=∑i=0nNi(t)dic(t) = \sum_{i=0}^{n} N_i(t) d_i, a planar cubic B-spline on the clamped knots t0,…,tn+4t_0, \dots, t_{n+4} with simple inner knots t4<⋯<tnt_4 < \dots < t_n. Let 4≤r≤n4 \le r \le n, and let τ\tau be the knot vector without trt_r, so τi=ti\tau_i = t_i for i<ri < r and τi=ti+1\tau_i = t_{i+1} for i≥ri \ge r.

Lemma 1 (the step is removal and reinsertion)

Let ei=die_i = d_i for i≤r−4i \le r - 4, er−3=Le_{r-3} = L, er−2=Re_{r-2} = R and ei=di+1e_i = d_{i+1} for i≥r−1i \ge r - 1, a cubic spline ee with nn control points on τ\tau. Boehm insertion of trt_r into ee gives exactly the control points d^\hat d of the step: d^i=di\hat d_i = d_i for i≠r−2i \ne r - 2, and d^r−2=(1−αr−2)L+αr−2R\hat d_{r-2} = (1 - \alpha_{r-2}) L + \alpha_{r-2} R.

Proof. The knot trt_r lies in the span τr−1≤tr<τr\tau_{r-1} \le t_r < \tau_r of τ\tau, since τr−1=tr−1<tr<tr+1=τr\tau_{r-1} = t_{r-1} < t_r < t_{r+1} = \tau_r. Boehm's rule for inserting trt_r into a cubic on τ\tau with span index r−1r - 1 keeps eie_i for i≤r−4i \le r - 4, shifts ei−1e_{i-1} to place ii for i≥ri \ge r, and for i=r−3,r−2,r−1i = r - 3, r - 2, r - 1 sets the new point to (1−ai)ei−1+aiei(1 - a_i) e_{i-1} + a_i e_i with ai=(tr−τi)/(τi+3−τi)a_i = (t_r - \tau_i)/(\tau_{i+3} - \tau_i). With τr−3=tr−3\tau_{r-3} = t_{r-3} and τr=tr+1\tau_r = t_{r+1} this is ar−3=αr−3a_{r-3} = \alpha_{r-3}, and in the same way ar−2=αr−2a_{r-2} = \alpha_{r-2} and ar−1=αr−1a_{r-1} = \alpha_{r-1}. The denominators are positive, and 0<αr−30 < \alpha_{r-3} and αr−1<1\alpha_{r-1} < 1 because the inner knots are simple, so LL and RR are defined. Now:

  • for i=r−3i = r - 3 the new point is (1−αr−3)dr−4+αr−3L=dr−3(1 - \alpha_{r-3}) d_{r-4} + \alpha_{r-3} L = d_{r-3}, by the definition of LL;
  • for i=r−1i = r - 1 it is (1−αr−1)R+αr−1dr=dr−1(1 - \alpha_{r-1}) R + \alpha_{r-1} d_r = d_{r-1}, by the definition of RR;
  • for i=r−2i = r - 2 it is (1−αr−2)L+αr−2R=d^r−2(1 - \alpha_{r-2}) L + \alpha_{r-2} R = \hat d_{r-2};
  • all other points are did_i.

□\square

Theorem 1 (the step removes the jump)

After the step at trt_r the curve c^=∑iNid^i\hat c = \sum_i N_i \hat d_i is a single cubic polynomial on (tr−1,tr+1)(t_{r-1}, t_{r+1}). Hence c^′′′\hat c''' is continuous at trt_r, and, if c^′(tr)≠0\hat c'(t_r) \ne 0, the jump Δr\Delta_r of the curvature derivative at trt_r is 00. Only the control point dr−2d_{r-2} changes.

Proof. By Lemma 1, c^\hat c equals ee after knot insertion, and knot insertion does not change a curve, so c^=e\hat c = e. The knot vector τ\tau has no knot in (tr−1,tr+1)(t_{r-1}, t_{r+1}), so ee is one polynomial of degree 33 there. Its derivatives of every order are continuous at trt_r. The curvature derivative is the formula of the page in c′c', c′′c'' and c′′′c''', which is continuous wherever c′≠0c' \ne 0. The last claim is part of Lemma 1. □\square

Lemma 2 (the jump of the curvature derivative)

At a simple inner knot a cubic spline is C2C^2. If c′(tr)≠0c'(t_r) \ne 0, then κ′\kappa' jumps at trt_r by Δr=c′(tr)×(c′′′(tr+)−c′′′(tr−))/∣c′(tr)∣3\Delta_r = c'(t_r) \times (c'''(t_r^+) - c'''(t_r^-)) / |c'(t_r)|^3.

Proof. Differentiate κ=(c′×c′′)/∣c′∣3\kappa = (c' \times c'')/|c'|^3. Since (c′×c′′)′=c′′×c′′+c′×c′′′=c′×c′′′(c' \times c'')' = c'' \times c'' + c' \times c''' = c' \times c''' and (∣c′∣−3)′=−3(c′⋅c′′)∣c′∣−5(|c'|^{-3})' = -3 (c' \cdot c'') |c'|^{-5},

κ′=c′×c′′′∣c′∣3−3(c′×c′′)(c′⋅c′′)∣c′∣5.\kappa' = \frac{c' \times c'''}{|c'|^3} - 3 \frac{(c' \times c'')(c' \cdot c'')}{|c'|^5}.

At trt_r the values c′c' and c′′c'' are the same from both sides, so the second term has no jump and the first jumps by the stated amount. □\square

The implementation returns Δr2=(c′×δ)2/(c′⋅c′)3\Delta_r^2 = (c' \times \delta)^2 / (c' \cdot c')^3 with δ\delta the jump of c′′′c''', which is a rational number when the input is rational.

Theorem 2 (the curve stays within the tolerance)

Let d0d^0 be the first control points and dd the control points at any time. Then ∣cd(t)−cd0(t)∣≤max⁡i∣di−di0∣≤ε|c_d(t) - c_{d^0}(t)| \le \max_i |d_i - d^0_i| \le \varepsilon for all tt.

Proof. The knots never change, so cd(t)−cd0(t)=∑iNi(t)(di−di0)c_d(t) - c_{d^0}(t) = \sum_i N_i(t)(d_i - d^0_i). The B-spline basis functions are non negative and sum to 11 on the parameter interval, so this is a convex combination of the vectors di−di0d_i - d^0_i, and its length is at most the largest of their lengths. Line L6 accepts a step only if every ∣d^i−di0∣≤ε|\hat d_i - d^0_i| \le \varepsilon, so the bound holds after every accepted step, and it holds at the start. □\square

Theorem 3 (termination)

The loop ends after at most the given number of rounds, and the measure EE 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 E(d^)<EE(\hat d) < E. □\square

Lemma 3 (the count of curvature sign changes)

On a knot interval [a,b][a, b] the function f=c′×c′′f = c' \times c'' is a polynomial of degree at most 22, and the signs of f(a)f(a), of ff at its vertex if the vertex lies in (a,b)(a, b), and of f(b)f(b), with zeros dropped, have exactly as many sign changes as ff has on [a,b][a, b].

Proof. On the interval cc is a cubic polynomial, c(t)=At3+Bt2+Ct+Dc(t) = A t^3 + B t^2 + C t + D with vectors A,B,C,DA, B, C, D. Then c′=3At2+2Bt+Cc' = 3 A t^2 + 2 B t + C and c′′=6At+2Bc'' = 6 A t + 2 B, and the coefficient of t3t^3 in c′×c′′c' \times c'' is 3⋅6 (A×A)=03 \cdot 6 \, (A \times A) = 0. So ff has degree at most 22. A polynomial of degree at most 22 is monotone on [a,b][a, b], or monotone on each side of its vertex ss. On a monotone piece ff 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 [a,s][a, s] and [s,b][s, b], or [a,b][a, b] alone, so the sequence of signs at aa, ss and bb sees every change. Since c′c' and c′′c'' are continuous at simple knots, the sequences of consecutive intervals join without new changes at the knots. The curvature has the sign of ff where c′≠0c' \ne 0. The implementation finds ff from its values at aa, (a+b)/2(a + b)/2 and bb, which determine a polynomial of degree at most 22. □\square

What is not claimed

The method does not guarantee that the number of curvature sign changes falls. A lower EE 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 EE, but both inflections remain, and no further step lowers EE.

Complexity

Let n+1n + 1 be the number of control points and RR the number of rounds. The implementation computes the derivative curves for each jump, in O(n)O(n), so the measure costs O(n2)O(n^2). In a round it may try all n−3n - 3 knots and compute EE for each, so a round costs O(n3)O(n^3) and the whole run O(Rn3)O(R n^3). A step changes one control point, which changes the jumps at most at the five knots tr−2,…,tr+2t_{r-2}, \dots, t_{r+2}. An implementation that keeps the jumps in a priority queue and updates only these five costs O(log⁡n)O(\log n) per step after O(n)O(n) set up. The extra space is the copy of the first control points, Θ(n)\Theta(n).

Properties

  • Local. A step moves one control point, so the curve changes only on the four knot intervals of Nr−2N_{r-2}, [tr−2,tr+2][t_{r-2}, t_{r+2}].
  • 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 C3C^3 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 ∣c′×c′′∣|c' \times c''| 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 EE 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 EE 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 ∣c′∣3|c'|^3, 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 C1C^1, 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 EE, and curvature_sign_changes, which counts the sign changes of the curvature exactly: on each knot interval of a cubic, c′×c′′c' \times c'' is a polynomial of degree at most 22, 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.

knot_removal_fairing.pyI0RawGitHub
# 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

  1. Farin, Rein, Sapidis and Worsey 1987, local fairing of cubic B-spline curves by inversion of knot insertion, judged by the curvature plot
  2. 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
  3. 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
  4. 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.

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